branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import React from 'react'
import {FaFacebook, FaTwitterSquare, FaYoutubeSquare} from 'react-icons/fa'
export default [
{
icon:<FaFacebook/>,
url:'https://google.com'
},
{
icon: <FaTwitterSquare />,
url: 'https://twitter.com'
},
{
icon: <FaYoutubeSquare />,
url: 'https://youtube.com'
},
] | 5a9e09b18691400c398ebe4586767cf4b162f0d3 | [
"JavaScript"
] | 1 | JavaScript | PeterEfland/gatsby-backroads | feb2b5bb49d84a812f0bccbb0f523a2dd73b14a1 | 0562bc6295174dbdd08ac703e064551784e88874 |
refs/heads/master | <file_sep>import { useHistory } from "react-router-dom";
import React from "react";
import { Input } from "antd";
import { Upload, Button, Icon, Alert } from "antd";
import { Formik } from "formik";
import "./CreateEvent.css";
import { connect } from "react-redux";
import { createEvent, uploadImage } from "./../../actions";
import PlacesInput from "./PlacesInput";
import Header from "./../Header/Header";
const CreateEvent = props => {
let uploader;
const imageUpload = file => {
console.log(file.fileList);
uploader = file.fileList;
};
return (
<Formik
initialValues={{
name: "",
maxMembers: "",
description: "",
price: "",
contactNumber: "",
places: ""
}}
onSubmit={async values => {
const urls = await props.uploadImage(uploader, values.name);
props.createEvent({
...values,
creator: props.creatorId,
images: urls
});
props.history.push("/homePage");
}}
>
{({
values,
errors,
handleChange,
handleSubmit,
isSubmitting,
setFieldValue
}) => (
<>
<Header />
<div className="form-container">
<form className="form" onSubmit={handleSubmit}>
<div className="form-field">
<label htmlFor="eventName">Event Name</label>
<Input
type="text"
placeholder="Event name"
id="name"
name="name"
onChange={handleChange}
value={values.name}
></Input>
</div>
<div className="form-field">
<label htmlFor="maxMembers">Maxium Members</label>
<Input
type="number"
id="maxMembers"
name="maxMembers"
onChange={handleChange}
value={values.maxMembers}
></Input>
</div>
<div className="form-field">
<label htmlFor="description">Event Description</label>
<Input.TextArea
placeholder="Describe your event...."
type="text"
id="description"
name="description"
// autoSize={true}
autoSize={{ minRows: 1, maxRows: 7 }}
onChange={handleChange}
value={values.description}
></Input.TextArea>
</div>
<div className="form-field">
<label htmlFor="price">Price per ticket</label>
<Input
type="number"
id="price"
name="price"
onChange={handleChange}
value={values.price}
></Input>
</div>
<div className="form-field">
<label htmlFor="contactNumber">Contact Number</label>
<Input
type="number"
id="contactNumber"
name="contactNumber"
onChange={handleChange}
value={values.contactNumber}
></Input>
</div>
<div className="form-field">
<label>Venue</label>
<PlacesInput setFieldValue={setFieldValue} />
</div>
<div className="form-field">
<Upload onChange={imageUpload} multiple>
<Button>
<Icon type="upload" /> Upload
</Button>
</Upload>
</div>
<div className="form-field">
<button
className="create-event-button"
onClick={handleSubmit}
type="submit"
>
Create Event
{props.loading === true && (
<Icon
type="loading"
style={{ color: "white", margin: "3px" }}
></Icon>
)}
</button>
</div>
</form>
<div className="error-div">
{props.error === true && (
<Alert
style={{
margin: "1em",
width: "300px",
textAlign: "center"
}}
type="error"
message="Something went wrong"
></Alert>
)}
</div>
</div>
</>
)}
</Formik>
);
};
const mapStateToProps = state => {
return {
url: state.imageUpload.url,
creatorId: state.firebase.auth.uid,
imageUpload: state.imageUpload,
fetchedValues: state.updateEvent,
loading: state.loadingReducer,
error: state.errorReducer
};
};
const mapDispatchToProps = {
createEvent,
uploadImage
};
export default connect(mapStateToProps, mapDispatchToProps)(CreateEvent);
<file_sep>import React from "react";
import { connect } from "react-redux";
import { useFirestoreConnect } from "react-redux-firebase";
import { Icon, Carousel } from "antd";
import EventDetailMap from "./EventDetailMap";
import "./EventDetail.css";
import Header from "./../../components/Header/Header";
const EventDetail = (props) => {
const [isVisible, setVisibility] = React.useState(false);
const toggleVisibilityButoon = () => {
setVisibility(!isVisible);
};
useFirestoreConnect([{ collection: "Events" }]);
console.log(props.event.images);
return (
<div className="detailPage">
<Header />
<div className="event-detail-div">
<div className="img-name">
<Carousel autoplay>
{props.event.images &&
props.event.images.map((image) => (
<img src={image} alt="img" className="event-detail-img" />
))}
</Carousel>
<div className="event-details-div">
<div>
<h1 className="event-name-heading ">{props.event.name}</h1>
</div>
<div className="detail-field">
<div>
<span>
<Icon type="phone" className="event-detail-icon" />
</span>
<span style={{ fontSize: "18px", color: "#637d96" }}>
Contact:
</span>
</div>
<span className="event-span">{props.event.contactNumber}</span>
</div>
<div className="detail-field">
<div>
<span>
<Icon type="user" className="event-detail-icon" />
</span>
<span style={{ fontSize: "18px", color: "#637d96" }}>
Maximum Members:
</span>
</div>
<span className="event-span">{props.event.maxMembers}</span>
</div>
<div className="detail-field">
<div>
<span>
{" "}
<Icon type="tag" className="event-detail-icon" />
</span>
<span style={{ fontSize: "18px", color: "#637d96" }}>
Ticket:
</span>
</div>
<span className="event-span">{`${props.event.price} Rs`}</span>
</div>
<div className="event-description-div">
<p className="event-description">{props.event.description}</p>
</div>
<div className="show-map-div">
<button onClick={toggleVisibilityButoon} className="show-map-btn">
{isVisible === false ? "Show Map" : "Hide Map"}
</button>
</div>
<div className="map">
{props.event.places && isVisible === true && (
<EventDetailMap
latitude={props.event.places.lat}
longitude={props.event.places.lng}
/>
)}
</div>
</div>
</div>
</div>
</div>
);
};
const mapStateToProps = (state, ownProps) => {
const events = state.firestore.ordered.Events;
const id = ownProps.match.params.id;
const event = events
? events.filter((event) => event.id === id)[0]
: "loading";
return {
event,
};
};
export default connect(mapStateToProps)(EventDetail);
<file_sep>import { useHistory } from "react-router-dom";
import React from "react";
import { connect } from "react-redux";
import { Card, Icon, Alert } from "antd";
import { useFirestoreConnect } from "react-redux-firebase";
import "./MyEvents.css";
import { deleteEvent, fetchValues } from "./../../actions/";
import Header from "./../Header/Header";
const MyEvents = props => {
let history = useHistory();
let myEvents;
useFirestoreConnect([{ collection: "Events" }]);
myEvents = props.events
? props.events.filter(event => event.creator === props.user)
: null;
return (
<div className="my-events">
<Header />
<div className="my-events-container">
<div className="heading">
<h1 className="my-events-heading">My Events</h1>
</div>
<div className="my-events-list">
{myEvents &&
myEvents.map(event => (
<Card
className="ant-card"
key={event.id}
style={{ margin: "1em" }}
>
<img
src={event.images[0]}
alt="img"
className="event-img"
></img>
<div className="details">
<h1 className="event-heading">{event.name}</h1>
<p className="my-events-description">{event.description}</p>
<div className="my-events-buttons">
<div>
<button
className="view-more-button"
onClick={() => props.history.push(`event/${event.id}`)}
>
{" "}
View More
</button>
</div>
<div>
<button
onClick={() => props.deleteEvent(event)}
className="delete-button"
>
Delete Event
</button>
</div>
<div>
<button
className="edit-button"
onClick={() => {
props
.fetchValues(event.id, props.events)
.then(res => history.push("/editForm"));
}}
>
Edit
</button>
</div>
<div className="delete-edit-icons">
<Icon
type="delete"
className="delete"
onClick={() => props.deleteEvent(event)}
/>
<Icon
type="edit"
className="edit"
onClick={() => {
props
.fetchValues(event.id, props.events)
.then(res => history.push("/editForm"));
}}
/>
</div>
</div>
</div>
</Card>
))}
</div>
<div className="error-div">
{props.error === true && (
<Alert
style={{
margin: "1em",
width: "300px",
textAlign: "center"
}}
type="error"
message="Something went wrong"
className="error-alert"
></Alert>
)}
</div>
</div>
</div>
);
};
const mapStateToProps = state => {
return {
events: state.firestore.ordered.Events,
user: state.firebase.auth.uid,
error: state.errorReducer
};
};
const mapDispatchToProps = {
deleteEvent,
fetchValues
};
export default connect(mapStateToProps, mapDispatchToProps)(MyEvents);
<file_sep>import React, { Component } from "react";
import "antd/dist/antd.css";
import "./HomePage.css";
import { Layout, Alert } from "antd";
import EventList from "./events/EventList";
import { connect } from "react-redux";
import Header from "./Header/Header";
class HomePage extends Component {
render() {
const { error } = this.props;
return (
<div className="App">
<Layout className="layout-style">
<Header />
<section className="events-list">
<EventList />
</section>
<div className="error-div">
{this.props.error === true && (
<Alert
style={{
margin: "1em",
width: "300px",
textAlign: "center"
}}
type="error"
message="Something went wrong."
></Alert>
)}
</div>
</Layout>
</div>
);
}
}
const mapStateToProps = state => {
return {
error: state.errorReducer
};
};
export default connect(mapStateToProps)(HomePage);
<file_sep>import React from "react";
import "./LandingPage.css";
import { Button, Icon } from "antd";
import { NavLink } from "react-router-dom";
const LandingPage = () => {
return (
<div className="landing-page">
<p className="landing-page-heading">Events</p>
<NavLink to="/homePage">
<button className="landing-page-button">
Get Started <Icon type="arrow-right" className="landing-page-icon" />
</button>
</NavLink>
</div>
);
};
export default LandingPage;
<file_sep>import React, { Component } from "react";
import HomePage from "./components/HomePage";
import LoginForm from "./components/form/LoginForm";
import RegisterForm from "./components/form/RegisterForm";
import CreateEvent from "./components/form/CreateEvent";
import MyEvents from "./components/events/MyEvents";
import EvenDetail from "./components/events/EventDetail";
import EditForm from "./components/form/EditForm";
import LandingPage from "./components/LandingPage";
import { BrowserRouter } from "react-router-dom";
import { Route, Switch } from "react-router-dom";
class App extends Component {
render() {
return (
<BrowserRouter basename={process.env.PUBLIC_URL}>
<div className="App">
<Switch>
<Route exact path="/" component={LandingPage}></Route>
<Route exact path="/homePage" component={HomePage}></Route>
<Route path="/login" component={LoginForm}></Route>
<Route path="/register" component={RegisterForm}></Route>
<Route path="/createEvent" component={CreateEvent}></Route>
<Route path="/MyEvents" component={MyEvents}></Route>
<Route path="/event/:id" component={EvenDetail}></Route>
<Route path="/editForm" component={EditForm} />
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
<file_sep>import { useHistory } from "react-router-dom";
import React from "react";
import { Input } from "antd";
import { Upload, Button, Icon } from "antd";
import { Formik } from "formik";
import "./CreateEvent.css";
import { connect } from "react-redux";
import { updateValues, uploadImage } from "./../../actions";
import PlacesInput from "./PlacesInput";
import Header from './../Header/Header';
const CreateEvent = props => {
let history = useHistory();
let uploader;
const imageUpload = file => {
console.log(file.fileList);
uploader = file.fileList;
};
return (
<Formik
initialValues={{
name: props.obj && props.obj.name,
maxMembers: props.obj && props.obj.maxMembers,
description: props.obj && props.obj.description,
price: props.obj && props.obj.price,
contactNumber: props.obj && props.obj.contactNumber,
places: ""
}}
onSubmit={values => {
props.updateValues(
props.obj.id,
values.name,
values.description,
values.price,
values.maxMembers,
values.contactNumber,
values.places,
history
);
props.isUpdated === true && props.history.push("/MyEvents");
}}
>
{({
values,
errors,
handleChange,
handleSubmit,
isSubmitting,
setFieldValue
}) => (
<>
<Header/>
<div className="form-container">
<form className="form" onSubmit={handleSubmit}>
<div className="form-field">
<label htmlFor="eventName">Event Name</label>
<Input
type="text"
placeholder="Event name"
id="name"
name="name"
onChange={handleChange}
value={values.name}
></Input>
</div>
<div className="form-field">
<label htmlFor="maxMembers">Maxium Members</label>
<Input
type="number"
id="maxMembers"
name="maxMembers"
onChange={handleChange}
value={values.maxMembers}
></Input>
</div>
<div className="form-field">
<label htmlFor="description">Event Description</label>
<Input.TextArea
placeholder="Describe your event...."
type="text"
id="description"
name="description"
autoSize={true}
maxLength={1000}
onChange={handleChange}
value={values.description}
></Input.TextArea>
</div>
<div className="form-field">
<label htmlFor="price">Price per ticket</label>
<Input
type="number"
id="price"
name="price"
onChange={handleChange}
value={values.price}
></Input>
</div>
<div className="form-field">
<label htmlFor="contactNumber">Contact Number</label>
<Input
type="number"
id="contactNumber"
name="contactNumber"
onChange={handleChange}
value={values.contactNumber}
></Input>
</div>
<div className="form-field">
<label>Venue</label>
<PlacesInput setFieldValue={setFieldValue} />
</div>
<div className="form-field">
<Upload onChange={imageUpload} multiple>
<Button>
<Icon type="upload" /> Upload
</Button>
</Upload>
</div>
<div className="form-field">
<button
className="create-event-button"
onClick={handleSubmit}
type="submit"
>
Save
</button>
</div>
</form>
</div>
</>
)}
</Formik>
);
};
const mapStateToProps = state => {
return {
url: state.imageUpload.url,
createrId: state.firebase.auth.uid,
imageUpload: state.imageUpload,
obj: state.updateEvent[0],
isUpdated: state.updateEvent.isUpdated,
loading: state.loadingReducer
};
};
const mapDispatchToProps = {
updateValues,
uploadImage
};
export default connect(mapStateToProps, mapDispatchToProps)(CreateEvent);
<file_sep>
let initialState = {
fetchedValues: [],
isUpdated: false
};
const updateEvent = (state = initialState, action) => {
switch (action.type) {
case "FETCHED_VALUES":
return action.payload;
case "UPDATED":
return {
...state,
isUpdated: true
};
default:
return state;
}
};
export default updateEvent;
<file_sep>Deployed At : https://event-management-app.netlify.app/
<file_sep>import React from "react";
import { Menu, Dropdown, Icon } from "antd";
import { NavLink } from "react-router-dom";
import { connect } from "react-redux";
import { signOut } from "./../actions";
import "./DropDown.css";
const DropDown = props => {
const menu = (
<Menu>
<Menu.Item key="0">
<NavLink to="/createEvent">Create Event</NavLink>
</Menu.Item>
<Menu.Divider />
<Menu.Item key="1" onClick={props.signOut}>
Sign Out
</Menu.Item>
<Menu.Divider />
<Menu.Item key="3">
<NavLink to="/MyEvents">My Events</NavLink>
</Menu.Item>
</Menu>
);
return (
<div className="drop-down">
<Dropdown overlay={menu} trigger={["click"]}>
<Icon
type="more"
style={{
fontSize: "20px",
margin: "4px"
}}
/>
</Dropdown>
</div>
);
};
const mapDispatchToProps = dispatch => {
return {
signOut: () => {
dispatch(signOut());
}
};
};
export default connect(null, mapDispatchToProps)(DropDown);
| 5f52cf5380aa6df0fe5c11a3022943164a87634a | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | alizaLakhani14/Event-Mangement-App | d9aa6ae839d64287ec0f3fd00a963662a30c143b | ca41dbfcf1f24fa1181a872c330deb7df45f7f52 |
refs/heads/main | <file_sep>//a helper to redirect unauthenticated users attempting to access the login page
const withAuth = (req,res, next) => {
if (!req.session.user_id) {
res.redirect('/login');
}else{
next();
}
};
module.exports = withAuth;<file_sep>//
const { User } = require('../models');
const userData = [
{
username: "kelly_Reese",
twitter: "kellyR",
github: "kellyR",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
username: "carl_b",
twitter: "carlb",
github: "carlb",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
username: "carol_c",
twitter: "carol",
github: "carol",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
username: "Gary_n",
twitter: "GaryP",
github: "GaryP",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
username: "Suzanner",
twitter: "Suzanneri23",
github: "Suzanneri23",
email: "<EMAIL>",
password: "<PASSWORD>"
},
{
username: "Sydney",
twitter: "Sydney_w",
github: "Sydney",
email: "<EMAIL>",
password: "<PASSWORD>"
}
]
const seedUsers = () => User.bulkCreate(userData);
module.exports = seedUsers;<file_sep># mvc-tech-blog
https://still-fortress-27031.herokuapp.com/
https://flying-dink.github.io/mvc-tech-blog/
## Description
A blog style website where developers can create an account, edit info, post and comment.
## Installation
To install download or clone the files from the repository and open them in vscode. Then from the root directory run 'npm i' in the command line. Then from the root directory create a .env file with DB_NAME='myadventures_DB' DB_USER='' DB_PW='' and fill in your username and password for mysql. Then to the .env file add your cloudinary credentials CLOUD_NAME= ''API_KEY= '' API_SECRET=''.
## Usage
To use this program complete the installation instructions. Then iniate the database by logging into mysql using 'npm run seed' and running SOURCE ./db/schema.sql. Finally from the root directory run 'npm start' in the command line to run the program.
## Screenshot

## Contributors
None
## Collaborators
None
## Questions
<EMAIL>
| 139a27861c98125d4eb9a50a81844c2f41ff53e8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Flying-dink/mvc-tech-blog | 707de11c0191f21e8d16da1d070baf9a405730bc | 1ff339f1c9357902832eb3bcbdc3546872b8d91f |
refs/heads/master | <file_sep><?php
########################################################################
# Extension Manager/Repository config file for ext "ajax_google_search".
#
#
########################################################################
$EM_CONF[$_EXTKEY] = array(
'title' => 'Ajax Tabbed Google Search',
'description' => 'Advanced tabbed ajax based google search.',
'category' => 'plugin',
'author' => '<NAME>',
'author_email' => '<EMAIL>',
'shy' => '',
'dependencies' => '',
'conflicts' => '',
'priority' => '',
'module' => '',
'state' => 'alpha',
'internal' => '',
'uploadfolder' => 0,
'createDirs' => '',
'modify_tables' => '',
'clearCacheOnLoad' => 0,
'lockType' => '',
'author_company' => '',
'version' => '0.0.1',
'constraints' => array(
'depends' => array(
),
'conflicts' => array(
),
'suggests' => array(
),
),
'_md5_values_when_last_written' => 'a:10:{s:9:"ChangeLog";s:4:"868b";s:10:"README.txt";s:4:"ee2d";s:12:"ext_icon.gif";s:4:"1bdc";s:17:"ext_localconf.php";s:4:"1328";s:14:"ext_tables.php";s:4:"6e2d";s:16:"locallang_db.xml";s:4:"9c8d";s:19:"doc/wizard_form.dat";s:4:"5623";s:20:"doc/wizard_form.html";s:4:"34e9";s:37:"pi1/class.tx_ajaxgooglesearch_pi1.php";s:4:"f3d3";s:17:"pi1/locallang.xml";s:4:"58a3";}',
);
?>
<file_sep>This is a simple ajax based tabbed google search.
Not much "readme" documentation required for it. :P
<file_sep><?php
/***************************************************************
* Copyright notice
*
* (c) 2010 <NAME> <<EMAIL>>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* [CLASS/FUNCTION INDEX of SCRIPT]
*
* Hint: use extdeveval to insert/update function index above.
*/
require_once(PATH_tslib.'class.tslib_pibase.php');
/**
* Plugin 'Ajax Google Search' for the 'ajax_google_search' extension.
*
* @author <NAME> <<EMAIL>>
* @package TYPO3
* @subpackage tx_ajaxgooglesearch
*/
class tx_ajaxgooglesearch_pi1 extends tslib_pibase {
var $prefixId = 'tx_ajaxgooglesearch_pi1'; // Same as class name
var $scriptRelPath = 'pi1/class.tx_ajaxgooglesearch_pi1.php'; // Path to this script relative to the extension dir.
var $extKey = 'ajax_google_search'; // The extension key.
var $pi_checkCHash = true;
/**
* The main method of the PlugIn
*
* @param string $content: The PlugIn content
* @param array $conf: The PlugIn configuration
* @return The content that is displayed on the website
*/
function main($content, $conf) {
$this->conf = $conf;
$this->pi_setPiVarDefaults();
$this->pi_loadLL();
$content='<style type="text/css">
.search-control { margin: 10px;}
</style><link href="http://www.google.com/uds/css/gsearch.css" type="text/css" rel="stylesheet"/><script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=<KEY>" type="text/javascript"></script>
<script type="text/javascript">
function OnLoad() {
var tabbed = new GSearchControl();
tabbed.setLinkTarget(GSearch.LINK_TARGET_BLANK );
tabbed.addSearcher(new GwebSearch());
tabbed.addSearcher(new GlocalSearch());
tabbed.addSearcher(new GblogSearch());
tabbed.addSearcher(new GnewsSearch());
tabbed.addSearcher(new GbookSearch());
tabbed.addSearcher(new GvideoSearch());
var cseId = "017576662512468239146:omuauf_lfve";
var searcher;
var options;
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction("000455696194071821846:comparisons");
searcher.setUserDefinedLabel("Prices");
tabbed.addSearcher(searcher, options);
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction("000455696194071821846:community");
searcher.setUserDefinedLabel("Forums");
tabbed.addSearcher(searcher, options);
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction("000455696194071821846:shopping");
searcher.setUserDefinedLabel("Shopping");
tabbed.addSearcher(searcher, options);
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction(cseId, "Lectures");
searcher.setUserDefinedLabel("Lectures");
tabbed.addSearcher(searcher, options);
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction(cseId, "Assignments");
searcher.setUserDefinedLabel("Assignments");
tabbed.addSearcher(searcher, options);
searcher = new GwebSearch();
options = new GsearcherOptions();
searcher.setSiteRestriction(cseId, "Reference");
searcher.setUserDefinedLabel("Reference");
tabbed.addSearcher(searcher, options);
var drawOptions = new GdrawOptions();
drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);
tabbed.draw(document.getElementById("search_control_tabbed"), drawOptions);
tabbed.execute("");
}
GSearch.setOnLoadCallback(OnLoad);
</script>
<div class="search-control" id="search_control_tabbed" height="710" width="330"></div>
';
return $this->pi_wrapInBaseClass($content);
}
}
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_google_search/pi1/class.tx_ajaxgooglesearch_pi1.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/ajax_google_search/pi1/class.tx_ajaxgooglesearch_pi1.php']);
}
?>
| 349e5a7d5d14a75458bbb500990a1b4e05ad0901 | [
"Text",
"PHP"
] | 3 | PHP | TYPO3-svn-archive/ajax_google_search | 42b2f05c2a09cbd0c4290b19673170e898c6ca60 | 54fbb8154753f332d6d237453aeb2faee6e9e73f |
refs/heads/main | <file_sep>#include <windows.h>
#include <fstream>
#include <string>
using namespace std;
// counter for the keystrokes
static unsigned long long counter = 0;
// length of the expression "SESSION="
constexpr short session_word_length = 8;
// length of the expression "TOTAL="
constexpr short total_word_length = 6;
// ___source___: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
// virtual key value of the first "pressable" character
constexpr short BACKSPACE_ASCII = 0x8;
// virtual key value of the last "pressable" character
constexpr short DOT_ASCII = 0xBE;
BOOL write_to_file()
{
try
{
unsigned short session_number = 1;
unsigned long long total_keys_pressed = 0;
// try to open the data file
fstream data_file;
data_file.open("data.txt");
// if it does not exist
if (!data_file)
{
//create one
data_file.open("data.txt", fstream::in | fstream::out | fstream::app);
//add the starting data to the new file
data_file << "SESSION=" << session_number << endl;
data_file << "TOTAL=" << counter << endl;
data_file.close();
}
else
{
// close to open with new parameters
data_file.close();
// open the file with flags: input file, output file, append to file
data_file.open("data.txt", fstream::in | fstream::out | fstream::app);
// read the session info line into a string
string session_string;
getline(data_file, session_string);
// the session number is positioned right after the "SESSION=" expression
// convert it from string to int
session_number = stoi(session_string.substr(session_word_length, session_string.length() - 1));
// increase it by one to represent the current session
++session_number;
// read the total keys pressed info line into another string
string total_string;
getline(data_file, total_string);
// the total amount of keys pressed is positioned right after the "TOTAL=" expression
// convert it from string to int
total_keys_pressed = stoi(total_string.substr(total_word_length, total_string.length() - 1));
// add the newly pressed amount to it
total_keys_pressed += counter;
// close the file after we've gathered our info
data_file.close();
// reopen it with the trunc flag to clear any text inside it
data_file.open("data.txt", fstream::in | fstream::out | fstream::trunc);
//write the new data to the file
data_file << "SESSION=" << session_number << endl;
data_file << "TOTAL=" << total_keys_pressed << endl;
// close the file
data_file.close();
}
// try to open the log file
fstream log_file;
log_file.open("log.txt");
// if it does not exist
if (!log_file)
{
// create one
log_file.open("log.txt", fstream::in | fstream::out | fstream::app);
log_file << "Keys pressed in session #" << session_number << ": " << counter << endl;
log_file.close();
}
else
{
// close in order to open with new parameters
log_file.close();
// open the file with flags: input file, output file, append to file
log_file.open("log.txt", fstream::in | fstream::out | fstream::app);
// append the new record
log_file << "Keys pressed in session #" << session_number << ": " << counter << endl;
// close the file
log_file.close();
}
return TRUE;
}
catch (...)
{
return FALSE;
}
}
// if the console window gets closed, the process gets terminated ------------- this doesn't work! or the PC shuts down
// call write_to_file which returns TRUE if it runs successfully
// and returns FALSE if it fails
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_CLOSE_EVENT ||
dwCtrlType == CTRL_SHUTDOWN_EVENT ||
dwCtrlType == CTRL_BREAK_EVENT)
return write_to_file();
}
int main()
{
// kasnije dodaj key u registry da se pokrece na startupu, mozda ovo (?)https://stackoverflow.com/questions/15913202/add-application-to-startup-registry, provjeri za svaki slucaj
//assign the console handler routine to the console window
BOOL ret = SetConsoleCtrlHandler(HandlerRoutine, TRUE);
//hide the console window
ShowWindow(GetConsoleWindow(), SW_MINIMIZE);
while (1)
{
// iterate over the virtual key set
// starting at the first and finishing at the last pressable character
for (int i = BACKSPACE_ASCII; i <= DOT_ASCII; i++)
{
// check if the i-th key was pressed using the bitwise & 0x01
// more info: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
if (GetAsyncKeyState(i) & 0x01)
{
// if a certain key gets pressed increase the counter and break out of the loop
counter++;
break;
}
}
}
return 0;
}<file_sep># KeyloggerCPP
This is a simple C++ keylogger made as an exercise.
The code is flawed probably on more than several occasions,
but it is used as a learning resource and not a commercially viable product.
| 8f010012a653c287f8167d8c64a2dfd2d35b30aa | [
"Markdown",
"C++"
] | 2 | C++ | ZPetricusic/KeyloggerCPP | 5ab3f9387c77675b3c43589cb59e2975b2f1e50b | 82877a2906fa547e6686af34c20667881061de4b |
refs/heads/main | <repo_name>iamdustan/dotfiles<file_sep>/README.md
Dustan’s computer setup and dotfiles.
Originally forked from [paulirish/dotfiles](https://www.github.com/paulirish/dotfiles).
Currently it’s pretty hard-coded for OSX, and there is no intention to change
that.
<file_sep>/config/nvim/lua/config/keymaps.lua
local keymap = vim.keymap.set
-- Remap for dealing with word wrap
keymap("n", "k", "v:count == 0 ? 'gk' : 'k'", { expr = true })
keymap("n", "j", "v:count == 0 ? 'gj' : 'j'", { expr = true })
-- Better viewing keymap("n", "n", "nzzzv")
keymap("n", "N", "Nzzzv")
keymap("n", "g,", "g,zvzz")
keymap("n", "g;", "g;zvzz")
-- Better escape using jk in insert and terminal mode
keymap("i", "jk", "<ESC>")
keymap("t", "jk", "<C-\\><C-n>")
keymap("t", "<C-h>", "<C-\\><C-n><C-w>h")
keymap("t", "<C-j>", "<C-\\><C-n><C-w>j")
keymap("t", "<C-k>", "<C-\\><C-n><C-w>k")
keymap("t", "<C-l>", "<C-\\><C-n><C-w>l")
-- Add undo break-points
keymap("i", ",", ",<c-g>u")
keymap("i", ".", ".<c-g>u")
keymap("i", ";", ";<c-g>u")
-- Better indent
keymap("v", "<", "<gv")
keymap("v", ">", ">gv")
-- Paste over currently selected text without yanking it
keymap("v", "p", '"_dP')
-- Move Lines
keymap("n", "<A-j>", ":m .+1<CR>==")
keymap("v", "<A-j>", ":m '>+1<CR>gv=gv")
keymap("i", "<A-j>", "<Esc>:m .+1<CR>==gi")
keymap("n", "<A-k>", ":m .-2<CR>==")
keymap("v", "<A-k>", ":m '<-2<CR>gv=gv")
keymap("i", "<A-k>", "<Esc>:m .-2<CR>==gi")
-- Resize window using <shift> arrow keys
keymap("n", "<S-Up>", "<cmd>resize +2<CR>")
keymap("n", "<S-Down>", "<cmd>resize -2<CR>")
keymap("n", "<S-Left>", "<cmd>vertical resize -2<CR>")
keymap("n", "<S-Right>", "<cmd>vertical resize +2<CR>")
-- Save files
keymap("n", "<C-S>", ":w<CR>", { silent = true, noremap = true })
keymap("i", "<c-s>", "<c-o>:w<CR>", { noremap = true })
keymap("v", "<C-s>", "<esc>:w<CR>gv", { noremap = true })
-- Quickfix
keymap("n", "]q", "<cmd>cnext<CR>", { noremap = true })
keymap("i", "]q", "<c-o>:cnext<CR>", { noremap = true })
keymap("n", "[q", "<cmd>cprevious<CR>", { noremap = true })
keymap("i", "[q", "<c-o>:cprevious<CR>", { noremap = true })
<file_sep>/config/nvim/lua/plugins/colorscheme/init.lua
return {
{
"folke/styler.nvim",
event = "VeryLazy",
config = function()
require("styler").setup {
themes = {
markdown = { colorscheme = "gruvbox" },
help = { colorscheme = "gruvbox" },
},
}
end,
},
{
"folke/tokyonight.nvim",
lazy = false,
priority = 1000,
config = function()
local tokyonight = require "tokyonight"
tokyonight.setup { style = "storm" }
tokyonight.load()
end,
},
{
"catppuccin/nvim",
lazy = false,
name = "catppuccin",
priority = 1000,
},
{
"ellisonleao/gruvbox.nvim",
lazy = false,
priority = 1000,
config = function()
require("gruvbox").setup()
end,
},
}
<file_sep>/config/nvim/lua/plugins/filetree/init.lua
local M = {
"nvim-tree/nvim-tree.lua",
requires = {
"nvim-tree/nvim-web-devicons", -- optional, for file icons
},
event = "VeryLazy",
keys = {
{ "<leader>n", "<cmd>NvimTreeToggle<cr>" },
},
config = function()
local lib = require("nvim-tree.lib")
local view = require("nvim-tree.view")
local function collapse_all()
require("nvim-tree.actions.tree-modifiers.collapse-all").fn()
end
local function edit_or_open()
-- open as vsplit on current node
local action = "edit"
local node = lib.get_node_at_cursor()
-- Just copy what's done normally with vsplit
if node.link_to and not node.nodes then
require("nvim-tree.actions.node.open-file").fn(action, node.link_to)
view.close() -- Close the tree if file was opened
elseif node.nodes ~= nil then
lib.expand_or_collapse(node)
else
require("nvim-tree.actions.node.open-file").fn(action, node.absolute_path)
view.close() -- Close the tree if file was opened
end
end
local function vsplit_preview()
-- open as vsplit on current node
local action = "vsplit"
local node = lib.get_node_at_cursor()
-- Just copy what's done normally with vsplit
if node.link_to and not node.nodes then
require("nvim-tree.actions.node.open-file").fn(action, node.link_to)
elseif node.nodes ~= nil then
lib.expand_or_collapse(node)
else
require("nvim-tree.actions.node.open-file").fn(action, node.absolute_path)
end
-- Finally refocus on tree if it was lost
view.focus()
end
local function vsplit()
-- open as vsplit on current node
local action = "vsplit"
local node = lib.get_node_at_cursor()
-- Just copy what's done normally with vsplit
if node.link_to and not node.nodes then
require("nvim-tree.actions.node.open-file").fn(action, node.link_to)
elseif node.nodes ~= nil then
lib.expand_or_collapse(node)
else
require("nvim-tree.actions.node.open-file").fn(action, node.absolute_path)
end
end
local config = {
view = {
mappings = {
custom_only = false,
list = {
{ key = "l", action = "edit", action_cb = edit_or_open },
{ key = "L", action = "vsplit_preview", action_cb = vsplit_preview },
{ key = "S", action = "vsplit", action_cb = vsplit },
{ key = "h", action = "close_node" },
{ key = "H", action = "collapse_all", action_cb = collapse_all },
},
},
},
actions = {
-- open_file = {
-- quit_on_open = false,
-- },
},
}
require("nvim-tree").setup(config)
end,
}
return M
<file_sep>/bin/afk
#!/bin/sh
#
# Go afk on OSX 10.13 (High Sierra)
osascript -e 'tell application "System Events" to keystroke "q" using {command down, control down}'
<file_sep>/setup-apps.sh
#!/bin/bash
#
# Setup a new machine!
print_error() {
# Print output in red
printf "\e[0;31m [✖] $1 $2\e[0m\n"
}
print_info() {
# Print output in purple
printf "\n\e[0;35m $1\e[0m\n\n"
}
print_question() {
# Print output in yellow
printf "\e[0;33m [?] $1\e[0m"
}
print_result() {
[ $1 -eq 0 ] \
&& print_success "$2" \
|| print_error "$2"
[ "$3" == "true" ] && [ $1 -ne 0 ] \
&& exit
}
print_success() {
# Print output in green
printf "\e[0;32m [✔] $1\e[0m\n"
}
# setup vim/neovim
# Plug
setup_nvim() {
# this is a bit of a hack. It’s still taking a vim-first approach and
# configuring normal vim, then symlinking
# if [ ! -f $HOME/.vim/autoload/plug.vim ]
# then
# curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
# https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# fi
# vim +PlugInstall +qall
mkdir ~/.config > /dev/null 2>&1
ln -fs $(pwd)/config/nvim ~/.config/nvim
# ln -s ~/.vimrc ~/.config/nvim/init.vim > /dev/null 2>&1
print_success "nvim configured"
}
setup_osx() {
# support closing Finder
defaults write com.apple.finder QuitMenuItem -bool YES
# clear out the Dock
defaults write com.apple.dock persistent-apps -array
print_success "osx defaults configured"
}
setup_alacritty() {
mkdir ~/.config > /dev/null 2>&1
# mkdir ~/.config/alacritty > /dev/null 2>&1
ln -fs $(pwd)/config/alacritty ~/.config/alacritty
print_success "alacritty configured"
}
main() {
print_info "Configuring apps"
setup_nvim
setup_osx
setup_alacritty
print_info " Finished configuring apps"
}
main
<file_sep>/config/nvim/lua/plugins/telescope.lua
return {
{
"nvim-telescope/telescope.nvim",
cmd = "Telescope",
keys = {
{ "<leader><space>", "<cmd>Telescope find_files<cr>", desc = "Find Files" },
{ "<leader>ff", "<cmd>Telescope find_files<cr>", desc = "Find Files" },
{ "<leader>fr", "<cmd>Telescope oldfiles<cr>", desc = "Recent" },
{ "<leader>fb", "<cmd>Telescope buffers<cr>", desc = "Buffers" },
{ "<leader>fg", "<cmd>Telescope git_files<cr>", desc = "Git Files" },
{ "<leader>f/", "<cmd>Telescope live_grep<cr>", desc = "Grep" },
-- NERDTree open bindings
-- { "<leader>n", "<cmd>Telescope file_browser<cr><esc>", },
-- Ctrl-p ftw
{ "<C-p>", "<cmd>Telescope find_files<cr>", desc = "Find files" },
},
dependencies = {
"nvim-telescope/telescope-file-browser.nvim",
},
config = function()
require("telescope").load_extension("file_browser")
end,
},
{
"nvim-telescope/telescope-file-browser.nvim",
dependencies = {
"nvim-lua/plenary.nvim",
"sharkdp/fd",
},
},
}
<file_sep>/bin/mp4-to-gif
#!/bin/sh
#
# Convert an mp4 video into a gif
#
# TODO: test for existence of ffmpeg and gifski
# https://ffmpeg.org/
# https://gif.ski/
video_file=$1
if [ "$video_file" == "" ]; then
echo "You must pass a video file"
exit 1
fi
if [ ! -f "$video_file" ]; then
echo "Could not find file \"$video_file\"";
exit 1
fi
output_file="video.gif"
if [ "$2" != "" ]; then
output_file=$2
fi
tmp_dir=$(mktemp -d -t ci-XXXXXXXXXX)
echo "Converting $video_file to images in $tmp_dir"
ffmpeg -i $video_file $tmp_dir/frame%04d.png
echo "Converting images in $tmp_dir to $output_file"
gifski -o $output_file $tmp_dir/frame*.png
rm -rf $tmp_dir
<file_sep>/install.sh
#!/bin/bash
#
# Install sheesh
print_error() {
# Print output in red
printf "\e[0;31m [✖] $1 $2\e[0m\n"
}
print_info() {
# Print output in purple
printf "\n\e[0;35m $1\e[0m\n\n"
}
print_question() {
# Print output in yellow
printf "\e[0;33m [?] $1\e[0m"
}
print_result() {
[ $1 -eq 0 ] \
&& print_success "$2" \
|| print_error "$2"
[ "$3" == "true" ] && [ $1 -ne 0 ] \
&& exit
}
print_success() {
# Print output in green
printf "\e[0;32m [✔] $1\e[0m\n"
}
cmd_exists() {
[ -x "$(command -v "$1")" ] \
&& return 0 \
|| return 1
}
file_exists() {
[ -d $1 ] \
&& return 0 \
|| return 1
}
install_homebrew() {
if ! cmd_exists "brew"
then
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
print_success "homebrew installed"
else
print_success "homebrew already installed"
fi
}
install_watchman() {
if ! cmd_exists "watchman"
then
brew install watchman
print_success "watchman installed"
else
print_success "watchman already installed"
fi
}
install_nvm() {
if ! cmd_exists "nvm"
then
if file_exists "$HOME/.nvm"
then
curl -o- https://raw.githubusercontent.com/creationix/nvm/v1.33.0/install.sh | bash
print_success "nvm installed"
else
print_success "nvm already installed"
fi
fi
}
install_fnm() {
if ! cmd_exists "fnm"
then
if file_exists "$HOME/.fnm"
then
brew install Schniz/tap/fnm
print_success "fnm installed"
else
print_success "fnm already installed"
fi
fi
}
install_node() {
if ! cmd_exists "node"
then
fnm install v18 &>/dev/null
print_success "node v18.x.x installed"
else
print_success "node v18.x.x already installed"
fi
if ! cmd_exists "yarn"
then
brew install yarn &>/dev/null
print_success "yarn installed"
else
print_success "yarn already installed"
fi
}
install_ocaml() {
# TODO install these independently
if ! cmd_exists "opam"
then
brew install ocaml &>/dev/null
print_success "ocaml installed"
brew install opam &>/dev/null
print_success "opam installed"
else
print_success "ocaml already installed"
print_success "opam already installed"
fi
if ! cmd_exists "yarn"
then
brew install yarn &>/dev/null
else
print_success "yarn already installed"
fi
}
install_rustup() {
if ! cmd_exists "cargo"
then
curl https://sh.rustup.rs -sSf | sh
print_success "cargo installed"
else
print_success "cargo already installed"
fi
}
# OpenGL terminal emulator
# https://github.com/alacritty/alacritty
install_alacritty() {
if ! brew cask info alacritty &>/dev/null;
then
brew cask install alacritty
sudo tic -xe alacritty,alacritty-direct extra/alacritty.info
print_success "alacritty installed"
else
print_success "alacritty already installed"
fi
}
# vim for the modern era
# https://neovim.io/
install_neovim() {
if ! cmd_exists "nvim"
then
brew install neovim/neovim/neovim
print_success "neovim (nvim) installed"
else
print_success "neovim already installed"
fi
}
# github maintained git util library
# https://github.com/github/hub
install_hub() {
if ! cmd_exists "hub"
then
brew install hub
print_success "hub installed"
fi
}
# terminal multiplexer
# https://github.com/tmux/tmux/wiki
install_tmux() {
if ! cmd_exists "tmux"
then
brew install tmux
print_success "tmux installed"
else
print_success "tmux already installed"
fi
}
# zsh / ohmyzsh is an interactive shell
# https://ohmyz.sh/
install_zsh() {
if file_exists $HOME/.zshrc
then
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
print_success "zsh installed"
else
print_success "zsh already installed"
fi
}
# fzf is a general-purpose command-line fuzzy finder.
# https://github.com/junegunn/fzf
install_fzf() {
if ! cmd_exists "fzf"
then
brew install fzf
print_success "fzf (ag) installed"
else
print_success "fzf (ag) already installed"
fi
}
install_ag() {
if ! cmd_exists "ag"
then
brew install the_silver_searcher
print_success "the_silver_searcher (ag) installed"
else
print_success "the_silver_searcher (ag) already installed"
fi
}
install_ripgrep() {
if ! cmd_exists "rg"
then
brew install ripgrep
print_success "ripgrep (rg) installed"
else
print_success "ripgrep (rg) already installed"
fi
}
# A simple, fast and user-friendly alternative to 'find'
# https://github.com/sharkdp/fd
install_fd() {
if ! cmd_exists "fd"
then
brew install fd
print_success "fd installed"
else
print_success "fd already installed"
fi
}
install_amethyst() {
if ! brew info amethyst &>/dev/null;
then
brew install amethyst
print_success "amethyst installed"
else
print_success "amethyst already installed"
fi
}
install_lazygit() {
if ! brew info lazygit &>/dev/null;
then
brew install jesseduffield/lazygit/lazygit
brew install lazygit
print_success "lazygit installed"
else
print_success "lazygit already installed"
fi
}
upgrade_casks() {
print_info "upgrading casks"
brew cask upgrade
}
print_info "Installing base developer applications"
install_homebrew
install_watchman
# fnm > nvm
# install_nvm
install_fnm
install_fzf
install_fd
install_rustup
# I prefer building alacritty from source...
# install_alacritty
install_neovim
install_hub
install_tmux
install_zsh
# install_ag
install_ripgrep
install_node
install_ocaml
install_amethyst
install_lazygit
# upgrade_casks
print_info "Remember to build alacritty from source"
print_info " git clone <EMAIL>:alacritty/alacritty.git && cd alacritty && make app"
print_info " Finished installing base applications"
<file_sep>/config/nvim/lua/plugins/init.lua
return {
"nvim-lua/plenary.nvim",
"MunifTanjim/nui.nvim",
{
"nvim-tree/nvim-web-devicons",
config = { default = true },
},
-- numb.nvim is a Neovim plugin that peeks lines of the buffer in non-obtrusive way.
-- :{number} does line previews
{ "nacro90/numb.nvim", event = "BufReadPre", config = true },
{
"lukas-reineke/indent-blankline.nvim",
event = "BufReadPre",
config = true,
},
-- Neovim plugin to improve the default vim.ui interfaces
{
"stevearc/dressing.nvim",
event = "VeryLazy",
config = true,
},
{
"rcarriga/nvim-notify",
event = "VeryLazy",
enabled = true,
config = { default = true }, -- same as config = true
},
{
"monaqa/dial.nvim",
event = "BufReadPre",
config = function()
vim.api.nvim_set_keymap("n", "<C-a>", require("dial.map").inc_normal(), { noremap = true })
vim.api.nvim_set_keymap("n", "<C-x>", require("dial.map").dec_normal(), { noremap = true })
vim.api.nvim_set_keymap("v", "<C-a>", require("dial.map").inc_visual(), { noremap = true })
vim.api.nvim_set_keymap("v", "<C-x>", require("dial.map").dec_visual(), { noremap = true })
vim.api.nvim_set_keymap("v", "g<C-a>", require("dial.map").inc_gvisual(), { noremap = true })
vim.api.nvim_set_keymap("v", "g<C-x>", require("dial.map").dec_gvisual(), { noremap = true })
end,
},
-- Smooth scrolling
{
"karb94/neoscroll.nvim",
event = "VeryLazy",
config = true,
},
}
<file_sep>/config/nvim/lua/plugins/git/init.lua
return {
{
"sindrets/diffview.nvim",
cmd = { "DiffviewOpen", "DiffviewClose", "DiffviewToggleFiles", "DiffviewFocusFiles" },
config = true,
},
{
"TimUntersberger/neogit",
cmd = "Neogit",
config = {
integrations = { diffview = true },
},
keys = {
{ "<leader>gs", "<cmd>Neogit kind=floating<cr>", desc = "Status" },
},
},
{
"kdheepak/lazygit.vim",
event = "VeryLazy",
keys = {
{ "<leader>gg", "<cmd>LazyGit<cr>", desc = "LazyGit" },
},
},
-- :GBrowse
{ "tpope/vim-fugitive", event = "VeryLazy" },
{ "tpope/vim-rhubarb", event = "VeryLazy" },
}
<file_sep>/setup.sh
#!/bin/bash
#
# Setup a new machine!
#
# Install applications
./install.sh
# Setup dotfiles
./setup-dotfiles.sh
# Setup applications
./setup-apps.sh
<file_sep>/config/nvim/lua/config/options.lua
local indent = 2
vim.o.formatoptions = "jcroqlnt"
-- vim.o.shortmess = "filnxtToOFWIcC"
vim.opt.breakindent = true
vim.opt.cmdheight = 0
vim.opt.completeopt = "menuone,noselect"
vim.opt.conceallevel = 3
vim.opt.confirm = true
vim.opt.cursorline = true
vim.opt.expandtab = true
vim.opt.hidden = true
vim.opt.hlsearch = true
vim.opt.ignorecase = true
vim.opt.inccommand = "nosplit"
vim.opt.joinspaces = false
vim.opt.laststatus = 0
vim.opt.list = true
vim.opt.mouse = "a"
vim.opt.number = true
vim.opt.pumblend = 10
vim.opt.pumheight = 10
vim.opt.relativenumber = true
vim.opt.scrolloff = 8
vim.opt.sessionoptions = { "buffers", "curdir", "tabpages", "winsize" }
vim.opt.shiftround = true
vim.opt.shiftwidth = indent
vim.opt.showmode = false
vim.opt.sidescrolloff = 8
vim.opt.signcolumn = "yes"
vim.opt.smartcase = true
vim.opt.smartindent = true
vim.opt.splitbelow = true
-- vim.opt.splitkeep = "screen"
vim.opt.splitright = true
vim.opt.tabstop = indent
vim.opt.textwidth = 80
vim.opt.termguicolors = true
vim.opt.timeoutlen = 300
vim.opt.undofile = true
vim.opt.updatetime = 200
vim.opt.wildmode = "longest:full,full"
vim.opt.laststatus = 2 -- always display the status line
vim.g.mapleader = " "
vim.g.maplocalleader = ","
vim.keymap.set({ "n", "v" }, "<Space>", "<Nop>", { silent = true })
<file_sep>/config/nvim/lua/plugins/noice.lua
local M = {
"folke/noice.nvim",
event = "VeryLazy",
enabled = false, -- disable for now
}
function M.config()
require("noice").setup({
lsp = {
override = {
["vim.lsp.util.convert_input_to_markdown_lines"] = true,
["vim.lsp.util.stylize_markdown"] = true,
["cmp.entry.get_documentation"] = true,
},
},
presets = {
-- bottom_search = true,
command_palette = true,
long_message_to_split = true,
inc_rename = true,
lsp_doc_border = false,
cmdline_output_to_split = false,
},
})
end
return M
<file_sep>/config/nvim/lua/plugins/whichkey.lua
return {
"folke/which-key.nvim",
event = "VeryLazy",
config = function()
local wk = require("which-key")
wk.setup({
show_help = false,
plugins = { spelling = true },
key_labels = { ["<leader>"] = "SPC" },
triggers = "auto",
})
wk.register({
w = { "<cmd>update!<CR>", "Save" },
q = { "<cmd>lua require('util').smart_quit()<CR>", "Quit" },
f = { name = "+File" },
g = { name = "+Git" },
d = { name = "+Debugger" },
t = { name = "+VimTest" },
c = {
name = "+Code",
x = {
name = "Swap Next",
f = "Function",
p = "Parameter",
c = "Class",
},
X = {
name = "Swap Previous",
f = "Function",
p = "Parameter",
c = "Class",
},
},
}, { prefix = "<leader>" })
end,
}
<file_sep>/config/nvim/lua/plugins/lsp/init.lua
return {
{
"neovim/nvim-lspconfig",
event = "BufReadPre",
dependencies = {
-- 💼 Neovim plugin to manage global and project-local settings
{ "folke/neoconf.nvim", cmd = "Neoconf", config = true },
-- 💻 Neovim setup for init.lua and plugin development with full signature help, docs and completion for the nvim lua API.
{ "folke/neodev.nvim", config = true },
-- Standalone UI for nvim-lsp progress. Eye candy for the impatient
{ "j-hui/fidget.nvim", config = true },
-- Incremental LSP renaming based on Neovim's command-preview feature.
{ "smjonas/inc-rename.nvim", config = true },
-- Tools for better development in rust using neovim's builtin lsp
"simrat39/rust-tools.nvim",
"rust-lang/rust.vim",
-- Easily install and manage LSP servers, DAP servers, linters, and formatters.
"williamboman/mason.nvim",
-- Extension to mason.nvim that makes it easier to use lspconfig with mason.nvim. Strongly recommended for Windows users.
"williamboman/mason-lspconfig.nvim",
-- nvim-cmp source for neovim's built-in language server client.
"hrsh7th/cmp-nvim-lsp",
-- nvim-cmp source for displaying function signatures with the current parameter emphasized:
"hrsh7th/cmp-nvim-lsp-signature-help",
},
config = function(plugin)
require("plugins.lsp.servers").setup(plugin)
end,
},
-- Easily install and manage LSP servers, DAP servers, linters, and formatters.
{
"williamboman/mason.nvim",
cmd = "Mason",
keys = { { "<leader>cm", "<cmd>Mason<cr>", desc = "Mason" } },
ensure_installed = {
"stylua",
},
config = function(plugin)
require("mason").setup()
local mr = require("mason-registry")
for _, tool in ipairs(plugin.ensure_installed) do
local p = mr.get_package(tool)
if not p:is_installed() then
p:install()
end
end
end,
},
-- Use Neovim as a language server to inject LSP diagnostics, code actions, and more via Lua.
{
"jose-elias-alvarez/null-ls.nvim",
event = "BufReadPre",
dependencies = { "mason.nvim" },
config = function()
local nls = require("null-ls")
nls.setup({
sources = {
-- lua
nls.builtins.formatting.stylua,
-- javascript
nls.builtins.formatting.prettier,
nls.builtins.diagnostics.eslint_d,
-- cljoure
nls.builtins.formatting.cljstyle,
},
})
end,
},
-- A VS Code like winbar for Neovim
{
"utilyre/barbecue.nvim",
event = "VeryLazy",
dependencies = {
"neovim/nvim-lspconfig",
"SmiteshP/nvim-navic",
"nvim-tree/nvim-web-devicons",
},
config = true,
},
}
<file_sep>/config/nvim/lua/plugins/extras/lang/rust.lua
local install_root_dir = vim.fn.stdpath("data") .. "/mason"
local extension_path = install_root_dir .. "/packages/codelldb/extension/"
local codelldb_path = extension_path .. "adapter/codelldb"
local liblldb_path = extension_path .. "lldb/lib/liblldb.so"
return {
{
"nvim-treesitter/nvim-treesitter",
opts = function(_, opts)
vim.list_extend(opts.ensure_installed, { "rust" })
end,
},
{
"neovim/nvim-lspconfig",
dependencies = { "simrat39/rust-tools.nvim", "rust-lang/rust.vim" },
opts = {
servers = {
rust_analyzer = {
settings = {
["rust-analyzer"] = {
cargo = { allFeatures = true },
checkOnSave = {
command = "cargo clippy",
extraArgs = { "--no-deps" },
},
},
},
},
},
setup = {
rust_analyzer = function(_, opts)
local lsp_utils = require("plugins.lsp.utils")
lsp_utils.on_attach(function(client, buffer)
-- stylua: ignore
if client.name == "rust_analyzer" then
vim.keymap.set("n", "<leader>cR", "<cmd>RustRunnables<cr>", { buffer = buffer, desc = "Runnables" })
vim.keymap.set("n", "<leader>cl", function() vim.lsp.codelens.run() end, { buffer = buffer, desc = "Code Lens" })
end
end)
require("rust-tools").setup({
tools = {
hover_actions = { border = "solid" },
on_initialized = function()
vim.api.nvim_create_autocmd({ "BufWritePost", "BufEnter", "CursorHold", "InsertLeave" }, {
pattern = { "*.rs" },
callback = function()
vim.lsp.codelens.refresh()
end,
})
end,
},
server = opts,
dap = {
adapter = require("rust-tools.dap").get_codelldb_adapter(codelldb_path, liblldb_path),
},
})
return true
end,
},
},
},
{
"mfussenegger/nvim-dap",
opts = {
setup = {
codelldb = function()
local dap = require("dap")
dap.adapters.codelldb = {
type = "server",
port = "${port}",
executable = {
command = codelldb_path,
args = { "--port", "${port}" },
-- On windows you may have to uncomment this:
-- detached = false,
},
}
dap.configurations.cpp = {
{
name = "Launch file",
type = "codelldb",
request = "launch",
program = function()
return vim.fn.input("Path to executable: ", vim.fn.getcwd() .. "/", "file")
end,
cwd = "${workspaceFolder}",
stopOnEntry = false,
},
}
dap.configurations.c = dap.configurations.cpp
dap.configurations.rust = dap.configurations.cpp
end,
},
},
},
}
<file_sep>/dotfiles/.bashrc
export NODE_ENV='development'
export LS_OPTIONS='--color=auto'
eval "`dircolors`"
force_color_prompt=yes
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$
'
alias ls='ls $LS_OPTIONS'
alias ll='ls $LS_OPTIONS -l'
alias l='ls $LS_OPTIONS -lA'
# Detect my Pis and force a different shell to avoid
# the vim startup shell not found error
if [[ `uname` == 'Linux' ]]; then
TERM=xterm
fi
[ -s "$HOME/.config/env" ] && \. "$HOME/.config/env"
[ -s "$HOME/.config/.aliases" ] && \. "$HOME/.config/.aliases"
EDITOR=nvim
export EDITOR=nvim
# --files: List files that would be searched but do not search
# --no-ignore: Do not respect .gitignore, etc...
# --hidden: Search hidden files and folders
# --follow: Follow symlinks
# --glob: Additional conditions for search (in this case ignore everything in the .git/ folder)
export FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow --glob "!.git/*"'
[ -f ~/.fzf.bash ] && source ~/.fzf.bash
| f13a17af2e631a938ae2aab276bb7c499d38d1ab | [
"Markdown",
"Shell",
"Lua"
] | 18 | Markdown | iamdustan/dotfiles | 0da86b2ed21df09caa73058c91e4efe820d4fa90 | 6bcbcc8e9a044cbb395f7acc71326bbaadb7fe3e |
refs/heads/master | <repo_name>shimberger/cwput<file_sep>/examples/collect-metrics.sh
#!/bin/bash
# Configure region and namespace
REGION="eu-central-1"
NAMESPACE="TestNamespace"
# Shorthand to make putting metrics easier
CMD="./cwput --region $REGION --namespace "${NAMESPACE}" --dimensions Server=$(hostname -s)"
# Save load average
LOAD_AVG="$(uptime | awk -F'[a-z]:' '{ print $2}' | cut -d' ' -f 2)"
$CMD --metric "Load Average" --unit "Count" --value="${LOAD_AVG}"
# Save free disk space
DISKSPACE=$(df -h | grep /dev/disk1s1 | awk '/[0-9]%/{print $(5)}' | tr -d '%')
$CMD --metric "Free Disk Space (disk1s1)" --unit "Percent" --value="${DISKSPACE}"<file_sep>/main.go
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"gopkg.in/alecthomas/kingpin.v2"
"strings"
"time"
)
var (
region = kingpin.Flag("region", "The region to use.").Required().String()
namespace = kingpin.Flag("namespace", "The namespace to use").Required().String()
dimensions = kingpin.Flag("dimensions", "The dimensions to use").Default("").String()
metric = kingpin.Flag("metric", "The metric to use").Required().String()
unit = kingpin.Flag("unit", "The unit to use").Required().String()
value = kingpin.Flag("value", "The value to use").Required().Float64()
resolution = kingpin.Flag("resolution", "The resolution to use").Default("60").Int64()
)
func main() {
kingpin.Parse()
// Create the AWS session
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(*region),
}))
dims := make([]*cloudwatch.Dimension, 0, 0)
for _, arg := range strings.Split(*dimensions, ",") {
parts := strings.Split(arg, "=")
d := &cloudwatch.Dimension{}
d.SetName(parts[0])
d.SetValue(parts[1])
dims = append(dims, d)
}
now := time.Now()
datum := &cloudwatch.MetricDatum{
MetricName: aws.String(*metric),
Unit: aws.String(*unit),
Dimensions: dims,
Timestamp: &now,
Value: value,
StorageResolution: resolution,
}
datums := []*cloudwatch.MetricDatum{datum}
// Create a cloudwatch client
cw := cloudwatch.New(sess)
// Upload the file to cloud watch
_, err := cw.PutMetricData(&cloudwatch.PutMetricDataInput{
MetricData: datums,
Namespace: aws.String(*namespace),
})
// Check for errors
if err != nil {
fmt.Printf("Failed to publish metric, %v\n", err)
return
}
}
<file_sep>/README.md
# cwput - Standalone binary to write cloudwatch metrics
I know exists, I needed it anyway.. again.
## Usage
It uses the standard s3cli authentication methods.
cwput --region=<region> --metric=LoadAverage --namespace="CustomNamespace" --unit=Count --value=1.0 --dimensions="Server=$(hostname -s)"
You can use environment variables to provide secret key & access key:
AWS_SECRET_KET=abc AWS_ACCESS_KEY=def cwput ...
## Developing
Build the binary:
go build -o cwput *.go
Run the script:
./examples/collect-metrics.sh
Or both in one:
go build -o cwput *.go && ./examples/collect-metrics.sh | b8901f4eded285b4aab67a10667dd284d877f6da | [
"Markdown",
"Go",
"Shell"
] | 3 | Shell | shimberger/cwput | 21dae570c4a77566ab05c7a670fa519c8c2a0d57 | 56ddc8e2408402b977f3b8eeacb91a9a586b670b |
refs/heads/master | <repo_name>MrSescon/projetoFinalAngular<file_sep>/src/app/conversor/Models/index.ts
export * from './moeda.model';
export * from './convesao.model';
export * from './conversao-response.model';
| 82bfe560aae3d709a392c9438c27ea5cb99f2797 | [
"TypeScript"
] | 1 | TypeScript | MrSescon/projetoFinalAngular | 6224b0f4881d5c584d74e533fce513854efbaf06 | c9f9b30b5127b7be2abeb0f4c15e88816ab87662 |
refs/heads/main | <repo_name>luisbraganca/morning<file_sep>/src/components/Button/index.jsx
import React, { useState } from "react";
import useStyle from "./useStyle";
export default function Button({
onClick,
style: parentStyle,
children,
disabled,
}) {
const [hover, setHover] = useState(false);
const style = useStyle({ hover, disabled });
return (
<button
style={{ ...style.root, ...parentStyle }}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
onClick={disabled ? null : onClick}
>
{children}
</button>
);
}
<file_sep>/src/components/Loader/index.jsx
import { useEffect, useState } from "react";
import useStyle from "./useStyle";
export default function Loader({
open,
color,
weight,
height,
width,
speed = 250,
}) {
const [angle, setAngle] = useState(0);
const style = useStyle({
color,
weight,
height,
width,
angle,
speed: `0.${speed}s`,
});
useEffect(() => {
const timeoutId = setTimeout(() => setAngle(angle + 180), speed + 1);
return () => clearTimeout(timeoutId);
}, [angle, speed]);
return open ? <div style={style.root}></div> : null;
}
<file_sep>/src/components/Notes/index.jsx
import { useState } from "react";
import useLocalStorage from "../../hooks/useLocalStorage";
import useHotkey from "../../hooks/useHotkey";
import useStyle from "./useStyle";
import Editor from "../Editor";
import Button from "../Button";
export default function Notes() {
const [open, setOpen] = useState(false);
const [notes, setNotes] = useLocalStorage("notes", "");
const style = useStyle({ open });
useHotkey(
() => setOpen(!open),
(e) => e.ctrlKey && e.altKey && e.code === "ArrowRight"
);
return (
<div style={style.root}>
<Button onClick={() => setOpen(!open)} style={style.button}>
{open ? "×" : "n"}
</Button>
{open && (
<Editor onChange={(e) => setNotes(e.target.value)} value={notes} />
)}
</div>
);
}
<file_sep>/.env.example
REACT_APP_WEATHER_API_KEY='00000000000000000000000000000000'
REACT_APP_WEATHER_LATITUDE='40.730610'
REACT_APP_WEATHER_LONGITUDE='-73.935242'
GENERATE_SOURCEMAP=false
PUBLIC_URL=
<file_sep>/src/hooks/useOpenWeather/index.js
import axios from "axios";
import { useEffect, useState } from "react";
const request = axios.create({
baseURL: "https://api.openweathermap.org/data/2.5",
headers: {
"Content-type": "application/json",
},
});
export default function useOpenWeather(
type,
{ apiKey, latitude, longitude, count, units }
) {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
(async () => {
setIsLoading(true);
try {
const response = await request.get(`/${type}`, {
params: {
appid: apiKey,
lat: latitude,
lon: longitude,
units: units ?? "standard",
...(count ? { cnt: count } : {}),
},
});
setData(response.data);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
})();
}, [type, apiKey, latitude, longitude, units, count]);
return {
data,
isLoading,
error,
};
}
<file_sep>/src/hooks/useFocus/index.js
import { useRef } from "react";
export default function useFocus() {
const ref = useRef();
const focus = (selection) => {
const element = ref.current;
if (element) {
element.focus();
selection &&
element.setSelectionRange(
selection.start,
selection.end,
selection.direction
);
}
};
return [ref, focus];
}
<file_sep>/src/components/SearcherForm/useStyle.js
import { useMediaQuery } from "react-responsive";
export default function useStyle() {
const isSmallScreen = useMediaQuery({ maxWidth: 720 });
return {
root: {
width: "100%",
marginTop: 50,
},
input: {
textAlign: "center",
fontSize: 20,
border: "none",
outline: "none",
color: "white",
textShadow: "0px 0px 1px white",
borderBottom: "1px solid white",
borderRadius: 5,
backgroundColor: "rgba(0, 0, 0, 0.5)",
...(isSmallScreen
? { width: "95%", padding: "2.5%" }
: { width: "75%", padding: 25 }),
},
};
}
<file_sep>/src/components/OpenWeather/CurrentWeatherIcon/index.jsx
import { useEffect } from "react";
import useOpenWeather from "../../../hooks/useOpenWeather";
import Loader from "../../Loader";
import icons from "../icons";
import useStyle from "./useStyle";
export default function CurrentWeatherIcon({
apiKey,
latitude,
longitude,
units,
onError,
}) {
const { data, isLoading, error } = useOpenWeather("weather", {
apiKey,
latitude,
longitude,
units,
});
const style = useStyle();
useEffect(() => {
onError(error);
}, [onError, error]);
return (
<div style={style.root}>
<Loader height="100%" width="100%" open={isLoading} />
{data && (
<img
style={style.image}
alt="Weather"
src={icons[data.weather[0].icon]}
/>
)}
</div>
);
}
<file_sep>/src/components/Searcher/useStyle.js
import { useMediaQuery } from "react-responsive";
export default function useStyle({ open, visible }) {
const isSmallScreen = useMediaQuery({ query: "(max-width: 720px)" });
return {
selected: {
width: 60,
height: 60,
margin: 0,
},
selector: {
display: "block",
backgroundColor: "rgba(0, 0, 0, 0.5)",
transition: "0.4s",
transitionTimingFunction: "ease-in-out",
padding: isSmallScreen ? "0 5px" : "0 150px",
maxHeight: open ? "100%" : 0,
opacity: open ? 0.8 : 0.0,
},
};
}
<file_sep>/README.md

# morning
Powerful and customizable home page with weather, notes and search engines support.

## Demo
[Check here](https://zealous-hopper-aed1ae.netlify.app)
## Features
### Power search
Quickly switch between search engines by typing the corresponding `bang` value. For example, to switch to `duckduckgo` simply type `!dd` and add a space.
You can also toggle the search engines selector visibility by pressing `Ctrl Alt Up` (or by clicking on the selected engine) and select the engine wih `Tab`. It's not as fast but it allows you to remember which engines are available.
### Menu
Simplified APP selector, toggle its visibility with `Ctrl Alt Down` or by clicking `menu`. You can save your favorite websites here.
> **TIP:** Try using complete `URL`s, for example if you clear all cookies on exiting the browser, it may be useful to put the `URL`to the login pages. Or if you're constantly going to a section on a website, try using the `URL` that leads directly to that section.
### Notes
Simple notes editor. You can open it with `Ctrl Alt Right` or by clicking `n`. The caret position (and also the selection if any) is saved in your browser's storage so if you `refresh`/`close` your browser, the caret position will remain the same.
I didn't put much effort on this editor but its styled with a mono-spaced font allowing you to manually type a table:
```
Shopping list:
Quantity | Item
---------|----------
2 | Water bottles
10 | Bubble gum
```
> **WARNING:** Keep in mind that all the text saved here rely on your browser's storage so if you uninstall/clean your browser you may loose your notes.
### Weather
On your upper left corner there's an icon representing the current weather. If you click it (or press `Ctrl Alt Left`) you'll be able to see a forecast with the temperatures and the humidity.
Once you open `morning`, it will try to ask your permission to access your location in order to show you the weather for your location. If for some reason it can't access your location, it will use the fallback coordinates specified on `config.js`, you can also specify here that you want to always use the fallback coordinates not accessing your location (See [Develop](#develop) for more info on how to customize your own `morning` version), you can also remove this feature entirely.
## Develop
1. [Install](#install)
2. [Configure](#configure)
1. Weather
2. Background image
3. Search engines
4. Menu
3. [Build](#build)
### Install
```
git clone <EMAIL>:luisbraganca/morning.git
npm i
```
### Configure
#### Weather
If you don't want to use this feature at all, simply change the `weather` value in your `src/config.js` file to the following and skip the rest of this section
```js
(...)
export const weather = null;
```
1. Create an `.env` file, this is where all your personal sensitive info will be stored. You can either rename `.env.example` to `.env`, or copy and empty one and copy the contents from `.env.example`.
2. Firstly you need to go to [OpenWeatherMap](https://openweathermap.org) and get yourself an `API` `token` (the free plan should be enough).
3. Create an account.
4. Go [Here](https://home.openweathermap.org/api_keys), generate a `key` if you have none.
5. Put your `key` on the `.env` file.
6. Put your home's coordinates on the `.env` file.
7. Now, if you wish to try to use your browser's location instead (and only use the `.env`'s coordinates as fallback), then on the `src/config.js` file set `tryNavigation` to `true`. If you don't want to use browser's location at all and always use your home's coordinates, set it to `false`.
8. Set your desired `units` on the `src/config.js`, possible values are `"standard"`, `"metric"`, `"imperial"`.
#### Background image
Simply replace the image `public/img/background.jpg` with the one you want.
#### Search engines
All the search engines are defined on the `src/config.js` file on the `engines` array. The first one is used as `default`, so move the one you want as default to the first place.
To remove a search engine, simply the object from the array.
To add a search engine, you need 2 steps. First, add an object to the array:
```js
export const engines = [
{
/**
* `bang` defines the characters to type after the `!`
* in order to switch to this engine. It doesn't necessarily
* need to be 2 characters long.
*/
bang: "bs",
/**
* The `URL`, `{search}` will be replaced with the result
* of the `parser` function.
*/
action: "https://search.brave.com/search?q={search}",
/**
* The name of this search engine. It will be used for the
* icon (it assumes there's always an icon at `public/img/icons/«name».png`).
* This value is also used on the input's placeholder, showing `Search «name»`.
*/
name: "bravesearch",
/**
* This function is optional, if it's not provided, the search entered
* will only be trimmed and directly replaced on the `action` `URL`.
* This is useful when you need to change the search entry before
* moving it to the `URL`.
* Some engines want the value to ve encoded (`encodeURIComponent`),
* others simply want white spaces to be replaced with `+`.
*/
parser: (search) => encodeURIComponent(search).replace(/[ ]/g, "+"),
},
(...)
];
(...)
```
The second step is to add the added search engine's image to `public/img/icons/«name».png` (check the folder first, maybe I already made an icon for you).
#### Menu
This one is quite easy to setup. Simply add an entry defining the `name` (once again, used for the image) and the `href`, the `URL` where it leads to.
```js
export const apps = [
{ name: "protonmail", href: "https://account.protonmail.com/login" },
(...)
];
(...)
```
Once again, you should add an image to the added entry. Put it under `public/img/icons/«name».png` named after the value you put on `name`.
### Build
```
npm run build
```
Host ONLY the contents on the `build` folder (it contains all the necessary files).
> **NOTE:** If you wish to host the website on a subfolder on your directory (for example, instead of `example.com`, you want to put it under `example.com/morning/`), you need o add `PUBLIC_URL='morning'` on your `.env` file.
<file_sep>/src/components/OpenWeather/icons/index.js
import icon01d from "./01d.png";
import icon01n from "./01n.png";
import icon02d from "./02d.png";
import icon02n from "./02n.png";
import icon03d from "./03d.png";
import icon03n from "./03n.png";
import icon04d from "./04d.png";
import icon04n from "./04n.png";
import icon09d from "./09d.png";
import icon09n from "./09n.png";
import icon10d from "./10d.png";
import icon10n from "./10n.png";
import icon11d from "./11d.png";
import icon11n from "./11n.png";
import icon13d from "./13d.png";
import icon13n from "./13n.png";
import icon50d from "./50d.png";
import icon50n from "./50n.png";
const icons = {
"01d": icon01d,
"01n": icon01n,
"02d": icon02d,
"02n": icon02n,
"03d": icon03d,
"03n": icon03n,
"04d": icon04d,
"04n": icon04n,
"09d": icon09d,
"09n": icon09n,
"10d": icon10d,
"10n": icon10n,
"11d": icon11d,
"11n": icon11n,
"13d": icon13d,
"13n": icon13n,
"50d": icon50d,
"50n": icon50n,
};
export default icons;
<file_sep>/src/components/CurrentDateTime/index.jsx
import React from 'react';
import useDateTimeString from '../../hooks/useDateTimeString';
import useStyle from './useStyle';
export default function CurrentDateTime() {
const style = useStyle();
const { dateString, timeString } = useDateTimeString();
return (
<div style={style.root}>
<h1 style={style.time}>{timeString}</h1>
<h3 style={style.date}>{dateString}</h3>
</div>
);
}
<file_sep>/src/components/OpenWeather/DetailedWeather/index.jsx
import { useEffect, useState } from "react";
import useHotkey from "../../../hooks/useHotkey";
import useOpenWeather from "../../../hooks/useOpenWeather";
import Button from "../../Button";
import Loader from "../../Loader";
import WeatherItem from "../WeatherItem";
import useStyle from "./useStyle";
export default function DetailedWeather({
apiKey,
latitude,
longitude,
units,
count,
onError,
}) {
const { data, isLoading, error } = useOpenWeather("forecast", {
apiKey,
latitude,
longitude,
units: units ?? "metric",
count: count ?? 40,
});
const length = data?.list.length;
const [index, setIndex] = useState(0);
const style = useStyle();
useEffect(() => {
onError(error);
}, [onError, error]);
useHotkey(
() => index !== length - 1 && setIndex(index + 1),
(e) => e.code === "ArrowRight"
);
useHotkey(
() => index !== 0 && setIndex(index - 1),
(e) => e.code === "ArrowLeft"
);
return (
<div style={style.root}>
<Loader height="100%" width="100%" color="#ddd" open={isLoading} />
{data && (
<>
<Button
disabled={index === 0}
style={style.paginator}
onClick={() => setIndex(index - 1)}
>
{"<"}
</Button>
<WeatherItem data={data.list[index]} />
<Button
disabled={index === length - 1}
style={style.paginator}
onClick={() => setIndex(index + 1)}
>
{">"}
</Button>
</>
)}
{error && <p>{error.message}</p>}
</div>
);
}
<file_sep>/src/components/CurrentDateTime/useStyle.js
import { useMediaQuery } from 'react-responsive';
export default function useStyle() {
const keyboardOpen = useMediaQuery({ maxWidth: 720, maxHeight: 720 });
return {
root: {
display: keyboardOpen ? 'none' : 'block',
width: '100%',
overflow: 'hidden',
textShadow: '0px 0px 5px black',
},
time: {
outline: 'none',
overflow: 'none',
fontSize: 80,
fontWeight: 400,
},
date: {
fontSize: 30,
fontWeight: 400,
},
};
}
<file_sep>/src/components/Searcher/engines.js
import { engines } from "../../config";
export default engines;
<file_sep>/src/components/Toast/useStyle.js
import { Type } from "./index";
export default function useStyle({ open, type, from }) {
let backgroundColor;
if (type === Type.SUCCESS) {
backgroundColor = "#a0bbb6";
} else if (type === Type.WARNING) {
backgroundColor = "#f4d1b8";
} else if (type === Type.ERROR) {
backgroundColor = "#f5c4c3";
} else {
// Type.INFO
backgroundColor = "#c1d4f6";
}
return {
root: {
position: "fixed",
minWidth: "50vw",
left: "50%",
transform: "translateX(-50%)",
zIndex: 2000,
color: "#fff",
textAlign: "center",
borderRadius: 5,
padding: 16,
fontSize: 16,
backgroundColor,
...(open
? {
[from]: 100,
opacity: 1,
}
: {
[from]: -500,
opacity: 0,
}),
},
};
}
<file_sep>/src/components/Loader/useStyle.js
export default function useStyle({
weight,
color,
width,
height,
angle,
speed,
}) {
return {
root: {
borderRadius: "50%",
borderTopColor: color ?? "#000",
borderTopStyle: "solid",
borderTopWidth: weight ?? 2,
width: width ?? 64,
height: height ?? 64,
transition: speed ?? "0.25s",
transitionTimingFunction: "linear",
transform: `rotate(${angle}deg)`,
},
};
}
<file_sep>/src/components/Editor/index.jsx
import { useEffect } from "react";
import useFocus from "../../hooks/useFocus";
import useLocalStorage from "../../hooks/useLocalStorage";
import useStyle from "./useStyle";
export default function Editor({ value, onChange }) {
const style = useStyle();
const [ref, focus] = useFocus();
const [caretPosition, setCaretPosition] = useLocalStorage("selection", {
start: 0,
end: 0,
direction: "forward",
});
const updateCaretPosition = ({
target: {
selectionStart: start,
selectionEnd: end,
selectionDirection: direction,
},
}) => setCaretPosition({ start, end, direction });
useEffect(() => {
focus(caretPosition);
}, [focus, caretPosition]);
return (
<textarea
ref={ref}
onClick={updateCaretPosition}
onKeyUp={updateCaretPosition}
onChange={(e) => {
updateCaretPosition(e);
onChange(e);
}}
spellCheck="false"
style={style.root}
value={value}
/>
);
}
<file_sep>/src/components/Editor/useStyle.js
export default function useStyle() {
return {
root: {
fontSize: "14pt",
fontFamily: "monospace",
textAlign: "left",
margin: "5px 1%",
padding: "5px 1%",
boxShadow: "0 0 5px 0 rgba(0, 0, 0, 0.6)",
height: "calc(100% - 90px)",
width: "96%",
backgroundColor: "#222",
outline: "none",
border: "none",
color: "#ddd",
resize: "none",
},
};
}
<file_sep>/src/hooks/useDateTimeString/index.js
import { useEffect, useState } from "react";
const weekdays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const yearMonths = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const numberFormat = (number, digits) =>
"0".repeat(digits - number.toString().length) + number.toString();
export default function useDateTimeString() {
const [dateString, setDateString] = useState("");
const [timeString, setTimeString] = useState("");
const updateDateTime = () => {
var date = new Date();
var weekDay = weekdays[date.getDay()];
var yearMonth = yearMonths[date.getMonth()];
setDateString(
`${weekDay}, ${date.getDate()} ${yearMonth} ${date.getFullYear()}`
);
setTimeString(
`${numberFormat(date.getHours(), 2)}:${numberFormat(
date.getMinutes(),
2
)}`
);
};
useEffect(() => {
const intervalId = setInterval(updateDateTime, 1000);
updateDateTime();
return () => {
clearInterval(intervalId);
};
}, []);
return {
dateString,
timeString,
};
}
<file_sep>/src/components/IconButton/useStyle.js
export default function useStyle({ name, hover }) {
return {
root: {
background: "none",
border: "none",
borderRadius: 3,
margin: 15,
display: "inline-block",
width: 50,
height: 50,
transition: "0.3s",
backgroundImage: `url('${process.env.PUBLIC_URL}/img/icons/${name}.png')`,
boxShadow: "1px 1px 5px black",
backgroundSize: "cover",
cursor: "pointer",
...(hover ? { transform: "scale(1.2)" } : {}),
},
};
}
<file_sep>/src/components/Weather/index.jsx
import { useState } from "react";
import { CurrentWeatherIcon, DetailedWeather } from "../OpenWeather";
import useHotkey from "../../hooks/useHotkey";
import config from "./config";
import useStyle from "./useStyle";
import useLocation, { useManualCoordinates } from "../../hooks/useLocation";
import Button from "../Button";
import Loader from "../Loader";
import Toast, { Type } from "../Toast";
export default function Weather() {
const { apiKey, units, tryNavigation } = config;
const [open, setOpen] = useState(false);
const style = useStyle({ open });
const [weatherError, setWeatherError] = useState(null);
const {
coordinates: { latitude, longitude },
isLoading,
error,
} = useLocation(
null,
{
latitude: config.latitude,
longitude: config.longitude,
},
tryNavigation
? useManualCoordinates.AS_FALLBACK
: useManualCoordinates.ALWAYS
);
useHotkey(
() => setOpen(!open),
(e) => e.ctrlKey && e.altKey && e.code === "ArrowLeft"
);
let buttonChild;
if (isLoading) {
buttonChild = <Loader height="100%" width="100%" open={isLoading} />;
} else if (error) {
buttonChild = null;
} else if (open) {
buttonChild = "×";
} else {
buttonChild = (
<CurrentWeatherIcon
apiKey={apiKey}
latitude={latitude}
longitude={longitude}
onError={setWeatherError}
/>
);
}
if (weatherError) {
return (
<Toast type={Type.ERROR} open={!!weatherError}>
{`Error fetching weather info (${weatherError?.message}).`}
</Toast>
);
}
return (
<div style={style.root}>
<Button onClick={() => setOpen(!open)} style={style.button}>
{buttonChild}
</Button>
{open && (
<DetailedWeather
apiKey={apiKey}
latitude={latitude}
longitude={longitude}
units={units}
onError={setWeatherError}
/>
)}
</div>
);
}
<file_sep>/src/components/AppMenu/index.jsx
import React, { useState } from "react";
import useStyle from "./useStyle";
import apps from "./apps";
import IconButton from "../IconButton";
import useHotkey from "../../hooks/useHotkey";
import Button from "../Button";
const onClick = (href) => {
window.open(href, "_blank");
};
export default function AppMenu() {
const [open, setOpen] = useState(false);
const style = useStyle({ open });
useHotkey(
() => setOpen(!open),
(e) => e.ctrlKey && e.altKey && e.code === "ArrowDown"
);
return (
<div style={style.root}>
<Button style={style.menu} onClick={() => setOpen(!open)}>
{open ? "×" : "menu"}
</Button>
{open && (
<div style={style.apps}>
{apps.map(({ name, href }) => (
<IconButton key={name} name={name} onClick={() => onClick(href)} />
))}
</div>
)}
</div>
);
}
<file_sep>/src/hooks/useHotkey/index.js
import { useEffect } from "react";
export default function useHotkey(callback, condition) {
useEffect(() => {
const hotkeyHandler = (e) => condition(e) && callback();
window.addEventListener("keydown", hotkeyHandler);
return () => window.removeEventListener("keydown", hotkeyHandler);
}, [callback, condition]);
}
<file_sep>/src/components/Button/useStyle.js
export default function useStyle({ hover, disabled }) {
let color = "#ccc";
if (disabled) {
color = "#222";
} else if (hover) {
color = "#fff";
}
return {
root: {
background: "none",
border: "none",
transition: "0.3s",
cursor: "pointer",
color,
},
};
}
<file_sep>/src/components/Notes/useStyle.js
export default function useStyle({ open }) {
return {
root: {
position: "fixed",
top: 0,
right: 0,
transition: "0.3s",
transitionTimingFunction: "ease-in-out",
marginLeft: 10,
textAlign: "center",
boxShadow: "0 0 5px 0 #000",
...(open
? {
zIndex: 900,
height: "100%",
width: "100%",
paddingTop: 15,
backgroundColor: "rgba(0, 0, 0, 0.8)",
}
: {
zIndex: 20,
height: 55,
width: 55,
backgroundColor: "rgba(0, 0, 0, 0.6)",
}),
},
button: {
width: "100%",
fontWeight: "bold",
cursor: "pointer",
textDecoration: "none",
display: "block",
transition: "0.3s",
background: "none",
border: "none",
fontSize: 40,
height: 50,
...(open
? { padding: "2px 1%", textAlign: "right" }
: { padding: 2, textAlign: "center" }),
},
};
}
<file_sep>/src/components/Toast/index.jsx
import useStyle from "./useStyle";
export default function Toast({
open,
type,
style: parentStyle,
from = "bottom",
children,
onClick = () => {},
}) {
const style = useStyle({ open, type, from });
return (
<div onClick={onClick} style={{ ...style.root, ...parentStyle }}>
{children}
</div>
);
}
export const Type = {
SUCCESS: 1,
INFO: 2,
WARNING: 3,
ERROR: 4,
};
| 6596389ae0517dffd788c660ce5f069012787501 | [
"JavaScript",
"Markdown",
"Shell"
] | 27 | JavaScript | luisbraganca/morning | 5a973f981a6a87c3d46579f607c5c31e08a6208c | d48677793f6ca17b5b7fc903b26f3d326e6367f4 |
refs/heads/master | <repo_name>bwelco/Industry4.0APP<file_sep>/app/src/main/java/com/bwelco/app/RoutePlanActivity.java
package com.bwelco.app;
import android.app.Activity;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.TransitRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption.DrivingPolicy;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRoutePlanOption.TransitPolicy;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* 路线规划
*
* @author ys
*/
/**
* 此demo用来展示如何进行驾车、步行、公交路线搜索并在地图使用RouteOverlay、TransitOverlay绘制
* 同时展示如何进行节点浏览并弹出泡泡
*
*/
public class RoutePlanActivity extends Activity {
private MapView mapView;
private BaiduMap bdMap;
// private EditText startEt;
// private EditText endEt;
// private String startPlace;// 开始地点
// private String endPlace;// 结束地点
//
// private Button driveBtn;// 驾车
// private Button walkBtn;// 步行
// private Button transitBtn;// 换成 (公交)
// private Button nextLineBtn;
//
// private Spinner drivingSpinner, transitSpinner;
private Button checkButton;
private RoutePlanSearch routePlanSearch;// 路径规划搜索接口
private int index = -1;
private int totalLine = 0;// 记录某种搜索出的方案数量
private int drivintResultIndex = 0;// 驾车路线方案index
private int transitResultIndex = 0;// 换乘路线方案index
private String city; //城市
private String address;//详细地址
private double longitude, latitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//无标题栏
setContentView(R.layout.activity_routeplan);
Bundle bundle = this.getIntent().getExtras();
city = bundle.getString("city");
address = bundle.getString("address");
init();
drivingSearch(0);
}
/**
*
*/
private void init() {
mapView = (MapView) findViewById(R.id.mapview);
mapView.showZoomControls(false);
bdMap = mapView.getMap();
checkButton = (Button) findViewById(R.id.check_button);
//确定按钮
checkButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(1);
finish();//结束该activity
}
});
// startEt = (EditText) findViewById(R.id.start_et);
// endEt = (EditText) findViewById(R.id.end_et);
// driveBtn = (Button) findViewById(R.id.drive_btn);
// transitBtn = (Button) findViewById(R.id.transit_btn);
// walkBtn = (Button) findViewById(R.id.walk_btn);
// nextLineBtn = (Button) findViewById(R.id.nextline_btn);
// nextLineBtn.setEnabled(false);
// driveBtn.setOnClickListener(this);
// transitBtn.setOnClickListener(this);
// walkBtn.setOnClickListener(this);
// nextLineBtn.setOnClickListener(this);
//
// drivingSpinner = (Spinner) findViewById(R.id.driving_spinner);
// String[] drivingItems = getResources().getStringArray(
// R.array.driving_spinner);
// ArrayAdapter<String> drivingAdapter = new ArrayAdapter<>(this,
// android.R.layout.simple_spinner_item, drivingItems);
// drivingSpinner.setAdapter(drivingAdapter);
// drivingSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//
// @Override
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// if (index == 0) {
// drivintResultIndex = 0;
// drivingSearch(drivintResultIndex);
// }
// }
//
// @Override
// public void onNothingSelected(AdapterView<?> parent) {
// }
// });
//
// transitSpinner = (Spinner) findViewById(R.id.transit_spinner);
// String[] transitItems = getResources().getStringArray(
// R.array.transit_spinner);
// ArrayAdapter<String> transitAdapter = new ArrayAdapter<>(this,
// android.R.layout.simple_spinner_item, transitItems);
// transitSpinner.setAdapter(transitAdapter);
// transitSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
// @Override
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// if (index == 1) {
// transitResultIndex = 0;
// transitSearch(transitResultIndex);
// }
// }
//
// @Override
// public void onNothingSelected(AdapterView<?> parent) {
//
// }
// });
routePlanSearch = RoutePlanSearch.newInstance();
routePlanSearch
.setOnGetRoutePlanResultListener(routePlanResultListener);
}
/**
* 路线规划结果回调
*/
OnGetRoutePlanResultListener routePlanResultListener = new OnGetRoutePlanResultListener() {
/**
* 步行路线结果回调
*/
@Override
public void onGetWalkingRouteResult(
WalkingRouteResult walkingRouteResult) {
bdMap.clear();
if (walkingRouteResult == null
|| walkingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(RoutePlanActivity.this, "抱歉,未找到结果",
Toast.LENGTH_SHORT).show();
}
if (walkingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
// TODO
return;
}
if (walkingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
WalkingRouteOverlay walkingRouteOverlay = new WalkingRouteOverlay(
bdMap);
walkingRouteOverlay.setData(walkingRouteResult.getRouteLines()
.get(drivintResultIndex));
bdMap.setOnMarkerClickListener(walkingRouteOverlay);
walkingRouteOverlay.addToMap();
walkingRouteOverlay.zoomToSpan();
totalLine = walkingRouteResult.getRouteLines().size();
// Toast.makeText(RoutePlanActivity.this,
// "共查询出" + totalLine + "条符合条件的线路", 1000).show();
if (totalLine > 1) {
// nextLineBtn.setEnabled(true);
}
}
}
/**
* 换成路线结果回调
*/
@Override
public void onGetTransitRouteResult(
TransitRouteResult transitRouteResult) {
bdMap.clear();
if (transitRouteResult == null
|| transitRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(RoutePlanActivity.this, "抱歉,未找到结果",
Toast.LENGTH_SHORT).show();
}
if (transitRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
// 起终点或途经点地址有岐义,通过以下接口获取建议查询信息
// drivingRouteResult.getSuggestAddrInfo()
return;
}
if (transitRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
TransitRouteOverlay transitRouteOverlay = new TransitRouteOverlay(
bdMap);
transitRouteOverlay.setData(transitRouteResult.getRouteLines()
.get(drivintResultIndex));// 设置一条驾车路线方案
bdMap.setOnMarkerClickListener(transitRouteOverlay);
transitRouteOverlay.addToMap();
transitRouteOverlay.zoomToSpan();
totalLine = transitRouteResult.getRouteLines().size();
// Toast.makeText(RoutePlanActivity.this,
// "共查询出" + totalLine + "条符合条件的线路", 1000).show();
if (totalLine > 1) {
// nextLineBtn.setEnabled(true);
}
// 通过getTaxiInfo()可以得到很多关于打车的信息
Toast.makeText(
RoutePlanActivity.this,
"该路线打车总路程"
+ transitRouteResult.getTaxiInfo()
.getDistance(), 1000).show();
}
}
/**
* 驾车路线结果回调 查询的结果可能包括多条驾车路线方案
*/
@Override
public void onGetDrivingRouteResult(
DrivingRouteResult drivingRouteResult) {
bdMap.clear();
if (drivingRouteResult == null
|| drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(RoutePlanActivity.this, "没有查找到该地点!",
Toast.LENGTH_SHORT).show();
// drivingCitySearch();
}
if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
// 起终点或途经点地址有岐义,通过以下接口获取建议查询信息
// drivingRouteResult.getSuggestAddrInfo()
return;
}
if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
bdMap);
drivingRouteOverlay.setData(drivingRouteResult.getRouteLines()
.get(drivintResultIndex));// 设置一条驾车路线方案
bdMap.setOnMarkerClickListener(drivingRouteOverlay);
drivingRouteOverlay.addToMap();
drivingRouteOverlay.zoomToSpan();
totalLine = drivingRouteResult.getRouteLines().size();
// Toast.makeText(RoutePlanActivity.this,
// "共查询出" + totalLine + "条符合条件的线路", 1000).show();
if (totalLine > 1) {
// nextLineBtn.setEnabled(true);
}
// 通过getTaxiInfo()可以得到很多关于打车的信息
// Toast.makeText(
// RoutePlanActivity.this,
// "该路线打车总路程"
// + drivingRouteResult.getTaxiInfo()
// .getDistance(), 1000).show();
}
}
@Override
public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
}
};
/**
* 驾车线路查询
*/
private void drivingSearch(int index) {
DrivingRoutePlanOption drivingOption = new DrivingRoutePlanOption();
// drivingOption.policy(DrivingPolicy.values()[drivingSpinner
// .getSelectedItemPosition()]);// 设置驾车路线策略
drivingOption.policy(DrivingPolicy.values()[1]);// 设置驾车路线策略
drivingOption.from(PlanNode.withCityNameAndPlaceName("杭州", "市政府"));// 设置起点
if(city.equals("南京")){
drivingOption.to(PlanNode.withCityNameAndPlaceName(city, "南京工程学院(江宁校区)-4号门 "));
Toast.makeText(RoutePlanActivity.this,
"南京", 1000).show();
}else{
drivingOption.to(PlanNode.withCityNameAndPlaceName(city, "市政府"));
}
routePlanSearch.drivingSearch(drivingOption);// 发起驾车路线规划
}
private void drivingCitySearch() {
DrivingRoutePlanOption drivingOption = new DrivingRoutePlanOption();
drivingOption.policy(DrivingPolicy.values()[1]);// 设置驾车路线策略
drivingOption.from(PlanNode.withCityNameAndPlaceName("杭州", "杭州市环城东路1号城站广场"));// 设置起点
drivingOption.to(PlanNode.withCityNameAndPlaceName(city, "市政府"));
Log.i("RouteActivity", city);
routePlanSearch.drivingSearch(drivingOption);// 发起驾车路线规划
}
// /**
// * 换乘路线查询
// */
// private void transitSearch(int index) {
// TransitRoutePlanOption transitOption = new TransitRoutePlanOption();
// transitOption.city("北京");// 设置换乘路线规划城市,起终点中的城市将会被忽略
// transitOption.from(PlanNode.withCityNameAndPlaceName("北京", startPlace));
//
//// transitOption.to( PlanNode.withLocation(new LatLng(118.894324, 31.940233)));
// transitOption.to(PlanNode.withCityNameAndPlaceName("南京", "新街口"));
// transitOption.policy(TransitPolicy.values()[transitSpinner
// .getSelectedItemPosition()]);// 设置换乘策略
// routePlanSearch.transitSearch(transitOption);
// }
// /**
// * 步行路线查询
// */
// private void walkSearch() {
// WalkingRoutePlanOption walkOption = new WalkingRoutePlanOption();
// walkOption.from(PlanNode.withCityNameAndPlaceName("北京", startPlace));
// walkOption.to(PlanNode.withCityNameAndPlaceName("北京", endPlace));
// routePlanSearch.walkingSearch(walkOption);
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.drive_btn:// 驾车
// index = 0;
// drivintResultIndex = 0;
// startPlace = startEt.getText().toString();
// endPlace = endEt.getText().toString();
// driveBtn.setEnabled(false);
// transitBtn.setEnabled(true);
// walkBtn.setEnabled(true);
// nextLineBtn.setEnabled(false);
// drivingSearch(drivintResultIndex);
// break;
// case R.id.transit_btn:// 换乘
// index = 1;
// transitResultIndex = 0;
// startPlace = startEt.getText().toString();
// endPlace = endEt.getText().toString();
// transitBtn.setEnabled(false);
// driveBtn.setEnabled(true);
// walkBtn.setEnabled(true);
// nextLineBtn.setEnabled(false);
// transitSearch(transitResultIndex);
// break;
// case R.id.walk_btn:// 步行
// index = 2;
// startPlace = startEt.getText().toString();
// endPlace = endEt.getText().toString();
// walkBtn.setEnabled(false);
// driveBtn.setEnabled(true);
// transitBtn.setEnabled(true);
// nextLineBtn.setEnabled(false);
// walkSearch();
// break;
// case R.id.nextline_btn:// 下一条
// switch (index) {
// case 0:
// drivingSearch(++drivintResultIndex);
// break;
// case 1:
// transitSearch(transitResultIndex);
// break;
// case 2:
//
// break;
// }
// break;
// }
// }
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
routePlanSearch.destroy();// 释放检索实例
mapView.onDestroy();
}
}
<file_sep>/app/src/main/java/com/bwelco/app/MainActivity.java
package com.bwelco.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.transition.Explode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import com.fragments.LoginFragment;
import Utils.ConfigUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
LinearLayout send;
LinearLayout query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Explode explode = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
explode = new Explode();
explode.setDuration(500);
getWindow().setExitTransition(explode);
getWindow().setEnterTransition(explode);
}
getSupportActionBar().setTitle("智能管理系统");
send = (LinearLayout) this.findViewById(R.id.send);
query = (LinearLayout) this.findViewById(R.id.query);
send.setOnClickListener(this);
query.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send: {
if (ConfigUtil.nickName.equals("-1")) {
LoginFragment fragment = new LoginFragment();
fragment.show(getSupportFragmentManager(), null);
} else {
Intent intent = new Intent(MainActivity.this, OrderActivity.class);
startActivity(intent);
}
break;
}
case R.id.query: {
if (ConfigUtil.nickName.equals("-1")) {
LoginFragment fragment = new LoginFragment();
fragment.show(getSupportFragmentManager(), null);
} else {
Intent intent = new Intent(MainActivity.this, OrderListActivity.class);
startActivity(intent);
}
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
startActivity(intent);
break;
case R.id.login:
LoginFragment fragment = new LoginFragment();
fragment.show(getSupportFragmentManager(), null);
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/app/src/main/java/comity/bawujw/citytest/WheelView/utils/CancelableTask.java
package comity.bawujw.citytest.WheelView.utils;
/**
* @author <NAME>
* @version V1.0
* @Description �ɳ�������ӿ�
* @Createdate 14-9-3 15:53
*/
public interface CancelableTask {
public boolean cancel(boolean mayInterruptIfRunning);
}<file_sep>/app/src/main/java/com/bwelco/app/MyApp.java
package com.bwelco.app;
import android.app.Application;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.mapapi.SDKInitializer;
import Utils.ConfigUtil;
import Utils.CrashHandler;
/**
* Created by bwelco on 2016/7/1.
*/
public class MyApp extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
ToastMgr.builder.init(getApplicationContext());
context = getApplicationContext();
CrashHandler.getInstance().init(this);
ConfigUtil.URL = ConfigUtil.getURL();
// 在使用 SDK 各组间之前初始化 context 信息,传入 ApplicationContext
SDKInitializer.initialize(this);
}
public enum ToastMgr {
builder;
private View view;
private TextView tv;
private Toast toast;
/**
* 初始化Toast
*
* @param context
*/
public void init(Context context) {
view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
tv = (TextView) view.findViewById(R.id.toast_textview);
toast = new Toast(context);
toast.setView(view);
}
/**
* 显示Toast
* @param content
* @param duration Toast持续时间
*/
public void display(CharSequence content, int duration) {
if (content.length() != 0) {
tv.setText(content);
toast.setDuration(duration);
toast.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL, 0, 0);
toast.show();
}
}
}
}
<file_sep>/app/src/main/java/com/Bean/WuLiuBean.java
package com.Bean;
import java.util.List;
/**
* Created by bwelco on 2016/8/15.
*/
public class WuLiuBean {
/**
* Time : 2016-08-14 10:37:54
* Location : 深圳
*/
private List<LogisticsBean> Logistics;
public List<LogisticsBean> getLogistics() {
return Logistics;
}
public void setLogistics(List<LogisticsBean> Logistics) {
this.Logistics = Logistics;
}
public static class LogisticsBean {
private String Time;
private String Location;
public String getTime() {
return Time;
}
public void setTime(String Time) {
this.Time = Time;
}
public String getLocation() {
return Location;
}
public void setLocation(String Location) {
this.Location = Location;
}
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.bwelco.app"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.github.john990:WaveView:v0.9'
compile 'com.google.code.gson:gson:2.7'
compile 'com.jakewharton:butterknife:5.1.1'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:cardview-v7:23.0.0'
/* xutils2 aar库 */
compile(name: 'library-release', ext: 'aar')
}
<file_sep>/app/src/main/java/com/fragments/LoginFragment.java
package com.fragments;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.transition.Explode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.bwelco.app.R;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import Utils.ConfigUtil;
import Utils.MyHttpUtil;
import Utils.ToastUtil;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
/**
* Created by bwelco on 2016/8/16.
*/
public class LoginFragment extends DialogFragment {
@InjectView(R.id.et_username)
EditText etUsername;
@InjectView(R.id.et_password)
EditText etPassword;
@InjectView(R.id.bt_go)
Button btGo;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_login, null);
ButterKnife.inject(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@OnClick(R.id.bt_go)
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_go:
final Explode[] explode = {null};
RequestParams params = new RequestParams();
//params.setBodyEntity(b);
JSONObject object = new JSONObject();
try {
object.put("UserName", etUsername.getText().toString());
object.put("Password", etPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
params.addBodyParameter("request", object.toString());
Log.i("admin", ConfigUtil.getURL());
MyHttpUtil.getInstance().send(HttpRequest.HttpMethod.GET,
ConfigUtil.URL + "gy4/AppCheckUser.jsp", params,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Log.i("admin", responseInfo.result);
try {
JSONObject object = new JSONObject(responseInfo.result);
String userID = object.getString("UserID");
String nickName = object.getString("Nickname");
Log.i("admin", "userid = " + userID + " nickname = " + nickName);
if (userID.equals("-1") && nickName.equals("-1")) {
ToastUtil.toast("登录失败!请检查用户名密码");
} else {
ToastUtil.toast("登录成功!");
saveUserInfo();
ConfigUtil.userID = userID;
ConfigUtil.nickName = nickName;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
// explode[0] = new Explode();
// explode[0].setDuration(500);
//
// getActivity().getWindow().setExitTransition(explode[0]);
// getActivity().getWindow().setEnterTransition(explode[0]);
// }
//
// ActivityOptionsCompat oc2 =
// ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity());
// Intent i2 = new Intent(getActivity(), MainActivity.class);
// startActivity(i2, oc2.toBundle());
LoginFragment.this.dismiss();
// LoginActivity.this.finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(HttpException e, String s) {
ToastUtil.toast("登录失败!请检查网络连接。\n" + "请检查网络设置或者重新设置IP。");
}
});
break;
}
}
public void saveUserInfo(){
SharedPreferences sp = getActivity().getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("username", etUsername.getText().toString());
editor.putString("password", etPassword.getText().toString());
editor.commit();
}
public void setInfo(){
SharedPreferences sp = getActivity().getSharedPreferences("userinfo",Activity.MODE_PRIVATE);
etUsername.setText(sp.getString("username", null));
etPassword.setText(sp.getString("password", null));
}
}
<file_sep>/app/src/main/java/com/Bean/DealingFormBean.java
package com.Bean;
/**
* Created by bwelco on 2016/8/15.
*/
public class DealingFormBean {
/**
* OrderState : 订单已提交
* OrderProgress : 0%
* ProductNumber : 10
* SuccessNumber : 0
* StartTime : null
*/
private String OrderState;
private String OrderProgress;
private String ProductNumber;
private String SuccessNumber;
private Object StartTime;
public String getOrderState() {
return OrderState;
}
public void setOrderState(String OrderState) {
this.OrderState = OrderState;
}
public String getOrderProgress() {
return OrderProgress;
}
public void setOrderProgress(String OrderProgress) {
this.OrderProgress = OrderProgress;
}
public String getProductNumber() {
return ProductNumber;
}
public void setProductNumber(String ProductNumber) {
this.ProductNumber = ProductNumber;
}
public String getSuccessNumber() {
return SuccessNumber;
}
public void setSuccessNumber(String SuccessNumber) {
this.SuccessNumber = SuccessNumber;
}
public Object getStartTime() {
return StartTime;
}
public void setStartTime(Object StartTime) {
this.StartTime = StartTime;
}
}
<file_sep>/app/src/main/java/model/OrderModel.java
package model;
/**
* Created by bwelco on 2016/7/10.
*/
public class OrderModel {
String name; //收货人姓名
String phone; //收货人手机号
String address; //地址
String goods_type;//货物的类型
String goods_num; //货物的量
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGoods_type() {
return goods_type;
}
public void setGoods_type(String goods_type) {
this.goods_type = goods_type;
}
public String getGoods_num() {
return goods_num;
}
public void setGoods_num(String goods_num) {
this.goods_num = goods_num;
}
}
<file_sep>/app/src/main/java/com/entity/LogisticsInfo.java
package com.entity;
/**
* 物流
* @author zad
*
*/
public class LogisticsInfo {
private String info;
private String dateTime;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
}
<file_sep>/app/src/main/java/com/adapter/LogisticsAdapter.java
package com.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import com.bwelco.app.R;
import com.entity.LogisticsInfo;
import com.logisticsView.CustomTextView;
import java.util.ArrayList;
import java.util.List;
public class LogisticsAdapter extends BaseAdapter {
private List<LogisticsInfo> list;
private Context context;
private List<Float> nodeRadiusDistances;
public LogisticsAdapter(List<LogisticsInfo> list, Context context) {
this.list = list;
this.context = context;
this.nodeRadiusDistances = new ArrayList<Float>();
for (int i = 0; i < list.size() + 2; i++) {
// 倒数第二个用于装载item顶部内边距,倒数第一个用于装载listview分割线高度
this.nodeRadiusDistances.add(0.0f);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//这里只所以不用复用,是因为使用了复用之后测量出item的高度就不准确了
convertView = LayoutInflater.from(context).inflate(
R.layout.person_logistics_info_item_line, null);
CustomTextView info_txt = (CustomTextView) convertView
.findViewById(R.id.info_txt);
CustomTextView dateTime_txt = (CustomTextView) convertView
.findViewById(R.id.dateTime_txt);
info_txt.setText(list.get(position).getInfo());
dateTime_txt.setText(list.get(position).getDateTime());
//监听View的伸展,以便测量高度
ViewTreeObserver vto = info_txt.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new MyGlobalLayoutListener(info_txt,
dateTime_txt, position));
return convertView;
}
class ViewHolder{
CustomTextView info_txt;
CustomTextView dateTime_txt;
}
public List<Float> getNodeRadiusDistances() {
return nodeRadiusDistances;
}
/**
* 监听TextView高度的改变
*
* @author zad
*
*/
private class MyGlobalLayoutListener implements OnGlobalLayoutListener {
// private ViewHolder holder;
private int position;
private CustomTextView info_txt;
private CustomTextView dateTime_txt;
public MyGlobalLayoutListener(CustomTextView info_txt,
CustomTextView dateTime_txt, int position) {
// this.holder = holder;
this.position = position;
this.info_txt = info_txt;
this.dateTime_txt = dateTime_txt;
// 倒数第二个位置装载顶部内边距
nodeRadiusDistances.set(nodeRadiusDistances.size() - 2,
(float) info_txt.getParentPaddingTop());
}
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
/**
* 获取子项的真实高度
*/
float realHeight = info_txt.getTxtHeight()
+ info_txt.getParentPaddingTop()
+ info_txt.getParentPaddingBotton()
+ dateTime_txt.getTxtHeight();
LayoutParams childparams = (LayoutParams) info_txt
.getLayoutParams();
realHeight += childparams.bottomMargin;
if (realHeight > nodeRadiusDistances.get(position)) {
nodeRadiusDistances.set(position, realHeight);
}
}
}
}
<file_sep>/app/src/main/java/comity/bawujw/citytest/View/CityPop.java
package comity.bawujw.citytest.View;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import com.bwelco.app.R;
import com.interfaces.OnPopSelectListener;
import java.util.ArrayList;
import java.util.List;
import comity.bawujw.citytest.WheelView.WheelView;
import comity.bawujw.citytest.manage.CityManage;
/**
* Created by Sunday on 15/8/7.
*/
public class CityPop {
private Context context;
private Display display;
private OnPopSelectListener mListener;
/**
* 取消按钮
*/
private Button btnCancel;
/**
* 确定按钮
*/
private Button btnConfirm;
/**
* 屏幕的宽度,用于动态设定滑动块的宽度
* */
private int screenWidth;
//省
private WheelView wvProvince;
//市
private WheelView wvCity;
//关闭按钮
private ImageView ivDismiss;
/**
* 省数据列表
*/
private List<String> provinceList;
/**
* 省对应的市的数据列表
*/
private List<String> cityList;
/**
* 管理器
*/
private CityManage cityManage;
private PopupWindow popupWindow;
public CityPop(Context context, OnPopSelectListener listener){
this.context = context;
this.mListener = listener;
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
display = windowManager.getDefaultDisplay();
screenWidth = display.getWidth();
cityManage = new CityManage(context);
}
/**
* 创建PHRightShareAndSaveView对象
* @return PHRightShareAndSaveView实体
*/
public CityPop builder(){
// PopView
View view = LayoutInflater.from(context).inflate(
R.layout.pop_city, null);
loadCity(view);
// android.view.View#getWindowToken()
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,false);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOnDismissListener(new PopDismissListener());
popupWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
popupWindow.setAnimationStyle(R.style.PopAnimationDownUp);
return this;
}
public void loadCity(View view){
btnCancel = (Button) view.findViewById(R.id.btn_cancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
btnConfirm = (Button) view.findViewById(R.id.btn_confirm);
btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CityPop.this.mListener.OnSelectDown(wvProvince.getSeletedItem(), wvCity.getSeletedItem());
}
});
wvProvince = (WheelView) view.findViewById(R.id.wheel_view1);
wvProvince.getLayoutParams().width = screenWidth / 2;
wvCity = (WheelView) view.findViewById(R.id.wheel_view2);
wvCity.getLayoutParams().width = screenWidth / 2;
provinceList = new ArrayList<>();
cityList = new ArrayList<>();
//获取 北京 作为默认
provinceList = cityManage.getCityNameFromProvinceId("1");
cityList = cityManage.getCityNameFromProvinceId("2");
wvProvince.setOffset(2);
wvProvince.setItems(provinceList);
wvCity.setOffset(2);
wvCity.setItems(cityList);
wvProvince.setOnWheelViewListener(new WheelView.OnWheelViewListener(){
@Override
public void onSelected(int selectedIndex, String item) {
super.onSelected(selectedIndex, item);
//重新初始化城市数据
cityList = cityManage.getCityNameFromProvinceId(cityManage.getProvinceIdFromProvinceName(item));
//替换显示数据
wvCity.replace(cityList);
wvCity.setSeletion(0);
}
});
wvCity.setOnWheelViewListener(new WheelView.OnWheelViewListener(){
@Override
public void onSelected(int selectedIndex, String item) {
super.onSelected(selectedIndex, item);
}
});
}
/**
* 显示
*/
public void show(){
if (null != popupWindow){
setBackgroundAlpha(0.5f);
popupWindow.update();
}
}
/**
* 撤销
*/
public void dismiss(){
if (null != popupWindow){
popupWindow.dismiss();
}
}
/**
* 设置背景透明度
* @param alpha 背景的Alpha
*/
private void setBackgroundAlpha(float alpha){
WindowManager.LayoutParams lp = ((Activity)context).getWindow().getAttributes();
lp.alpha = alpha;
((Activity)context).getWindow().setAttributes(lp);
}
private class PopDismissListener implements PopupWindow.OnDismissListener{
@Override
public void onDismiss() {
//更改背景透明度
setBackgroundAlpha(1.0f);
}
}
}
<file_sep>/app/src/main/java/com/fragments/DealingListFragment.java
package com.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.Bean.OrderListBean;
import com.adapter.OrderListAdapter;
import com.bwelco.app.OrderListActivity;
import com.bwelco.app.QueryActivity;
import com.bwelco.app.R;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import Utils.ConfigUtil;
import Utils.GsonUtil;
import Utils.MyHttpUtil;
import Utils.ToastUtil;
/**
* Created by bwelco on 2016/8/15.
*/
public class DealingListFragment extends Fragment implements AdapterView.OnItemClickListener {
private static SwipeRefreshLayout refresh;
private static OrderListAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_order_list, null);
ListView listView = (ListView) view.findViewById(R.id.orderListView);
TextView textView = (TextView) view.findViewById(R.id.noItem);
refresh = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
refresh.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
android.R.color.holo_orange_light, android.R.color.holo_green_light);
/* 取消右侧滑动条 */
listView.setVerticalScrollBarEnabled(false);
listView.setEmptyView(textView);
listView.setOnItemClickListener(this);
adapter = new OrderListAdapter(getContext(),
R.layout.item_order_list, OrderListActivity.dealingList);
listView.setAdapter(adapter);
textView.setText("无生产中订单");
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshList();
}
});
return view;
}
public void refreshList() {
RequestParams params = new RequestParams();
JSONObject object = new JSONObject();
try {
object.put("UserID", ConfigUtil.userID);
} catch (JSONException e) {
e.printStackTrace();
}
params.addBodyParameter("userid", object.toString());
MyHttpUtil.getInstance().send(HttpRequest.HttpMethod.GET,
ConfigUtil.URL + "gy4/AppGetAllOrderInfo.jsp", params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
if (refresh.isRefreshing()) {
refresh.setRefreshing(false);
}
Log.i("admin", responseInfo.result);
Type type = new TypeToken<OrderListBean>() {
}.getType();
OrderListActivity.orderList = (OrderListBean) GsonUtil.getInstance().fromJson(responseInfo.result, type);
OrderListActivity.dealingList.clear();
OrderListActivity.overList.clear();
for (OrderListBean.OrderInfoBean bean : OrderListActivity.orderList.getOrderInfo()) {
if (bean.getOrderStateCode().equals("-1") || bean.getOrderStateCode().equals("0")) {
/* 还没开始生产 */
OrderListActivity.dealingList.add(bean);
} else if (bean.getOrderStateCode().equals("1")) {
/* 生产结束 */
OrderListActivity.overList.add(bean);
}
}
adapter.notifyDataSetChanged();
}
@Override
public void onFailure(HttpException e, String s) {
Log.i("admin", "failcode = " + s);
if (refresh.isRefreshing()) {
refresh.setRefreshing(false);
}
ToastUtil.toast("请求失败。请检查网络设置或者重新设置IP。");
adapter.notifyDataSetChanged();
}
});
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String orderID = OrderListActivity.dealingList.get(position).getOrderID();
Intent intent = new Intent(getActivity(), QueryActivity.class);
intent.putExtra("order", OrderListActivity.orderList);
intent.putExtra("id", OrderListActivity.dealingList.get(position).getOrderID());
startActivity(intent);
}
}
<file_sep>/app/src/main/java/com/logisticsView/CustomTextView.java
package com.logisticsView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class CustomTextView extends TextView {
/**
* TextView的文本高度
*/
private float txtHeight;
public CustomTextView(Context context) {
this(context, null);
// TODO Auto-generated constructor stub
}
public CustomTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// TODO Auto-generated constructor stub
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@SuppressLint("FloatMath")
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
txtHeight = getMeasuredHeight();
}
/**
* 获取TextView的文本高度
* @return
*/
public float getTxtHeight() {
return txtHeight;
}
/**
* 获取父控件的顶部内边距
* @return
*/
public int getParentPaddingTop(){
return ((View)this.getParent()).getPaddingTop();
}
/**
* 获取父控件的底部内边距
* @return
*/
public int getParentPaddingBotton(){
return ((View)this.getParent()).getPaddingBottom();
}
}
| 3d9b03c8d4c331a33661ee255b7ed0bd622904fa | [
"Java",
"Gradle"
] | 14 | Java | bwelco/Industry4.0APP | 47095f755b6ad2da77e58a0faf5e4866cfad47f5 | 8424b465bf3562c40628f7348c67bdf3c744271c |
refs/heads/master | <file_sep>package main
import (
"example.com/m/v2/reexec"
)
func main() {
// Running in init mode
reexec.Init()
}
<file_sep>module example.com/m/v2
go 1.13
require (
github.com/docker/docker v1.13.1 // indirect
github.com/docker/libcontainer v2.2.1+incompatible
github.com/gorilla/mux v1.7.3
github.com/tchap/go-patricia v2.3.0+incompatible
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e // indirect
)
| d0e59601e59428e7615f6ec52fc8d51ff1f33225 | [
"Go Module",
"Go"
] | 2 | Go | jindp1/docker-an | 814dddeb36ac4084913b620e7ad72c737d3b7280 | d4808f24dafe8a75dc9119b3881192a4c693bee9 |
refs/heads/main | <file_sep>import React from "react";
const Year = ({ year, currentDate, onYearChangeHandler }) => {
const tempCurrentYear = new Date(currentDate).getFullYear();
let className = "year-picker-month-cell";
if (year === tempCurrentYear) {
className += " selectedMonth";
}
const handleOnClickOverYear = () => {
onYearChangeHandler(year);
};
return (
<td className={className} onClick={handleOnClickOverYear}>
{year}
</td>
);
};
export default Year;
<file_sep>import React, { useEffect, useRef, useState } from "react";
import moment from "moment";
import DatePicker from "./DatePicker";
import "./datepicker_input.scss";
const DatePickerInput = ({
format, minDate, maxDate, onChange, placeholder, defaultValue
}) => {
const [showDatePicker, setShowDatePicker] = useState(false)
const [date, setDate] = useState(defaultValue || '')
const datePickerRef = useRef(null)
const openDatePicker = () => {
setShowDatePicker(prevState => !prevState)
}
useEffect(() => {
document.addEventListener("mousedown", closeDatePickerOnOutsideClick);
// return function to be called when unmounted
return () => {
document.removeEventListener("mousedown", closeDatePickerOnOutsideClick);
};
}, [])
const closeDatePickerOnOutsideClick = (e) => {
if (!datePickerRef.current.contains(e.target)) {
setShowDatePicker(false)
}
}
const dateChangeHandler = (date) => {
setDate(moment(date).format(format))
setShowDatePicker(false)
}
const clearDateInput = () => {
setDate('')
}
useEffect(() => {
if (onChange instanceof Function) {
onChange({
dateString: date,
dateObject: moment(date).toDate()
})
}
}, [date])
return (
<div
ref={datePickerRef}
className="react-datepicker-input-conatiner">
<input
className="datepicker-input"
onClick={openDatePicker}
value={date}
placeholder={placeholder}
readOnly
/>
{date && (
<i
className="fa fa-times clear-calendar-icon"
onClick={clearDateInput}
/>
)}
<i
className="fa fa-calendar datepicker-calendar-icon"
onClick={openDatePicker}
/>
{showDatePicker && (
<DatePicker
dateChangeHandler={dateChangeHandler}
className="floating-datepicker"
date={date}
minDate={minDate}
maxDate={maxDate}
format={format}
/>
)}
</div>
);
};
DatePickerInput.defaultProps = {
format: "MM/DD/YYYY",
minDate: null,
maxDate: null,
placeholder: 'MM/DD/YYYY'
}
export default DatePickerInput
<file_sep># react-datepicker-ui
Date picker component for React
## How to Install
Make sure you have [Node.js](http://nodejs.org/) and NPM installed.
Dependencies for the packge is [moment]
```sh
npm install react-datepicker-ui moment
```
Or
```sh
yarn add react-datepicker-ui moment
```
## How to Use
```sh
import React from 'react'
import DatePickerInput from 'react-datepicker-ui'
const DatePicker = () => {
const handleOnChange = (date) => {
console.log('date', date)
}
return (
<DatePickerInput
onChange={handleOnChange}
/>
)
}
```
## Demo

Check out [Online Demo](https://korimi.in/projects) here.
```sh
import React from 'react'
import moment from 'moment'
import DatePickerInput from 'react-datepicker-ui'
const DatePickerDemo = () => {
const handleOnChange = (date) => {
console.log('date', date)
}
const minDate = moment()
const maxDate = moment().add(1, 'M')
return (
<DatePickerInput
onChange={handleOnChange}
minDate={minDate}
maxDate={maxDate}
placeholder="DD/MM/YYYY"
format="DD/MM/YYYY"
/>
)
}
```
## Available PropTypes
| Prop Name | Type | Default Value | Description |
| ------------ | -------- | ------------- | ------------------------------------------------------- |
| defaultValue | String | '' | Initial Value for datepicker |
| format | String | 'MM/DD/YYYY' | Format of the date to be returned |
| minDate | Date | null | Disable dates before mentioned dates to select |
| maxDate | Date | null | Disable dates after mentioned dates to select |
| onChange | Function | null | Callback function to get the selected date |
| placeholder | String | 'MM/DD/YYYY' | Placeholder to display on input |
<file_sep>import React from "react";
const Month = ({
month,
monthIndex,
rowIndex,
currentYear,
currentDate,
onMonthChangeHandler,
}) => {
const selectedMonth = rowIndex * 3 + monthIndex;
const tempSelectedDate = new Date(currentDate);
let className = "month-picker-month-cell";
if (
selectedMonth === tempSelectedDate.getMonth() &&
currentYear === tempSelectedDate.getFullYear()
) {
className += " selectedMonth";
}
const handleOnClickOverMonth = () => {
const selectedMonth = rowIndex * 3 + monthIndex;
onMonthChangeHandler(selectedMonth);
};
return (
<td className={className} onClick={handleOnClickOverMonth}>
{month}
</td>
);
};
export default Month;
<file_sep>import React from "react";
import Day from "./Day";
const Week = ({
week,
dateChangeHandler,
month,
year,
minDate,
maxDate,
selected,
}) => {
return (
<tr>
{week.map((day, index) => {
return (
<Day
dateChangeHandler={dateChangeHandler}
day={day}
key={`day-${month}-${index}`}
month={month}
year={year}
minDate={minDate}
maxDate={maxDate}
selected={selected}
/>
);
})}
</tr>
);
};
export default Week;
<file_sep>export const MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
export const HEADER_DAY_NAMES = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
export const FINAL_MONTH_INDEX = 11;
export const INITIAL_MONTH_INDEX = 0;
export const YEAR_PERIOD = 12;
export const DAY_VIEW = "Day";
export const MONTH_VIEW = "Month";
export const YEAR_VIEW = "Year";
export const getNumberOfDaysInMonth = (year, month) => {
return new Date(year, month + 1, 0).getDate();
};
export const getDaysOfMonth = (month, year) => {
let monthDays = [];
const numberOfDays = getNumberOfDaysInMonth(year, month);
let week = ['', '', '', '', '', '', ''];
for (let j = 1; j <= numberOfDays; j++) {
let tempDate = new Date();
tempDate.setFullYear(year);
tempDate.setDate(j);
tempDate.setMonth(month);
let dayIndex = tempDate.getDay();
if (dayIndex === 0 && j !== 1 && j !== numberOfDays) {
monthDays.push(week);
week = ['', '', '', '', '', '', ''];
week[dayIndex] = j;
} else if (dayIndex === 0 && j === 1) {
week[dayIndex] = j;
} else if (dayIndex !== 0 && j !== numberOfDays) {
week[dayIndex] = j;
} else if (j === numberOfDays) {
if (dayIndex !== 0) {
week[dayIndex] = j;
monthDays.push(week);
} else if (dayIndex === 0) {
monthDays.push(week);
week = ['', '', '', '', '', '', ''];
week[dayIndex] = j;
monthDays.push(week);
}
}
}
return monthDays;
};
export const getYears = (startYear, endYear) => {
const YEARS = [];
let count = 0;
let yearRow = [];
for (let i = startYear; i <= endYear; i++) {
yearRow.push(i);
count++;
if (count % 3 === 0) {
count = 0;
YEARS.push(yearRow);
yearRow = [];
}
}
return YEARS;
}
<file_sep>import moment from "moment";
import React from "react";
const Day = ({
day, dateChangeHandler, month, year,
minDate, maxDate, selected
}) => {
const onDateClickHandler = () => {
const isDisabledDate = getDateDisabledStatus();
if (day && !isDisabledDate) {
const selectedDate = new Date();
selectedDate.setDate(day);
selectedDate.setMonth(month);
selectedDate.setFullYear(year);
dateChangeHandler(selectedDate);
}
}
const getDateDisabledStatus = () => {
const currentDate = new Date();
currentDate.setDate(day);
currentDate.setMonth(month);
currentDate.setFullYear(year);
let flag = false
if (minDate && minDate instanceof Date && moment(currentDate).isBefore(moment(minDate))) {
return true;
}
if (maxDate && maxDate instanceof Date && moment(currentDate).isSameOrAfter(moment(maxDate))) {
return true;
}
return flag
}
let className;
const tempSelectedDate = new Date(selected);
const isDisabledDate = getDateDisabledStatus();
if (day && isDisabledDate) {
className = "date-picker-monthday disabledDate";
} else if (day) {
className = "date-picker-monthday";
} else {
className = "date-picker-non-month-day";
}
if (
day === tempSelectedDate.getDate() &&
month === tempSelectedDate.getMonth() &&
year === tempSelectedDate.getFullYear()
) {
className += " selectedDate";
}
return (
<td className={className} onClick={onDateClickHandler}>
{day}
</td>
);
}
export default Day
<file_sep>import React from "react";
import Month from "./Month";
const MonthRow = ({
months,
rowIndex,
onMonthChangeHandler,
currentYear,
currentDate,
}) => {
return (
<tr className="month-picker-row">
{months.map((month, index) =>{
return (
<Month
month={month}
rowIndex={rowIndex}
monthIndex={index}
currentYear={currentYear}
currentDate={currentDate}
key={`MonthPickerMonth-${index}`}
onMonthChangeHandler={onMonthChangeHandler}
/>
);
})}
</tr>
);
};
export default MonthRow
<file_sep>import React from "react";
import Year from "./Year";
const YearRow = ({
years,
rowIndex,
currentYear,
currentDate,
onYearChangeHandler,
}) => {
return (
<tr className="year-picker-row">
{years.map((year, index) => {
return (
<Year
year={year}
rowIndex={rowIndex}
monthIndex={index}
currentYear={currentYear}
currentDate={currentDate}
key={`YearRow-${index}`}
onYearChangeHandler={onYearChangeHandler}
/>
);
})}
</tr>
);
};
export default YearRow;
<file_sep>import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import postcss from 'rollup-plugin-postcss';
import sass from 'rollup-plugin-sass'
import pkg from './package.json';
const INPUT_FILE_PATH = 'src/index.js';
const OUTPUT_NAME = 'datepicker';
const GLOBALS = {
react: 'React',
'react-dom': 'ReactDOM',
'moment': 'moment',
};
const PLUGINS = [
postcss({
extract: true,
}),
babel({
exclude: 'node_modules/**',
}),
resolve({
browser: true,
resolveOnly: [
/^(?!react$)/,
/^(?!react-dom$)/,
/^(?!moment)/,
],
}),
commonjs(),
sass({ insert: true }),
];
const EXTERNAL = [
'react',
'react-dom',
'moment',
];
// https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
const CJS_AND_ES_EXTERNALS = EXTERNAL.concat(/@babel\/runtime/);
const OUTPUT_DATA = [
{
file: pkg.main,
format: 'cjs',
}
];
const config = OUTPUT_DATA.map(({ file, format }) => ({
input: INPUT_FILE_PATH,
output: {
file,
format,
name: OUTPUT_NAME,
globals: GLOBALS,
exports: 'auto'
},
external: ['cjs', 'es'].includes(format) ? CJS_AND_ES_EXTERNALS : EXTERNAL,
plugins: PLUGINS,
}));
export default config;<file_sep>import React, { useEffect, useState } from "react";
import moment from "moment";
import DatePickerWeek from "./Week";
import MonthPicker from "./MonthPicker";
import YearPicker from "./YearPicker";
import DatePickerNavigation from "./PickerNavigation";
import {
DAY_VIEW, FINAL_MONTH_INDEX, getDaysOfMonth,
HEADER_DAY_NAMES,
INITIAL_MONTH_INDEX, MONTH_VIEW, YEAR_PERIOD, YEAR_VIEW
} from "./date_utils";
import "./datepicker.scss";
import "./monthpicker.scss";
import "./yearpicker.scss";
const DayPickerHeader = () => {
return (
<thead className="datepicker-table-header">
<tr>
{HEADER_DAY_NAMES && HEADER_DAY_NAMES.map((hd, index) => (
<th key={`${hd}-${index}`}>{hd}</th>
))}
</tr>
</thead>
)
}
const DatePicker = ({
date, dateChangeHandler, minDate, maxDate, format
}) => {
const [curDate, setCurDate] = useState(null);
const [curMonth, setCurMonth] = useState(null);
const [curYear, setCurYear] = useState(null);
const [curView, setCurView] = useState(DAY_VIEW);
const setInitialState = () => {
const dateObj = date ? new Date(date) : new Date();
setCurDate(dateObj);
setCurMonth(dateObj.getMonth());
setCurYear(dateObj.getFullYear());
};
const navigateMonthLeft = () => {
if (curMonth > INITIAL_MONTH_INDEX) {
setCurMonth(curMonth - 1);
} else if (curMonth === INITIAL_MONTH_INDEX) {
setCurMonth(FINAL_MONTH_INDEX);
setCurYear(curYear - 1);
}
};
const navigateMonthRight = () => {
if (curMonth < FINAL_MONTH_INDEX) {
setCurMonth(curMonth + 1);
} else if (curMonth === FINAL_MONTH_INDEX) {
setCurMonth(INITIAL_MONTH_INDEX);
setCurYear(curYear + 1);
}
};
const navigateYearLeft = () => {
setCurYear(curYear - 1);
};
const navigateYearRight = () => {
setCurYear(curYear + 1);
};
const navigateYearPeriodLeft = () => {
setCurYear(curYear - YEAR_PERIOD);
};
const navigateYearPeriodRight = () => {
setCurYear(curYear + YEAR_PERIOD);
};
const showMonthPickerView = () => {
setCurView(MONTH_VIEW);
};
const onMonthChangeHandler = (month) => {
setCurMonth(month);
setCurView(DAY_VIEW);
};
const handleOnDateChange = (date) => {
setCurDate(moment(date).format(format));
};
const onYearChangeHandler = (year) => {
setCurYear(year);
setCurView(MONTH_VIEW);
};
const changeModeToYear = () => {
setCurView(YEAR_VIEW);
};
useEffect(() => {
setInitialState();
}, []);
const getCurrentView = () => {
switch(curView) {
case DAY_VIEW: {
const monthDays = getDaysOfMonth(curMonth, curYear);
const dateChangeHandlerFunc = dateChangeHandler
? dateChangeHandler
: handleOnDateChange;
return (
<div className='floating-datepicker'>
<DatePickerNavigation
currentMonth={curMonth}
currentYear={curYear}
navigateOnLeft={navigateMonthLeft}
navigateOnRight={navigateMonthRight}
navigateOnCenter={showMonthPickerView}
currentView={curView}
/>
<table className="datepicker-table">
<DayPickerHeader />
<tbody>
{monthDays.map(function (week, index) {
return (
<DatePickerWeek
dateChangeHandler={dateChangeHandlerFunc}
week={week}
key={"week" + index}
month={curMonth}
year={curYear}
minDate={minDate}
maxDate={maxDate}
selected={curDate}
/>
);
})}
</tbody>
</table>
</div>
)
}
case MONTH_VIEW: return (
<div className='floating-datepicker'>
<MonthPicker
currentYear={curYear}
currentMonth={curMonth}
currentDate={curDate}
navigateYearLeft={navigateYearLeft}
navigateYearRight={navigateYearRight}
onMonthChangeHandler={onMonthChangeHandler}
changeModeToYear={changeModeToYear}
/>
</div>
)
case YEAR_VIEW: return (
<div className='floating-datepicker'>
<YearPicker
currentYear={curYear}
currentMonth={curMonth}
currentDate={curDate}
startYear={curYear - 6}
endYear={curYear + 5}
navigateYearPeriodLeft={navigateYearPeriodLeft}
navigateYearPeriodRight={navigateYearPeriodRight}
onYearChangeHandler={onYearChangeHandler}
/>
</div>
)
default: return ''
}
}
return (
<div className='date-picker-container'>
{getCurrentView()}
</div>
);
};
export default DatePicker | d7d606ee654d9d8c58d9b96d7a5334c1f782cfa2 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | Santhosh1392/react-datepicker-ui | 496ed3ab78ef2b88c8cedf6b3c89204f3fffa8a0 | 2c9989e01699ee6c724d9c55c5536f20b6e10970 |
refs/heads/master | <repo_name>cran/FisherEM<file_sep>/R/fem.loglik.R
fem.loglik <-
function(prms,K,Y,U){
# Initialization
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
prop = c(prms[1:(K-1)],1-sum(prms[1:(K-1)]))
alpha = prms[K:(2*K-1)]
beta = prms[(2*K):(3*K-1)]
my = matrix(prms[(3*K):length(prms)],ncol=p,byrow=T)
d = min(p-1,(K-1))
QQ = matrix(NA,n,K)
QQ2 = matrix(NA,n,K)
T = matrix(NA,n,K)
D = array(0,c(K,p,p))
# Compute posterior probabilities
for (k in 1:K){
D[k,,] = diag(c(rep(alpha[k],d),rep(beta[k],(p-d))))
bk = D[k,p,p]
YY = Y-t(matrix(rep(my,n),p,n))
projYY = YY %*% U %*% t(U) # proj dans l'espace latent
if (d==1){
for (i in 1:n){QQ[i,k] = 1/D[k,1,1] * sum(projYY[i,]^2) + 1/D[k,p,p]*sum((YY[i,] - projYY[i,])^2) + (p-d)*log(bk) + log(D[k,1,1]) - 2*log(prop[k]) + p*log(2*pi)}
}
else{
sY = U %*% ginv(D[k,(1:d),(1:d)]) %*% t(U)
for (i in 1:n){QQ[i,k] = projYY[i,] %*% sY %*% as.matrix(projYY[i, ],p,1) + 1/bk*sum((YY[i,] - projYY[i,])^2) + (p-d)*log(bk) + log(det(D[k,(1:d),(1:d)])) - 2*log(prop[k]) + p*log(2*pi)}
}
}
A = -1/2 * QQ
loglik = sum(log(rowSums(exp(A-apply(A,1,max))))+apply(A,1,max))
}
<file_sep>/R/simu_bfem.R
#' Experimental setting of the chapter BFEM
#'
#' @param n Number of observations
#' @param which Type of simulation, either:
#' \itemize{
#' \item "Chang1983" - Simulate the dataset of Chang's (1983) paper : a mixture of 2 Gaussian with in dimension p=15.
#' \item "section4.2" - Experimental setting of Section 4.2: DLM model in dimension p with d=2 and K=3, with noisy dimensions.
#' \item "section4.3" - Experimental setting of Section 4.3: Same as `"section4.2"` except the noise is expressed in term of signal-to-noise ration (decibels).
#' }
#' @param ... Additional param controlling the simulation
#' \itemize{
#' \item p - The desired observed space dimension, the latent dimension is kept fixed to d=2 and noisy Gaussian dimensions are added (useless for `"Chang1983"`)
#' \item noise (for `"section4.2"` only) - Variance of the noise
#' \item snr (for `"section4.3"` only) - Signal-to-noise ratio (in decibels) representing the ratio of signal and noise variances in logarithmic scale. The greater snr, the smaller noise variance.
#' }
#'
#' @return A list with slots
#' \itemize{
#' \item Y - The simulated data.
#' \item cls - The true clustering.
#' }
#'
#' @export
#' @examples
#' n = 300
#'
#' # Chang's 1983 setting
#' simu = simu_bfem(n = n, which = "Chang1983")
#'
#' # Section 4.2 setting
#' p = 25
#' noise = 1
#' simu = simu_bfem(n, which = "section4.2", p = p, noise = noise)
#'
#' # Section4.3 setting
#' snr = 3 # noise variance is 2 times smaller than that of the signal.
#' simu = simu_bfem(n, which = "section4.3", snr = 10)
simu_bfem <- function(n, which = "Chang1983", ...) {
simu = switch(which,
"Chang1983" = simu.Chang1983(n=n),
"section4.2" = simu.section4.2(n=n, ...),
"section4.3" = simu.section4.3(n=n, ...))
return(simu)
}
# Chang 1983 dataset
simu.Chang1983 <- function(n = 300) {
p = 15
cte = matrix(rep(0.95 - 0.05* (1:p), n), nrow = n, byrow = T)
Z = stats::rbinom(n=n, size=1, prob = 0.2)
mu = rep(0, p)
Sigma = diag(1, p)
f = c(rep(-0.9, 8), rep(0.5, 7))
for(i in 1:p) {
for (j in 1:p) {
if (j!= i) Sigma[i,j] = -0.13 * f[i] * f[j]
}
}
X = MASS::mvrnorm(n=n, mu = mu, Sigma = Sigma)
Y = 0.5 * cte + Z * cte + X
return(list(Y=Y, cls = factor(Z)))
}
# High-dimensional setting of Section 4.2
simu.section4.2 <- function(n, p = 50, noise = 1) {
d = 2
K = 3
S = array(0,c(d,d,K))
S[,,2] = S[,,3] = S[,,1] = matrix(c(1.5,0.75, 0.75, 0.45))
cst = 2.5
mu = matrix(0, d, K)
mu[,1] = c(0, 0)
mu[,2] = cst * c(1, 0)
mu[,3] = cst * c(2, 0)
n1 = round(4*n/10)
n2 = round(3*n/10)
n3 = round(3*n/10)
ind = sample(1:n)
X = rbind(mvrnorm(n1,mu[,1],S[,,1]),mvrnorm(n2,mu[,2],S[,,2]),mvrnorm(n3,mu[,3],S[,,3]))
X = X[ind,]
A = mvrnorm(p, mu = rep(0,p),Sigma = diag(25, p, p))
W = qr.Q(qr(A))
B = mvrnorm(n,rep(0, p-d), diag(noise, p-d, p-d))
y = cbind(X,B)
Y = y %*% t(W)
cls = c(rep(1,n1),rep(2,n2),rep(3,n3))[ind]
return(list(Y = Y, W = W, X = X, cls = cls))
}
# Signal-to-noise ratio of section 4.3
simu.section4.3 <- function(n, p = 150, snr = 3) {
# inverse formula: snr = 10*log10(1.95 / beta)
beta = 1.95 / (exp(snr * log(10)/10))
simu.section4.2(n=n, p = p, noise = beta)
}<file_sep>/demo/FisherEM.r
old.par <- par(no.readonly = TRUE)
palette(c("#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C",
"#FDBF6F", "#FF7F00", "#CAB2D6", "#6A3D9A", "#FFFF99", "#B15928"))
data(iris)
Y = iris[,-5]
lbl= as.numeric(iris[,5])
K = 3
set.seed(12345)
Tinit = t(rmultinom(150,1,c(rep(1/K,K))))
U = fem(Y,3,init='user',Tinit=Tinit,model='AkB',maxit=1,method='gs',eps=1e-3,disp=FALSE)$U
cls1 = cls = max.col(Tinit)
for (i in 1:15){
# x11()
# def.par <- par(no.readonly = TRUE)
x = as.matrix(Y)%*%U
min1= round(min(x[,1]),1)-1
max1= round(max(x[,1],1))+1
min2= round(min(x[,2]),1)-1
max2= round(max(x[,2]),1)+1
cls[cls==1]='lightgreen'
cls[cls==2]='gray'
cls[cls==3]='darkblue'
x1 = split(x[,1],cls)
x2 = split(x[,2],cls)
xhist1 <- hist(x1$'lightgreen',breaks=seq(min1,max1,0.1), plot=FALSE)
xhist2 <- hist(x1$'gray',breaks=seq(min1,max1,0.1), plot=FALSE)
xhist3 <- hist(x1$'darkblue',breaks=seq(min1,max1,0.1), plot=FALSE)
yhist1 <- hist(x2$'lightgreen',breaks=seq(min2,max2,0.1), plot=FALSE)
yhist2 <- hist(x2$'gray',breaks=seq(min2,max2,0.1), plot=FALSE)
yhist3 <- hist(x2$'darkblue',breaks=seq(min2,max2,0.1), plot=FALSE)
topX <- max(c(xhist1$counts,xhist2$counts,xhist3$counts))
topY <- max(c(yhist3$counts,yhist3$counts,yhist3$counts))
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
xrange <- c(min1,max1)
yrange <- c(min2,max2)
par(mar=c(3,3,1,1))
plot(x,col=as.numeric(as.factor(cls)),pch=cls1,xlim=xrange, ylim=yrange,cex=1.5)
# , xlim=xrange, ylim=yrange, xlab="", ylab="")
par(mar=c(0,3,1,1))
barplot(xhist1$counts, axes=FALSE,col=1,ylim=c(0,topX), space=0)
barplot(xhist2$counts, axes=FALSE,col=2, ylim=c(0,topX), space=0,add=T)
barplot(xhist3$counts, axes=FALSE,col=3, ylim=c(0,topX), space=0,add=T)
par(mar=c(3,0,1,1))
barplot(yhist1$counts, axes=FALSE,col=1, xlim=c(0,topY), space=0, horiz=TRUE)
barplot(yhist2$counts, axes=FALSE,col=2, xlim=c(0,topY), space=0, horiz=TRUE,add=T)
barplot(yhist3$counts, axes=FALSE,col=3, xlim=c(0,topY), space=0, horiz=TRUE,add=T)
res = fem(Y,3,init='user',Tinit=Tinit,model='AkB',maxit=1,method='gs',eps=1e-3,disp=FALSE)
Tinit = res$P
cls1 = cls = res$cls
U = res$U
}
par(old.par)
<file_sep>/R/print.fem.R
print.fem <- function(x,...){
cat('* Model: ')
cat('The chosen model is ',as.character(x$model),' with K = ',x$K,' (',x$crit,'=',x$critValue,')\n',sep='')
if (nrow(x$U)<20){
cat('* Loading matrix (zero values are denoted by .):\n')
U = x$U
U[U==0] = NA
U[U<0.001] = 0.001
print.default(U, digits=3, na.print='.')
} else if(x$call[[1]]=='sfem') {
cat('* Loading matrix:',sum(rowSums(abs(x$U))>1e-5),'variables are active over the',nrow(x$U),'original ones\n')
}
}<file_sep>/man/print.fem.Rd
\name{print.fem}
\alias{print.fem}
\title{
The print function for 'fem' objects.
}
\description{
This function summarizes 'fem' objects. It in particular indicates which DLM model has been chosen and displays the loading matrix 'U' if the original dimension is smaller than 10.
}
\usage{
\method{print}{fem}(x,...)
}
\arguments{
\item{x}{The fem object.}
\item{...}{Additional options to pass to the summary function.}
}
\seealso{fem, sfem, fem.ari, plot.fem}
\examples{
data(iris)
res = fem(iris[,-5],K=3,model='DkBk',method='reg')
res
plot(res)
fem.ari(res,as.numeric(iris[,5]))
}
<file_sep>/R/fstep.qiao.R
fstep.qiao <- function(X,T,kernel){
# Initialization
K = ncol(T)
p = ncol(X)
d = min(p-1,(K-1))
m = matrix(NA,K,p)
# Compute summary statistics
Xbar = colMeans(X)
n = colSums(T)
for (k in 1:K){ m[k,] = colSums((as.matrix(T[,k]) %*% matrix(1,1,p))* X) / n[k] }
# browser()
# Matrices Hb and Hw
Hb = as.matrix(sqrt(n) * (m - matrix(1,K,1) %*% Xbar))/sqrt(nrow(X))
Hw = X - t(apply(T,1,'%*%',m))/sqrt(nrow(X))
Hw = as.matrix(Hw)
# Cholesky decomposition of t(Hw) %*% Hw
if (nrow(X)>p)Rw = chol(t(Hw)%*%Hw) else {
gamma = 0.5
Rw = chol(t(Hw)%*%Hw + gamma*diag(p))}
# LASSO & SVD
Binit = eigen(ginv(cov(X))%*%(t(Hb)%*%Hb))$vect[,1:d]
if (is.complex(Binit)) Binit = matrix(Re(Binit),ncol=d,byrow=F)
if (is.null(dim(Binit))) {B = matrix(Binit)} else B = Binit
res.svd = svd(t(ginv(Rw))%*%t(Hb)%*%Hb%*%B)
A = res.svd$u %*% t(res.svd$v)
# browser()
for (j in 1:d){
W = rbind(Hb,Rw)
y = rbind(Hb %*% ginv(Rw) %*% A[,j],matrix(0,p,1))
# res.enet = enet(W,y,lambda=1,intercept=FALSE)
# B[,j] = predict.enet(res.enet,X,type="coefficients",mode="fraction",s=1)$coef
# browser()
res.ls = lsfit(W,y,intercept=FALSE)
B[,j] = res.ls$coef
}
normtemp = sqrt(apply(B^2, 2, sum))
normtemp[normtemp == 0] = 1
Beta = t(t(B)/normtemp)
res.svd = svd(t(ginv(Rw))%*%t(Hb)%*%Hb%*%Beta)
A = res.svd$u %*% t(res.svd$v)
Beta = svd(Beta)$u %*% t(svd(Beta)$v)
# Beta = svd(Beta)$u
# Beta = qr.Q(qr(Beta))
# return the sparse loadings
Beta
}
<file_sep>/R/fem.mstep.par.R
fem.mstep.par <- function(Y,U,T,model,method){
# 12 different submodels: [DkBk] ... [AkjBk]
# Initialization
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
K = ncol(T)
d = min(p-1,(K-1))
U = as.matrix(U)
mu = matrix(NA,K,d)
m = matrix(NA,K,p)
prop = rep(c(NA),1,K)
D = array(0,c(K,d,d))
b = rep(NA,K)
# Projection
X = as.matrix(Y) %*% as.matrix(U)
# Estimation
test = 0
fun <- function(k){
nk = sum(T[,k])
if (nk ==0) stop("some classes become empty\n",call.=FALSE)
# Prior Probability
prop[k] = nk / n
# Mean in the latent space
mu[k,] = colSums((T[,k]*matrix(1,n,d))* X) / nk
# Observed space
m[k,] = colSums(T[,k]*matrix(1,n,p)* Y) / nk
YY = as.matrix(Y - t(m[k,]*matrix(1,p,n)))
if (nk < 1) denk = 1 else denk = (nk-1)
YYk = T[,k] * matrix(1,n,p) * YY
#browser()
if (model %in% c('DkB','DB','AkjB','AkB','AjB','AB')){
TT = t(apply(T,1,"/",sqrt(colSums(T))))
W = (crossprod(YY) - crossprod(t(TT)%*%YY)) / n
}
# Estimation of Delta k amongst 8 submodels
if (model=='DkBk'){ # OK !!!
D[k,(1:d),(1:d)] = crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DkB'){
D[k,(1:d),(1:d)] = crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk
bk = (sum(diag(W)) - sum(diag(crossprod(W%*%U,U)))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DBk'){
D[k,(1:d),(1:d)] = crossprod(YY%*%U,YY%*%U)/n
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='DB'){
D[k,(1:d),(1:d)] = crossprod(YY%*%U,YY%*%U)/n
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkjBk'){
if (d==1){D[k,1,1] = diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))}
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkjB'){
if (d==1){D[k,1,1] = diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkBk'){
if (d==1){D[k,1,1] = sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d} else{
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d,d))}
bk = (sum(YYk*YY)/denk - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AkB'){
if (d==1){D[k,1,1] = sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d} else{
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))/d,d))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AjBk'){
if (d==1){D[k,1,1] = diag(crossprod(YY%*%U,YY%*%U)/n)} else {
D[k,(1:d),(1:d)] = diag(diag(crossprod(YY%*%U,YY%*%U)/n))}
bk = (sum(YYk*YY)/denk - sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AjB'){
if (d==1){D[k,1,1] = diag(crossprod(YY%*%U,YY%*%U)/n)} else{
D[k,(1:d),(1:d)] = diag(diag(crossprod(YY%*%U,YY%*%U)/n))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='ABk'){
if (d==1){D[k,1,1] = sum(diag(crossprod(YY%*%U,YY%*%U)/n))} else {
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(YY%*%U,YY%*%U)/n))/d,d))}
bk = (sum(YYk*YY)/denk - sum(diag(crossprod(T[,k]*matrix(1,n,d)* YY %*%U, YY%*%U) / denk))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
else if (model=='AB'){
if (d==1){D[k,1,1] = sum(diag(crossprod(YY%*%U,YY%*%U)/n))} else {
D[k,(1:d),(1:d)] = diag(rep(sum(diag(crossprod(YY%*%U,YY%*%U)/n))/d,d))}
bk = (sum(YY*YY)/n - sum(diag(D[k,(1:d),(1:d)]))) / (p-d)
bk[bk<=0] = 1e-3
b[k] = bk
if (sum(diag(D[k,,]<1e-3))!=0) test = test+1
}
}
prms = list(K=K,p=p,mean=mu,my=m,prop=prop,D=D,b=b,model=model,method=method,V=U,test=test)
}
<file_sep>/R/bfem.criteria.R
bfem.criteria = function(Y, final_elbo, U, prms, tau, model, hypers, var_param, method) {
n = nrow(tau)
K = ncol(tau)
p = nrow(U)
d = ncol(U)
nu = hypers$nu
# set vague prior
lambda = 1e10
Varmeank = var_param$Varmeank
Varcovk = var_param$Varcovk
# compute final_elbo with new U and q
Varcovk = updateVarcovk(prms, lambda, tau)
Varmeank = updateVarmeank(Y,U, prms, nu, tau = tau, Varcovk = Varcovk)
prms = bfem.mstep(Y, U, tau, Varmeank, Varcovk, model)
final_elbo = bfem.elbo(Y, U, prms, nu, lambda, log(tau), Varmeank, Varcovk)
# compute penalty
if (method=='sparse'){ p = sum(abs(U) > 1e-2) }
comp = switch(as.character(model),
'DkBk' = (K-1) + d*(p-(d+1)/2) + K*d*(d+1)/2 + K,
'DkB' = (K-1) + d*(p-(d+1)/2) + K*d*(d+1)/2 + 1,
'DBk' = (K-1) + d*(p-(d+1)/2) + d*(d+1)/2 + K,
'DB' = (K-1) + d*(p-(d+1)/2) + d*(d+1)/2 + 1,
'AkjBk'= (K-1) + d*(p-(d+1)/2) + K*d + K,
'AkjB' = (K-1) + d*(p-(d+1)/2) + K*d+1,
'AkBk' = (K-1) + d*(p-(d+1)/2) + K + K,
'AkB' = (K-1) + d*(p-(d+1)/2) + K + 1,
'AjBk' = (K-1) + d*(p-(d+1)/2) + d + K,
'AjB' = (K-1) + d*(p-(d+1)/2) + d + 1,
'ABk' = (K-1) + d*(p-(d+1)/2) + 1 + K,
'AB' = (K-1) + d*(p-(d+1)/2) + 1 + 1)
if (!is.na(final_elbo)) {
aic = final_elbo - comp # AIC criterion
bic = final_elbo - 1/2 * comp * log(n) # BIC criterion
cl = max.col(tau)
tau.cl = matrix(0, n, K)
for (i in 1:n) tau.cl[i, cl[i]] = 1
icl = final_elbo - 1/2 * comp * log(n) - sum(tau.cl * log(tau+1e-15))
} else {
aic = bic = icl = -Inf
}
list(aic=aic,bic=bic,icl=icl, comp=comp)
}
<file_sep>/tests/testthat/test-plot.R
library(ggplot2)
set.seed(12345)
n= 200
simu = simu_bfem(n, which = "Chang1983")
Y = simu$Y
p = ncol(Y)
K = 2
d= K - 1
res.bfem = bfem(Y, K, model="DB", init = 'kmeans', nstart = 2, mc.cores = 2)
test_that("Plot bound", {
expect_true(is.ggplot(plot.bfem(res.bfem, type = "elbo")))
})
test_that("Plot crit", {
expect_true(is.ggplot(plot.bfem(res.bfem, type = "criterion", crit = 'bic')))
expect_true(is.ggplot(plot.bfem(res.bfem, type = "criterion", crit = 'icl')))
expect_true(is.ggplot(plot.bfem(res.bfem, type = "criterion", crit = 'aic')))
})
# d == 1 non implemented yet
# test_that("Plot subspace", {
# expect_true(is.ggplot(plot.bfem(res.bfem, type = "subspace")))
# })<file_sep>/R/fstep.fisher.R
fstep.fisher <- function(XX,T,S,kernel){
n = nrow(XX)
p = ncol(XX)
K = ncol(T)
#m = colMeans(Y)
d = min(p-1,(K-1))
# Compute S
#XX = as.matrix(Y - t(m*t(matrix(1,n,p))))
TT = t(apply(T,1,"/",sqrt(colSums(T))))
if (n>p & kernel==''){
#S = t(XX) %*% XX /n
B = t(XX)%*%TT%*%t(TT)%*%XX / n
# Eigendecomposition of S^-1 * B
eig = svd(ginv(S)%*%B,nu=d,nv=0)
#eig = svds(ginv(S)%*%B,d,nu=d,nv=0)
U = eig$u[,1:d]
}
else{
if (n<p | kernel=='linear') G = XX %*% t(XX)
if (kernel=='rbf') {sigma=1; G = as.matrix(exp(dist(XX,diag=T)^2/(2*sigma^2)))}
if (kernel=='sigmoid') {a=1;r=0.1;G = tanh(a * XX %*% t(XX) + r)}
lambda = 0.5
S = G %*% G + lambda*diag(n)
B = G %*% TT %*% t(TT) %*% G
H = svd(ginv(S)%*%B,nu=d,nv=0)$u[,1:d]
U = svd(t(XX) %*% H,nu=d,nv=0)$u[,1:d]
}
return(as.matrix(U))
}
<file_sep>/R/bfem.elbo.R
bfem.elbo <- function(Y, U, prms, nu, lambda, logtau, Varmeank, Varcovk) {
# Set quantities
Sk = prms$Sk
PI = prms$PI
p = ncol(Y)
K = length(PI)
d = ncol(U)
tau = exp(logtau)
tau = tau / rowSums(tau)
nk = colSums(tau)
# H(q(z))
E1 = -sum(tau * logtau, na.rm = T)
# E_z[log p(z)]
E3 = sum(nk * log(PI))
E2 = E4 = E5 = 0
for (k in 1:K) {
# H[q(mu)]
E2 = E2 + 0.5 * (d * (log(2*pi) + 1) + c(determinant(as.matrix(Varcovk[,,k]))$modulus))
# E_mu[log p(mu)]
E4 = E4 - 0.5 * (d * log(2*pi)
+ d * log(lambda)
+ (1/lambda) * (Trace(Varcovk[,,k]) + sum(Varmeank[,k]^2)
- 2 * t(nu) %*% Varmeank[,k]
+ sum(nu^2)
)
)
# E_{z, mu}[log p(Y|Z,mu)]
Ypondk = tau[,k] * Y
sumYpondk = colSums(Ypondk)
projk = U %*% Varmeank[,k]
if (nk[k] < 1e-16) {
E5 = NaN
warning('Cluster ', k, ' is emptied.')
break
} else {
Ck = (1 / nk[k]) * (t(Ypondk) %*% Y -
sumYpondk %*% t(projk) -
projk %*% t(sumYpondk)
) +
U %*% (Varcovk[,,k] + Varmeank[,k] %*% t(Varmeank[,k])) %*% t(U)
tUCkU = t(U) %*% Ck %*% U
E5 = E5 - 0.5 * nk[k] * (p * log(2*pi) + Sk$logdetk[k] +
(p - d) * log(Sk$Beta[k]) +
Trace(Sk$invSigmak[,,k] %*% tUCkU) +
(1/Sk$Beta[k]) * (Trace(Ck) - Trace(tUCkU))
)
}
}
bound = c(E1 + E2 + E3 + E4 + E5)
return(bound)
}<file_sep>/R/plot.fem.R
plot.fem <- function(x,frame=0,crit=c(),...){
# Color palette
palette(c("#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C",
"#FDBF6F", "#FF7F00", "#CAB2D6", "#6A3D9A", "#FFFF99", "#B15928"))
old.par <- par(no.readonly = TRUE)
Y = eval.parent(x$call[[2]])
# Model selection
if ((frame==0 || frame==1) & (length(x$allCriteria$K)>1 || length(x$allCriteria$models)>1)){
K = x$allCriteria$K; models = x$allCriteria$model
if (length(crit)==0) crit = x$crit
if (crit=='bic') val = x$allCriteria$bic; if (crit=='aic') val = x$allCriteria$aic; if (crit=='icl') val = x$allCriteria$icl
val[val==-Inf] = NA
if (length(models)>1){
plot(K,val,type='n',xlab='K',ylab=crit,main='Model selection')
for (m in 1:length(levels(models))){
modl = levels(models)[m]
lines(K[models==modl],val[models==modl],col=m,lty=m,lwd=2)
}
legend('bottomleft',levels(models),col=1:length(models),lty=1:length(models),
ncol=round(length(models)/3),cex=1)
}
else plot(K,val,type='b',xlab='K',ylab=crit,col=1:length(models),lty=1:length(models),main='Selection of the number of groups',...)
if (x$call[[1]]=='sfem'){
if (crit=='bic') val = x$allCriteria$l1$bic; if (crit=='aic') val = x$allCriteria$l1$aic; if (crit=='icl') val = x$allCriteria$l1$icl
plot(x$allCriteria$l1$l1,val,type='b',xlab='l1 value',ylab=crit,main='Selection of the sparsity penalty',...)
}
}
# Log-likelihood
if (frame==0) Sys.sleep(0.5)
if (frame==0 || frame==2) if (x$call[[1]]!='sfem') plot(x$loglik.all,type='b',xlab='Iterations',
ylab='Log-likelihood',main='Log-likelihood',col=2,pch=20,cex=0.5,...)
# Discriminative subspace
if (frame==0) Sys.sleep(0.5)
if (frame==0 || frame==3){
Y = as.matrix(Y)
p = ncol(Y)
n = nrow(Y)
if (ncol(x$U)>1){
xx = as.matrix(Y)%*%x$U[,1:2]
cls = x$cls
min1= round(min(xx[,1]),1)-1
max1= round(max(xx[,1],1))+1
min2= round(min(xx[,2]),1)-1
max2= round(max(xx[,2]),1)+1
topX = topY = 0
xhist = yhist = list()
for (k in 1:max(cls)){
xhist[[k]] = hist(xx[cls==k,1],breaks=seq(min1,max1,0.1), plot=FALSE)
yhist[[k]] = hist(xx[cls==k,2],breaks=seq(min2,max2,0.1), plot=FALSE)
topX = max(topX,xhist[[k]]$counts); topY = max(topY,yhist[[k]]$counts)
}
nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE)
xrange <- c(min1,max1); yrange <- c(min2,max2)
par(mar=c(3,3,1,1))
plot(xx,col=cls,pch=cls,xlim=xrange, ylim=yrange,cex=1.5)
par(mar=c(0,3,1,1))
for (k in 1:max(cls)) barplot(xhist[[k]]$counts,axes=FALSE,col=k,ylim=c(0,topX),space=0,add=(k>1))
par(mar=c(3,0,1,1))
for (k in 1:max(cls)) barplot(yhist[[k]]$counts,axes=FALSE,horiz=TRUE,col=k,xlim=c(0,topY),space=0,add=(k>1))
par(old.par)
}
else {
cat('Since K=2, the data and the discriminative subspace have been projected on the 2 first PCs','\n')
if (ncol(Y)<nrow(Y)) Z = -eigen(cov(Y),symmetric=T)$vectors[,1:2]
else {
z = eigen(Y%*%t(Y),symmetric=T)
Z = matrix(NA,p,2)
for (i in 1:2) Z[,i] = t(Y)%*%z$vectors[,i]/sqrt(n*z$values[i])
}
MU = colMeans(Y)
proj= matrix(NA,2,p)
axU = matrix(x$U,p,1)%*%matrix(x$U,1,p)%*%matrix(10, p, 1)
proj= axU+matrix(MU,p,1)
Yproj = Y%*%Z
u = matrix(proj,1,p)%*%Z # projection sur les 2 pc
ybar = matrix(MU,1,p) %*% Z # proj des moyennes des cls sur les 2 pc
plot(Yproj,col=x$cls+1,xlab='comp.1',ylab='comp.2',pch=x$cls+1)
pente=(u[1,2]-ybar[1,2])/(u[1,1]-ybar[1,1])
oo=u[1,2]-pente*u[1,1]
xb=(2*ybar[1,1]-sqrt(50^2/(pente^2+1)))/2
xa=(2*ybar[1,1]+sqrt(50^2/(pente^2+1)))/2
#cat(xa,xb,oo+pente*c(xa,xb),'\n')
lines(c(xa,xb),oo+pente*c(xa,xb),col=1,type='l',lwd=2)
title(main='Estimated discriminative subspace (projected onto PCA axes)')
}
par(old.par)
}
# Plot of the group means
if (frame==0) Sys.sleep(0.5)
if (frame==0 || frame==4){
matplot(t(x$mean),type='l',lwd=1.5,xaxt='n',ylab='')
axis(1,at=1:ncol(Y),labels=colnames(Y),las=2)
title(main='Group means')
legend('bottomleft',paste('Group ',1:max(x$cls),sep=''),col=1:max(x$cls),lty=1:max(x$cls),
ncol=round(max(cls)/3),cex=0.8,...)
}
# Return to user graphic parameters
par(old.par)
}
<file_sep>/tests/testthat/test-simu_bfem.R
n = 100
test_that("test Chang1983 simulation", {
simu = simu_bfem(n, which = "Chang1983")
expect_equal(nrow(simu$Y), n)
expect_equal(ncol(simu$Y), 15)
expect_equal(length(simu$cls), n)
expect_equal(length(unique(simu$cls)), 2)
})
test_that("test section4.2 simulation", {
p = 25
noise = 3
simu = simu_bfem(n, which = "section4.2", p = p, noise = noise)
expect_equal(nrow(simu$Y), n)
expect_equal(ncol(simu$Y), p)
expect_equal(length(simu$cls), n)
expect_equal(length(unique(simu$cls)), 3)
})
#
#
# test_that("test section4.3 simulation", {
# snr = 10
# simu = simu_bfem(n, which = "section4.3", snr = 10)
# expect_equal(nrow(simu$Y), n)
# expect_equal(ncol(simu$Y), p)
# expect_equal(length(simu$cls), n)
# expect_equal(length(unique(simu$cls)), 3)
# })
<file_sep>/R/fem.R
fem <- function(Y,K=2:6,model='AkjBk',method='gs',crit='icl',maxit=50,eps=1e-4,init='kmeans',
nstart=5,Tinit=c(),kernel='',disp=FALSE,mc.cores=(detectCores()-1),subset=NULL){
call = match.call()
MOD = c('DkBk','DkB','DBk','DB','AkjBk','AkjB','AkBk','AkB','AjB','AjBk', 'ABk', 'AB','all')
MET = c('svd','reg','gs')
KER = c('','sigmoid','linear','rbf')
CRI = c('bic','aic','icl','sh')
INIT = c('user','random','kmeans','hclust')
if (sum(is.na(Y))>0) stop("NA values are not allowed.\n",call.=FALSE)
if (any(!model%in%MOD)) stop("Invalid model name.\n",call.=FALSE)
if (any(!method%in%MET)) stop("Invalid method name.\n",call.=FALSE)
if (any(!kernel%in%KER)) stop("Invalid kernel name.\n",call.=FALSE)
if (any(!crit%in%CRI)) stop("Invalid criterion name.\n",call.=FALSE)
if (any(!init%in%INIT)) stop("Invalid initialization name.\n",call.=FALSE)
if (init=='hclust' & nrow(Y)>5000) stop('Too much data for this initialization.\n',call.=FALSE)
# if (K>=ncol(Y)) stop("K must be strictly less than the number of variables",call.=FALSE)
if (nrow(Y)<=ncol(Y) & method=='gs') stop("n<<p case: use method REG or SVD.\n",call.=FALSE)
if (length(model)==1) if (model=='all') model = MOD[MOD!='all']
if (sum(apply(Y,2,var) == 0) > 0) stop("Some variables have zero variance. Please remove them and try again.\n",call.=FALSE)
if (!is.null(subset)) {
Yfull = Y
sel = sample(nrow(Y),subset)
Y = Y[sel,]
if (init=='user') Tinit = Tinit[sel,]
}
# Run FEM depending on Windows or not (allows parallel computing)
if (Sys.info()[['sysname']] == 'Windows' | mc.cores == 1){
prms = expand.grid(model=model,K=K)
RES = list()
for (i in 1:nrow(prms)){
RES[[i]] = fem.main(Y=Y,K=prms$K[i],model=prms$model[i],init=init,nstart=nstart,maxit=maxit,
eps=eps,Tinit=Tinit,kernel=kernel,method=method)
}
}
else {
prms = expand.grid(model=model,K=K)
MoreArgs = list(Y=Y,init=init,nstart=nstart,maxit=maxit,eps=eps,Tinit=Tinit,kernel=kernel,method=method)
RES = do.call(mcmapply, c(list(FUN="fem.main",MoreArgs=MoreArgs,mc.cores=mc.cores,
mc.silent=TRUE,mc.preschedule=FALSE),prms))
}
#Post-treatment of results
if (is.matrix(RES)){ # Parallization without errors (output is a matrix)
bic = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
aic = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
icl = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
comp = unlist(apply(RES,2,function(x){if (is.list(x)){x$comp} else NA}))
loglik = unlist(apply(RES,2,function(x){if (is.list(x)){x$loglik} else NA}))
if (crit=='bic'){ id_max = which.max(bic); crit_max = bic[id_max]}
if (crit=='aic'){ id_max = which.max(aic); crit_max = aic[id_max]}
if (crit=='icl'){ id_max = which.max(icl); crit_max = icl[id_max]}
}
else{ # Parallization with errors (output is a list)
bic = unlist(lapply(RES,function(x){if(is.list(x)){x$bic} else{-Inf}}))
aic = unlist(lapply(RES,function(x){if(is.list(x)){x$aic} else{-Inf}}))
icl = unlist(lapply(RES,function(x){if(is.list(x)){x$icl} else{-Inf}}))
comp = unlist(lapply(RES,function(x){if(is.list(x)){x$comp} else{-Inf}}))
loglik = unlist(lapply(RES,function(x){if(is.list(x)){x$loglik} else{-Inf}}))
if (crit=='bic'){ id_max = which.max(bic); crit_max = bic[id_max]}
if (crit=='aic'){ id_max = which.max(aic); crit_max = aic[id_max]}
if (crit=='icl'){ id_max = which.max(icl); crit_max = icl[id_max]}
}
nm = length(model)
allCriteria = data.frame(model=prms$model,K=prms$K,comp=comp,loglik=loglik,bic=bic,aic=aic,icl=icl)
if (is.matrix(RES)) {res = RES[,id_max]} else res = RES[[id_max]]
res$aic = res$bic = res$icl = NULL
res$model = as.character(res$model)
res$allCriteria = allCriteria
res$crit = crit
res$critValue = unlist(crit_max)
res$allResults = RES
res$call = call
if (!is.null(subset)) {
browser()
prms = list(mean=res$mean,my=res$my,K=res$K,prop=res$prop,D=res$D,b=res$b)
resFull = fem.estep(prms,Yfull,res$U)
res$P = resFull$T
res$cls = max.col(resFull$T)
}
# Display and return results
if (disp) cat('The selected model is',res$model,'with K =',res$K,'(',crit,'=',res$critValue,')\n')
class(res)='fem'
res
}<file_sep>/R/bfem.R
#' The Bayesian Fisher-EM algorithm.
#'
#' The Bayesian Fisher-EM algorithm is built on a Bayesian formulation of the
#' model used in the \code{\link{fem}}. It is a subspace clustering method for
#' high-dimensional data. It is based on a Gaussian Mixture Model and on the
#' idea that the data lives in a common and low dimensional subspace. A VEM-like
#' algorithm estimates both the discriminative subspace and the parameters of
#' the mixture model.
#'
#' @param Y The data matrix.
#' Categorical variables and missing values are not
#' allowed.
#' @param K An integer vector specifying the numbers of mixture components
#' (clusters) among which the model selection criterion will choose the most
#' appropriate number of groups. Default is 2:6.
#' @param model A vector of Bayesian discriminative latent mixture (BDLM) models
#' to fit. There are 12 different models: "DkBk", "DkB", "DBk", "DB", "AkjBk",
#' "AkjB", "AkBk", "AkBk", "AjBk", "AjB", "ABk", "AB". The option "all"
#' executes the Fisher-EM algorithm on the 12 DLM models and select the best
#' model according to the maximum value obtained by model selection criterion.
#' Similar to \code{\link{fem}}
#' @param method The method used for the fitting of the projection matrix
#' associated to the discriminative subspace. Three methods are available:
#' 'gs' (Gram-Schmidt, the original proposition), 'svd' (based on SVD, faster)
#' and 'reg' (the Fisher criterion is rewritten as a regression problem). The
#' 'gs' method is the default method.
#' @param crit The model selection criterion to use for selecting the most
#' appropriate model for the data. There are 3 possibilities: "bic", "aic" or
#' "icl". Default is "icl".
#' @param maxit.em The maximum number of iterations before the stop of the main
#' EM loop in the BFEM algorithm.
#' @param eps.em The threshold value for the likelihood differences (Aitken's
#' criterion) to stop the BFEM algorithm.
#' @param maxit.ve The maximum number of iterations before the stop of the
#' VE-step loop (fixed point algorithm)
#' @param eps.ve The threshold value for the likelihood differences (Aitken's
#' criterion) to stop the BFEM algorithm.
#' @param lambda The initial value for the variance of the Gaussian prior on the
#' means in the latent space.
#' @param emp.bayes Should the hyper-parameters (mean and variance) of the prior be updated ? Default to TRUE.
#' @param init The initialization method for the Fisher-EM algorithm. There are
#' 4 options: "random" for a randomized initialization, "kmeans" for an
#' initialization by the kmeans algorithm, "hclust" for hierarchical
#' clustering initialization or "user" for a specific initialization through
#' the parameter "Tinit". Default is "kmeans". Notice that for "kmeans" and
#' "random", several initializations are asked and the initialization
#' associated with the highest likelihood is kept (see "nstart").
#' @param nstart The number of restart if the initialization is "kmeans" or
#' "random". In such a case, the initialization associated with the highest
#' likelihood is kept.
#' @param Tinit A n x K matrix which contains posterior probabilities for
#' initializing the algorithm (each line corresponds to an individual).
#' @param kernel It enables to deal with the n < p problem. By default, no
#' kernel (" ") is used. But the user has the choice between 3 options for the
#' kernel: "linear", "sigmoid" or "rbf".
#' @param disp If true, some messages are printed during the clustering. Default
#' is false.
#' @param mc.cores The number of CPUs to use to fit in parallel the different
#' models (only for non-Windows platforms). Default is the number of available
#' cores minus 1.
#' @param subset A positive integer defining the size of the subsample, default
#' is NULL. In case of large data sets, it might be useful to fit a FisherEM
#' model on a subsample of the data, and then use this model to predict
#' cluster assignments for the whole data set. Notice that in, such a case,
#' likelihood values and model selection criteria are computed for the
#' subsample and not the whole data set.
#'
#' @return A list is returned: \itemize{
#' \item K - The number of groups.
#' \item cls - the group membership of each individual estimated by the BFEM algorithm
#' \item Tinit - The initial posterior probalities used to start the algorithm
#' \item d - the dimension of the discriminative subspace
#' \item elbos - A vector containing the evolution of the variational lower bound at each iteration
#' \item loglik - The final value of the variational lower bound
#' \item n_ite - The number of iteration until convergence of the BFEM algorithm
#' \item P - the posterior probabilities of each individual for each group
#' \item U - The loading matrix which determines the orientation of the discriminative subspace
#' \item param - A list containing the estimated parameters of the model
#' \itemize{
#' \item PI - The mixture proportions
#' \item Sigmak - An array containing estimated cluster covariances in the latent space
#' \item Beta - The noise variance in each cluster
#' }
#' \item var_param - A list containing the variational distribution parameters
#' \itemize{
#' \item logtau - A n x K matrix containing the logarithm of the multinomial parameters of q(Z)
#' \item Varmeank - A K x d matrix containing the variational mean
#' \item Varcovk - A d x d x K array containing the variational covariance matrices.
#' }
#' \item proj - The projected data on the discriminative subspace.
#' \item aic - The value of the Akaike information criterion
#' \item bic - The value of the Bayesian information criterion
#' \item icl - The value of the integrated completed likelihood criterion
#' \item method - The method used in the F-step
#' \item call - The call of the function
#' \item crit - The model selection criterion used }
#' @export
#' @seealso \code{\link{fem}}
#' @examples
#' # Chang's 1983 setting
#' simu = simu_bfem(300, which = "Chang1983")
#' Y = simu$Y
#' res.bfem = bfem(Y, K = 2:6, model=c('AB'), init = 'kmeans', nstart = 1,
#' maxit.em = 10, eps.em = 1e-3, maxit.ve = 3, mc.cores = 2)
#'
bfem <- function(Y, K=2:6, model='AkjBk', method='gs', crit='icl', maxit.em=100,
eps.em=1e-6, maxit.ve=3, eps.ve=1e-4, lambda = 1e3, emp.bayes=T,
init='kmeans', nstart=10, Tinit=c(), kernel='',
disp=FALSE, mc.cores=(detectCores()-1), subset=NULL) {
call = match.call()
control_bfem = list(var = list(tol = eps.ve, max.iter = maxit.ve),
em = list(tol = eps.em, max.iter = maxit.em),
emp.bayes = emp.bayes)
MOD = c('DkBk','DkB','DBk','DB','AkjBk','AkjB','AkBk','AkB',
'AjB','AjBk', 'ABk', 'AB','all')
MET = c('svd','reg','gs')
KER = c('','sigmoid','linear','rbf')
CRI = c('bic','aic','icl','sh')
INIT = c('user','random','kmeans','hclust')
if (sum(is.na(Y))>0) stop("NA values are not allowed.\n",call.=FALSE)
if (any(!model%in%MOD)) stop("Invalid model name.\n",call.=FALSE)
if (any(!method%in%MET)) stop("Invalid method name.\n",call.=FALSE)
if (any(!kernel%in%KER)) stop("Invalid kernel name.\n",call.=FALSE)
if (any(!crit%in%CRI)) stop("Invalid criterion name.\n",call.=FALSE)
if (any(!init%in%INIT)) stop("Invalid initialization name.\n",call.=FALSE)
if (init=='hclust' & nrow(Y)>5000) stop('Too much data for this initialization.\n',call.=FALSE)
# if (K>=ncol(Y)) stop("K must be strictly less than the number of variables",call.=FALSE)
if (nrow(Y)<=ncol(Y) & method=='gs') stop("n<<p case: use method REG or SVD.\n",call.=FALSE)
if (length(model)==1) if (model=='all') model = MOD[MOD!='all']
if (sum(apply(Y,2,var) == 0) > 0) stop("Some variables have zero variance. Please remove them and try again.\n",call.=FALSE)
if (!is.null(subset)) {
Yfull = Y
sel = sample(nrow(Y),subset)
Y = Y[sel,]
if (init=='user') Tinit = Tinit[sel,]
}
# Run FEM depending on Windows or not (allows parallel computing)
if (Sys.info()[['sysname']] == 'Windows' | mc.cores == 1){
prms = expand.grid(model=model,K=K)
RES = list()
for (i in 1:nrow(prms)){
RES[[i]] = bfem.main(Y=Y,K=prms$K[i],model=prms$model[i],init=init,
nstart=nstart, control_bfem=control_bfem,
Tinit=Tinit,kernel=kernel,method=method, lambda=lambda)
}
}
else {
prms = expand.grid(model=model,K=K)
MoreArgs = list(Y=Y,init=init,nstart=nstart,control_bfem=control_bfem,
Tinit=Tinit,kernel=kernel,method=method, lambda=lambda)
RES = do.call(mcmapply, c(list(FUN="bfem.main",MoreArgs=MoreArgs,mc.cores=mc.cores,
mc.silent=TRUE,mc.preschedule=FALSE),prms))
}
#Post-treatment of results
if (is.matrix(RES)){ # Parallization without errors (output is a matrix)
bic = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
aic = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
icl = unlist(apply(RES,2,function(x){if (is.list(x)){x$bic} else NA}))
comp = unlist(apply(RES,2,function(x){if (is.list(x)){x$comp} else NA}))
loglik = unlist(apply(RES,2,function(x){if (is.list(x)){x$loglik} else NA}))
if (crit=='bic'){ id_max = which.max(bic); crit_max = bic[id_max]}
if (crit=='aic'){ id_max = which.max(aic); crit_max = aic[id_max]}
if (crit=='icl'){ id_max = which.max(icl); crit_max = icl[id_max]}
}
else{ # Parallization with errors (output is a list)
bic = unlist(lapply(RES,function(x){if(is.list(x)){x$bic} else{-Inf}}))
aic = unlist(lapply(RES,function(x){if(is.list(x)){x$aic} else{-Inf}}))
icl = unlist(lapply(RES,function(x){if(is.list(x)){x$icl} else{-Inf}}))
comp = unlist(lapply(RES,function(x){if(is.list(x)){x$comp} else{-Inf}}))
loglik = unlist(lapply(RES,function(x){if(is.list(x)){x$loglik} else{-Inf}}))
if (crit=='bic'){ id_max = which.max(bic); crit_max = bic[id_max]}
if (crit=='aic'){ id_max = which.max(aic); crit_max = aic[id_max]}
if (crit=='icl'){ id_max = which.max(icl); crit_max = icl[id_max]}
}
nm = length(model)
allCriteria = data.frame(model=prms$model,K=prms$K,comp=comp,loglik=loglik,bic=bic,aic=aic,icl=icl)
if (is.matrix(RES)) {res = RES[,id_max]} else res = RES[[id_max]]
res$aic = res$bic = res$icl = NULL
res$model = as.character(res$model)
res$allCriteria = allCriteria
res$crit = crit
res$critValue = unlist(crit_max)
res$allResults = RES
res$call = call
if (!is.null(subset)) {
browser()
prms = list(mean=res$mean,my=res$my,K=res$K,prop=res$prop,D=res$D,b=res$b)
resFull = fem.estep(prms,Yfull,res$U)
res$P = resFull$T
res$cls = max.col(resFull$T)
}
# Display and return results
if (disp) cat('The selected model is',res$model,'with K =',res$K,'(',crit,'=',res$critValue,')\n')
class(res)='bfem'
res
}<file_sep>/man/fem.ari.Rd
\name{fem.ari}
\alias{fem.ari}
\title{
Adjusted Rand index
}
\description{
The function computes the adjusted Rand index (ARI) which allows to compare two clustering partitions.}
\usage{
fem.ari(x,y)
}
\arguments{
\item{x}{
A 'fem' object containing the first partition to compare.
}
\item{y}{
The second partition to compare (as vector).
}
}
\value{
\item{ari}{The value of the ARI.}
}
\seealso{fem, sfem, plot.fem, summary.fem}
\examples{
data(iris)
res = fem(iris[,-5],K=3,model='DkBk',method='reg')
res
plot(res)
fem.ari(res,as.numeric(iris[,5]))
}
<file_sep>/man/FisherEM-package.Rd
\name{FisherEM-package}
\alias{FisherEM-package}
\alias{FisherEM}
\docType{package}
\title{The FisherEM Algorithm to Simultaneously Cluster and Visualize High-Dimensional Data}
\description{
The FisherEM algorithm, proposed by Bouveyron & Brunet (201) <doi:10.1007/s11222-011-9249-9>, is an efficient method for the clustering of high-dimensional data. FisherEM models and clusters the data in a discriminative and low-dimensional latent subspace. It also provides a low-dimensional representation of the clustered data. A sparse version of Fisher-EM algorithm is also provided.
}
\details{
\tabular{ll}{
Package: \tab FisherEM\cr
Type: \tab Package\cr
Version: \tab 1.2\cr
Date: \tab 2012-07-09\cr
License: \tab GPL-2\cr
LazyLoad: \tab yes\cr
}
}
\author{
<NAME>, <NAME> & <NAME>.
Maintainer: <NAME> <<EMAIL>>
}
\references{
<NAME>, Camille Brunet (2012), "Simultaneous model-based clustering and visualization in the Fisher discriminative subspace.", Statistics and Computing, 22(1), 301-324 <doi:10.1007/s11222-011-9249-9>.
<NAME> and Camille Brunet (2014), "Discriminative variable selection for clustering with the sparse Fisher-EM algorithm", Computational Statistics, vol. 29(3-4), pp. 489-513 <10.1007/s00180-013-0433-6>.
}
<file_sep>/R/bfem.vestep.R
bfem.vestep <- function(Y, U, prms, nu, lambda, logtau,
Varmeank = NULL, Varcovk = NULL,
ve.tol = 1e-4, ve.max.iter = 3) {
tau = exp(logtau)
ve.count = 0
if (is.null(Varmeank) | is.null(Varcovk)) {
Varcovk = updateVarcovk(prms, lambda, tau)
Varmeank = updateVarmeank(Y, U, prms, nu, tau, Varcovk)
}
elbo = bfem.elbo(Y, U, prms, nu, lambda, logtau, Varmeank, Varcovk)
ve.elbos = c(elbo)
conv = c(elbo, Inf)
test = F
while (abs(diff(conv)/conv[1]) > ve.tol & ve.count < ve.max.iter) {
logtau = updatelogTau(Y, U, prms, Varmeank, Varcovk)
tau = exp(logtau)
Varcovk = updateVarcovk(prms, lambda, tau)
Varmeank = updateVarmeank(Y, U, prms, nu, tau, Varcovk)
elbo = bfem.elbo(Y, U, prms, nu, lambda, logtau, Varmeank, Varcovk)
if (is.na(elbo)) {test = T; break}
ve.elbos = c(ve.elbos, elbo)
conv = c(elbo, conv[1])
ve.count = ve.count + 1
}
if (sum(diff(ve.elbos) >= -1e-10) != length(ve.elbos) - 1) {
message('Elbo decrease : ', diff(ve.elbos))
# warning(paste0('The elbo is decreasing in VE-step'))
}
return(list(logtau = logtau, Varmeank = Varmeank, Varcovk = Varcovk,
ve.elbos = ve.elbos, n_iter = ve.count, test = test))
}
updatelogTau <- function(Y, U, prms, Varmeank, Varcovk) {
# Initialization
Sk = prms$Sk
PI = prms$PI
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
d = ncol(U)
K = ncol(Varmeank)
prop = PI
D = array(0, dim = c(K, d, d))
for (k in 1:K) D[k,,] = Sk$Sigmak[,,k]
b = Sk$Beta
QQ = matrix(NA,n,K)
T = matrix(NA,n,K)
# Compute posterior probabilities
for (k in 1:K){
bk = b[k]
mY = t(U %*% Varmeank[,k])
YY = Y-t(matrix(rep(mY,n),p,n))
projYY = YY %*% U %*% t(U)
if (d==1){
QQ[,k] = (1/D[k,1,1]) * rowSums(projYY^2) + 1/bk*rowSums((YY - projYY)^2) + (p-d)*log(bk) + log(D[k,1,1]) - 2*log(prop[k]) + p*log(2*pi)
# add variational correction
QQ[,k] = QQ[,k] + (1/D[k,1,1]) * Varcovk[1,1,k]
} else{
tmp = eigen(D[k,(1:d),(1:d)])
A = projYY %*% U %*% tmp$vect %*% diag(sqrt(1/tmp$val))
QQ[,k] = rowSums(A^2) + 1/bk*rowSums((YY - projYY)^2) + (p-d)*log(bk) + log(det(D[k,(1:d),(1:d)])) - 2*log(prop[k]) + p*log(2*pi)
# add variational correction
QQ[,k] = QQ[,k] + sum(Varcovk[,,k] * Sk$invSigmak[,,k])
}
}
# Compute posterior probabilities
for (k in 1:K) {T[,k] = 1 / rowSums(exp((QQ[,k]*matrix(1,n,K)-QQ)/2))}
# Return the results
return(log(T))
}
updateVarcovk = function(prms, lambda, tau) {
# tau is a matrix with dim (nxK)
Sk = prms$Sk
nk = colSums(tau)
K = ncol(tau)
d = dim(Sk$invSigmak)[1]
res = array(0, dim = c(d,d, K))
for (k in 1:K) {
res[,,k] = solve(diag(1/lambda, nrow = d) + nk[k] * Sk$invSigmak[,,k])
}
return(res)
}
updateVarmeank = function(Y, U, prms, nu, tau, Varcovk) {
# Varcovk is an array with dim (d x d x K)
# invSigmak is an array with dim (p x p x K)
Sk = prms$Sk
K = ncol(tau)
nk = colSums(tau)
d = ncol(U)
res = matrix(0, nrow = d, ncol = K)
for (k in 1:K) {
sumYpondk = colSums(tau[,k] * Y)
res[,k] = nu + Varcovk[,,k] %*% Sk$invSigmak[,,k] %*% (t(U) %*% sumYpondk - nk[k] * nu )
}
return(res)
}
<file_sep>/R/bfem.emp.bayes.R
updateNu = function(Varmeank) {
return(rowMeans(Varmeank))
}
updateLambda = function(Varmeank, Varcovk, nu) {
d = dim(Varcovk)[1]
K = dim(Varcovk)[3]
lambda = 0
for (k in 1:K) {
lambda = lambda + Trace(Varcovk[,,k]) + sum(Varmeank[,k]^2)
- 2 * t(nu) %*% Varmeank[,k]
+ sum(nu^2)
}
return(lambda / (d * K))
}
<file_sep>/R/fstep.GramSc.R
fstep.GramSc <-
function(XX,T,S,kernel){
n = nrow(XX)
p = ncol(XX)
K = ncol(T)
#m = colMeans(Y)
d = min(p-1,(K-1))
U = matrix(NA,p,d)
# Compute S
#XX = as.matrix(Y - t(m*t(matrix(1,n,p))))
TT = t(apply(T,1,"/",sqrt(colSums(T))))
if (n>p & kernel==''){
#S = cov(Y)*(n-1)/n
B = t(XX)%*%TT%*%t(TT)%*%XX / n
# Eigendecomposition of S^-1 * B
eig = eigen(ginv(S)%*%B)
#eig = eigs(ginv(S)%*%B,1) # requires the rARPACK library
U[,1] = matrix(Re(eig$vec[,1]),ncol=1)
if (d>1){
for (k in 2:d){
W = as.matrix(U[,-c(k:d)])
# start of the gram-schmidt algorithm
base = diag(p)
base <- as.matrix(base[,1:(p-k+1)])
W = cbind(W,base)
v <- W
for (l in 2:p){
proj <- c(crossprod(W[,l],v[,1:(l-1)])) / diag(crossprod(v[,1:(l-1)]))
v[,l] <- matrix(W[,l],ncol=1) - matrix(v[,1:(l-1)],nrow=p) %*% matrix(proj,ncol=1)
v[,l] <- v[,l] / rep(sqrt(crossprod(v[,l])),p)
}
P = v[,k:ncol(v)]
# P = qr.Q(qr(W),complete=TRUE)[,k:p]
B.p = crossprod(P,crossprod(t(B),P))
S.p = crossprod(P,crossprod(t(S),P))
eig = eigen(ginv(S.p)%*%B.p)
#eig = eigs(ginv(S.p)%*%B.p,1) # requires the rARPACK library
Umax = matrix(Re(eig$vec[,1]),ncol=1)
U[,k]= P%*%Umax
}
}
}
if (d==1) {U = U[,1]}
as.matrix(U)
}
<file_sep>/man/plot.fem.Rd
\name{plot.fem}
\alias{plot.fem}
\title{
The plot function for 'fem' objects.
}
\description{
This function plots different information about 'fem' objects such as model selection, log-likelihood evolution and visualization of the clustered data into the discriminative subspace fitted by the Fisher-EM algorithm.}
\usage{
\method{plot}{fem}(x, frame=0, crit=c(),...)
}
\arguments{
\item{x}{The fem object.
}
\item{frame}{0: all plots; 1: selection of the number of groups; 2: log-likelihood; projection of the data into the discriminative subspace.
}
\item{crit}{
The model selection criterion to display. Default is the criterion used in the 'fem' function ('icl' by default).
}
\item{...}{
Additional options to pass to the plot function.
}
}
\seealso{fem, sfem, fem.ari, summary.fem}
\examples{
data(iris)
res = fem(iris[,-5],K=3,model='DkBk',method='reg')
res
plot(res)
fem.ari(res,as.numeric(iris[,5]))
}
<file_sep>/R/bfem.main.R
bfem.main <- function(Y,K,init,nstart,control_bfem,Tinit,model,kernel,method,lambda){
em.tol = control_bfem$em$tol
ve.tol = control_bfem$var$tol
ve.max.iter = control_bfem$var$max.iter
em.max.iter = control_bfem$em$max.iter
emp.bayes = control_bfem$emp.bayes
# Initialization
colNames = colnames(Y)
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
d = min((K-1),(p-1))
# Compute S
m = colMeans(Y)
XX = as.matrix(Y - t(m*t(matrix(1,n,p))))
S = t(XX) %*% XX /n
# ========== Initialization of tau with a frequentist EM-step ==============
if (init=='user'){ tau = Tinit}
else if (init=='hclust'){
tau = matrix(0,n,K)
ind = cutree(hclust(dist(Y),method='ward.D2'),K)
for (i in 1:n){ tau[i,ind[i]] = 1 }
}
else if (init=='kmeans' || init=='random'){
Ltmp = rep(NA,nstart); tau_list = list()
for (i in 1:nstart){
if (init=='random'){tau_list[[i]] = t(rmultinom(n,1,c(rep(1/K,K))))}
else{
tau = matrix(0,n,K)
ind = kmeans(Y,K,nstart=10)$cluster
for (i in 1:n){ tau[i,ind[i]] = 1 }
tau_list[[i]] = tau
}
U = switch(method,
'svd'= fstep.fisher(XX,tau_list[[i]],S,kernel),
'gs'= fstep.GramSc(XX,tau_list[[i]],S,kernel),
'reg' = fstep.qiao(Y,tau_list[[i]],kernel))
prms = fem.mstep(Y,U,tau_list[[i]],model=model,method=method)
res.estep = fem.estep(prms,Y,U)
Ltmp[i] = res.estep$loglik
}
tau = tau_list[[which.max(Ltmp)]]
}
Tinit = tau # stock to return
logtau = log(tau)
# ================ Set initial quantities fo BFEM ==========================
# initial F-step
U = switch(method,'svd'= fstep.fisher(XX,tau,S,kernel),
'gs'= fstep.GramSc(XX,tau,S,kernel),
'reg' = fstep.qiao(Y,tau,kernel))
# Initialize nu
if(emp.bayes) {
X = Y %*% U
nu = colMeans(X)
} else {
nu = rep(0, d)
}
# Initial M-step: use frequentist estimates of Sk and PI
prms.fem = fem.mstep(Y,U,tau,model=model,method=method)
prms = transform_param_fem_to_bfem(prms.fem)
# Inital VE-step: 1 iteration of fixed point for var parameter of q(\mu_k)
Varcovk = updateVarcovk(prms, lambda, tau)
Varmeank = updateVarmeank(Y, U, prms, nu, tau, Varcovk)
elbo = bfem.elbo(Y, U, prms, nu, lambda, logtau, Varmeank, Varcovk)
# ================ Main loop BFEM ===============================
conv = c(Inf)
Lobs = rep(-Inf , 1, em.max.iter + 1)
Lobs[1] = elbo
Linf_new = Lobs[1]
for (i in 1:em.max.iter) {
# if (verbose > 0) cat('BFEM iteration : ', i,'\n')
# F-step
U = switch(method,
'svd'= fstep.fisher(XX,tau,S,kernel),
'gs'= fstep.GramSc(XX,tau,S,kernel),
'reg' = fstep.qiao(Y,tau,kernel))
# Variational E-step (don't change tau yet, only q(\mu_k))
ve_step = bfem.vestep(Y, U, prms, nu, lambda, logtau,
Varmeank=NULL, Varcovk=NULL, ve.tol, ve.max.iter)
Varmeank = ve_step$Varmeank
Varcovk = ve_step$Varcovk
# Mstep
prms = bfem.mstep(Y, U, tau, Varmeank, Varcovk, model)
if(is.null(prms$Sk)) return(list(k=K, Tinit=Tinit, loglik=-Inf,
icl = -Inf, bic = -Inf, aic = -Inf,
model = model, K=K, cls = max.col(tau), P = tau,
error=1))
# Update of tau and logtau after M-step
logtau = updatelogTau(Y, U, prms, Varmeank, Varcovk)
tau = exp(logtau)
# Hyper-params
if (emp.bayes) {
nu = updateNu(Varmeank)
lambda = updateLambda(Varmeank, Varcovk, nu)
}
elbo = bfem.elbo(Y, U, prms, nu, lambda, logtau, Varmeank, Varcovk)
# Stop criterion
if (is.na(elbo)) {
warning('Likelihood becomes NA (probably emptied cluster).')
break
}
Lobs[i+1] = elbo
if (i >= 3) {
acc = (Lobs[i+1] - Lobs[i]) / (Lobs[i] - Lobs[i-1])
Linf_old = Linf_new
Linf_new <- try( Lobs[i] + 1/(1 - acc) * (Lobs[i+1] - Lobs[i]))
if (is.na(Linf_new)){warnings('acc=', acc);break}
if (abs(Linf_new - Linf_old) < em.tol) {break}
}
}
Lobs = Lobs[Lobs != -Inf]
# Returning the results
cls = apply(tau, 1, which.max)
param = list(PI = prms$PI, Sigmak = prms$Sk$Sigmak, Beta = prms$Sk$Beta)
var_param = list(logtau = logtau, Varmeank = Varmeank, Varcovk = Varcovk)
hypers = list(lambda = lambda, nu = nu)
proj = Y %*% U
rownames(U) = colNames
final_elbo = utils::tail(Lobs, 1)
crit = bfem.criteria(Y, final_elbo, U, prms, tau, model, hypers, var_param, method)
return(list(K = K, Tinit = Tinit, d = d, cls = cls, P = tau,
elbos = Lobs, loglik=final_elbo, n_ite = i,
U = U, param = param, var_param = var_param, proj = proj,
model = model, aic=crit$aic, bic=crit$bic, icl=crit$icl,
comp=crit$comp,
hypers = hypers,
call = call)
)
}
transform_param_fem_to_bfem <- function(prms.fem) {
# New code use different structure for parameters
# This a helper function to transform prms.fem
# into the structure used in bfem.main()
K = prms.fem$K
p = prms.fem$p
d = min(p-1, K-1)
# new structure
prms = list(Sk = list(), PI = NULL)
prms$PI = prms.fem$prop
prms$Sk = list(Sigmak = array(0, dim = c(d,d,K)),
invSigmak = array(0, dim = c(d,d,K)),
Beta = prms.fem$b,
logdetk = rep(NA, K))
for (k in 1:K) {
prms$Sk$Sigmak[,,k] = prms.fem$D[k,,]
prms$Sk$invSigmak[,,k] = solve(prms$Sk$Sigmak[,,k])
prms$Sk$logdetk[k] = c(determinant(as.matrix(prms$Sk$Sigmak[,,k]))$modulus)
}
return(prms)
}
<file_sep>/R/fem.main.R
fem.main <- function(Y,K,init,nstart,maxit,eps,Tinit,model,kernel='',method){
# Initialization
colnames = colnames(Y)
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
d = min((K-1),(p-1))
# Compute S
m = colMeans(Y)
XX = as.matrix(Y - t(m*t(matrix(1,n,p))))
S = t(XX) %*% XX /n
# New objects
Lobs = rep(c(-Inf),1,(maxit+1))
# Initialization of T
if (init=='user'){ T = Tinit}
else if (init=='hclust'){
T = matrix(0,n,K)
ind = cutree(hclust(dist(Y),method='ward.D2'),K)
for (i in 1:n){ T[i,ind[i]] = 1 }
}
else if (init=='kmeans' || init=='random'){
Ltmp = rep(NA,nstart); TT = list()
for (i in 1:nstart){
if (init=='random'){TT[[i]] = t(rmultinom(n,1,c(rep(1/K,K))))}
else{
T = matrix(0,n,K)
ind = kmeans(Y,K,nstart=10)$cluster
for (i in 1:n){ T[i,ind[i]] = 1 }
TT[[i]] = T
}
V = switch(method,
'svd'= fstep.fisher(XX,TT[[i]],S,kernel),
'gs'= fstep.GramSc(XX,TT[[i]],S,kernel),
'reg' = fstep.qiao(Y,TT[[i]],kernel))
prms = fem.mstep(Y,V,TT[[i]],model=model,method=method)
res.estep = fem.estep(prms,Y,V)
Ltmp[i] = res.estep$loglik
}
T = TT[[which.max(Ltmp)]]
}
V = switch(method,'svd'= fstep.fisher(XX,T,S,kernel),
'gs'= fstep.GramSc(XX,T,S,kernel),
'reg' = fstep.qiao(Y,T,kernel))
prms = fem.mstep(Y,V,T,model=model,method=method)
res.estep = fem.estep(prms,Y,V)
Lobs[1] = res.estep$loglik
# Main loop
Linf_new = Lobs[1]
for (i in 1:maxit){
# The three main steps F, M and E
V = switch(method,
'svd'= fstep.fisher(XX,T,S,kernel),
'gs'= fstep.GramSc(XX,T,S,kernel),
'reg' = fstep.qiao(Y,T,kernel))
prms = fem.mstep(Y,V,T,model=model,method=method)
if (prms$test !=0) {warning("some classes become empty\n",call.=F); break}
res.estep = fem.estep(prms,Y,V)
T = res.estep$T
Lobs[i+1] = res.estep$loglik
# Stop criterion
if (i>=3){
acc = (Lobs[i+1] - Lobs[i]) / (Lobs[i] - Lobs[i-1])
Linf_old = Linf_new
Linf_new <- try( Lobs[i] + 1/(1-acc) * (Lobs[i+1] - Lobs[i]))
if (is.na(Linf_new)){warning("some classes become empty\n",call.=F); break}
if (abs(Linf_new - Linf_old) < eps) {break}
}
}
# Returning the results
cls = max.col(T)
crit = fem.criteria(Lobs[(i+1)],T,prms,n)
rownames(V) = colnames
colnames(V) = paste('U',1:d,sep='')
list(model=prms$model,K=K,cls=cls,P=T,U=V,mean=prms$my,prop=prms$prop,D=prms$D,beta=prms$b,
aic=crit$aic,bic=crit$bic,icl=crit$icl,comp=crit$comp,loglik.all=Lobs[2:(i+1)],
loglik=Lobs[i+1],method=method)
}
<file_sep>/tests/testthat.R
library(testthat)
library(FisherEM)
test_check("FisherEM")
<file_sep>/R/fem.criteria.R
fem.criteria <-
function(loglik,T,prms,n){
K = prms$K
d = K-1
V = prms$V
if (prms$method=='sparse'){ p = sum(abs(V) > 1e-2) } else {p = prms$p}
comp = switch(as.character(prms$model),
'DkBk' = (K-1) + K*d + (K-1)*(p-K/2) + K^2*(K-1)/2 + K,
'DkB' = (K-1) + K*d + (K-1)*(p-K/2) + K^2*(K-1)/2 + 1,
'DBk' = (K-1) + K*d + (K-1)*(p-K/2) + K*(K-1)/2 + K,
'DB' = (K-1) + K*d + (K-1)*(p-K/2) + K*(K-1)/2 + 1,
'AkjBk'= (K-1) + K*d + (K-1)*(p-K/2) + K^2,
'AkjB' = (K-1) + K*d + (K-1)*(p-K/2) + K*(K-1)+1,
'AkBk' = (K-1) + K*d + (K-1)*(p-K/2) + 2*K,
'AkB' = (K-1) + K*d + (K-1)*(p-K/2) + K+1,
'AjBk' = (K-1) + K*d + (K-1)*(p-K/2) + (K-1)+K,
'AjB' = (K-1) + K*d + (K-1)*(p-K/2) + (K-1)+1,
'ABk' = (K-1) + K*d + (K-1)*(p-K/2) + K+1,
'AB' = (K-1) + K*d + (K-1)*(p-K/2) + 2)
aic = loglik - comp # AIC criterion
bic = loglik - 1/2 * comp * log(n) # BIC criterion
Z = ((T - apply(T,1,max))==0) + 0
icl = loglik - 1/2 * comp * log(n) - sum(Z*log(T+1e-15)) # ICL criterion
list(aic=aic,bic=bic,icl=icl,comp=comp)
}
<file_sep>/R/plot.bfem.R
## For CRAN check ...
## https://stackoverflow.com/questions/9439256/how-can-i-handle-r-cmd-check-no-visible-binding-for-global-variable-notes-when/12429344#12429344
utils::globalVariables(names = c('elbo', 'iteration', 'Cluster',
'x', 'y', '.id', 'sigma', 'V1', 'V2'))
#' Plotting function
#'
#' Utility function to plot the results of the BFEM algorithm. The S3 plot
#' function is a wrapper function over the 3 other functions
#' @param x The results of \code{\link{bfem}}.
#' @param type The plot type: \itemize{ \item "subspace" (default) - Uses
#' \code{plot_subspace()} to plot the projected data \item "criterion" - Uses
#' \code{plot_crit()} to plot the criterion value. \item "elbo" - Uses
#' \code{plot_bound()} to plot the variational lower bound evolution. }
#' @param ... Additional parameter to pass to corxponding functions:
#' @param crit Used to specify which criterion should be plotted. Possible values are "aic", "bic" and 'icl. The default is the criterion used in the algorithm.
#' @param alpha_levels A vector giving the desired Gaussian ellipses level set. Default to 0.95.
#' @param plot.dims The dimension to be plotted. Default to the first two dimensions.
#' @param show.ellipses Should Gaussian ellipses be plotted. Default to TRUE
#' @param show.uncertainty Should uncertainty be plotted. A point is considered uncertain if its posterior probability of membership is peaked toward 2 or more clusters. Graphically, it can be displayed with a bigger point size depending on the uncertainty level, bigger points being more uncertain.
#' @param size The point size.
#' @param cex.uncertainty The multiplicative factor for the basic point size controlling the size of uncertain points.
#' @return a ggplot2 plot object
#'
#' @rdname plot.bfem
#' @export
#'
#' @examples
#' \donttest{
#' data(iris)
#' Y = iris[,-5]
#' res = bfem(Y, 3, model = 'DB')
#' gg = plot(x=res, type = "subspace")
#' print(gg)
#' }
plot.bfem <- function(x, type = "subspace", ...) {
gg = switch (type,
"subspace" = plot_subspace(x, ...),
"elbo" = plot_bound(x),
"criterion" = plot_crit(x, ...)
)
gg
}
# plot.bfem <- function(x, ...) {
# mc = match.call()
# if(is.null(mc$type)) mc$type = "subspace"
# type = mc$type
# localPlot_bound <- function(x, ..., type) plot_bound(x, ...)
# localPlot_crit <- function(x, ..., type) plot_crit(x, ...)
# localPlot_subspace <- function(x, ..., type) plot_subspace(x, ...)
#
# gg = switch (type,
# "subspace" = localPlot_subspace(x, ...),
# "elbo" = localPlot_bound(x, ...),
# "criterion" = localPlot_crit(x, ...)
# )
# gg
# }
#--- Plot results from BFEM
bubble <- function(u, cex = c(0.2, 3), alpha = c(0.1, 1))
{
# Uncertainty computing function from Mclust
# Return size and transparency for points
u <- as.vector(u)
cex <- cex[!is.na(cex)]
alpha <- alpha[!is.na(alpha)]
u <- (u - min(u))/(max(u) - min(u) + sqrt(.Machine$double.eps))
n <- length(u)
r <- sqrt(u/pi)
r <- (r - min(r, na.rm = TRUE))/
(max(r, na.rm = TRUE) - min(r, na.rm = TRUE) + sqrt(.Machine$double.eps))
cex <- r * diff(range(cex)) + min(cex)
alpha <- u * diff(range(alpha)) + min(alpha)
return(list(cex = cex, alpha = alpha))
}
#' @describeIn plot.bfem Plot Y projected on the `plot.dims` dimensions of the latent space
# along with gaussian ellipses corxponding to p(\mu_k)
#' @export
plot_subspace <- function(x, alpha_levels = c(0.95), plot.dims = c(1,2),
show.ellipses = T, show.uncertainty = T,
size = 2, cex.uncertainty = 1, ...) {
if (x$d == 1) {
message('Not implemented for d=1.')
return(NULL)
}
if (sum(plot.dims > x$d) != 0) stop('Plot dimensions must be < d')
X_est = x$proj
df = as.data.frame(X_est[,plot.dims])
df$Cluster = as.factor(x$cl)
ndim = length(plot.dims)
if(ndim == 2) {
gg = ggplot2::ggplot(df,
ggplot2::aes(x = V1, y = V2, col = Cluster, shape = Cluster))
if (show.uncertainty) {
# inspired from Mclust uncertainty, adapted for ggplot2
z = x$P
uncertainty <- 1 - apply(z, 1, max)
u = (uncertainty - min(uncertainty))/(max(uncertainty) - min(uncertainty)
+ sqrt(.Machine$double.eps))
b <- bubble(u, cex = cex.uncertainty * c(size, size+2), alpha = c(1, 0.7))
gg = gg +
ggplot2::geom_point(size = b$cex,
alpha = max(b$alpha) - b$alpha + min(b$alpha))
} else {
gg = gg +
ggplot2::geom_point(size = size)
}
# -- code for ellipse
if (show.ellipses) {
alpha_levels = sort(alpha_levels)
names(alpha_levels) <- alpha_levels ## to get id column in xult
contour_data = NULL
for (k in 1:x$K) {
m <- x$var_param$Varmeank[plot.dims,k]
sigma <- x$param$Sigmak[plot.dims,plot.dims,k]
contour_data = plyr::ldply(alpha_levels,
function(level)
ellipse::ellipse(level = level, x = sigma, centre = m))
contour_data$Cluster = as.factor(k)
gg = gg +
ggplot2::geom_path(data=contour_data,
ggplot2::aes(x, y, group = .id, col = Cluster),
linetype='dotdash',
alpha = rep(length(alpha_levels):1,each = 100)/1.5 ,
show.legend = F)
}
means = as.data.frame(t(x$var_param$Varmeank))
means$Cluster = as.factor(1:x$K)
gg = gg +
ggplot2::geom_point(data=means,
ggplot2::aes(x = V1, y = V2),shape = 3, size = 5, show.legend = F)
}
# Colorblind friendly palette
gg = gg +
ggplot2::scale_color_brewer(palette="Set2") +
ggplot2::xlab(paste0('U', plot.dims[1])) + ggplot2::ylab(paste0('U', plot.dims[2]))
return(gg)
} else {
base::message('ndim > 2 not implemented yet')
return(NULL)
}
}
#' @describeIn plot.bfem plot the variational bound evolution
#' @export
plot_bound = function(x, ...) {
elbos = x$elbos
df = data.frame(iteration = 1:length(elbos), elbo = elbos)
gg = ggplot2::ggplot(df, ggplot2::aes(x=iteration, y=elbo)) +
ggplot2::geom_point(size=1.5) +
ggplot2::geom_line(size=1, alpha = 0.7, linetype='dashed') +
ggplot2::xlab('Iteration') + ggplot2::ylab('Elbo') +
ggplot2::theme(text = ggplot2::element_text(size=20))
gg
}
#' @describeIn plot.bfem Plot the criterion xult
#' @export
plot_crit = function(x, crit = NULL, ...) {
color_palette = c("#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C",
"#FDBF6F", "#FF7F00", "#CAB2D6", "#6A3D9A", "#FFFF99", "#B15928")
shape_palette = factor(1:12)
if(is.null(crit)) crit = x$crit
df = x$allCriteria
df$K = as.integer(df$K)
gg = ggplot2::ggplot(df,
ggplot2::aes_string(x="K", y=crit, shape = "model",
linetype = "model", col = "model")) +
ggplot2::geom_point() +
ggplot2::geom_line() +
ggplot2::ylab(base::casefold(crit, upper = T)) +
ggplot2::scale_shape_manual(values = shape_palette) +
ggplot2::scale_linetype_manual(values = shape_palette) +
ggplot2::scale_color_manual(values = color_palette)
gg
}
<file_sep>/tests/testthat/test-bfem-2d.R
set.seed(12345)
Y = iris[,-5]
n = nrow(Y)
p = ncol(Y)
K = 2
d = K - 1
test_that("bfem kmeans init", {
res.bfem = bfem(Y, K, model="DB", init = 'kmeans', nstart = 2, mc.cores = 2)
expect_equal(res.bfem$K, K)
expect_equal(res.bfem$d, d)
expect_equal(dim(res.bfem$P), c(n, K))
expect_equal(dim(res.bfem$var_param$Varmeank), c(d, K))
expect_equal(dim(res.bfem$var_param$Varcovk), c(d, d, K))
expect_equal(dim(res.bfem$U), c(p, d))
expect_equal(dim(res.bfem$proj), c(n, d))
expect_equal(length(res.bfem$elbos), res.bfem$n_ite+1)
})
test_that("bfem random init", {
res.bfem = bfem(Y, K, model="DB", init = 'random', nstart = 2, mc.cores = 2)
expect_equal(res.bfem$K, K)
expect_equal(res.bfem$d, d)
expect_equal(dim(res.bfem$P), c(n, K))
expect_equal(dim(res.bfem$var_param$Varmeank), c(d, K))
expect_equal(dim(res.bfem$var_param$Varcovk), c(d, d, K))
expect_equal(dim(res.bfem$U), c(p, d))
expect_equal(dim(res.bfem$proj), c(n, d))
expect_equal(length(res.bfem$elbos), res.bfem$n_ite+1)
})
test_that("bfem user init", {
Tinit = t(rmultinom(n, 1, prob = rep(1/2,2)))
res.bfem = bfem(Y, K, model="DB", init = 'user', Tinit = Tinit, mc.cores = 2)
expect_equal(res.bfem$K, K)
expect_equal(res.bfem$d, d)
expect_equal(dim(res.bfem$P), c(n, K))
expect_equal(dim(res.bfem$var_param$Varmeank), c(d, K))
expect_equal(dim(res.bfem$var_param$Varcovk), c(d, d, K))
expect_equal(dim(res.bfem$U), c(p, d))
expect_equal(dim(res.bfem$proj), c(n, d))
expect_equal(length(res.bfem$elbos), res.bfem$n_ite+1)
})
# test_that("test all models", {
# res.bfem = bfem(Y, K, model="all", init = 'kmeans', nstart = 1, mc.cores = 2)
# expect_equal(res.bfem$K, K)
# expect_equal(res.bfem$d, d)
# expect_equal(dim(res.bfem$P), c(n, K))
# expect_equal(dim(res.bfem$var_param$Varmeank), c(d, K))
# expect_equal(dim(res.bfem$var_param$Varcovk), c(d, d, K))
# expect_equal(dim(res.bfem$U), c(p, d))
# expect_equal(dim(res.bfem$proj), c(n, d))
# expect_equal(length(res.bfem$elbos), res.bfem$n_ite+1)
# })
#
# test_that("test 3 models, K grid", {
# res.bfem = bfem(Y, K = 2:6, model=c('DkBk', 'AkjBk', 'AB'), init = 'kmeans', nstart = 1,
# maxit.em = 10, eps.em = 1e-3, maxit.ve = 3, mc.cores = 2)
# expect_equal(dim(res.bfem$var_param$Varmeank), c(res.bfem$d, res.bfem$K))
# expect_equal(dim(res.bfem$var_param$Varcovk), c(res.bfem$d, res.bfem$d, res.bfem$K))
# expect_equal(dim(res.bfem$U), c(p, res.bfem$d))
# expect_equal(dim(res.bfem$proj), c(n, res.bfem$d))
# expect_equal(length(res.bfem$elbos), res.bfem$n_ite+1)
# })
<file_sep>/R/fem.sparse.R
fem.sparse <- function(Y,K,maxit,eps,Tinit,model,method='reg',l1,nbit,l2){
colnames = colnames(Y)
if (length(l1)!=1 | l1>1) stop('The l1 penalty term is a single figure comprises between 0 and 1')
# Initialization
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
d = min((K-1),(p-1))
# New objects
Lobs = rep(c(-Inf),1,(maxit+1))
#
# Initialization of T
T = Tinit
V = fstep.sparse(Y,T,l1,nbit,l2)
prms = fem.mstep(Y,V,T,model=model,method=method)
res.estep = fem.estep(prms,Y,V)
T = res.estep$T
Lobs[1] = res.estep$loglik
# Main loop
Linf_new = Lobs[1]
for (i in 1:maxit){
# The three main steps F, M and E
V = fstep.sparse(Y,T,l1,nbit,l2)
prms = fem.mstep(Y,V,T,model=model,method=method)
res.estep = fem.estep(prms,Y,V)
T = res.estep$T
Lobs[i+1] = res.estep$loglik
# Stop criterion
if (i>=2){
acc = (Lobs[i+1] - Lobs[i]) / (Lobs[i] - Lobs[i-1])
Linf_old = Linf_new
Linf_new <- try( Lobs[i] + 1/(1-acc) * (Lobs[i+1] - Lobs[i]))
if (abs(Linf_new - Linf_old) < eps) {break}
}
}
# Returning the results
cls = max.col(T)
crit = fem.criteria(Lobs[(i+1)],T,prms,n)
rownames(V) = colnames
colnames(V) = paste('U',1:d,sep='')
res = list(K=K,cls=cls,P=T,U=V,aic=crit$aic,mean=prms$mean,my=prms$my,prop=prms$prop,D=prms$D,model=prms$model,bic=crit$bic,icl=crit$icl,loglik=Lobs[2:(i+1)],ll=Lobs[i+1],method=method)
res
}
<file_sep>/R/bfem.mstep.R
bfem.mstep = function(Y, U, tau, Varmeank, Varcovk, model) {
# 12 different submodels: [DkBk] ... [AkjBk]
# inspired from fem.mtep.R with the addition of variational correciton in BFEM
# Initialization
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
K = ncol(tau)
d = ncol(U)
U = as.matrix(U)
mu = matrix(NA,K,d)
m = matrix(NA,K,p)
prop = rep(c(NA),1,K)
D = array(0,c(K,d,d))
b = rep(NA,K)
# Projection
X = as.matrix(Y) %*% as.matrix(U)
# Estimation
test = 0
bk = 0
for (k in 1:K){
nk = sum(tau[,k])
# if (nk ==0) stop("some classes become empty\n",call.=FALSE)
# if (nk ==0) return(NULL)
# Prior Probability
prop[k] = nk / n
# Mean in the latent space
mu[k,] = Varmeank[,k]
m[k,] = mu[k,] %*% t(U)
YY = as.matrix(Y - t(m[k,]*matrix(1,p,n)))
if (nk < 1) denk = 1 else denk = nk
YYk = tau[,k] * matrix(1,n,p) * YY
# Estimation of Delta k amongst 12 submodels
if (model %in% c('DkBk', 'DkB', 'DBk', 'DB')) {
D[k,,] = crossprod(YYk%*%U, YY%*%U) / denk
}
else if (model %in% c('AkjBk', 'AkjB', 'AjBk', 'AjB')) {
D[k,,] = diag(diag(crossprod(YYk %*%U, YY%*%U) / denk), d)
}
else if (model %in% c('AkBk', 'AkB', 'ABk', 'AB')) {
D[k,,] = diag(rep(Trace(crossprod(YYk %*%U, YY%*%U) / denk)/d,d), d)
}
# compute b[k]
if (model %in% c('DkB','DB','AkjB', 'AjB', 'AkB','AB')) {
bk = bk + (1 / n) * (sum(YYk*YY) - Trace(D[k,,]))
} else {
b[k] = (sum(YYk*YY) - Trace(D[k,,])) / (denk * (p-d))
}
# add variational correction
if (model %in% c('DkBk', 'DkB', 'DBk', 'DB')) {
D[k,,] = D[k,,] + Varcovk[,,k]
}
else if (model %in% c('AkjBk', 'AkjB', 'AjBk', 'AjB')) {
D[k,,] = D[k,,] + diag(diag(as.matrix(Varcovk[,,k])), d)
} else {
D[k,,] = D[k,,] + diag(Trace(Varcovk[,,k])/d, d)
}
}
# Compute Sigma after loop for homoscedastic models
Sigma = matrix(0, d, d)
if (model %in% c('DBk', 'DB', 'AjBk', 'AjB', 'AB', 'ABk')) {
for (k in 1:K) {
nk = sum(tau[,k])
if (nk < 1) denk = 1 else denk = nk
Sigma = Sigma + (denk / n) * D[k,,]
}
for (k in 1:K) {
D[k,,] = Sigma
}
}
# compute beta for '*B' models
if (model %in% c('DkB','DB','AkjB','AkB','AjB','AB')) {
bk = bk / (p-d)
b = rep(bk, K)
}
# avoid numerical
b[b<=0] = 1e-3
for (k in 1:K) if (Trace(D[k,,]<1e-3)!=0) test = test+1
Sk = list()
Sk$Sigmak = Sk$invSigmak = array(0, dim = c(d,d,K))
Sk$logdetk = rep(NA, K)
for (k in 1:K) {
Sk$Sigmak[,,k] = D[k,,]
Sk$invSigmak[,,k] = solve(Sk$Sigmak[,,k])
Sk$logdetk[k] = c(determinant(as.matrix(Sk$Sigmak[,,k]))$modulus)
}
Sk$Beta = b
return(list(Sk=Sk, PI=prop))
}
<file_sep>/man/fem.Rd
\name{fem}
\alias{fem}
\title{
The Fisher-EM algorithm
}
\description{
The Fisher-EM algorithm is a subspace clustering method for high-dimensional data. It is based on the Gaussian Mixture Model and on the idea that the data lives in a common and low dimensional subspace. An EM-like algorithm estimates both the discriminative subspace and the parameters of the mixture model.
}
\usage{
fem(Y,K=2:6,model='AkjBk',method='gs',crit='icl',maxit=50,eps=1e-4,init='kmeans',
nstart=5,Tinit=c(),kernel='',disp=FALSE,mc.cores=(detectCores()-1),
subset=NULL)
}
\arguments{
\item{Y}{
The data matrix. Categorical variables and missing values are not allowed.
}
\item{K}{
An integer vector specifying the numbers of mixture components (clusters) among which the model selection criterion will choose the most appropriate number of groups. Default is 2:6.
}
\item{model}{A vector of discriminative latent mixture (DLM) models to fit. There are 12 different models: "DkBk", "DkB", "DBk", "DB", "AkjBk", "AkjB", "AkBk", "AkBk", "AjBk", "AjB", "ABk", "AB". The option "all" executes the Fisher-EM algorithm on the 12 DLM models and select the best model according to the maximum value obtained by model selection criterion.
}
\item{method}{
The method used for the fitting of the projection matrix associated to the discriminative subspace. Three methods are available: 'gs' (Gram-Schmidt, the original proposition), 'svd' (based on SVD, fastest approach, it should be preferred on large data sets) and 'reg' (the Fisher criterion is rewritten as a regression problem). The 'gs' method is the default method since it is the most efficient one on most data sets.
}
\item{crit}{The model selection criterion to use for selecting the most appropriate model for the data. There are 3 possibilities: "bic", "aic" or "icl". Default is "icl".
}
\item{maxit}{
The maximum number of iterations before the stop of the Fisher-EM algorithm.
}
\item{eps}{
The threshold value for the likelihood differences to stop the Fisher-EM algorithm.
}
\item{init}{
The initialization method for the Fisher-EM algorithm. There are 4 options: "random" for a randomized initialization, "kmeans" for an initialization by the kmeans algorithm, "hclust" for hierarchical clustering initialization or "user" for a specific initialization through the parameter "Tinit". Default is "kmeans". Notice that for "kmeans" and "random", several initializations are asked and the initialization associated with the highest likelihood is kept (see "nstart").
}
\item{nstart}{The number of restart if the initialization is "kmeans" or "random". In such a case, the initialization associated with the highest likelihood is kept.
}
\item{Tinit}{
A n x K matrix which contains posterior probabilities for initializing the algorithm (each line corresponds to an individual).
}
\item{kernel}{It enables to deal with the n < p problem. By default, no kernel (" ") is used. But the user has the choice between 3 options for the kernel: "linear", "sigmoid" or "rbf".
}
\item{disp}{
If true, some messages are printed during the clustering. Default is false.
}
\item{mc.cores}{The number of CPUs to use to fit in parallel the different models (only for non-Windows platforms). Default is the number of available cores minus 1.}
\item{subset}{A positive integer defining the size of the subsample, default is NULL. In case of large data sets, it might be useful to fit a FisherEM model on a subsample of the data, and then use this model to predict cluster assignments for the whole data set. Notice that in, such a case, likelihood values and model selection criteria are computed for the subsample and not the whole data set.}
}
\value{
A list is returned:
\item{K}{The number of groups.}
\item{cls}{the group membership of each individual estimated by the Fisher-EM algorithm.}
\item{P}{the posterior probabilities of each individual for each group.}
\item{U}{The loading matrix which determines the orientation of the discriminative subspace.}
\item{mean}{The estimated mean in the subspace.}
\item{my}{The estimated mean in the observation space.}
\item{prop}{The estimated mixture proportion.}
\item{D}{The covariance matrices in the subspace.}
\item{aic}{The value of the Akaike information criterion.}
\item{bic}{The value of the Bayesian information criterion.}
\item{icl}{The value of the integrated completed likelihood criterion.}
\item{loglik}{The log-likelihood values computed at each iteration of the FEM algorithm.}
\item{ll}{the log-likelihood value obtained at the last iteration of the FEM algorithm.}
\item{method}{The method used.}
\item{call}{The call of the function.}
\item{plot}{Some information to pass to the plot.fem function.}
\item{crit}{The model selction criterion used.}
}
\references{<NAME> and <NAME> (2012), Simultaneous model-based clustering and visualization in the Fisher discriminative subspace, Statistics and Computing, 22(1), 301-324 <doi:10.1007/s11222-011-9249-9>.
<NAME> and <NAME> (2014), "Discriminative variable selection for clustering with the sparse Fisher-EM algorithm", Computational Statistics, vol. 29(3-4), pp. 489-513 <10.1007/s00180-013-0433-6>.
}
\author{
<NAME>, <NAME> & <NAME>.
}
\seealso{sfem, plot.fem, fem.ari, summary.fem}
\examples{
data(iris)
res = fem(iris[,-5],K=3,model='AkBk',method='gs')
res
plot(res)
fem.ari(res,as.numeric(iris$Species))
table(iris$Species,res$cls)
\donttest{
# Fit several models and numbers of groups (use by default on non-Windows
# platforms the parallel computing).
res = fem(iris[,-5],K=2:6,model='all',method='gs', mc.cores=2)
res
plot(res)
fem.ari(res,as.numeric(iris$Species))
table(iris$Species,res$cls)
}
}
<file_sep>/R/utils.R
## --- Trace
Trace = function(A) {
if (is.matrix(A)) {
if (nrow(A) != ncol(A)) {
stop('Matrix should be square in Trace()')
}
}
return(sum(diag(A)))
}<file_sep>/R/fem.ari.R
fem.ari <- function(x,y){
x <- as.vector(x$cls)
y <- as.vector(y)
xx <- outer(x, x, "==")
yy <- outer(y, y, "==")
upper <- row(xx) < col(xx)
xx <- xx[upper]
yy <- yy[upper]
a <- sum(as.numeric(xx & yy))
b <- sum(as.numeric(xx & !yy))
c <- sum(as.numeric(!xx & yy))
d <- sum(as.numeric(!xx & !yy))
ni <- (b + a)
nj <- (c + a)
abcd <- a + b + c + d
q <- (ni * nj)/abcd
ari <- (a - q)/((ni + nj)/2 - q)
ari
}
<file_sep>/R/fem.estep.R
fem.estep <- function(prms,Y,U){
# require('MASS')
# Initialization
Y = as.matrix(Y)
n = nrow(Y)
p = ncol(Y)
K = prms$K
mu = prms$mean
prop = prms$prop
D = prms$D
b = prms$b
d = min(p-1,(K-1))
QQ = matrix(NA,n,K)
T = matrix(NA,n,K)
# Compute posterior probabilities
for (k in 1:K){
bk = b[k]
mY = prms$my[k,]
YY = Y-t(matrix(rep(mY,n),p,n))
projYY = YY %*% U %*% t(U)
if (d==1){
QQ[,k] = 1/D[k,1,1] * rowSums(projYY^2) + 1/bk*rowSums((YY - projYY)^2) + (p-d)*log(bk) + log(D[k,1,1]) - 2*log(prop[k]) + p*log(2*pi)
} else{
tmp = eigen(D[k,(1:d),(1:d)])
A = projYY %*% U %*% tmp$vect %*% diag(sqrt(1/tmp$val))
QQ[,k] = rowSums(A^2) + 1/bk*rowSums((YY - projYY)^2) + (p-d)*log(bk) + log(det(D[k,(1:d),(1:d)])) - 2*log(prop[k]) + p*log(2*pi)
}
}
# Compute the log-likelihood
A = -1/2 * QQ
loglik = sum(log(rowSums(exp(A-apply(A,1,max))))+apply(A,1,max))
# Compute posterior probabilities
for (k in 1:K) {T[,k] = 1 / rowSums(exp((QQ[,k]*matrix(1,n,K)-QQ)/2))}
# Return the results
list(T=T,loglik=loglik)
}
| 6b28896f46eabbddaf8f14cd08554cfeab591263 | [
"R"
] | 33 | R | cran/FisherEM | 4ff2e8e609a42942801b74290158e79e3c18c751 | 3b565591d45e456884b8296af38047421f8ade93 |
refs/heads/master | <file_sep>package tmechworks.common;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import tmechworks.common.SpoolRepairRecipe;
import cpw.mods.fml.common.registry.GameRegistry;
public class MechRecipes {
public static void registerAllTheThings ()
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MechContent.signalBus.blockID, 1, 0), "www", "sss", 'w', MechContent.lengthWire, 's', new ItemStack(Block.stoneSingleSlab, 1, OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MechContent.signalTerminal.blockID, 1, 0), "b", "g", "b", 'b', new ItemStack(MechContent.signalBus.blockID, 1, 0), 'g', new ItemStack(Block.glass, 1, OreDictionary.WILDCARD_VALUE)));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MechContent.lengthWire, 8), "a", "a", "a", 'a', "ingotAluminumBrass"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(MechContent.spoolWire, 1, 256 - 8), "www", "wrw", "www", 'w', MechContent.lengthWire, 'r', "stoneRod"));
GameRegistry.addRecipe(new SpoolRepairRecipe(new ItemStack(MechContent.spoolWire, 1, 256), new ItemStack(MechContent.lengthWire, 1)));
}
}
<file_sep>package tmechworks.client;
import tmechworks.client.block.SignalBusRender;
import tmechworks.client.block.SignalTerminalRender;
import tmechworks.common.CommonProxy;
import cpw.mods.fml.client.registry.RenderingRegistry;
public class ClientProxy extends CommonProxy {
public void registerTickHandler ()
{
super.registerTickHandler();
}
/* Registers any rendering code. */
public void registerRenderer ()
{
RenderingRegistry.registerBlockHandler(new SignalBusRender());
RenderingRegistry.registerBlockHandler(new SignalTerminalRender());
}
}
| 963bf966bf01ebb31eaca24717852b26cf88ac0f | [
"Java"
] | 2 | Java | TheVikingWarrior/TinkersMechworks | 0781be63c73486a0ad219fd976a05e1adc1ad77e | 73be898162c9c596efcd1ffb1c3c089be24ce52c |
refs/heads/master | <file_sep><?php
class Remora_RemoraIntegration_Helper_Data extends Mage_Core_Helper_Abstract {
}<file_sep><?php
class Remora_RemoraIntegration_Block_Remora extends Mage_Core_Block_Template {
} | c494cd5fb5e44c0e4b52850556da887244b4fa15 | [
"PHP"
] | 2 | PHP | remoraUK/MagentoV1 | 88ad146f4a228a76c4feb36f4893140019253678 | 1584220356e8a4a4f467851387d0e8596100594f |
refs/heads/master | <file_sep>import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { format, parseISO } from 'date-fns';
import pt from 'date-fns/locale/pt';
import { withNavigationFocus } from 'react-navigation';
import { Alert } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import api from '~/services/api';
import { cancelSubscriptionRequest } from '~/store/modules/meetup/actions';
import { Container, List, Text } from './styles';
import Background from '~/components/Background';
import Header from '~/components/Header';
import Meetup from '~/components/Meetup';
import Loading from '~/components/Loading';
function Subscriptions({ isFocused }) {
const dispatch = useDispatch();
const [loading, setLoading] = useState(true);
const [refreshing] = useState(false);
const [meetups, setMeetups] = useState([]);
async function loadSubscriptions() {
const response = await api.get('subscriptions');
const subscriptions = response.data.map(subs => ({
...subs.meetup,
formattedDate: format(
parseISO(subs.meetup.date),
"d 'de' MMMM 'de' yyyy 'às' HH:mm",
{ locale: pt }
),
}));
setMeetups(subscriptions);
setLoading(false);
}
useEffect(() => {
if (isFocused) {
setLoading(true);
loadSubscriptions();
}
}, [isFocused]);
async function handleCancel(id) {
dispatch(cancelSubscriptionRequest(id));
// try {
// await api.delete(`subscriptions/${id}`);
// Alert.alert('Sucesso', 'Sua inscrição foi cancelada');
// loadSubscriptions();
// } catch (error) {
// Alert.alert('Error', 'Falha ao cancelar inscrição');
// }
}
return (
<Background>
<Container>
<Header />
{loading && <Loading />}
{!loading &&
(meetups.length ? (
<List
data={meetups}
keyExtractor={item => String(item.id)}
renderItem={({ item }) => (
<Meetup
data={item}
handleCancel={() => handleCancel(item.id)}
/>
)}
onRefresh={loadSubscriptions}
refreshing={refreshing}
/>
) : (
<Text>Você ainda não está inscrito em nenhum Meetup</Text>
))}
</Container>
</Background>
);
}
Subscriptions.navigationOptions = {
tabBarLabel: 'Inscrições',
tabBarIcon: ({ tintColor }) => (
<Icon name="local-offer" size={26} color={tintColor} />
),
};
export default withNavigationFocus(Subscriptions);
<file_sep># MeetApp
Projeto desenvolvido como desafio final e certificação do [Bootcamp GoStack da Rocketseat.](https://rocketseat.com.br/bootcamp)
## Certificado
[Certificado de conclusão](https://github.com/robertomendoncaa/meetapp/blob/master/certificate/certificado.pdf)
## Screenshots
[Login](https://github.com/robertomendoncaa/meetapp/blob/master/assets/screenshots/login.png), [Register](https://github.com/robertomendoncaa/meetapp/blob/master/assets/screenshots/register.png), [Dashboard](https://github.com/robertomendoncaa/meetapp/blob/master/assets/screenshots/dashboard.png),
[Details](https://github.com/robertomendoncaa/meetapp/blob/master/assets/screenshots/details.png),
[Profile](https://github.com/robertomendoncaa/meetapp/blob/master/assets/screenshots/profile.png).
## Instalação
### Requerimentos
Para rodar essa aplicação completa é necessário o [NodeJs](https://nodejs.org/en/), [ReactJs](https://reactjs.org), [React Native](https://facebook.github.io/react-native/), [Docker](https://www.docker.com) e emulador android ([Android Studio](https://developer.android.com/studio) ou [Genymotion](https://www.genymotion.com)).
### Comandos
#### Instalação da API/Backend
Clone o repositório e instale as dependências dentro da pasta `meetapp/api`
```
git clone https://github.com/robertomendoncaa/meetapp.git
cd meetapp/api
yarn
```
#### Criação dos containers Docker
Será utilizado **Postgres** para base de dados principal, **MongoDB** para notificações e **Redis** para monitoramento de filas.
```
docker run --name database -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=meetapp -p 5432:5432 -d postgres
docker run --name mongomeetapp -p 27017:27017 -d -t mongo
docker run --name redismeetapp -p 6379:6379 -d -t redis:alpine
```
> Se já possuir o **Postgres** instalado em sua máquina, fazer redirecionamento de porta `5433:5432`
#### Criação das tabelas do banco de dados
Cria as tabelas do banco de dados a partir das migrations da pasta `src/database/migrations`
```
yarn sequelize db:migrate
```
> Renomear arquivo `.env.example` para `.env`
> Incluir seus dados de configurações: banco de dados, host, senha, email...
#### Rodar API/Backend
```bash
# modo desenvolvimento
yarn dev
# monitoramento de filas, envio de e-mails
yarn queue
```
#### Instalação do Frontend
Instale as dependências dentro da pasta `meetapp/web`
```
cd meetapp/web
yarn
```
#### Rodar Frontend
```
yarn start
```
#### Instalação do Aplicativo android (app mobile)
```
cd meetapp/app
yarn
```
#### Rodar App
```
react-native run-android
```<file_sep>import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Input } from '@rocketseat/unform';
import { MdSave } from 'react-icons/md';
import * as Yup from 'yup';
import PropTypes from 'prop-types';
import { zonedTimeToUtc } from 'date-fns-tz';
import ImageInput from '~/components/ImageInput';
import DatePicker from '~/components/DatePicker';
import { editMeetupRequest } from '~/store/modules/meetup/actions';
import { Container } from './styles';
const schema = Yup.object().shape({
file_id: Yup.number().required(),
title: Yup.string().required('Insira o título do meetup'),
description: Yup.string().required('Descreva o seu meetup'),
date: Yup.date().required('Insira uma data'),
location: Yup.string().required('Insira o local'),
});
export default function EditMeetup({ match }) {
const meetupId = Number(match.params.id);
const meetups = useSelector(state => state.meetup.meetups);
const dispatch = useDispatch();
const meetup = meetups.find(m => m.id === meetupId);
const currentMeetup = {
title: meetup.title,
description: meetup.description,
date: zonedTimeToUtc(meetup.defaultDate),
location: meetup.location,
file: {
url: meetup.file.url,
id: meetup.file.id,
path: meetup.file.path,
},
};
function handleSubmit({ file_id, title, description, date, location }) {
dispatch(
editMeetupRequest(meetupId, file_id, title, description, date, location)
);
}
return (
<Container>
<Form schema={schema} initialData={currentMeetup} onSubmit={handleSubmit}>
<ImageInput name="file_id" />
<Input name="title" placeholder="Título do meetup" />
<Input name="description" placeholder="Descrição completa" multiline />
<DatePicker name="date" placeholder="Data do meetup" />
<Input name="location" placeholder="Localização" />
<button type="submit" onClick={handleSubmit}>
<MdSave size={20} /> Salvar meetup
</button>
</Form>
</Container>
);
}
EditMeetup.propTypes = {
match: PropTypes.shape().isRequired,
};
<file_sep>import styled from 'styled-components/native';
export const Container = styled.View`
background: #fff;
border-radius: 4px;
margin-bottom: 20px;
overflow: hidden;
opacity: ${props => (props.past ? 0.7 : 1)};
`;
export const Banner = styled.Image.attrs({
resizeMode: 'cover',
})`
width: 100%;
height: 140px;
align-content: stretch;
`;
export const Info = styled.View`
flex-direction: column;
padding: 10px;
margin-left: 15px;
`;
export const Title = styled.Text`
font-size: 18;
font-weight: bold;
color: #444;
`;
export const Date = styled.Text`
margin-top: 7px;
font-size: 13;
color: #999;
`;
export const Location = styled.Text`
margin-top: 5px;
font-size: 13;
color: #999;
`;
export const Organizer = styled.Text`
margin-top: 5px;
font-size: 14;
color: #999;
`;
export const ButtonSubscribe = styled.TouchableOpacity`
height: 42px;
margin: 10px;
padding: 10px;
border-radius: 4px;
align-self: stretch;
align-items: center;
background: green;
`;
export const ButtonText = styled.Text`
font-size: 16px;
font-weight: bold;
color: #fff;
`;
export const CancelButton = styled.TouchableOpacity`
height: 42px;
margin: 10px;
padding: 10px;
border-radius: 4px;
align-self: stretch;
align-items: center;
background: #F94D6A;
`;
<file_sep>import styled from 'styled-components/native';
export const Container = styled.SafeAreaView`
flex: 1;
`;
export const List = styled.FlatList.attrs({
showsVerticalScrollIndicator: false,
contentContainerStyle: { padding: 20 },
})``;
export const Text = styled.Text`
color: #999;
font-size: 18px;
text-align: center;
line-height: 26px;
margin: 30px;
`;
<file_sep>import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { MdLoyalty, MdAddCircleOutline, MdChevronLeft, MdChevronRight, MdHighlightOff } from 'react-icons/md';
import { toast } from 'react-toastify';
import { loadMeetupRequest } from '~/store/modules/meetup/actions';
import history from '~/services/history';
import { Container, Button, List, Title, Date, Pagination } from './styles';
export default function Dashboard() {
const dispatch = useDispatch();
const meetups = useSelector(state => state.meetup.meetups);
const [page, setPage] = useState(1);
useEffect(() => {
async function loadMeetup() {
try {
dispatch(loadMeetupRequest());
} catch (error) {
toast.error('Erro ao carregar meetups');
}
}
loadMeetup();
}, [dispatch]);
function hanldeNewMeetup() {
history.push('/meetup/new');
}
function handleDetails(meetup) {
history.push(`/meetup/${meetup.id}/details`);
}
return (
<Container>
<header>
<strong>Meetups</strong>
<Button onClick={hanldeNewMeetup}>
<MdAddCircleOutline size={20} color="#fff" /> Novo meetup
</Button>
</header>
{meetups.length > 0 ? (
<ul>
{meetups.map(meetup => (
<List key={meetup.id} onClick={() => handleDetails(meetup)} past={meetup.past}>
<Title>
<strong>{meetup.title}</strong>
</Title>
<Date>
<span>{meetup.formattedDate}</span>
<MdLoyalty size={26} color="#fff" />
</Date>
</List>
))}
</ul>
) : (
<p>
<MdHighlightOff size={32} color="#F94D6A" />
Não foi encontrado nenhum Meetup cadastrado
</p>
)}
<Pagination>
<Button>
<MdChevronLeft size={30} color="#fff" />
</Button>
<Button>
<MdChevronRight size={30} color="#fff" />
</Button>
</Pagination>
</Container>
);
}
<file_sep>import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { MdEdit, MdDeleteForever, MdInsertInvitation, MdPlace } from 'react-icons/md';
import { toast } from 'react-toastify';
import PropTypes from 'prop-types';
import { cancelMeetupRequest } from '~/store/modules/meetup/actions';
import history from '~/services/history';
import { Container, Button, Banner, Content } from './styles';
export default function MeetupDetails({ match }) {
const meetupId = Number(match.params.id);
const meetups = useSelector(state => state.meetup.meetups);
const dispatch = useDispatch();
const meetup = meetups.find(m => m.id === meetupId);
function handleEdit() {
history.push(`/meetup/${meetupId}/edit`);
}
async function handleCancel() {
try {
dispatch(cancelMeetupRequest(meetupId));
} catch (error) {
toast.error('Erro ao cancelar meetup');
}
}
return (
<Container>
<header>
<strong>{meetup.title}</strong>
<div className="btn">
<Button type="button" className="btn-blue" onClick={handleEdit}>
<MdEdit size={20} color="#fff" /> Editar
</Button>
<Button type="button" className="btn-red" onClick={handleCancel}>
<MdDeleteForever size={20} color="#fff" /> Cancelar
</Button>
</div>
</header>
<Content>
<Banner>
<img src={meetup.file.url} alt={meetup.title} />
</Banner>
<div className="description">{meetup.description}</div>
<div>
<div className="info">
<MdInsertInvitation size={20} color="#fff" />
<span>{meetup.formattedDate}</span>
<MdPlace size={20} color="#fff" />
<span>{meetup.location}</span>
</div>
</div>
</Content>
</Container>
);
}
MeetupDetails.propTypes = {
match: PropTypes.shape().isRequired,
};
<file_sep>import React from 'react';
import { parseISO, format } from 'date-fns';
import pt from 'date-fns/locale/pt';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {
Container,
Banner,
Info,
Title,
Date,
Location,
Organizer,
ButtonSubscribe,
ButtonText,
CancelButton
} from './styles';
export default function Meetup({ data, handleSubscribe, handleCancel }) {
return (
<Container past={data.past}>
<Banner source={{ uri: data.file.url }} />
<Info>
<Title>{data.title}</Title>
<Date>
<Icon name="event" size={14} color="#999" />
{format(parseISO(data.date), " d' de' MMMM yyyy', às' HH:mm'h",
{ locale: pt }
)}
</Date>
<Location>
<Icon name="location-on" size={14} color="#999" /> {data.location}
</Location>
<Organizer>
<Icon name="person" size={16} color="#999" /> Organizador: {data.user.name}
</Organizer>
</Info>
{handleSubscribe && !data.past && (
<ButtonSubscribe onPress={handleSubscribe}>
<ButtonText>Inscrever-se</ButtonText>
</ButtonSubscribe>
)}
{handleCancel && (
<CancelButton onPress={handleCancel}>
<ButtonText>Cancelar Inscrição</ButtonText>
</CancelButton>
)}
</Container>
);
}
<file_sep>import { all, takeLatest, call, put } from 'redux-saga/effects';
import { toast } from 'react-toastify';
import pt from 'date-fns/locale/pt';
import { format, parseISO } from 'date-fns';
import api from '~/services/api';
import history from '~/services/history';
import {
loadMeetupSuccess,
failureMeetup,
newMeetupSuccess,
cancelMeetupSuccess,
} from './actions';
export function* loadMeetup() {
try {
const response = yield call(api.get, 'meetups');
// const response = yield call(api.get, 'organizing');
const meetups = response.data.map(meetup => ({
...meetup,
defaultDate: meetup.date,
formattedDate: format(parseISO(meetup.date), "d 'de' MMMM',' 'às' HH'h'", {
locale: pt,
}),
}));
yield put(loadMeetupSuccess(meetups));
} catch (error) {
toast.error('Erro ao listar meetups');
yield put(failureMeetup());
}
}
export function* newMeetup({ payload }) {
try {
const { file_id, title, description, date, location } = payload;
yield call(api.post, 'meetups', {
file_id,
title,
description,
date,
location,
});
toast.success('Meetup criado com sucesso');
yield put(newMeetupSuccess());
history.push('/dashboard');
} catch (error) {
toast.error('Falha ao cadastrar o meetup, verifique seus dados!');
}
}
export function* cancelMeetup({ payload }) {
try {
const { id } = payload;
yield call(api.delete, `meetups/${id}`);
toast.success('Meetup cancelado com sucesso');
yield put(cancelMeetupSuccess());
history.push('/dashboard');
} catch (error) {
toast.error('Erro ao cancelar, verifique seus dados, apenas organizadores podem cancelar o meetup');
}
}
export function* editMeetup({ payload }) {
try {
const { id, file_id, title, description, date, location } = payload;
const meetup = {
id,
title,
description,
date,
location,
file_id,
};
yield call(api.put, `meetups/${id}`, meetup);
toast.success('Meetup editado com sucesso');
history.push('/dashboard');
} catch (error) {
toast.error('Falha ao atualizar, verifique seus dados, apenas organizadores podem editar o meetup');
}
}
export default all([
takeLatest('@meetup/LOAD_MEETUPS_REQUEST', loadMeetup),
takeLatest('@meetup/NEW_MEETUP_REQUEST', newMeetup),
takeLatest('@meetup/CANCEL_MEETUP_REQUEST', cancelMeetup),
takeLatest('@meetup/EDIT_MEETUP_REQUEST', editMeetup),
]);
<file_sep>import styled from 'styled-components/native';
export const Container = styled.SafeAreaView`
flex: 1;
`;
export const DateSelect = styled.View`
margin: 10px;
/* margin-bottom: 10px; */
flex-direction: row;
justify-content: center;
align-items: center;
`;
export const DateButton = styled.TouchableOpacity``;
export const DateFormatted = styled.Text`
margin: 0 15px;
color: #fff;
font-size: 20px;
font-weight: bold;
`;
export const List = styled.FlatList.attrs({
showsVerticalScrollIndicator: false,
contentContainerStyle: { padding: 20 },
})``;
export const Text = styled.Text`
color: #999;
font-size: 18px;
text-align: center;
line-height: 26px;
margin: 30px;
`;
<file_sep>### Docker Container
- docker run --name database_meetapp -e POSTGRES_PASSWORD=<PASSWORD> -e POSTGRES_DB=database_meetapp -p 5432:5432 -d postgres
- docker run --name mongomeetapp -p 27017:27017 -d -t mongo
- docker run --name redismeetapp -p 6379:6379 -d -t redis:alpine
### Sequelize Migrations
- yarn sequelize migration:create --name=create-users
- yarn sequelize migration:create --name=create-files
- yarn sequelize migration:create --name=add-avatar-field-to-users
- yarn sequelize migration:create --name=create-meetups
- yarn sequelize migration:create --name=create-subscriptions
- yarn sequelize db:migrate
- yarn sequelize db:migrate:undo
ou
- npx sequelize-cli db:migrate
- npx sequelize-cli db:migrate:undo
## Running
- yarn dev - development mode, NODE_ENV
- yarn queue - backgound jobs, send notification emails
| de530df985889eb526dd90a92d355d1e8e6d2b9b | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | robertomendoncaa/meetapp | 53513e0673002b98187114cf3b3954ae6cc6a57b | 3e42311f40e10894a4e1f49b126b948648286962 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Terraria;
using TShockAPI;
using WhiteXHazSkillz;
using WhiteXHazSkillz.Events;
namespace TestPlugin
{
public class TestSkill : WhiteXHazSkillz.Plugin
{
public EventRegister register;
public override string Name { get { return "Test Skill"; }}
public TestSkill(EventRegister register) : base(register)
{
this.register = register;
}
public override void Initialize()
{
register.RegisterSkillHandler<PlayerDamageEvent>(this, OnPlayerTakesDamage, EventType.PlayerTakesDamage);
register.RegisterSkillHandler<PlayerDamageEvent>(this, OnPlayerDoesDamage, EventType.PlayerDoesDamage);
register.RegisterSkillHandler<NpcKilledEvent>(this, OnPlayerKillsNPC, EventType.NpcIsKilled);
register.RegisterSkillHandler<NpcDamageEvent>(this, OnPlayerDamagesNPC, EventType.NpcTakesDamage);
TShockAPI.Commands.ChatCommands.Add(new Command("", AddSkillPoint, "ts"));
}
protected override void Dispose(bool disposing)
{
if(disposing)
register.DeregisterSkillHandler(this, EventType.PlayerTakesDamage);
}
private void AddSkillPoint(CommandArgs args)
{
try
{
SkillPlayer ply = PlayerManager.GetPlayer(args.Player.Index);
SkillInformation info = ply.GetSkillInformation(Name);
SkillInformation newInfo;
if (info == null)
newInfo = new SkillInformation() {Name = this.Name, Value = 0};
else
newInfo = new SkillInformation() {Name = this.Name, Value = info.Value + 1};
ply.SetSkillInformation(newInfo);
}
catch (Exception e)
{
//player is not logged in
Console.WriteLine(e.Message);
}
}
Random rand = new Random();
private void OnPlayerTakesDamage(PlayerDamageEvent args)
{
try
{
SkillPlayer player = PlayerManager.GetPlayer(args.HurtPlayerIndex);
SkillInformation info = player.GetSkillInformation(Name);
if (info == null)
{
info = new SkillInformation(){Name = this.Name, Value = 0};
player.SetSkillInformation(info);
return;
}
if(info.Value > 0 && !args.PVP)
FireRocket(player, args.Damage, 1);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void OnPlayerDoesDamage(PlayerDamageEvent args)
{
//hurt another player
}
private void OnPlayerKillsNPC(NpcKilledEvent args)
{
try
{
SkillPlayer player = PlayerManager.GetPlayer(args.PlayerIndex);
SkillInformation info = player.GetSkillInformation(Name);
if (info == null)
{
info = new SkillInformation() { Name = this.Name, Value = 0 };
player.SetSkillInformation(info);
return;
}
if (info.Value > 0)
{
FireRocket(player, args.Damage, info.Value);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void OnPlayerDamagesNPC(NpcDamageEvent args)
{
try
{
SkillPlayer player = PlayerManager.GetPlayer(args.PlayerIndex);
SkillInformation info = player.GetSkillInformation(Name);
if (info == null)
{
info = new SkillInformation() { Name = this.Name, Value = 0 };
player.SetSkillInformation(info);
return;
}
if (info.Value > 0)
{
double ratio = Math.Min(info.Value / 20.0, 1.0);
int health = (int)Math.Ceiling(ratio * args.Damage);
player.Player.Heal(health);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private void FireRocket(SkillPlayer origin, int damage, int strikes)
{
for (int i = 0; i < strikes; i++)
{
int xOffset = rand.Next(-10 * strikes, 10 * strikes);
int projectileIndex = Projectile.NewProjectile(origin.Player.TPlayer.position.X + xOffset,
origin.Player.TPlayer.position.Y - 300, 0, 3, 207, damage, 50, origin.Player.Index, 0, 0);
NetMessage.SendData(27, -1, -1, "", projectileIndex);
}
}
}
}
<file_sep>TShockSkillPlugin
=================
Add in trigger based reaction type skills to terraria via TShock.
Compile this just like any other TSHock plugin, and compile the TestPlugin skill like any class library.
Put both dlls in the plugins folder and boot it up.
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Streams;
using System.Linq;
using System.Reflection;
using System.Text;
using Terraria;
using TerrariaApi.Server;
using TShockAPI;
using WhiteXHazSkillz.Events;
namespace WhiteXHazSkillz
{
[ApiVersion(1, 17)]
public class MainSkill : TerrariaPlugin
{
private EventManager manager;
private PluginManager plugins;
public MainSkill(Main game) : base(game)
{
manager = new EventManager();
plugins = new PluginManager(manager);
}
public override void Initialize()
{
ServerApi.Hooks.NetGetData.Register(this, OnGetData);
TShockAPI.Hooks.PlayerHooks.PlayerPostLogin += HandlePlayerLogin;
ServerApi.Hooks.ServerLeave.Register(this, OnLeave);
plugins.LoadPlugins();
}
protected override void Dispose(bool disposing)
{
plugins.UnloadPlugins();
if (disposing)
{
ServerApi.Hooks.NetGetData.Deregister(this, OnGetData);
TShockAPI.Hooks.PlayerHooks.PlayerPostLogin -= HandlePlayerLogin;
ServerApi.Hooks.ServerLeave.Deregister(this, OnLeave);
}
base.Dispose(disposing);
}
private void OnGetData(GetDataEventArgs e)
{
if (e.Handled)
return;
PacketTypes type = e.MsgID;
var player = TShock.Players[e.Msg.whoAmI];
if (player == null || !player.ConnectionAlive)
{
e.Handled = true;
return;
}
if (player.RequiresPassword && type != PacketTypes.PasswordSend)
{
e.Handled = true;
return;
}
if ((player.State < 10 || player.Dead) && (int)type > 12 && (int)type != 16 && (int)type != 42 && (int)type != 50 &&
(int)type != 38 && (int)type != 21)
{
e.Handled = true;
return;
}
using (var data = new MemoryStream(e.Msg.readBuffer, e.Index, e.Length))
{
if (type == PacketTypes.PlayerDamage)
OnPlayerDamage(new GetDataHandlerArgs(player, data));
if (type == PacketTypes.NpcStrike)
OnNpcDamaged(new GetDataHandlerArgs(player, data));
}
}
private void OnNpcDamaged(GetDataHandlerArgs args)
{
var npcid = args.Data.ReadInt16();
var damage = args.Data.ReadInt16();
args.Data.ReadSingle();
args.Data.ReadInt8();
var crit = args.Data.ReadBoolean();
manager.InvokeHandler(new NpcDamageEvent() { Crit = crit, Damage = damage, PlayerIndex = args.Player.Index, NpcIndex = npcid }, EventType.NpcTakesDamage);
int damageDone = damage - (int)Math.Ceiling(Main.npc[npcid].defense*.5f);
damageDone = (crit ? damageDone*2 : damageDone);
if(damageDone >= Main.npc[npcid].life)
manager.InvokeHandler(new NpcKilledEvent() { Crit = crit, Damage = damage, PlayerIndex = args.Player.Index, NpcIndex = npcid }, EventType.NpcIsKilled);
}
private void OnPlayerDamage(GetDataHandlerArgs args)
{
var id = args.Data.ReadInt8();
args.Data.ReadInt8();
var dmg = args.Data.ReadInt16();
var pvp = args.Data.ReadBoolean();
var crit = args.Data.ReadBoolean();
manager.InvokeHandler(new PlayerDamageEvent() { Crit = crit, Damage = dmg, HurtPlayerIndex = args.Player.Index, DamagingEntityIndex = id, PVP = pvp }, EventType.PlayerTakesDamage);
if(pvp)
manager.InvokeHandler(new PlayerDamageEvent() { Crit = crit, Damage = dmg, HurtPlayerIndex = args.Player.Index, DamagingEntityIndex = id, PVP = pvp }, EventType.PlayerDoesDamage);
}
private void OnLeave(LeaveEventArgs args)
{
PlayerManager.RemovePlayer(args.Who);
}
private void HandlePlayerLogin(TShockAPI.Hooks.PlayerPostLoginEventArgs args)
{
try
{
SkillPlayer ply = PlayerManager.GetPlayer(args.Player.Index);
PlayerManager.SavePlayer(ply);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
var player = PlayerManager.LoadPlayer(args.Player);
PlayerManager.ActivatePlayer(player, player.Player.Index);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WhiteXHazSkillz.Events;
namespace WhiteXHazSkillz
{
interface EventDispatcher
{
void InvokeHandler<T>(T args, EventType type);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using TerrariaApi.Server;
using TShockAPI;
namespace WhiteXHazSkillz
{
class PluginManager
{
private readonly Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();
private static readonly List<Plugin> plugins = new List<Plugin>();
private EventRegister eventRegister;
public PluginManager(EventRegister eventRegister)
{
this.eventRegister = eventRegister;
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
public void LoadPlugins()
{
List<FileInfo> fileInfos = new DirectoryInfo(ServerApi.ServerPluginsDirectoryPath).GetFiles("*.dll").ToList();
foreach (FileInfo fileInfo in fileInfos)
{
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);
try
{
Assembly assembly;
// The plugin assembly might have been resolved by another plugin assembly already, so no use to
// load it again, but we do still have to verify it and create plugin instances.
if (!loadedAssemblies.TryGetValue(fileNameWithoutExtension, out assembly))
{
assembly = Assembly.Load(File.ReadAllBytes(fileInfo.FullName));
loadedAssemblies.Add(fileNameWithoutExtension, assembly);
}
foreach (Type type in assembly.GetExportedTypes())
{
if (!type.IsSubclassOf(typeof(Plugin)) || !type.IsPublic || type.IsAbstract)
continue;
Plugin pluginInstance;
try
{
pluginInstance = (Plugin)Activator.CreateInstance(type, eventRegister);
}
catch (Exception ex)
{
// Broken plugins better stop the entire server init.
throw new InvalidOperationException(
string.Format("Could not create an instance of plugin class \"{0}\".", type.FullName), ex);
}
plugins.Add(pluginInstance);
}
}
catch (Exception ex)
{
// Broken assemblies / plugins better stop the entire server init.
throw new InvalidOperationException(
string.Format("Failed to load assembly \"{0}\".", fileInfo.Name), ex);
}
}
foreach (Plugin current in plugins)
{
try
{
current.Initialize();
}
catch (Exception ex)
{
// Broken plugins better stop the entire server init.
throw new InvalidOperationException(string.Format(
"Plugin \"{0}\" has thrown an exception during initialization.", current.Name), ex);
}
}
}
public void UnloadPlugins()
{
foreach (Plugin plugin in plugins)
{
try
{
plugin.Dispose();
}
catch (Exception ex)
{
Log.Error(string.Format("Plugin \"{0}\" has thrown an exception while being disposed:\n{1}", plugin.Name, ex));
}
}
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string fileName = args.Name.Split(',')[0];
string path = Path.Combine(ServerApi.ServerPluginsDirectoryPath, fileName + ".dll");
try
{
if (File.Exists(path))
{
Assembly assembly;
if (!loadedAssemblies.TryGetValue(fileName, out assembly))
{
assembly = Assembly.Load(File.ReadAllBytes(path));
loadedAssemblies.Add(fileName, assembly);
}
return assembly;
}
}
catch (Exception ex)
{
Log.Error(string.Format("Error on resolving assembly \"{0}.dll\":\n{1}", fileName, ex));
}
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhiteXHazSkillz.Events
{
public enum EventType
{
PlayerTakesDamage,
PlayerDoesDamage,
NpcTakesDamage,
NpcIsKilled
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhiteXHazSkillz
{
interface EventHandlerList
{
void Register(Plugin p, object t);
void Deregister(Plugin p);
void Invoke(object args);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WhiteXHazSkillz.Events;
namespace WhiteXHazSkillz
{
public interface EventRegister
{
void DeregisterSkillHandler(Plugin plugin, EventType type);
void RegisterSkillHandler<T>(Plugin plugin, Action<T> handler, EventType type);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhiteXHazSkillz
{
public class PlayerDamageEvent
{
public int Damage { get; set; }
public bool PVP { get; set; }
public bool Crit { get; set; }
public int HurtPlayerIndex { get; set; }
public int DamagingEntityIndex { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhiteXHazSkillz
{
public abstract class Plugin : IDisposable
{
public virtual string Name { get { return ""; }}
abstract public void Initialize();
public Plugin(EventRegister register)
{
}
~Plugin()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
public override bool Equals(object obj)
{
return GetType() == obj.GetType() && Equals((Plugin)obj);
}
public bool Equals(Plugin p)
{
return Name == p.Name;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Data.Sqlite;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using TShockAPI;
using TShockAPI.DB;
namespace WhiteXHazSkillz
{
public class PlayerManager
{
private static SkillPlayer[] players = new SkillPlayer[255];
private static IDbConnection database;
static PlayerManager()
{
if (TShock.Config.StorageType.ToLower() == "sqlite")
{
string sql = Path.Combine(TShock.SavePath, "tshock.sqlite");
database = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
}
else if (TShock.Config.StorageType.ToLower() == "mysql")
{
try
{
var hostport = TShock.Config.MySqlHost.Split(':');
database = new MySqlConnection();
database.ConnectionString =
String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
hostport[0],
hostport.Length > 1 ? hostport[1] : "3306",
TShock.Config.MySqlDbName,
TShock.Config.MySqlUsername,
TShock.Config.MySqlPassword
);
}
catch (MySqlException ex)
{
Log.Error(ex.ToString());
throw new Exception("MySql not setup correctly");
}
}
else
{
throw new Exception("Invalid storage type");
}
var table = new SqlTable("PlayerSkills",
new SqlColumn("UserAccountName", MySqlDbType.VarChar, 50) { Primary = true },
new SqlColumn("SkillInformation", MySqlDbType.Text)
);
var creator = new SqlTableCreator(database,
database.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
}
public static List<SkillPlayer> GetPlayers()
{
lock (players)
{
var list = new List<SkillPlayer>(players.ToList());
return list;
}
}
public static SkillPlayer GetPlayer(int index)
{
lock (players)
{
if (players[index] == null)
throw new InvalidOperationException(String.Format("Player at index {0} is null.", index));
return players[index];
}
}
public static void ActivatePlayer(SkillPlayer player, int index)
{
lock (players)
{
players[index] = player;
}
}
public static void RemovePlayer(int index)
{
SkillPlayer player = null;
lock (players)
{
if (players[index] != null)
{
player = new SkillPlayer(players[index]);
}
players[index] = null;
}
if(player != null)
SavePlayer(player);
}
public static void SavePlayer(SkillPlayer player)
{
try
{
database.Query("REPLACE INTO PlayerSkills (UserAccountName, SkillInformation) VALUES (@0, @1)", player.AccountName,
JsonConvert.SerializeObject(player.Skills()));
}
catch (Exception e)
{
TShockAPI.Log.ConsoleError("Failed to save player: {0}", e.Message);
}
}
public static SkillPlayer LoadPlayer(TSPlayer player)
{
var list = LoadSkills(player.UserAccountName);
SkillPlayer ply = new SkillPlayer(player, list);
return ply;
}
public static List<SkillInformation> LoadSkills(string name)
{
try
{
using (var reader = database.QueryReader("SELECT SkillInformation FROM PlayerSkills WHERE UserAccountName=@0", name)
)
{
if (reader.Read())
{
List<SkillInformation> info =
JsonConvert.DeserializeObject<List<SkillInformation>>(reader.Get<string>("SkillInformation"));
return info;
}
}
}
catch (Exception e)
{
TShockAPI.Log.ConsoleError("Failed to load player: {0}", e.Message);
}
return new List<SkillInformation>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using WhiteXHazSkillz.Events;
namespace WhiteXHazSkillz
{
class EventManager : EventDispatcher, EventRegister
{
public Dictionary<EventType, EventHandlerList> handlerList = new Dictionary<EventType, EventHandlerList>();
public void InvokeHandler<T>(T args, EventType type)
{
if (!handlerList.ContainsKey(type))
return;
EventHandlerList handlers = handlerList[type];
handlers.Invoke(args);
}
public void DeregisterSkillHandler(Plugin plugin, EventType type)
{
if (!handlerList.ContainsKey(type))
return;
EventHandlerList handlers = handlerList[type];
handlers.Deregister(plugin);
}
public void RegisterSkillHandler<T>(Plugin plugin, Action<T> handler, EventType type)
{
EventHandlerList handlers;
if (!handlerList.ContainsKey(type))
handlerList.Add(type, new SkillEventHandlerList<T>());
handlers = handlerList[type];
handlers.Register(plugin, handler);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace WhiteXHazSkillz
{
class SkillEventHandlerList<T> : EventHandlerList
{
readonly Dictionary<Plugin, Action<T>> handlers = new Dictionary<Plugin, Action<T>>();
public void Register(Plugin p, object t)
{
lock (handlers)
{
if (handlers.ContainsKey(p))
handlers.Remove(p);
handlers.Add(p, (Action<T>) t);
}
}
public void Deregister(Plugin p)
{
lock (handlers)
{
if (handlers.ContainsKey(p))
handlers.Remove(p);
}
}
public void Invoke(object args)
{
lock (handlers)
{
foreach (var handler in handlers.Values)
handler.Invoke((T) args);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WhiteXHazSkillz
{
public class NpcDamageEvent
{
public int Damage { get; set; }
public bool Crit { get; set; }
public int NpcIndex { get; set; }
public int PlayerIndex { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Terraria;
using TShockAPI;
namespace WhiteXHazSkillz
{
public class SkillPlayer
{
private List<SkillInformation> acquiredSkills = new List<SkillInformation>();
public string AccountName { get; set; }
public TSPlayer Player { get; set; }
public SkillPlayer(TSPlayer ply, List<SkillInformation> skills)
{
Player = ply;
AccountName = ply.UserAccountName;
acquiredSkills = skills;
}
public SkillPlayer(SkillPlayer old)
{
lock (old.acquiredSkills)
{
Player = old.Player;
AccountName = old.Player.UserAccountName;
acquiredSkills = old.acquiredSkills;
}
}
public SkillInformation GetSkillInformation(string name)
{
lock (acquiredSkills)
{
return acquiredSkills.FirstOrDefault(s => s.Name == name);
}
}
public void SetSkillInformation(SkillInformation info)
{
lock (acquiredSkills)
{
SkillInformation old = acquiredSkills.FirstOrDefault(s => s.Name == info.Name);
if (old != null)
{
acquiredSkills.Remove(old);
}
acquiredSkills.Add(info);
}
}
public List<SkillInformation> Skills()
{
lock (acquiredSkills)
{
return new List<SkillInformation>(acquiredSkills);
}
}
}
}
| b9af2090f5c3ce3fa1c564308a44b5720a4aa622 | [
"Markdown",
"C#"
] | 15 | C# | qipa/TShockSkillPlugin | bd28a2b4db759449a8777c9c11501943a018f57b | 6e0ff2456d2a78926067f63dbce5f61a956f8d78 |
refs/heads/master | <repo_name>rockycabaero/hellohaus<file_sep>/app1/www/js/services.js
starter.service('FbUser', function(UserAuth, $q) {
return {
name: function() {
var deffered = $q.defer();
FB.api(
"/"+UserAuth.get().userID,
function (response) {
if (response && !response.error) {
deffered.resolve(response);
}
}
);
return deffered.promise;
},
picture: function() {
var deffered = $q.defer();
FB.api(
"/"+UserAuth.get().userID+"/picture",
function (response) {
if (response && !response.error) {
deffered.resolve(response);
}
}
);
return deffered.promise;
}
};
});<file_sep>/app1/www/js/app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var starter = angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs).
// The reason we default this to hidden is that native apps don't usually show an accessory bar, at
// least on iOS. It's a dead giveaway that an app is using a Web View. However, it's sometimes
// useful especially with forms, though we would prefer giving the user a little more room
// to interact with the app.
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// Set the statusbar to use the default style, tweak this to
// remove the status bar on iOS or change it to use white instead of dark colors.
StatusBar.styleDefault();
}
});
})
.controller('mainCtrl', function($scope, UserAuth, FbUser, $q) {
UserAuth.loadFbSDK().then(function() {
$scope.FbLoaded = true;
});
$scope.fbLogin = function() {
FB.login(function(response) {
if(response.status === "connected") {
var authResponse = response.authResponse;
UserAuth.save(authResponse);
//save user name
FbUser.name().then(function(user) {
UserAuth.save(user, 'userName');
});
//save user picture
FbUser.picture().then(function(picture) {
UserAuth.save(picture, 'userPicture');
});
//wait for all data to be loaded
$q.all([authResponse, FbUser.name(), FbUser.picture()])
.then(function() {
UserAuth.goToIndex();
});
} else {
console.log('failed to login');
}
}, {scope: 'email'});
};
})
.controller('homeCtrl', function($scope, UserAuth) {
console.log(window.localStorage);
UserAuth.loadFbSDK();
$scope.getUserStatus = function() {
UserAuth.checkSession();
};
$scope.getUser = function() {
$scope.userName = UserAuth.get('userName');
$scope.userPicture = UserAuth.get('userPicture');
};
$scope.logOut = function() {
UserAuth.flush();
};
}); | db17e74d81a4097ecb5de1ade475236780f0f21c | [
"JavaScript"
] | 2 | JavaScript | rockycabaero/hellohaus | 46ef1fea220f181381b4b9185330799f230ed135 | 76b3b2e9d07084d61c3c72a9b44bc8940b0eae6e |
refs/heads/master | <repo_name>pratikgangan/pratik_solution<file_sep>/venv/Scripts/app.py
from flask import Flask, request
from Movies import movieMetadata
app = Flask(__name__)
@app.route('/')
def index():
return 'Server Works!'
@app.route('/api/movie/<string:name>')
def api(name):
merged=movieMetadata(name)
return merged
@app.route('/api/movie/')
def search():
search_value= request.args.get('search_field')
return '<h1> it is {}</h1>'.format(search_value)
<file_sep>/venv/Scripts/Movie.py
import glob, os
import requests
import json
#listing all the jason files in current foloder
# Opening JSON file
def movieMetadata(i):
f = open('C:/Users/Help/Source/Repos/pratik_solution2/movies/'+i+'.json')
# returns JSON object as
# a dictionary
df2 = json.load(f)
id=df2['imdbId']
# Closing file
f.close()
response=requests.get('http://www.omdbapi.com/?i='+id+'&apikey=68fd98ab')
df1=(response.json())
#new json payload
merged={}
#transformations
merged['Plot']=df1['Plot']
merged['Title']=df1['Title']
merged['Runntime']=df2['duration']
tempd={}
templ=[]
tempd2={}
for i,j in df2['userrating'].items():
tempd[i]=str(j)
# print(d)
for i,j in tempd.items():
tempd2['Source']=str(i)
tempd2['Value']=str(j)
templ.append(tempd2)
tempd2=tempd2.copy()
merged['Ratings']= df1['Ratings']+templ
merged['Actors']=df1['Actors'].split(', ')
merged['Director']=df1['Director'].split(', ')
merged['Writer']=df1['Writer'].split(', ')
merged['Year']=df1['Year']
merged['Released']=df1['Released']
merged['Genre']=df1['Genre']
merged['Language']=df1['Language']
merged['Country']=df1['Country']
merged['Awards']=df1['Awards']
merged['Metascore']=df1['Metascore']
merged['imdbRating']=df1['imdbRating']
merged['imdbVotes']=df1['imdbVotes']
merged['imdbID']=df1['imdbID']
merged['Type']=df1['Type']
merged['DVD']=df1['DVD']
merged['BoxOffice']=df1['BoxOffice']
merged['Production']=df1['Production']
merged['Website']=df1['Website']
merged['Response']=df1['Response']
merged['id']=df2['id']
merged['languges']=df2['languages']
print(merged)
return merged
| ec894678e15bd633106b798923f75cb08618919d | [
"Python"
] | 2 | Python | pratikgangan/pratik_solution | c4b08393a4efeb698e3017d5441b5953c056cebe | 89c584d5b9e6b024f139998085bedce9748f2dc3 |
refs/heads/master | <repo_name>eklitzke/drakebot<file_sep>/bot.cc
// -*- C++ -*-
// Copyright 2012, <NAME> <<EMAIL>>
#include "./bot.h"
#include <glog/logging.h>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/random.hpp>
#include <cassert>
#include <ctime>
#include <fstream>
#include <iterator>
using boost::asio::ssl::context;
using boost::asio::ip::tcp;
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket;
namespace drakebot {
boost::mt19937 rng;
boost::uniform_real<double> uniform(0.0, 1.0);
void InitializeRNG() {
struct timeval tv;
gettimeofday(&tv, nullptr);
rng.seed(tv.tv_usec);
}
IRCRobot::IRCRobot(boost::asio::io_service &service,
boost::asio::ssl::context &context,
const std::string "ations_file,
unsigned int interval,
const std::string &nick,
const std::string &password)
:io_service_(service), timer_(service), socket_(service, context),
quotations_file_(quotations_file), nick_(nick), password_(<PASSWORD>),
interval_(interval), state_(SEND_PASS), rand_(rng, uniform) {
reply_ = new char[MAX_LENGTH];
memset(static_cast<void *>(reply_), 0, sizeof(reply_));
}
IRCRobot::~IRCRobot() {
delete reply_;
}
void IRCRobot::Connect(boost::asio::ip::tcp::resolver::iterator
endpoint_iterator) {
boost::asio::ip::tcp::endpoint endpoint = *endpoint_iterator;
socket_.lowest_layer().async_connect(
endpoint,
boost::bind(&IRCRobot::HandleConnect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
}
void IRCRobot::HandleConnect(const boost::system::error_code& error,
tcp::resolver::iterator
endpoint_iterator) {
if (!error) {
socket_.async_handshake(boost::asio::ssl::stream_base::client,
boost::bind(&IRCRobot::HandleHandshake, this,
boost::asio::placeholders::error));
} else if (endpoint_iterator != boost::asio::ip::tcp::resolver::iterator()) {
socket_.lowest_layer().close();
boost::asio::ip::tcp::endpoint endpoint = *endpoint_iterator;
socket_.lowest_layer().async_connect(
endpoint,
boost::bind(&IRCRobot::HandleConnect, this,
boost::asio::placeholders::error, ++endpoint_iterator));
} else {
LOG(FATAL) << "Connect failed: " << error;
exit(1);
}
}
void IRCRobot::HandleHandshake(const boost::system::error_code& error) {
if (!error) {
if (password_.size()) {
std::string s = "PASS ";
s.append(password_);
SendLine(s);
} else {
state_ = SEND_NICK;
std::string s = "NICK ";
s.append(nick_);
SendLine(s);
}
boost::asio::async_read_until(
socket_, request_, '\n',
boost::bind(
&IRCRobot::HandleRead, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
} else {
LOG(FATAL) << "Handshake failed: " << error;
}
}
void IRCRobot::SendLine(const std::string &msg) {
assert(msg.size() < MAX_LENGTH);
memcpy(reply_, msg.c_str(), msg.size());
reply_[msg.size()] = '\n';
boost::asio::async_write(socket_,
boost::asio::buffer(reply_, msg.size() + 1),
boost::bind(
&IRCRobot::HandleWrite, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void IRCRobot::HandleRead(const boost::system::error_code &error,
size_t bytes_transferred) {
std::string line(
(std::istreambuf_iterator<char>(&request_)),
std::istreambuf_iterator<char>());
DLOG(INFO) << "Saw line " << line;
if (line.substr(0, 5) == "PING ") {
std::string::size_type colon_pos = line.find(":");
assert(colon_pos != std::string::npos);
std::string server_name = line.substr(colon_pos + 1, std::string::npos);
std::string command = "PONG ";
command.append(server_name);
SendLine(command);
}
}
void IRCRobot::HandleWrite(const boost::system::error_code& error,
size_t bytes_transferred) {
if (error) {
LOG(FATAL) << "Write error: " << error;
}
std::string s;
DLOG(INFO) << "Wrote " << bytes_transferred << " bytes";
switch (state_) {
case SEND_PASS:
state_ = SEND_NICK;
s = "NICK ";
s.append(nick_);
SendLine(s);
break;
case SEND_NICK:
state_ = SEND_USER;
SendLine("USER drakebot drakebot drakebot drakebot");
break;
case SEND_USER:
state_ = SEND_JOIN;
JoinChannels();
break;
case SEND_JOIN:
state_ = SEND_QUOTATIONS;
waiting_ = false;
break;
case SEND_QUOTATIONS:
break;
}
if (!waiting_ && state_ == SEND_QUOTATIONS) {
waiting_ = true;
unsigned int wait_time = PickWaitTime();
DLOG(INFO) << "Scheduling next quotation for " << wait_time <<
" seconds from now";
timer_.expires_from_now(boost::posix_time::seconds(wait_time));
timer_.async_wait(boost::bind(&IRCRobot::HandleTimeout, this,
boost::asio::placeholders::error));
}
}
void IRCRobot::HandleTimeout(const boost::system::error_code &error) {
DLOG(INFO) << "In handle timeout";
SendQuotation();
waiting_ = false;
}
void IRCRobot::AddChannel(const std::string &channel) {
channels_.push_back(channel);
}
bool IRCRobot::SendMessage(const std::string &msg) {
std::vector<std::string>::iterator cit;
std::vector<std::string>::iterator mit;
std::vector<std::string> messages;
std::string::size_type pos = 0;
while (true) {
std::string::size_type next = msg.find('\n', pos);
if (next == std::string::npos) {
messages.push_back(msg.substr(pos, next));
break;
} else {
messages.push_back(msg.substr(pos, next - pos));
pos = next + 1;
}
}
for (cit = channels_.begin(); cit != channels_.end(); ++cit) {
for (mit = messages.begin(); mit != messages.end(); ++mit) {
std::string s = "PRIVMSG ";
s.append(*cit);
s.append(" :\001ACTION croons: \"");
s.append(*mit);
s.append("\"\001");
SendLine(s);
}
}
return true;
}
bool IRCRobot::SendQuotation() {
std::string quotation = GetQuotation();
return SendMessage(quotation);
}
std::string IRCRobot::GetQuotation() {
std::string chosen = "ERROR";
std::ifstream quotations_file(quotations_file_.c_str());
int i = 1;
std::string q;
std::string s;
// Try to pick a random quotation from the file
if (quotations_file.is_open()) {
while (quotations_file.good()) {
getline(quotations_file, s);
if (s.size()) {
if (q.size()) {
q.push_back('\n');
q.append(s);
} else {
q.append(s);
}
} else {
if (i == 1) {
chosen = q;
} else if (rand_() < (1 / static_cast<double>(i))) {
chosen = q;
}
q.clear();
i++;
}
}
}
return chosen;
}
void IRCRobot::JoinChannels() {
std::vector<std::string>::iterator it;
for (it = channels_.begin(); it != channels_.end(); ++it) {
std::string s = "JOIN ";
s.append(*it);
SendLine(s);
}
}
unsigned int IRCRobot::PickWaitTime() {
double davg = static_cast<double>(interval_);
return static_cast<unsigned int>(davg * (0.5 + rand_()));
}
}
<file_sep>/bot.h
// -*- C++ -*-
// Copyright 2012, <NAME> <<EMAIL>>
#ifndef BOT_H_
#define BOT_H_
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/random.hpp>
#include <string>
#include <vector>
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket;
using boost::asio::ip::tcp;
namespace drakebot {
enum { MAX_LENGTH = 8096 };
enum SendState {
SEND_PASS,
SEND_NICK,
SEND_USER,
SEND_JOIN,
SEND_QUOTATIONS
};
void InitializeRNG();
class IRCRobot {
public:
explicit IRCRobot(boost::asio::io_service &service,
boost::asio::ssl::context &context,
const std::string "ations_file,
unsigned int interval,
const std::string &nick = "drakebot",
const std::string &password = "");
~IRCRobot();
void Connect(boost::asio::ip::tcp::resolver::iterator);
bool Authenticate(const std::string &, const std::string &,
const std::string &);
void AddChannel(const std::string &);
private:
boost::asio::io_service &io_service_;
boost::asio::deadline_timer timer_;
ssl_socket socket_;
const std::string quotations_file_;
const std::string nick_;
const std::string password_;
const unsigned int interval_;
SendState state_;
boost::variate_generator<boost::mt19937&, boost::uniform_real<double> > rand_;
bool waiting_;
std::vector<std::string> channels_;
char *reply_;
boost::asio::streambuf request_;
void HandleConnect(const boost::system::error_code&, tcp::resolver::iterator);
void HandleHandshake(const boost::system::error_code&);
void HandleWrite(const boost::system::error_code&, size_t);
void HandleTimeout(const boost::system::error_code&);
void HandleRead(const boost::system::error_code &, size_t);
void SendLine(const std::string &);
unsigned int PickWaitTime();
bool SendMessage(const std::string &);
bool SendQuotation();
void JoinChannels();
std::string GetQuotation();
};
}
#endif // BOT_H_
<file_sep>/main.cc
// -*- C++ -*-
// Copyright 2012, <NAME> <<EMAIL>>
#include <stdio.h>
#include <syslog.h>
#include <boost/asio/ssl.hpp>
#include <boost/lexical_cast.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <cstdlib>
#include <string>
#include <vector>
#include "./bot.h"
using boost::asio::ip::resolver_query_base;
using boost::asio::ssl::context;
DEFINE_bool(daemon, false, "Run as a daemon");
DEFINE_string(host, "irc.freenode.net", "Host to connect to");
DEFINE_int32(port, 6697, "Port to connect to");
DEFINE_string(password, "", "<PASSWORD>");
DEFINE_string(nick, "drakebot", "Nick to use");
DEFINE_string(channel, "", "Channel to connect to");
DEFINE_bool(ssl, true, "Use SSL");
DEFINE_string(quotations, "quotations.txt", "Quotations file to use");
DEFINE_int32(interval, 43200, "Mean interval to use");
int main(int argc, char **argv) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
if (!FLAGS_channel.size()) {
printf("Must specify a channel with --channel\n");
return 1;
}
if (!FLAGS_ssl) {
printf("Sorry, right now only --ssl is supported\n");
return 1;
}
char *real_path_name = realpath(FLAGS_quotations.c_str(), nullptr);
if (real_path_name == nullptr) {
printf("Failed to resolve path to quotations file, \"%s\"\n",
FLAGS_quotations.c_str());
return 1;
}
std::string quotations_path(real_path_name, strlen(real_path_name));
free(real_path_name);
boost::asio::io_service io_service;
if (FLAGS_daemon) {
if (pid_t pid = fork()) {
if (pid > 0) {
// We're in the parent process and need to exit.
exit(0);
} else {
syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
return 1;
}
}
setsid();
chdir("/");
umask(0);
// A second fork ensures the process cannot acquire a controlling terminal.
if (pid_t pid = fork()) {
if (pid > 0) {
exit(0);
} else {
syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
return 1;
}
}
// Close the standard streams
close(0);
close(1);
close(2);
// Inform the io_service that we have finished becoming a daemon.
io_service.notify_fork(boost::asio::io_service::fork_child);
}
drakebot::InitializeRNG();
// initiate the name resolution
std::string str_port = boost::lexical_cast<std::string>(FLAGS_port);
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(
FLAGS_host, str_port.c_str(), resolver_query_base::numeric_service);
boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
// set the SSL context
context ctx(boost::asio::ssl::context::sslv23);
ctx.set_default_verify_paths();
drakebot::IRCRobot robot(io_service, ctx, quotations_path, FLAGS_interval,
FLAGS_nick, FLAGS_password);
std::vector<std::string>::iterator it;
std::string channel_name = FLAGS_channel;
if (channel_name[0] != '#') {
channel_name.insert(0, "#");
}
robot.AddChannel(channel_name);
robot.Connect(iterator);
io_service.run();
return 0;
}
<file_sep>/drakebot.gyp
{
'target_defaults': {
'type': 'executable',
'cflags': ['-Wall', '-std=c++11'],
'conditions': [
['OS=="linux"', {
'ldflags': [
'-pthread',
],
'libraries': [
'-lboost_system',
'-lcrypto',
'-lgflags',
'-lglog',
'-lssl',
]
}]],
'sources': [
'bot.cc',
'main.cc'
]
},
'targets': [
{
# drakebot with debugging symbols, logging
'target_name': 'drakebot',
'cflags': ['-g'],
'defines': [ 'DEBUG', ],
},
{
# optimized drakebot
'target_name': 'drakebot_opt',
'cflags': ['-fomit-frame-pointer'],
'defines': [ 'NDEBUG', ],
'postbuilds': [
{
'postbuild_name': 'strip optimized binary',
'action': [
'strip',
'-s',
'$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'],
},
],
},
],
}
<file_sep>/README.md
Drakebot is a C++ IRC robot. It's built using boost::asio.
To build, first build the Makefile using [GYP](http://code.google.com/p/gyp/)
like this:
gyp --depth=. drakebot.gyp
Then run `make drakebot` (or `make drakebot_opt`). Your binary will (probably)
be located at `./out/Default/drakebot`.
You'll need the following libraries installed to successfully build:
* [boost](http://www.boost.org/)
* [gflags](http://code.google.com/p/gflags/)
* [glog](http://code.google.com/p/google-glog/)
Look at the `--help` or `--helpshort` options to get an idea on how to invoke
the binary.
| 8df00a0d5b862c3b8856bf4fb93d51b95cc6165d | [
"Markdown",
"Python",
"C++"
] | 5 | C++ | eklitzke/drakebot | bbcadff0a61b7b62e96e7a906ed6f7e5d4a37232 | a2cdfa8a63cde251671c1d8745fbba13d4ff2084 |
refs/heads/master | <repo_name>Thogi45/Support_Generator<file_sep>/Support_Shape.py
from stl import mesh
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.pyplot import autoscale
import numpy as np
import Support_Generator
def extremity_creation_triangle(axe,List):
'''
determined 2 faces exterimities of the support along x or y axis
'''
Shape_listfinal=np.shape(List)
if axe=='xy':
Faces=np.zeros((3,12))
for j in range (0,3):
for i in range(0,2):
if j==0 or j==1:
#First line is the face 1254 (j=0) and 2nd face is the face 2365 (j=1)
Faces[j,3*i]= List[0][i+j][0]
Faces[j,3*i+1]= List[0][i+j][1]
Faces[j,3*i+2]= List[0][i+j][2]
Faces[j,6+3*i]= List[1][1-i+j][0]
Faces[j,6+3*i+1]= List[1][1-i+j][1]
Faces[j,6+3*i+2]= List[1][1-i+j][2]
else:
Faces[j,3*i]= List[0][i*2][0]
Faces[j,3*i+1]= List[0][i*2][1]
Faces[j,3*i+2]= List[0][i*2][2]
Faces[j,6+3*i]= List[1][2-2*i][0]
Faces[j,6+3*i+1]= List[1][2-2*i][1]
Faces[j,6+3*i+2]= List[1][2-2*i][2]
elif axe=='z':
Faces=np.zeros((2,12))
for j in range (0,2):
for i in range(0,2):
#First is the face 1231 and 2nd face 4564
Faces[j,3*i]= List[j][i][0]
Faces[j,3*i+1]= List[j][i][1]
Faces[j,3*i+2]= List[j][i][2]
Faces[j,6+3*i]= List[j][2-2*i][0]
Faces[j,6+3*i+1]= List[j][2-2*i][1]
Faces[j,6+3*i+2]= List[j][2-2*i][2]
else:
return "axe is not well define"
# we need to cross the upper points to have a face (Face is point [1265] and not [1256]), that's why we have 1-i in the indices of ListFinal
return Faces
def extremity_creation(axe,List):
'''
determined 2 faces exterimities of the support along x or y axis
'''
Shape_listfinal=np.shape(List)
Faces=np.zeros((Shape_listfinal[0],Shape_listfinal[2]*2))
if axe=='x':
for j in range (0,Shape_listfinal[0]):
for i in range(0,np.int(Shape_listfinal[1]/2)):
#First line is the face 1265 (j=0) and 2nd face is the face 3487 (j=1)
Faces[j,3*i]= List[0][i+j*2][0]
Faces[j,3*i+1]= List[0][i+j*2][1]
Faces[j,3*i+2]= List[0][i+j*2][2]
Faces[j,6+3*i]= List[1][1+j*2-i][0]
Faces[j,6+3*i+1]= List[1][1+j*2-i][1]
Faces[j,6+3*i+2]= List[1][1+j*2-i][2]
elif axe=='y':
for i in range(0,np.int(Shape_listfinal[1]/2)):
#First is the face 2376
Faces[0,3*i]= List[0][i+1][0]
Faces[0,3*i+1]= List[0][i+1][1]
Faces[0,3*i+2]= List[0][i+1][2]
Faces[0,6+3*i]= List[1][2-i][0]
Faces[0,6+3*i+1]= List[1][2-i][1]
Faces[0,6+3*i+2]= List[1][2-i][2]
#2nd face is 1485
Faces[1,3*i]= List[0][i*3][0]
Faces[1,3*i+1]= List[0][i*3][1]
Faces[1,3*i+2]= List[0][i*3][2]
Faces[1,6+3*i]= List[1][3-3*i][0]
Faces[1,6+3*i+1]= List[1][3-3*i][1]
Faces[1,6+3*i+2]= List[1][3-3*i][2]
elif axe=='z':
for j in range (0,Shape_listfinal[0]):
for i in range(0,np.int(Shape_listfinal[1]/2)):
#First line is the face 1234 (j=0) and 2nd face is the face 5678(j=1)
Faces[j,3*i]= List[j][i][0]
Faces[j,3*i+1]= List[j][i][1]
Faces[j,3*i+2]= List[j][i][2]
Faces[j,6+3*i]= List[j][i+2][0]
Faces[j,6+3*i+1]= List[j][2+i][1]
Faces[j,6+3*i+2]= List[j][2+i][2]
else:
return "axe is not well define"
# we need to cross the upper points to have a face (Face is point [1265] and not [1256]), that's why we have 1-i in the indices of ListFinal
return Faces
def thetraedral_simple_support(List):
Facesxy=extremity_creation_triangle('xy',List)
Facesz=extremity_creation_triangle('z',List)
Faces= np.concatenate((Facesxy,Facesz),axis=0)
return Faces
def Rectangular_simple_support(List):
Facesx=extremity_creation('x',List)
Facesy=extremity_creation('y',List)
Facesz=extremity_creation('z',List)
Faces= np.concatenate((Facesx,Facesy,Facesz),axis=0)
return Faces
def line_support(axes,List,p):
'''
Creation of a line support
with p the gap between each face of the grid
'''
Faces= extremity_creation(axes, List)
#Coefficient i1 i2 i3 and d1 d2 d3 d4 aim to manage the surface creations when top and bottom are not parallel
i1=i2=i3=i4=d1=d2=d3=d4=0
m=np.zeros((1,1))
if Faces[0,2]>Faces[1,2]:
i1=-1
d1=np.int(np.abs(Faces[0,2]-Faces[1,2]))
m=np.append(m,np.array([[2]]),axis=0)
elif Faces[0,2]<Faces[1,2]:
i1=1
d1=np.int(np.abs(Faces[0,2]-Faces[1,2]))
m=np.append(m,np.array([[2]]),axis=0)
else:
i1=0
if Faces[0,5]>Faces[1,5]:
i2=-1
d2=np.int(np.abs(Faces[0,5]-Faces[1,5]))
m=np.append(m,np.array([[5]]),axis=0)
elif Faces[0,5]<Faces[1,5]:
i2=1
d2=np.int(np.abs(Faces[0,5]-Faces[1,5]))
m=np.append(m,np.array([[5]]),axis=0)
else:
i2=0
if Faces[0,8]>Faces[1,8]:
i3=-1
d3=np.int(np.abs(Faces[0,8]-Faces[1,8]))
m=np.append(m,np.array([[8]]),axis=0)
elif Faces[0,8]<Faces[1,8]:
i3=1
d3=np.int(np.abs(Faces[0,8]-Faces[1,8]))
m=np.append(m,np.array([[8]]),axis=0)
else:
i3=0
if Faces[0,11]>Faces[1,11]:
i4=-1
d4=np.int(np.abs(Faces[0,11]-Faces[1,11]))
m=np.append(m,np.array([[11]]),axis=0)
elif Faces[0,11]<Faces[1,11]:
i4=1
d4=np.int(np.abs(Faces[0,11]-Faces[1,11]))
m=np.append(m,np.array([[11]]),axis=0)
else:
i4=0
if axes!='z':
if i1==i2==i3==i4==0:
pass
else:
a=m[1,0]
b=m[2,0]
if Faces[0,np.int(a)]!=Faces[0,np.int(b)]:
i1=i2=i3=i4=0
if axes == 'x':
nx=np.int(np.abs(Faces[0,1]-Faces[1,4])*(1/p))-1
l=2
while nx == -1:
nx=np.int(np.abs(Faces[0,0]-Faces[1,3*l+1])*(1/p))-1
l+=1
a=np.zeros((nx,12))
if Faces[0,1]>Faces[1,1]:
for i in range(1, nx+1):
a[i-1,:]=np.array([Faces[0,0],Faces[0,1]-i*p,Faces[0,2]+(i*d1*i1)/nx,Faces[0,3],Faces[0,4]-i*p,Faces[0,5]+(i*d2*i2)/nx,Faces[0,6],Faces[0,7]-i*p,Faces[0,8]+(i*d3*i3)/nx,Faces[0,9],Faces[0,10]-i*p,Faces[0,11]+(i*d4*i4)/nx])
elif Faces[0,1]<Faces[1,1]:
for i in range(1, nx+1):
a[i-1,:]=np.array([Faces[0,0],Faces[0,1]+i*p,Faces[0,2]+(i*d1*i1)/nx,Faces[0,3],Faces[0,4]+i*p,Faces[0,5]+(i*d2*i2)/nx,Faces[0,6],Faces[0,7]+i*p,Faces[0,8]+(i*d3*i3)/nx,Faces[0,9],Faces[0,10]+i*p,Faces[0,11]+(i*d4*i4)/nx])
Faces= np.insert(Faces,1, a, axis=0)
#elif Faces[0,1]!= Faces[0,4] or Faces[0,1]!= Faces[0,7] or Faces[0,1]!= Faces[0,10]:
elif axes == 'y':
ny=np.int(np.abs(Faces[0,0]-Faces[1,3])*(1/p))-1
l=2
while ny == -1:
ny=np.int(np.abs(Faces[0,1]-Faces[1,3*l])*(1/p))-1
l+=1
a=np.zeros((ny,12))
if Faces[0,0]>Faces[1,0]:
for i in range(1, ny+1):
a[i-1,:]=np.array([Faces[0,0]-i*p,Faces[0,1],Faces[0,2]+(i*d1*i1)/ny,Faces[0,3]-i*p,Faces[0,4],Faces[0,5]+(i*d2*i2)/ny,Faces[0,6]-i*p,Faces[0,7],Faces[0,8]+(i*d3*i3)/ny,Faces[0,9]-i*p,Faces[0,10],Faces[0,11]+(i*d4*i4)/ny])
elif Faces[0,0]<Faces[1,0]:
for i in range(1, ny+1):
a[i-1,:]=np.array([Faces[0,0]+i*p,Faces[0,1],Faces[0,2]+(i*d1*i1)/ny,Faces[0,3]+i*p,Faces[0,4],Faces[0,5]+(i*d2*i2)/ny,Faces[0,6]+i*p,Faces[0,7],Faces[0,8]+(i*d3*i3)/ny,Faces[0,9]+i*p,Faces[0,10],Faces[0,11]+(i*d4*i4)/ny])
Faces= np.insert(Faces,1, a, axis=0)
elif axes=='z':
nz=np.int(np.abs(Faces[0,2]-Faces[1,2])*(1/p))-1
a=np.zeros((nz,12))
if Faces[0,2]>Faces[1,2]:
for i in range(1, nz+1):
a[i-1,:]=np.array([Faces[0,0],Faces[0,1],Faces[0,2]+(i*d1*i1)/nz,Faces[0,3],Faces[0,4],Faces[0,5]+(i*d2*i2)/nz,Faces[0,6],Faces[0,7],Faces[0,8]+(i*d3*i3)/nz,Faces[0,9],Faces[0,10],Faces[0,11]+(i*d4*i4)/nz])
elif Faces[0,2]<Faces[1,2]:
for i in range(1, nz+1):
a[i-1,:]=np.array([Faces[0,0],Faces[0,1],Faces[0,2]+(i*d1*i1)/nz,Faces[0,3],Faces[0,4],Faces[0,5]+(i*d2*i2)/nz,Faces[0,6],Faces[0,7],Faces[0,8]+(i*d3*i3)/nz,Faces[0,9],Faces[0,10],Faces[0,11]+(i*d4*i4)/nz])
Faces= np.insert(Faces,1, a, axis=0)
return Faces
def gridxy(List,p):
'''
Creation a grid along x and y axis
'''
Faces_x=line_support('x',List,p)
Faces_y=line_support('y',List,p)
Faces=np.concatenate((Faces_x,Faces_y),axis=0)
return Faces
def grid3D(List,p):
'''
Creation of a grid along x, y and z-axis
'''
Faces_x=line_support('x',List,p)
Faces_y=line_support('y',List,p)
Faces_z=line_support('z',List,p)
Faces=np.concatenate((Faces_x,Faces_y,Faces_z),axis=0)
return Faces
def ZigZag(List,p):
'''
Creation of the ZigZag shape
'''
Facesx=line_support('x',List,p)
Facesx= np.delete(Facesx,0,0)
Facesx_shape=Facesx.shape
Facesx= np.delete(Facesx,Facesx_shape[0]-1,0)
Faces_all_y=extremity_creation('y',List)
i1=i2=d1=d2=0
m=np.zeros((1,1))
if (Faces_all_y[0,2]>Faces_all_y[0,5] and np.abs(Faces_all_y[0,1])>np.abs(Faces_all_y[0,4])) or (Faces_all_y[0,2]<Faces_all_y[0,5]and np.abs(Faces_all_y[0,1])<np.abs(Faces_all_y[0,4])):
i1=-1
d1=np.int(np.abs(Faces_all_y[0,2]-Faces_all_y[0,5]))
m=np.append(m,np.array([[2]]),axis=0)
elif Faces_all_y[0,2]<Faces_all_y[0,5] and np.abs(Faces_all_y[0,1])>np.abs(Faces_all_y[0,4]):
i1=1
d1=np.int(np.abs(Faces_all_y[0,2]-Faces_all_y[0,5]))
m=np.append(m,np.array([[2]]),axis=0)
else:
i1=0
if Faces_all_y[0,8]>Faces_all_y[0,11]:
i2=-1
d2=np.int(np.abs(Faces_all_y[0,8]-Faces_all_y[0,11]))
m=np.append(m,np.array([[5]]),axis=0)
elif Faces_all_y[0,8]<Faces_all_y[0,11]:
i2=1
d2=np.int(np.abs(Faces_all_y[0,8]-Faces_all_y[0,11]))
m=np.append(m,np.array([[5]]),axis=0)
else:
i2=0
ny=np.int(np.abs(Faces_all_y[0,1]-Faces_all_y[0,4])*(1/(p*2)))
a1=np.zeros((ny,12))
a2=np.zeros((ny,12))
if Faces_all_y[0,1]>Faces_all_y[0,4]:
p=-p
else:
pass
for i in range(0, ny):
if i==0:
a1[i,:]=np.array([Faces_all_y[0,0],Faces_all_y[0,1]+i*(p*2),Faces_all_y[0,2],Faces_all_y[0,3],Faces_all_y[0,1]+p,Faces_all_y[0,5]+d1+(i1*d1)/ny,Faces_all_y[0,6],Faces_all_y[0,1]+p,Faces_all_y[0,8],Faces_all_y[0,9],Faces_all_y[0,10]+i*(p*2),Faces_all_y[0,11]+d2+(i2*d2)/ny])
a2[i,:]=np.array([Faces_all_y[1,0],Faces_all_y[1,1]+p,Faces_all_y[1,2],Faces_all_y[1,3],Faces_all_y[1,1]+2*p,Faces_all_y[1,5]+d1+(i1*d1)/ny,Faces_all_y[1,6],Faces_all_y[1,1]+2*p,Faces_all_y[1,8],Faces_all_y[1,9],Faces_all_y[1,10]+p,Faces_all_y[1,11]+d2+(i2*d2)/ny])
else:
a1[i,:]= np.array([Faces_all_y[0,0],Faces_all_y[0,1]+i*(p*2),a1[i-1,2]+(i1*d1)/ny,Faces_all_y[0,3],a1[i-1,1]+3*p,a1[i-1,5]+(i1*d1)/ny,Faces_all_y[0,6],a1[i-1,1]+3*p,a1[i-1,8]+(i2*d2)/ny,Faces_all_y[0,9],Faces_all_y[0,10]+i*(p*2),a1[i-1,11]+(i2*d2)/ny])
a2[i,:]=np.array([Faces_all_y[1,0],a2[i-1,1]+p*2,a2[i-1,2]+(i1*d1)/ny,Faces_all_y[1,3],a2[i-1,1]+3*p,a2[i-1,5]+(i1*d1)/ny,Faces_all_y[1,6],a2[i-1,1]+3*p,a2[i-1,8]+(i2*d2)/ny,Faces_all_y[1,9],a2[i-1,10]+p*2,a2[i-1,11]+(i2*d2)/ny])
a= np.concatenate((a1,a2),axis=0)
Faces=np.concatenate((Facesx,a),axis=0)
return Faces
def plot(FacesMatrix,my_mesh,xy_limmin,xy_limmax,z_limmin,z_limmax):
FacesMatrix_shape=np.shape(FacesMatrix)
figure2 = plt.figure()
ax2 = figure2.add_subplot(111, projection='3d')
verts=[[FacesMatrix[i,j*3:j*3+3] for j in range(4)] for i in range(FacesMatrix_shape[0])]
ax2.add_collection3d(Poly3DCollection(verts, alpha=0.25, facecolors='#800000', edgecolors='brown'))
ax2.add_collection3d(mplot3d.art3d.Poly3DCollection(my_mesh.vectors, edgecolors='navy'))
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')
ax2.set_xlim(xy_limmin,xy_limmax)
ax2.set_ylim(xy_limmin,xy_limmax)
ax2.set_zlim(z_limmin,z_limmax)
plt.show()
return
def plot_mesh(my_mesh):
figure2 = plt.figure()
ax2 = figure2.add_subplot(111, projection='3d')
ax2.add_collection3d(mplot3d.art3d.Poly3DCollection(my_mesh.vectors, edgecolors='navy'))
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')
ax2.set_xlim(-30,30)
ax2.set_ylim(-30,30)
ax2.set_zlim(0,60)
plt.show()
return
<file_sep>/Support_finder.py
from stl import mesh
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
import math
def needed_support_Bridge_rule (normal, vertices, critical_length):
'''
5 mm rule for bridges
If a bridge is more than 5 mm in length, it requires 3D printing support structure
'''
Shape_normal= np.shape(normal)
Shape_vertices=np.shape(vertices)
Unit_vector_normals=np.zeros((Shape_normal[0], 3))
dot_product=np.zeros((Shape_normal[0], 1))
angle=np.zeros((Shape_normal[0],1))
Vector_reference = np.array([[0],[0],[1]])
ab=np.zeros((0,9))
for i in range (0,Shape_normal[0]):
Unit_vector_normals[i,:]= normal[i,:]/np.linalg.norm(normal[i,:])
dot_product[i,:]=np.dot(Unit_vector_normals[i,:],Vector_reference)
angle[i,:]= np.arccos(dot_product[i,:])
if np.abs(angle[i,:])==0 or np.abs(angle[i,:])==np.pi:
b= np.array([vertices[i,:]])
ab=np.append(ab,b,axis=0)
else:
pass
ab_shape=np.shape(ab)
for j in range (0, ab_shape[0]):
for k in range (0, ab_shape[0]):
d1=0
d2=0
d3=0
for l in range (0,2):
if ab[j,2] != ab[k,3*l+2]:
d1+=1
else:
pass
if ab[j,5] != ab[k,3*l+2]:
d2+=1
else:
pass
if ab[j,8] != ab[k,3*l+2]:
d3+=1
else:
pass
Required_support = ["a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a11","a12","a13","a14","a15","a16","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a29","a30"]
i=0
m=0
while i<ab_shape[0]:
if i==0:
Required_support[m]=ab[i,:]
m+=1
else:
x1=x2=x3=0
y1=y2=y3=0
z1=z2=z3=0
if ab[i,0] != ab[i-1,0]:
x1+=1
else:
pass
if ab[i,3] != ab[i-1,3]:
x2+=1
else:
pass
if ab[i,6] != ab[i-1,6]:
x3+=1
else:
pass
if ab[i,1] != ab[i-1,1]:
y1+=1
else:
pass
if ab[i,4] != ab[i-1,4]:
y2+=1
else:
pass
if ab[i,7] != ab[i-1,7]:
y3+=1
else:
pass
if ab[i,2] != ab[i-1,2]:
z1+=1
else:
pass
if ab[i,5] != ab[i-1,5]:
z2+=1
else:
pass
if ab[i,8] != ab[i-1,8]:
z3+=1
else:
pass
if (x1+x2+x3+y1+y2+y3+z1+z2+z3)>3:
Required_support[m]=ab[i,:]
m+=1
else:
b=np.array(ab[i,:])
Required_support[m-1]=np.vstack((Required_support[m-1],b))
i+=1
Required_support=Required_support[0:m]
Shape_required_support=np.shape(Required_support)
from Support_Generator import FindContour
Contour = FindContour(Required_support)
Shape_contour=np.shape(Contour)
p=0
#print(Contour[1,:,:])
n=0
for j in range(0,m):
for k in range (0,m):
if j != k:
if (Contour[j][0][:2] == Contour[k][0][:2]).all() or (Contour[j][0][:2] == Contour[k][1][:2]).all() or (Contour[j][0][:2] == Contour[k][2][:2]).all() or (Contour[j][0][:2] == Contour[k][3][:2]).all():
if (Contour[j][1][:2] == Contour[k][0][:2]).all() or (Contour[j][1][:2] == Contour[k][1][:2]).all() or (Contour[j][1][:2] == Contour[k][2][:2]).all() or (Contour[j][1][:2] == Contour[k][3][:2]).all():
if (Contour[j][2][:2] == Contour[k][0][:2]).all() or (Contour[j][2][:2] == Contour[k][1][:2]).all() or (Contour[j][2][:2] == Contour[k][2][:2]).all() or (Contour[j][2][:2] == Contour[k][3][:2]).all():
if (Contour[j][3][:2] == Contour[k][0][:2]).all() or (Contour[j][3][:2] == Contour[k][1][:2]).all() or (Contour[j][3][:2] == Contour[k][2][:2]).all() or (Contour[j][3][:2] == Contour[k][3][:2]).all():
if Contour[j][0][2] <= 1e-5 or Contour[k][0][2] <= 1e-5:
Required_support[j]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
Required_support[k]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
elif Contour[j][0][2] > Contour[k][0][2]:
Required_support[j]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
else:
Required_support[k]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
'''Condition sur la distance'''
for l in range (0, Shape_contour[1]):
for p in range (0, Shape_contour[1]):
if Contour[j][0][0]!=Contour[j][l][0] and Contour[j][0][1]!=Contour[j][p][1]:
if abs(Contour[j][0][0]-Contour[j][l][0])<=critical_length and abs(Contour[j][0][1]-Contour[j][p][1])<=critical_length:
Required_support[j]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
else:
n+=1
pass
if (m % 2) == 0:
pass
else:
Required_support[j]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
Required_support[k]=np.zeros((Shape_required_support[1],Shape_required_support[2]))
n=0
Required_support=Required_support[0:n]
return Required_support
def support_45deg_rule (normal, vertices, critical_angle):
'''
45° rule for overhangs
If an overhang tilts at an angle less than 45 degress from the vertical it requires 3D printing support structures.
'''
#angle between reference z-axis and normal
Shape_normal= np.shape(normal)
Shape_vertices=np.shape(vertices)
Unit_vector_normals=np.zeros((Shape_normal[0], 3))
dot_product=np.zeros((Shape_normal[0], 1))
angle=np.zeros((Shape_normal[0],1))
Vector_reference = np.array([[0],[0],[1]])
#Mesh point that doesn't respect the 45° rule
A=np.zeros((1,9))
An=np.zeros((1,1))
a=np.zeros((0,9))
x=np.zeros((0,3))
y=np.zeros((0,3))
z=np.zeros((0,3))
t=0
for i in range (0,Shape_normal[0]):
Unit_vector_normals[i,:]= normal[i,:]/np.linalg.norm(normal[i,:])
dot_product[i,:]=np.dot(Unit_vector_normals[i,:],Vector_reference)
angle[i,:]= np.arccos(dot_product[i,:])
if np.abs(angle[i,:]) >= np.pi/2 + (critical_angle*np.pi/180) and np.pi + (critical_angle*np.pi/180) and np.abs(angle[i,:]) != np.pi:
b= np.array([vertices[i,:]])
a=np.append(a,b,axis=0)
t+=1
else:
angle[i,:]=An[0,0]
pass
Shape_support=np.shape(a)
l=0
a_shape=np.shape(a)
normal_support = np.zeros((0,3))
for i in range (0, Shape_vertices[0]):
for j in range (0, a_shape[0]):
if vertices[i,0]==a[j,0] and vertices[i,1]==a[j,1] and vertices[i,2]==a[j,2] and vertices[i,3]==a[j,3] and vertices[i,4]==a[j,4] and vertices[i,5]==a[j,5] and vertices[i,6]==a[j,6] and vertices[i,7]==a[j,7] and vertices[i,8]==a[j,8]:
b= np.array([normal[i,:]])
normal_support=np.append(normal_support,b,axis=0)
else:
pass
Shape_normal_support=np.shape(normal_support)
Unit_vector_normals_support=np.zeros((Shape_normal_support[0], 3))
dot_product_support=np.zeros((Shape_normal_support[0], 1))
angle_support=np.zeros((Shape_normal_support[0],1))
for i in range (0, Shape_normal_support[0]):
Unit_vector_normals_support[i,:]= normal_support[i,:]/np.linalg.norm(normal_support[i,:])
dot_product_support[i,:]=np.dot(Unit_vector_normals_support[i,:],Vector_reference)
angle_support[i,:]= np.arccos(dot_product_support[i,:])
i=0
m=0
Required_support = [1]*a_shape[0]
while i<a_shape[0]:
if i==0:
#Required_support.append(a[i,:])
Required_support[m]=np.array([a[i,:]])
m+=1
else:
x1=x2=x3=0
y1=y2=y3=0
z1=z2=z3=0
if a[i,0] != a[i-1,0]:
x1+=1
else:
pass
if a[i,3] != a[i-1,3]:
x2+=1
else:
pass
if a[i,6] != a[i-1,6]:
x3+=1
else:
pass
if a[i,1] != a[i-1,1]:
y1+=1
else:
pass
if a[i,4] != a[i-1,4]:
y2+=1
else:
pass
if a[i,7] != a[i-1,7]:
y3+=1
else:
pass
if a[i,2] != a[i-1,2]:
z1+=1
else:
pass
if a[i,5] != a[i-1,5]:
z2+=1
else:
pass
if a[i,8] != a[i-1,8]:
z3+=1
if angle_support[i] != angle_support[i-1]:
#Required_support.append(a[i,:])
Required_support[m]=np.array([a[i,:]])
m+=1
elif (x1+x2+x3+y1+y2+y3+z1+z2+z3)>3:
#Required_support.append(a[i,:])
Required_support[m]=np.array([a[i,:]])
m+=1
else:
b=np.array(a[i,:])
Required_support[m-1]=np.vstack((Required_support[m-1],b))
i+=1
Required_support=Required_support[0:m]
return Required_support
<file_sep>/User_Interface.py
import PyQt5
import PyQt5.QtWidgets
from tkinter import *
from tkinter import filedialog
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import Support_Generator
import mayavi
import vtk
from tvtk.api import tvtk
from mayavi import mlab
from stl import mesh
class Interface(Frame):
"""Our principal windows
All the widgets are stored as attributes in this window."""
def __init__(self, fenetre, **kwargs):
Frame.__init__(self, fenetre, **kwargs)
self.config(background='light steel blue')
self.pack()
self.STL = ""
self.OK = [False, False, False, False,False]
self.angle_verif = DoubleVar()
self.length_verif = DoubleVar()
self.PA = DoubleVar()
self.angle=0.0
self.bridge=0.0
self.shape = 0
self.pathN = 0.0
self.message3=Label(self,text=" Choose the Length for the Bridge Rule\n\n(must be between 4.5 to 5.5)",background='light steel blue')
self.message3.grid(column=0,row=4,pady=5,sticky=W)
self.photo = PhotoImage(file="Support_Generator.gif")
self.canvasA = Canvas(self,width=532,height=60,highlightcolor='medium blue',highlightbackground='medium blue')
self.canvasA.create_image(534/2,64/2,image=self.photo)
self.canvasA.grid(row=0,column=0,columnspan=7)
# Création de nos widgets
self.message = Label(self,justify=LEFT, text=" Choose a STL file",background='light steel blue')
self.message.grid(column=0,row=1,pady=0,rowspan=2,sticky=W)
self.message1 = Label(self, text="",bg='white',width=10)
self.message1.grid(column=1,row=1,pady=5,columnspan=3,rowspan=2)
self.bouton_OK = Button(self, text="Validate", command=self.disp)
self.bouton_OK.grid(column=5,row=2,pady=5,padx=5)
self.bouton_Plot = Button(self, text="View", command=self.View)
self.bouton_Plot.grid(column=6,row=1,pady=5,padx=5,rowspan=2)
self.bouton_Browse = Button(self, text="Browse",command=self.click)
self.bouton_Browse.grid(column=5,row=1,pady=5,padx=5)
self.message4=Label(self,text="Choose the Overhang Angle\n\n (must be between 40 to 50)",background='light steel blue')
self.message4.grid(column=0,row=3,pady=5,sticky=W)
self.angle_texte = Entry(self,textvariable = self.angle_verif)
self.angle_texte.grid(column=1,row=3,pady=5,columnspan=3)
self.bouton_OK2 = Button(self, text="Validate", command=self.disp2)
self.bouton_OK2.grid(column=5,row=3,columnspan=2,pady=5)
self.angle_texte = Entry(self,textvariable = self.length_verif)
self.angle_texte.grid(column=1,row=4,pady=5,columnspan=3)
self.bouton_OK3 = Button(self, text="Validate", command=self.disp3)
self.bouton_OK3.grid(column=5,row=4,columnspan=2,pady=5)
self.support = Label(self,justify=LEFT, text=" Choose your support shape",background='light steel blue')
self.support.grid(row=5,rowspan=2,column=0,pady=5,sticky=W)
self.canvas = Canvas(self,width=32,height=32,background='light steel blue',highlightbackground='light steel blue')
self.canvas.create_rectangle(2,2,30,30,fill="black")
self.canvas.grid(row=5,column=1)
self.canvas2 = Canvas(self,width=32,height=32,background='light steel blue',highlightbackground='light steel blue')
self.canvas2.create_line(2,2,29,2,fill="black")
self.canvas2.create_line(2,2,2,6,fill="black")
self.canvas2.create_line(2,6,29,6,fill="black")
self.canvas2.create_line(29,6,29,10,fill="black")
self.canvas2.create_line(29,10,2,10,fill="black")
self.canvas2.create_line(2,10,2,14,fill="black")
self.canvas2.create_line(2,14,29,14,fill="black")
self.canvas2.create_line(29,14,29,18,fill="black")
self.canvas2.create_line(2,18,29,18,fill="black")
self.canvas2.create_line(2,18,2,22,fill="black")
self.canvas2.create_line(2,22,29,22,fill="black")
self.canvas2.create_line(29,22,29,26,fill="black")
self.canvas2.create_line(2,26,29,26,fill="black")
self.canvas2.create_line(2,26,2,30,fill="black")
self.canvas2.create_line(2,30,29,30,fill="black")
self.canvas2.grid(row=5,column=2,padx=2)
self.canvas3 = Canvas(self,width=32,height=32,background='light steel blue',highlightbackground='light steel blue')
self.canvas3.create_line(5,2,5,29,fill="black")
self.canvas3.create_line(15,2,15,29,fill="black")
self.canvas3.create_line(25,2,25,29,fill="black")
self.canvas3.create_line(2,15,29,15,fill="black")
self.canvas3.create_line(2,5,29,5,fill="black")
self.canvas3.create_line(2,25,29,25,fill="black")
self.canvas3.grid(row=5,column=3,padx=2)
self.var_choix = StringVar()
self.choix_1 = Radiobutton(self, text="", variable=self.var_choix, value=1,background='light steel blue')
self.choix_2 = Radiobutton(self, text="", variable=self.var_choix, value=2,background='light steel blue')
self.choix_3= Radiobutton(self, text="", variable=self.var_choix, value=3,background='light steel blue')
self.choix_1.grid(row=6,column=1)
self.choix_2.grid(row=6,column=2)
self.choix_3.grid(row=6,column=3)
self.bouton_OK4 = Button(self, text="Validate", command=self.disp4)
self.bouton_OK4.grid(column=5,row=5,columnspan=2,rowspan=2,pady=5)
self.path = Label(self,justify=LEFT, text=" Choose your path",background='light steel blue')
self.path.grid(column=0,row=8,pady=5,sticky=W)
self.path1 = Entry(self,textvariable = self.PA)
self.path1.grid(column=1,row=8,pady=5,columnspan=3)
self.bouton_OK5 = Button(self, text="Validate", command=self.disp5)
self.bouton_OK5.grid(column=5,row=8,columnspan=2,pady=5)
self.bouton_Generate = Button(self, text='Generate',command=self.generate)
self.bouton_Generate.grid(column=2,row=9,columnspan=3,pady=5)
def click(self):
self.message1["text"]=filedialog.askopenfilename(title="Choose a STL file",filetypes=[("STL","*.stl")])
self.message1["width"]=len(self.message1["text"])
def disp(self):
if self.message1["text"]!="":
self.bouton_OK["fg"] = 'green'
self.OK[0]=True
self.STL = self.message1["text"]
else:
self.bouton_OK["fg"] = 'red'
self.STL = self.message1["text"]
def disp2(self):
try:
nbr=self.angle_verif.get()
if nbr>=40 and nbr<=50:
self.OK[1] = True
self.bouton_OK2['fg']="green"
self.angle = nbr
else:
self.bouton_OK2['fg']="red"
except:# If the user write something different than an integer we display "Please enter a number" and the loop start again.
self.bouton_OK2['fg']="red"
def disp3(self):
try:
nbr=self.length_verif.get()
if nbr>=4.5 and nbr<=5.5:
self.bouton_OK3['fg']="green"
self.OK[2] = True
else:
self.bouton_OK3['fg']="red"
except:# If the user write something different than an integer we display "Please enter a number" and the loop start again.
self.bouton_OK3['fg']="red"
def disp4(self):
try:
nbr=self.var_choix.get()
self.bouton_OK4['fg'] = "green"
self.OK[3]=True
if nbr=="":
self.bouton_OK4['fg'] = "red"
except:
self.bouton_OK4['fg'] = "red"
def disp5(self):
try:
nbr=float(self.PA.get())
self.bouton_OK5['fg'] = "green"
self.OK[4]=True
self.pathN = nbr
if nbr=="":
self.bouton_OK5['fg'] = "red"
except:
self.bouton_OK5['fg'] = "red"
def generate(self):
i = 0
for ij in range(len(self.OK)):
if self.OK[ij]== True:
i = i+1
if i == 5:
self.STL = self.message1["text"]
self.angle = self.angle_verif.get()
self.bridge = self.length_verif.get()
self.shape = int(self.var_choix.get())
my_mesh= mesh.Mesh.from_file(self.STL)
normal=my_mesh.normals
vertices=my_mesh.points
from Support_finder import support_45deg_rule
from Support_finder import needed_support_Bridge_rule
support_angle=support_45deg_rule(normal,vertices,self.angle)
support_bridge=needed_support_Bridge_rule(normal,vertices,self.bridge)
i=0
p=len(support_bridge)
k=0
while i<p:
if all(support_bridge[k][0,0:9]== 0):
del support_bridge[k]
else:
k=k+1
p=p-1
liste_support=[]
liste_support=support_bridge+support_angle
ListeContour=[]
from Support_Generator import AreasWithSameAngle, FindContour, Projection
from Support_Shape import thetraedral_simple_support, Rectangular_simple_support, gridxy, ZigZag, plot
for i in range(len(liste_support)):
A=AreasWithSameAngle(liste_support[i])
ListeContour.append(FindContour(A))
ListeProjete=Projection(ListeContour)
ListeProjete_shape=np.shape(ListeProjete)
if len(ListeProjete)==0:
print("you do not need any support")
else:
n=0
Faces=np.zeros((0,12))
if ListeProjete_shape[2]==3:
while n <ListeProjete_shape[0]:
The=thetraedral_simple_support(ListeProjete[:][n][:][:])
Faces= np.append(Faces,The,axis=0)
n+=1
plot(Faces,my_mesh,-50,50,0,80)
else:
if self.shape==1:
while n <ListeProjete_shape[0]:
Rec=Rectangular_simple_support(ListeProjete[:][n][:][:])
Faces= np.append(Faces,Rec,axis=0)
n+=1
elif self.shape==3:
while n <ListeProjete_shape[0]:
Grid=gridxy(ListeProjete[:][n][:][:],float(self.pathN))
Faces= np.append(Faces,Grid,axis=0)
n+=1
elif self.shape==2:
while n <ListeProjete_shape[0]:
ZZ=ZigZag(ListeProjete[:][n][:][:],float(self.pathN))
Faces= np.append(Faces,ZZ,axis=0)
n+=1
plot(Faces,my_mesh,-30,30,0,50)
def View(self):
if self.bouton_OK["fg"] == 'green':
reader = tvtk.STLReader()
reader.file_name = self.STL
reader.update()
surf = reader.output
mlab.pipeline.surface(surf)
mlab.show()
k=0
else:
self.bouton_OK["fg"] = 'red'
fenetre = Tk()
fenetre.title('Support Generator')
interface = Interface(fenetre)
interface.mainloop()
<file_sep>/Main.py
import os,sys, glob
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import time
from stl import mesh, Mesh
import numpy as np
from Support_finder import support_45deg_rule
from Support_finder import needed_support_Bridge_rule
from Support_Generator import AreasWithSameAngle
from Support_Generator import FindContour
from Support_Generator import Projection
from Support_Shape import line_support
from Support_Shape import Rectangular_simple_support
from Support_Shape import thetraedral_simple_support
from Support_Shape import gridxy
from Support_Shape import ZigZag
from Support_Shape import plot
from Support_Shape import plot_mesh
from Locate_STL import ShapeChoice
print("----------------------------------------\n")
print(" SUPPORT GENERATOR \n")
print("by <NAME> and <NAME> ")
print("----------------------------------------\n")
print("You need to choose the STL file you want to generate supports with.")
from Locate_STL import FindSTL
STL = FindSTL()
my_mesh= mesh.Mesh.from_file(STL)
normal=my_mesh.normals
vertices= my_mesh.points
support_angle=support_45deg_rule(normal,vertices,45)
support_bridge=needed_support_Bridge_rule(normal,vertices,5)
i=0
p=len(support_bridge)
k=0
while i<p:
if all(support_bridge[k][0,0:9]== 0):
del support_bridge[k]
else:
k=k+1
p=p-1
liste_support=[]
liste_support=support_bridge+support_angle
ListeContour=[]
for i in range(len(liste_support)):
A=AreasWithSameAngle(liste_support[i])
ListeContour.append(FindContour(A))
ListeProjete=Projection(ListeContour)
ListeProjete_shape=np.shape(ListeProjete)
if len(ListeProjete)==0:
print("you do not need any support")
else:
n=0
Faces=np.zeros((0,12))
if ListeProjete_shape[2]==3:
while n <ListeProjete_shape[0]:
The=thetraedral_simple_support(ListeProjete[:][n][:][:])
Faces= np.append(Faces,The,axis=0)
n+=1
plot(Faces,my_mesh,-50,50,0,80)
else:
Choice=ShapeChoice()
if Choice==1:
while n <ListeProjete_shape[0]:
Rec=Rectangular_simple_support(ListeProjete[:][n][:][:])
Faces= np.append(Faces,Rec,axis=0)
n+=1
elif Choice==2:
while n <ListeProjete_shape[0]:
Grid=gridxy(ListeProjete[:][n][:][:],1)
Faces= np.append(Faces,Grid,axis=0)
n+=1
elif Choice==3:
while n <ListeProjete_shape[0]:
ZZ=ZigZag(ListeProjete[:][n][:][:],1)
Faces= np.append(Faces,ZZ,axis=0)
n+=1
plot(Faces,my_mesh,-30,30,0,50)
<file_sep>/Locate_STL.py
import os,sys
from stl import mesh, Mesh
import glob
import time
def ShapeChoice():
print("You will choose the shape you want")
print("There are 3 types of shapes")
print("1st Shape: ___________")
print(" |.........|")
print(" |.........|")
print(" |.........|")
print(" |_________|\n")
print("2nd Shape: _|_|_|_|_|_")
print(" _|_|_|_|_|_")
print(" _|_|_|_|_|_")
print(" _|_|_|_|_|_")
print(" | | | | | \n")
print("3rd Shape: _________")
print(" ________|")
print(" |________ ")
print(" ________|")
print(" |_________")
typea=0
while typea!=1:
try:
nbr=int(input(("Select the shape you want to do (1,2 or 3):")))
if nbr>=0 and nbr<=3:
typea=1
else:
print("Enter a integer between ",0," and ",3)
except:#Mais si l'utilisateur à rentrer autre chose que un entier alors on lui affiche "Veuillez entrer un nombre" et la boucle recommence.
print("Enter a integer between ",0," and ",3)
return nbr
def FindSTL():
path=os.path.dirname(sys.argv[0])
files = os.listdir(path)
i=1
stllist=[]
nbr=0
OK2=False
while OK2==False:
i=1
LocateSTL1="{0}/*.stl".format(path)
Allfiles="{0}/*.*".format(path)
Allfiles2="{0}/.*".format(path)
Dir="{0}/*".format(path)
STL=glob.glob(LocateSTL1)
AllF=glob.glob(Allfiles)
AllF2=glob.glob(Allfiles2)
AllDF=glob.glob(Dir)
AllDF=AllDF+AllF2
AllF=AllF+AllF2
for k in range(len(AllF)):
AllDF.remove(AllF[k])
print("STL AVAILABLE IN THE FOLDER: ", path)
if len(STL)==0:
print("NO STL FILE, please go to another folder")
for name in STL:
print(name," ....... ",i)
i=i+1
print("NAVIGATION INTO FOLDERS")
for name in AllDF:
print("Go into folder: ",name," ....... ",i)
i=i+1
print("Look back in another folder ....... ",0)
typea=0
OK=False
while OK==False:
typea=0
while typea!=1:
try:
nbr=int(input(("Select a number for what do you want to do: ")))
if nbr>=0 and nbr<=i-1:
typea=1
else:
print("Enter a integer between ",0," and ",i-1)
except:#Mais si l'utilisateur à rentrer autre chose que un entier alors on lui affiche "Veuillez entrer un nombre" et la boucle recommence.
print("Enter a integer between ",0," and ",i-1)
if nbr>=1 and nbr<=len(STL):
print("You have selected: ", STL[nbr-1])
STL1=STL[nbr-1]
elif nbr>len(STL) and nbr<=len(STL)+len(AllDF):
print(nbr,len(STL))
path=AllDF[nbr-len(STL)-1]
files = os.listdir(path)
test=os.listdir(path)
print(files)
print(test)
else:
print("You have selected: Look in another folder")
path=os.path.dirname(path)
files = os.listdir(path)
test=os.listdir(path)
print(files)
print(test)
Answer=input("Are you sure about your choice? YES/Y/y/yes/Yes: ")
Yes=["YES","Y","y","yes","Yes"]
if Answer not in Yes:
OK=False
else:
if nbr>=1 and nbr<=len(STL):
OK2=True
OK=True
return STL1
<file_sep>/Support_Generator.py
from stl import mesh
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import copy as cp
import math
from skimage.draw import polygon,ellipsoid
from skimage import measure
def AreasWithSameAngle(vertices):
a=0
plan=vertices
Zones=[]
supp=0
compteur=0
za=0
while a < len(vertices):
PetitZone=[]
zi=0
ref=plan[0,0:9]
plan=np.delete(plan,0,axis=0)
PetitZone.append(ref)
# Zones[za,zi]=ref
v1=np.array([ref[0]-ref[3],ref[1]-ref[4],ref[2]-ref[5]])
v2=np.array([ref[0]-ref[6],ref[1]-ref[7],ref[2]-ref[8]])
normal1=np.cross(v1,v2)
Pref=ref[0:3]
len1= len(plan)
i=0
compteur=0
while i < len1:
P1=plan[0,0:3]
P2=plan[0,3:6]
P3=plan[0,6:9]
v3=np.array([P1[0]-Pref[0],P1[1]-Pref[1],P1[2]-Pref[2]])
v4=np.array([P2[0]-Pref[0],P2[1]-Pref[1],P2[2]-Pref[2]])
v5=np.array([P3[0]-Pref[0],P3[1]-Pref[1],P3[2]-Pref[2]])
if np.dot(v3,normal1)==0 and (np.dot(v4,normal1)==0 and np.dot(v5,normal1)==0) :
zi=zi+1
PetitZone.append(plan[0,0:9])
# Zones[za,zi]=plan[0,0:9]
plan=np.delete(plan,0,axis=0)
compteur=compteur+1
i=i+1
Zones.append(PetitZone)
za=za+1
a=a+compteur+1
return Zones
def FindContour(Zones):
ListeContour=[]
ij=-1
while ij<len(Zones)-1:
ij = ij+1
IndexContour=[]
IndexContour.append(0)
shapes=np.shape(Zones[ij])
Contour=np.zeros((shapes[0]*3,6))
SmallZone=Zones[ij]
p=0
for a in range(len(SmallZone)):
IsExt=SmallZone[a][0:6]
BIsExt=True
IsExt2=SmallZone[a][3:9]
BIsExt2=True
IsExt3=np.concatenate((SmallZone[a][0:3],SmallZone[a][6:9]))
BIsExt3=True
numberContour=1
for i in range(len(SmallZone)):
if i!=a:
IsExt4=SmallZone[i][0:6]
IsExt5=SmallZone[i][3:9]
IsExt6=np.concatenate((SmallZone[i][0:3],SmallZone[i][6:9]))
IsExt7=np.concatenate((SmallZone[i][3:6],SmallZone[i][0:3]))
IsExt8=np.concatenate((SmallZone[i][6:9],SmallZone[i][0:3]))
IsExt9=np.concatenate((SmallZone[i][6:9],SmallZone[i][3:6]))
A =np.array([IsExt == IsExt4,IsExt == IsExt5,IsExt == IsExt6,IsExt == IsExt7,IsExt == IsExt8,IsExt == IsExt9])
B =np.array([IsExt2 == IsExt4,IsExt2 == IsExt5,IsExt2 == IsExt6,IsExt2 == IsExt7,IsExt2 == IsExt8,IsExt2 == IsExt9])
C =np.array([IsExt3 == IsExt4,IsExt3 == IsExt5,IsExt3 == IsExt6,IsExt3 == IsExt7,IsExt3 == IsExt8,IsExt3 == IsExt9])
for ii in range(len(A)):
Test=0
Test2=0
Test3=0
for il in range(len(A[ii])):
if A[ii,il] == True:
Test=Test+1
if B[ii,il] == True:
Test2=Test2+1
if C[ii,il] == True:
Test3=Test3+1
if Test==6:
BIsExt=False
if Test2==6:
BIsExt2=False
if Test3==6:
BIsExt3=False
if BIsExt==True:
Contour[p,0:6]=IsExt
p=p+1
if BIsExt2==True:
Contour[p,0:6]=IsExt2
p=p+1
if BIsExt3==True:
Contour[p,0:6]=IsExt3
p=p+1
for i in range(p,shapes[0]*3):
Contour=np.delete(Contour,p,axis=0)
if numberContour>1:
Contour1=[]
IndexContour.append(len(Contour))
for l in range(len(IndexContour)-1):
Contour1.append(Contour[IndexContour[l]:IndexContour[l+1]])
for i in range(IndexContour[1],len(Contour)):
Contour=np.delete(Contour,IndexContour[1],axis=0)
if numberContour==1:
Contour1=[]
Contour1.append(Contour)
#Tri Contour
for KON in range(len(Contour1)):
Contour=Contour1[KON]
if len(Contour)!=0:
IsFollow1=Contour[0,3:6]
p=0
while p<len(Contour)-1:
p=p+1
BisFollow=False
for i in range(p,len(Contour)):
IsFollow2=Contour[i,0:3]
IsFollow3=Contour[i,3:6]
A =np.array([IsFollow1 == IsFollow2,IsFollow1 == IsFollow3])
for ii in range(len(A)):
Test=0
for il in range(len(A[ii])):
if A[ii,il] == True:
Test=Test+1
if Test==3:
BisFollow=True
k=ii
a=i
if k==0 and BisFollow==True:
Contour=np.insert(Contour,p,Contour[a],axis=0)
Contour=np.delete(Contour,a+1,axis=0)
IsFollow1=Contour[p,3:6]
if k==1 and BisFollow==True:
Sauv=Contour[a,0:3]
Sauv2=Contour[a,3:6]
Sauv=np.concatenate((Sauv2,Sauv))
Contour=np.insert(Contour,a,Sauv,axis=0)
Contour=np.delete(Contour,a+1,axis=0)
Contour=np.insert(Contour,p,Contour[a],axis=0)
Contour=np.delete(Contour,a+1,axis=0)
IsFollow1=Contour[p,3:6]
ListeContour.append(Contour)
return ListeContour
def Projection(ListeContour):
ListeProjete=[]
ListC2=cp.deepcopy(ListeContour)
ListC3=[]
ListC4=[]
if len(ListC2)!=0:
ListC3=ListC2[0]
if ListC3[0][0,0]==ListC3[0][1,0]:
ListC3[0]=Organization(ListC3[0])
ListC4=ListeContour[0]
if ListC4[0][0,0]==ListC4[0][1,0]:
ListC4[0]=Organization(ListC4[0])
if len(ListC2)>0:
for i in range(1,len(ListC2)):
ListC3=ListC3+ListC2[i]
if ListC3[i][0,0]==ListC3[i][1,0]:
ListC3[i]=Organization(ListC3[0])
ListC4=ListC4+ListeContour[i]
if ListC4[i][0,0]==ListC4[i][1,0]:
ListC4[i]=Organization(ListC4[i])
for ij in range(len(ListC3)):
for i in range(len(ListC3[ij])):
ListC3[ij][i][2]=0
ListC3[ij][i][5]=0
for i in range(len(ListC2)):
ListeProjete1=[]
ListeProjete1.append(ListC4[i])
ListeProjete1.append(ListC3[i])
ListeProjete.append(ListeProjete1)
return ListeProjete
def Organization(Contour):
A=Contour[0]
A=np.reshape(A,newshape=(1,6))
Contour=np.delete(Contour,0,axis=0)
c=np.append(Contour,A,axis=0)
return c
| 6a44854b7d64ab89e9e795e1c2fb3c0993937153 | [
"Python"
] | 6 | Python | Thogi45/Support_Generator | 65d0deae52ccd5ea0f5a9f3cd61ac0ad01ac9bf3 | 5bae088f52a3d523239a5dfa60445f2c6b5cb87e |
refs/heads/main | <file_sep>def kill_all():
for proc in psutil.process_iter(['pid', 'name', 'username']):
try:
if((proc.info['username'] == None)): #If username is None then process will not be Killed
print('skipped :',proc.info['pid'])
elif((proc.info['name'] == None)):# Ignore this one
print('skipped :',proc.info['pid'])
elif('conhost.exe' in proc.info['name']):# Important file for windows
print('skipped 2 :',proc.info['pid'])
elif('python.exe' in proc.info['name']):# Python is Important
print('skipped 2 :',proc.info['pid'])
elif('cmd.exe' in proc.info['name']):# Running this script on what?
print('skipped 2 :',proc.info['pid'])
elif(psutil.users()[0][0] not in proc.info['username']):# Ignore this one too
print('skipped :',proc.info['pid'])
else:
print(proc.info)
print('killed')
proc.kill()
except Exception as e:
print(e)
pass
kill_all()
<file_sep># Kill_all_Process
This script can be used to kill all the process that are on User Level
| 90d91e752a1ca7a453ca070b661602cb84bc69a2 | [
"Markdown",
"Python"
] | 2 | Python | starkk242/Kill_all_Process | 1a1b05227c4e137aa375368eed9688213973803c | 4dbae4dc0e46f2eb6bdb404c29f1700dbd920626 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WelcomeController extends Controller
{
public function about() {
$heroes = ["悟空", "達爾", "鳴人", "佐助", "魯夫"];
return view("pages.about", ['heroes' => $heroes]);
}
}
| e27e0a187d6d376fdbff20b8bff679d80236ab95 | [
"PHP"
] | 1 | PHP | c108156144/my-blog | 6a162b9ac7784af7e8312f4d984a5c2ca65cc8d7 | 6f01af70654036ce6b2c8ee8a3e428cce646f34a |
refs/heads/master | <repo_name>mariogao/microclient<file_sep>/go.mod
module github.com/mariogao/microclient
go 1.15
require (
github.com/mariogao/microservice v0.0.0-20201211090610-1bb065b5a350 // indirect
github.com/micro/go-micro/v2 v2.9.1
)
<file_sep>/readme.md
golang 微服务项目客户端代码
客户端要调用服务端代码,就需要按服务端定义的接口,及参数来调用,
所以客户端内要引入服务端项目
把 github.com/mariogao/microservice 下载好,启动当服务端用,再启动本项目 <file_sep>/main.go
package main
import (
"context"
"fmt"
pb "github.com/mariogao/microservice/proto"
"github.com/micro/go-micro/v2"
)
func main() {
//构建微服务
server := micro.NewService()
server.Init()
// 调用服务端 /microServer/proto/hello.pb.micro.go中的方法
// 得到一个结构体(该结构体实现了 client api 的方法)
helloService := pb.NewHelloService("myMicro", server.Client())
// 调用服务端 /microServer/proto/hello.pb.go中的方法
// 得到入参结构体
HelloReq := &pb.HelloReq{
Name: "my name",
}
// 调用 /microServer/proto/hello.pb.micro.go中的方法(client api)
// (client api 这个方法的具体实现中调用了 Server API 的MyHelloService 方法)
// Server API 中的这个方法最终是由/microServer/controller中的 HelloService 实现了
res, err := helloService.MyHelloService(context.Background(), HelloReq)
fmt.Println("res:", res, "err:", err)
}
| 9f7ede4ef0f75554489e911154d3afa1219e3bb4 | [
"Markdown",
"Go Module",
"Go"
] | 3 | Go Module | mariogao/microclient | de85db55fac8171d1de38cab7fc9bbb65f5b2e2d | aa3277cfb01e81e0b625c96daef03f55ea0539e0 |
refs/heads/master | <file_sep>using System;
public class OmniaClubPromoter : Promoter
{
public OmniaClubPromoter()
{
}
public OmniaClubPromoter(string firstName, string lastName, int cellPhone) : base(firstName, lastName, cellPhone)
{
}
protected override void ShareWithInnerCircle()
{
Console.WriteLine(" I share it on Instagram.");
}
protected override void UsePaidAds()
{
Console.WriteLine(" I use Google Adwords.");
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace App_Udemy
{
class Program
{
static void Main(string[] args)
{
List<Promoter> promoters = new List<Promoter>() {new XSClubPromoter("Jim", "Jamesson", 22266677)}; // Posso declarar aqui
promoters.Add(new XSClubPromoter("John", "Jones", 55544488)); // Ou da forma tradicional
promoters.Add(new OmniaClubPromoter("James", "Jackson", 11155566));
foreach(var promoter in promoters)
{
promoter.Promote();
}
List<Writer> writers = new List<Writer>() {new BookWriter("Jesse", "Jordan"), new BookWriter("Jefrey", "Jock")};
writers.Add(new BlogWriter("James", "Jeckins"));
foreach(var writer in writers)
{
writer.Write();
}
List<IBodyBuilder> bodyBuilders = new List<IBodyBuilder>() {new XSClubPromoter("John", "Jones", 55544488), new XSClubPromoter("James", "Jackson", 11155566)};
foreach(var builder in bodyBuilders)
{
builder.Workout();
}
List<IVlogger> vloggers = new List<IVlogger>();
vloggers.Add(new BookWriter("John", "Jones"));
vloggers.Add(new XSClubPromoter("James", "Jackson", 11155566));
foreach(var vlogger in vloggers)
{
vlogger.Vlog();
}
}
}
}
<file_sep>using System;
public class BookWriter : Writer
{
public BookWriter()
{
}
public BookWriter(string firstName, string lastName) : base(firstName, lastName)
{
}
public override void Vlog()
{
Console.WriteLine(" I vlog using my iPhone.");
}
public override void Write()
{
Console.WriteLine(" I write using my Samgung Note.");
}
} | 7e6e9dc4406ca701c40d6493825b268dcb5b7273 | [
"C#"
] | 3 | C# | wlricardo/Pilares_do_POO | bc739595fccad818e18d0005bd85be09917e2591 | 326d038074411b67776699b6750a241b7d093a24 |
refs/heads/master | <file_sep>import React, { useState } from 'react';
import jacket from '../../img/jacket.jpg';
import tankTop from '../../img/tank-top.jpg';
import classicJacket from '../../img/classic-jacket.jpg';
import classicTankTop from '../../img/classic-tank-top.jpg';
import noir from '../../img/noir.jpg';
import military from '../../img/military.jpg';
import elzaWalker from '../../img/elza-walker.jpg';
import './CostumeChanger.css';
export default function CostumeChanger() {
const [costume, changeCostume] = useState(jacket);
return (
<section>
<ul>
<li onMouseOver={() => changeCostume(jacket)}>Jacket</li>
<li onMouseOver={() => changeCostume(tankTop)}>Tank Top</li>
<li onMouseOver={() => changeCostume(classicJacket)}>Class Jacket</li>
<li onMouseOver={() => changeCostume(classicTankTop)}>Classic Tank Top</li>
<li onMouseOver={() => changeCostume(noir)}>Noir</li>
<li onMouseOver={() => changeCostume(military)}>Military</li>
<li onMouseOver={() => changeCostume(elzaWalker)}>Elza Walker</li>
</ul>
<img src={costume} alt='Costume' />
</section>
)
}
| 7db29d32d617395f7e8ecbe05bc31c3b768a73ca | [
"JavaScript"
] | 1 | JavaScript | Alpesh-Jadav/Costume-changer | da9530fad896066211aaaf47f0163d250ac7fa63 | 536c5683e3463839b944c50c85c22414f2bdd500 |
refs/heads/master | <file_sep>OUTPUT_FILE = "encrypted.txt"
INPUT_FILE = "plain_text.txt"
BASE_SIZE = 128
CHUNK_DIV = 15410
def break_apart(num,c=None): # break a number into a list of it's digits
if c is None:
c = CHUNK_DIV
gooshes = []
while num >0:
gooshes.append(num%c)
num = num // c
return gooshes
def join_together(gooshes, c=None):
if c is None:
c = CHUNK_DIV
s = ''
n = 0
mag = 1
max_digits = len(str(max(gooshes)))
for a in gooshes:
n += a*mag
mag *= c
return n
def random_from2_between(a,b, border):
return ((a+b)**2)%border
def shuffle_using_key(l, key, duration=1):
# shuffle the list l using the key
for i in range(duration *len(l)):
# for each item in the list, find a random place in the list, and push it there
tmp = l[i]
new_loc = random_from2_between(key, i, len(l))
l[i] = l[new_loc]
l[new_loc] = tmp
return l
def int2string(num):
s = ''
while num >0:
s += chr(num%BASE_SIZE)
num = num // BASE_SIZE
return s
def pad_left(w, l, c):
# pad the string w to the length of l with the character c, to the left
s = w # start with the string w
while len(s) < l: # while it's too short
s = c + s # add to it's left another padding character
return s # return the padded string
def intlist2string(l, maximum):
# create a string from a list of ints, and the maximum size an int can have
max_len = len(str(len(str(maximum)))) # the amount of digits it takes to describe the amount of digits in the largest number possible
n = '1' # n is the string form of the number to stringify
for item in l:
item_str = str(item) # the number (in string form)
item_l = pad_left(str(len(item_str)),max_len,'0') # the length number(in string form)
n += item_l+item_str
s = int2string(int(n)) # stringify the number
return s
def break_joint(n, maximum):
max_len = len(str(len(str(maximum)))) # the number of digits that are used to describe the amount of digits in one chunk
s = str(string2int(n)) # get the number(in string format)
# print("s: " + s)
l = []
# print(max_len)
s = s[1:]
while len(s) > 0:
nxt_l = int(s[:max_len]) # the length of the next chunk
# print("len(s): " + str(len(s)) + ", nxt_l: " + str(nxt_l))
num = int(s[max_len:nxt_l+max_len]) # use the achieved next digit length to pull the next chunk
l.append(num)
s = s[nxt_l+max_len:] # cut the used part until now
return l
def string2int(s):
num = 0
mag = 1
for c in s:
num += ord(c)*mag
mag*=BASE_SIZE
return num
def get_string_from_file(name=INPUT_FILE):
with open(name, 'r', newline='') as f:
s = f.read()
f.close()
return s
def put_string_to_file(data, name=OUTPUT_FILE):
with open(name, 'w', newline='') as f:
f.write(data)
f.close()
def get_max(ch, key, it):
# calculate the maximum number possible for encryption using a chunk_div_size, the key, and number of iterations
num = ch
for i in range(it):
num = max(num*key, ((key*(num+i))+i)^key)
# print("key: " + str(key) + ", c: " + str(ch) + ", i: " + str(i) + "/" + str(it-1) + ", num: " + str(num))
return num
def encrypt(p, k, iterations=1, ch=CHUNK_DIV, b=BASE_SIZE):
"""
:param p: string plaintext
:param k: int secret key
:param iterations: int iterations
:param c: int chunk_division_size
:param b: int size of base for string-int transform(128 for normal ascii, as default)
:return: encrypted string
"""
plain = string2int(p)
chunks = break_apart(plain, ch)
shuffled_loc = list(range(len(chunks))) # initialize shuffle list: each cell in this array contains the index of the actuall index in the actual array
for i in range(iterations): # for each iteration of encryption
result = [-1] * len(chunks) # initialize results list
shuffled_loc = shuffle_using_key(shuffled_loc[:], k) # shuffle the shuffle list
for c in range(len(chunks)): # for each chunk
my_loc = shuffled_loc[c] # find actual location using the shuffle list
if c != (i+k+4*(k + i)**3) % len(chunks): # if not weak link
nxt = shuffled_loc[(c + 1) % len(chunks)] # find actual location of the referring chunk
val = k * (chunks[my_loc] ^ chunks[nxt]) # calculate the next value of this chunk
else: # if is weak link
val = ((k * chunks[my_loc]) + ((k + 1) * i)) ^ k # calculate the next value of this chunk
result[my_loc] = val
chunks = result
encrypted = intlist2string(chunks, get_max(ch, k, iterations))
return encrypted
def decrypt(enc, k, its=1, ch=CHUNK_DIV, b=BASE_SIZE):
result = break_joint(enc, get_max(ch, k, its))
shuffled_loc = list(range(len(result)))
shuffles = []
for i in range(its):
shuffled_loc = shuffle_using_key(shuffled_loc[:], k)
shuffles.append(shuffled_loc)
for i in range(its - 1, -1, -1):
shuffled_loc = shuffles[i]
# print(shuffles[i])
chuks = [-1] * len(result) # blank list of empty chunks
start_c = (i+k+4*(k + i)**3) % len(chuks)
chuks[shuffled_loc[start_c]] = ((result[shuffled_loc[start_c]] ^ k) - ((k + 1) * i)) // k # solve the weak link
c = (start_c - 1) % len(chuks) # go back
prev = start_c
while c != start_c:
chuks[shuffled_loc[c]] = ((result[shuffled_loc[c]]//k) ^ chuks[shuffled_loc[prev]]) # use the key and the last discovered value to discover this value
prev = c
c = (c - 1) % len(chuks)
# c = shuffled_loc.index(c)
result = chuks
return int2string(join_together(result))
my_string = get_string_from_file(INPUT_FILE)
my_key = 3141895618
iterations = 10
E = encrypt(my_string,my_key,iterations) # encrypt
print("FINISHED ENCRYPTING")
put_string_to_file(str(E)) # save encrypted file
encr = get_string_from_file(OUTPUT_FILE) # open encrypted file and read it
D = decrypt(encr, my_key, iterations) # decrypt the encrypted data
print("FINISHED DECRYPTING")
print(D)
# github update test
| f750e87d5442e92ffd8c57b010c8338aa5c864fa | [
"Python"
] | 1 | Python | Itaay/encryption | b675891643e1c77a0bd3e14b5db7f2ada66b9d91 | 51dfb92f9d6389ce4fc5b3fa84c9ffb255f01aa6 |
refs/heads/master | <file_sep>package com.kaneri.admin.mywhatsapp.settings;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.kaneri.admin.mywhatsapp.R;
import com.kaneri.admin.mywhatsapp.finalchatapp.Login;
public class SettingsActivity extends AppCompatActivity {
TextView changePassword, changeEmail, signout, deleteProfile;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
auth = FirebaseAuth.getInstance();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(SettingsActivity.this, Login.class));
finish();
}
}
};
changeEmail = (TextView) findViewById(R.id.changeEmail);
changePassword = (TextView) findViewById(R.id.changePassword);
signout = (TextView) findViewById(R.id.signOut);
deleteProfile = (TextView) findViewById(R.id.deleteAccount);
deleteProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SettingsActivity.this, DeleteProfile.class));
}
});
changeEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//signOut();
startActivity(new Intent(SettingsActivity.this,ChangeEmail.class));
}
});
changePassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signOut();
startActivity(new Intent(SettingsActivity.this, ChangePassword.class));
}
});
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signOut();
startActivity(new Intent(SettingsActivity.this, Login.class));
}
});
}
public void signOut() {
auth.signOut();
}
}<file_sep>package com.kaneri.admin.mywhatsapp.finalchatapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.kaneri.admin.mywhatsapp.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| e5f9feb6be4160af01a0cb8ab6fb7abdd8ac3fcd | [
"Java"
] | 2 | Java | karanfc/MyWhatsapp | 2cf785fc3703edc5b28f21287bc2022f5bd4e1b0 | 44d5f634d43d311de4216fc3ed19185e46cf2c40 |
refs/heads/master | <repo_name>vbrutt/JavaChatApplication<file_sep>/src/Program.java
public class Program {
public static void main(String[] args) {
try {
TestProject testProject = new TestProject();
testProject.doStuff();
testProject.dispose();
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
| 0a78ddaa4870415308700c9800004165d22c9667 | [
"Java"
] | 1 | Java | vbrutt/JavaChatApplication | 4b3296a70c1bec279a62017d2d7d4b501a4fe2b4 | df42b4b1696f71ce75e3320b310e10fe83325b69 |
refs/heads/master | <file_sep>package test;
import com.dream.utils.JDBCUtils;
import com.dream.utils.UUIDUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.sql.*;
public class JdbcTest {
@Test
public void testJdbc() throws Exception {
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Connection root = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/library?useUnicode=true&characterEncoding=utf-8", "root", "123456");
System.out.println(root);
}
@Test
public void testC3P0() throws Exception {
//获取ComboPooledDataSource数据源
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("mysql-library");
// comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
// comboPooledDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/library?useUnicode=true&characterEncoding=utf-8");
// comboPooledDataSource.setUser("root");
// comboPooledDataSource.setPassword("<PASSWORD>");
Connection connection = comboPooledDataSource.getConnection();
String sql = "select * from sys_user";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
String userId = resultSet.getString("userId");
System.out.println(userId);
}
resultSet.close();
preparedStatement.close();
connection.close();
comboPooledDataSource.close();
}
@Test
public void testAddSysUser() throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = null;
String userId = UUIDUtils.getUUID();
try {
sql = "insert into sys_user(userId,userName,loginName,password) values (?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,userId);
preparedStatement.setString(2,"管理员");
preparedStatement.setString(3,"admin");
preparedStatement.setString(4,"123456");
preparedStatement.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeConnection(connection);
}
}
}
<file_sep>package com.dream.sys.dao.impl;
import com.dream.sys.bean.SysUser;
import com.dream.sys.dao.SysUserDao;
import com.dream.utils.JDBCUtils;
import com.dream.utils.UUIDUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class SysUserDaoImpl implements SysUserDao {
@Override
public SysUser getSysUserById(String userId) {
return null;
}
@Override
public List<SysUser> getSysUserAll() {
return null;
}
@Override
public boolean addSysUser(SysUser sysUser) {
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement = null;
String sql = null;
String userId = UUIDUtils.getUUID();
try {
sql = "insert into sys_user(userId,userName,loginName,password) values (?,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,userId);
preparedStatement.setString(2,sysUser.getUserName());
preparedStatement.setString(3,sysUser.getLoginName());
preparedStatement.setString(4,sysUser.getPassword());
preparedStatement.executeUpdate();
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}finally {
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBCUtils.closeConnection(connection);
}
}
@Override
public boolean updateSysUserById(SysUser sysUser) {
return false;
}
@Override
public boolean deleteSysUserById(String userId) {
return false;
}
@Override
public String checkPassword(String loginName) {
Connection connection = JDBCUtils.getConnection();
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "";
String password = <PASSWORD>;
try{
sql = "select password from sys_user where loginName = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,loginName);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
password = resultSet.getString("password");
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBCUtils.closeConnection(connection);
}
return password;
}
}
<file_sep>package com.dream.sys.controller;
import com.dream.sys.service.SysUserService;
import com.dream.sys.service.impl.SysUserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class LoginServlet extends HttpServlet {
private SysUserService sysUserService = new SysUserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String,Object> map = new HashMap<>();
// 获取请求参数
String loginName = req.getParameter("loginName");
String password = req.getParameter("password");
// 去请求相应的service
String passwordData = sysUserService.checkPassword(loginName);
if (loginName != null && password != null && password.equals(passwordData)){
req.setAttribute("loginName",loginName);
req.getRequestDispatcher("/sys/jsp/index.jsp").forward(req,resp);
return;
}else {
req.setAttribute("msg","登陆失败,用户名或密码不正确");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
return;
}
}
}
<file_sep>package com.dream.utils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JSONUtils {
public static ObjectMapper initJson(){
ObjectMapper mapper = new ObjectMapper();
// 美化输出
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 允许序列化空的POJO类 (否则会抛出异常)
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 把java.util.Date, Calendar输出为数字(时间戳)
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 在遇到未知属性的时候不抛出异常
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 强制JSON 空字符串("")转换为null对象值:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
// 在JSON中允许C/C++ 样式的注释(非标准,默认禁用)
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
// 允许没有引号的字段名(非标准)
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 允许单引号(非标准)
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 强制转义非ASCII字符
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
// 将内容包裹为一个JSON属性,属性名由@JsonRootName注解指定
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
return mapper;
}
}
| 8a5c7b2a0701010791e28393a67fbc3176c2eb79 | [
"Java"
] | 4 | Java | shitianyang/SunDream | 6a5e90ece159d3013e52e307baeb4ea958a8bfb3 | dd630cec4508e2f0217bf92a470c4cf3264a9883 |
refs/heads/master | <repo_name>Keerthanawizara/surepay_server<file_sep>/src/property/propertyController.js
const propertyCollection = require('./propertyModel');
const mongoose = require('mongoose');
const Joi = require('joi');
//server side Data validation initialize
const schema = Joi.object().keys({
county: Joi.string(),
pin: Joi.string(),
address: Joi.string(),
city: Joi.string(),
state:Joi.string(),
zip: Joi.string(),
township:Joi.string(),
class_code: Joi.string(),
assessed_value: Joi.string(),
market_value: Joi.string(),
taxes_per_year: Joi.string(),
PREEQEXM: Joi.string(),
home_owners: Joi.string(),
senior_exemption: Joi.string(),
senior_freeze: Joi.string(),
total_acres: Joi.string(),
legal_description: Joi.string(),
google_map_view: Joi.string()
})
//create API initialize
const propertyDetail = async(req,h) => {
var data = req.payload
Joi.validate(data, schema,(err)=>{
return err
})
let docs = await propertyCollection.propertyDetail(data)
if(docs){
return docs
}else{
return err
}
}
// // property table List Page
const propertyDataList = async(req,h) => {
let docs = await propertyCollection.propertyDataList(req)
if(docs){
return docs
}else{
return err
}
}
const propertyRecord = async(req,h) => {
const query = req.query;
const params = {_id: mongoose.Types.ObjectId(req.params.id),pin:query.pin};
let docs = await propertyCollection.propertyRecord(params)
if(docs){
return docs
}else{
return err
}
}
// // //update property details
const propertyRecordUpdate = async(req,h) => {
const query = req.query;
const params = {_id: mongoose.Types.ObjectId(req.params.id),pin:query.pin};
let docs = await propertyCollection.propertyRecordUpdate(params)
if(docs){
return docs
}else{
return err
}
}
// // // delete property details
const propertyRecordDelete = async(req,h) => {
const query = req.query;
const params = {_id: mongoose.Types.ObjectId(req.params.id),pin:query.pin};
let docs = await propertyCollection.propertyRecordDelete(params)
if(docs){
return docs
}else{
return err
}
}
module.exports = {
propertyDataList,
propertyDetail,
propertyRecord,
propertyRecordUpdate,
propertyRecordDelete
}<file_sep>/src/Assessee/assesseeSchema.js
const mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
//get the Schema class
const Schema = mongoose.Schema;
const AssesseeSchema = new Schema({
name:String,
emailId:String,
phone:String,
propertyId:String
});
AssesseeSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('assesseeList', AssesseeSchema, 'assesseeList');<file_sep>/src/County/countySchema.js
const mongoose = require('mongoose');
//get the Schema class
const Schema = mongoose.Schema;
const CountySchema = new Schema({
county : String,
city : String,
state : String,
zip : String
});
module.exports = mongoose.model('countyList', CountySchema, 'countyList');<file_sep>/src/users/userController.js
const userCollection = require('./userModel')
const userAuthentication = require('../common/authenticator')
const Joi = require('joi');
//server side data validation initialize
const schema = Joi.object().keys({
username: Joi.string().email({ minDomainAtoms: 2 }).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{8,10}$/)
}).with('username', '<PASSWORD>');
//create user API
const createUser = async(req,h) => {
var data = req.payload
Joi.validate(data, schema,(err)=>{
return err
})
let docs = await userCollection.createUser(data)
if(docs){
return docs
}else{
return err
}
}
//GetUserList
const getUserList = async(req,h) => {
let docs = await userCollection.getUserList(req)
if(docs){
return docs
}else{
return err
}
}
const userAuthController = async (request) => {
const userCredentials = request.payload
if (userCredentials && (userCredentials.username && userCredentials.password)) {
const userData = await userCollection.userAuthController(userCredentials).then(doc=>doc).catch(err=>err)
if (userData[0]._id) {
const userAuth = new userAuthentication(userData[0]._id)
return {
status: 'success',
token: userAuth.getToken()
}
}
} else {
return {
status: 'failure',
result: 'Cannot identify username or password.'
}
}
}
module.exports = {
createUser,
userAuthController,
getUserList
}<file_sep>/src/property/propertyModel.js
const propertySchema = require('./propertySchema');
const propertyDetail = async(req) => {
let docs = await propertySchema.create(req)
if(docs){
return docs
}else{
return err
}
}
const propertyDataList =async()=>{
let docs = await propertySchema.paginate({},{offset:0, limit:10})
if(docs) {
return docs;
}else {
return err;
}
}
const propertyRecord = async(req)=> {
let docs = await propertySchema.findOne(req)
if(docs) {
return docs;
}else {
return err;
}
}
const propertyRecordUpdate = async(req) => {
let docs = await propertySchema.updateOne({ $set:req.payload })
if(docs) {
return docs;
}else {
//console.log(err)
return err;
}
}
const propertyRecordDelete = async(req) =>{
let docs = await propertySchema.deleteOne(req)
if(docs) {
return docs;
}else {
return err;
}
}
module.exports ={
propertyDetail,
propertyDataList,
propertyRecord,
propertyRecordUpdate,
propertyRecordDelete
} <file_sep>/src/Assessee/assesseeController.js
const assesseeCollection = require('./assesseeModel');
const mongoose = require('mongoose');
const Joi = require('joi');
const axios = require('axios');
//server side data validation
const schema = Joi.object().keys({
name :Joi.string().min(3).max(30).required(),
emailId :Joi.string().email({ minDomainAtoms: 3 }).required(),
phone :Joi.string(),
propertyId: Joi.string()
})
//create assessee api
const assesseeDetail = async(req,h) => {
var data = req.payload
Joi.validate(data, schema,(err)=>{
return err
})
let docs = await assesseeCollection.assesseeDetail(data)
if(docs){
return docs
}else{
return err
}
}
// //assessee Data list Api
const assesseeDataList = async(req,h) => {
let docs = await assesseeCollection.assesseeDataList(req)
if(docs){
return docs
}else{
return err
}
}
const assesseeRecord = async(req,h) => {
const params = {_id: mongoose.Types.ObjectId(req.params.id)};
let docs = await assesseeCollection.assesseeRecord(params)
if(docs){
return docs
}else{
return err
}
}
// //assessee record update api using id
const assesseeRecordUpdate = async(req,h) => {
var data = req.payload
const params = {_id: mongoose.Types.ObjectId(req.params.id)};
let docs = await assesseeCollection.assesseeRecordUpdate(params,data)
if(docs){
return docs
}else{
return err
}
}
// // // delete assessee details api using id
const assesseeRecordDelete = async(req,h) => {
const params = {_id: mongoose.Types.ObjectId(req.params.id)};
let docs = await assesseeCollection.assesseeRecordDelete(params)
if(docs){
return docs
}else{
return err
}
}
module.exports ={
assesseeDetail,
assesseeDataList,
assesseeRecord,
assesseeRecordUpdate,
assesseeRecordDelete
}<file_sep>/src/property/propertySchema.js
const mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
//get the Schema class
const Schema = mongoose.Schema;
const PropertySchema = new Schema({
county: {
required: true,
type: String
},
pin: {
required : true,
type : String
},
address: String,
city : String,
state : String,
zip : Number,
township : String,
class_code : String,
assessed_value : String,
market_value : String,
taxes_per_year : String,
PREEQEXM : String,
home_owners : String,
senior_exemption : String,
senior_freeze : String,
total_acres : String,
legal_description : String,
google_map_view : String
});
PropertySchema.plugin(mongoosePaginate);
module.exports = mongoose.model('propertyList', PropertySchema, 'propertyList');
| ddb43fc9d8dd5f84e0f055acd1df8a71909517cb | [
"JavaScript"
] | 7 | JavaScript | Keerthanawizara/surepay_server | 2e51759b7a476e1d1315f34ecd043913cdae2c9b | a0a6ff830f92c0425781f430183ebea344a09702 |
refs/heads/master | <file_sep>var cwise = require('cwise')
var genfun = require('generate-function')
var colorStyles = require('pixel-to-css-color')
var Ndpixels = require('ndpixels')
var Tc = require('tcomb')
//module.exports = Tc.func([Ndpixels], Tc.Nil)
// .of(createPixelsToCanvasRenderer)
module.exports = createPixelsToCanvasRenderer
function createPixelsToCanvasRenderer (canvas) {
var ctx = canvas.getContext('2d')
return function updateCanvas (pixels) {
render(ctx, pixels)
}
}
var iteration = cwise({
args: ['scalar', 'scalar', 'scalar', 'shape', 'index', { blockIndices: -1 }],
body: function (ctx, fillStyle, fillRect, shape, index, pixel) {
fillStyle(pixel[0], pixel[1], pixel[2], pixel[3])
fillRect(index[0], index[1])
},
funcName: 'iteratePixels'
})
function render (ctx, pixels) {
var fillStyle = genFillStyle(ctx, pixels.format)
var fillRect = genFillRect(ctx, pixels.shape)
return iteration(ctx, fillStyle, fillRect, pixels)
}
function genFillStyle (ctx, format) {
var toCss = colorStyles[format]
if (toCss == null) {
throw new Error('pixels-canvas: unsupported color format: ', format)
}
var fn
switch (format) {
case 'keyword':
fn = genfun('function fillStyle (a) { ctx.fillStyle = toCss(a) }')
break;
case 'rgb':
case 'hsl':
fn = genfun('function fillStyle (a, b, c) { ctx.fillStyle = toCss(a, b, c) }')
break;
case 'hsla':
case 'rgba':
fn = genfun('function fillStyle (a, b, c, d) { ctx.fillStyle = toCss(a, b, c, d) }')
break;
}
return fn.toFunction({ ctx: ctx, toCss: toCss })
}
function genFillRect (ctx, shape) {
var dimension = shape.length - 1
var width, height
switch (dimension) {
case 2:
width = ctx.canvas.width / shape[0]
height = ctx.canvas.height / shape[1]
break;
case 1:
width = ctx.canvas.width / shape[0]
height = 1
break;
default:
width = 1
height = 1
}
var fn
switch (dimension) {
case -1:
case 0:
fn = genfun('function fillRect () { ctx.fillRect(0, 0, %d, %d) }', width, height)
break
case 1:
fn = genfun('function fillRect (x) { ctx.fillRect(x * %d, 0, %d, %d) }', width, width, height)
break
case 2:
fn = genfun('function fillRect (x, y) { ctx.fillRect(x * %d, y * %d, %d, %d) }', width, height, width, height)
break
default:
throw new Error('pixels-canvas: cannot iterate in ' + dimension + ' dimensions')
}
return fn.toFunction({ ctx: ctx })
}
<file_sep>var rainbowPixels = require('rainbow-pixels')
var raf = require('pull-raf')
var pull = require('pull-stream')
var canvas = document.createElement('canvas')
var pixelsToCanvas = require('./')(canvas)
document.body.appendChild(canvas)
pull(
rainbowPixels({
shape: [
Math.floor(document.body.clientWidth / 16),
Math.floor(document.body.clientHeight / 16)
]
}),
raf(),
pull.map(function (pixels) {
pixelsToCanvas(pixels)
}),
pull.drain()
)
<file_sep># pixels-canvas
canvas renderer for [pixels](https://github.com/livejs/pixels)
```shell
npm install --save pixels-canvas
```
## usage
### `toCanvas = require('pixels-canvas')`
### `pixelsToCanvas = toCanvas(canvas)`
`canvas`: required canvas dom element
### `pixelsToCanvas(pixels)`
`pixels`: required [2d pixels](https://github.com/livejs/ndpixels)
## example
```js
var toCanvas = require('pixels-canvas')
var pixelsToCanvas = toCanvas(canvas)
document.body.appendChild(canvas)
pixelsToCanvas(pixels)
```
for a full example, see [./example](http://livejs.github.io/pixels-canvas)
## License
The Apache License
Copyright © 2016 <NAME> (@ahdinosaur)
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.
| b2c7cadf47be1dd2b1071e7bb903e8044b27a4f8 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | livejs/pixels-canvas | 44e2f7e7b5c08c3b07149dad315661f9fc8bd1db | 6dcf6d7a516f754b0ee23bfb479be82a75501d71 |
refs/heads/master | <repo_name>thekidfromyesterday/ap_java<file_sep>/Missing Assignments/src/RationalTester.java
public class RationalTester {
public static void main(String[] args)
{
Rational testRational = new Rational(1,3);
Rational testRational2 = new Rational(2,6);
testRational.printRational();
testRational.negate();
testRational.printRational();
testRational.toDouble();
testRational.add(testRational2);
testRational.reduce(testRational2);
}
}
<file_sep>/HelloWorld/src/bottlesOfBeer.java
public class bottlesOfBeer {
public static void beer(int n)
{
if (n > 1)
{
System.out.println(n + " bottles of beer on the wall, " + n + " bottles of beer, Take one down, pass it around" );
beer(n-1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
beer(99);
System.out.println("1 bottle of beer on the wall, 1 bottle of beer.");
System.out.println("Take one down and pass it around, no more bottles of beer on the wall.");
System.out.println("No more bottles of beer on the wall, no more bottles of beer.");
System.out.println("Go to the store and buy some more, 99 bottles of beer on the wall.");
}
}
<file_sep>/KarelJRobot/fig5_7.java
import kareltherobot.*;
public class fig5_7 implements Directions{
public static void task()
{
SuperRobot karel = new SuperRobot(1,1, East, 0);
karel.move();
karel.keepMoving();
karel.turnLeft();
karel.move();
karel.checkAndPick();
karel.turnLeft();
karel.turnAround();
karel.move_two();
karel.turnRight();
karel.move();
karel.keepMoving();
karel.turnLeft();
karel.move();
karel.move();
karel.move_and_pick();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
World.setDelay(20);
World.readWorld("fig5-7.txt");
World.setVisible();
task();
}
}
<file_sep>/Vending Machine/src/VendingMachine.java
public class VendingMachine
{
String name;
double totalMoney;
int amountOfSodas;
Soda[] sodas;
public VendingMachine()
{
this.name = "My Vending Machine";
this.totalMoney = 0;
this.amountOfSodas = 32;
}
}
<file_sep>/KarelJRobot/garden.java
import kareltherobot.Directions;
import kareltherobot.World;
public class garden implements Directions
{
public static void task()
{
CyberMan karel = new CyberMan(5,5, East, 30);
karel.garden();
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
World.setDelay(10);
World.readWorld("garden68.txt");
World.setVisible();
task();
}
}
<file_sep>/Missing Assignments/src/Card.java
public class Card
{
int suit;
int rank;
public Card()
{
this.suit = 0;
this.rank = 0;
}
public Card(int suit, int rank)
{
this.suit=suit;
this.rank=rank;
}
public static void printCard(Card a)
{
String [] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String [] ranks = {"narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
System.out.println(ranks[a.rank] + " of " + suits[a.suit]);
}
public static boolean sameCard(Card a, Card b)
{
if ((a.suit == b.suit) && (a.rank == b.rank) )
{
return true;
}
return false;
}
//suit first card 2n
public static int compareCard(Card a, Card b)
{
if(a.suit > b.suit)
{
return 1;
}
if(a.suit < b.suit)
{
return -1;
}
if(a.rank > b.rank)
{
return 1;
}
if (a.rank < b.rank)
{
return -1;
}
return 0;
}
public static void printDeck(Card[] a)
{
for (int k = 0; k < a.length;k++)
{
printCard(a[k]);
}
}
public static Card[] makeDeck()
{
int index = 0;
Card[] deck = new Card[52];
for (int suit = 0; suit < 4; suit++)
{
for (int rank = 1; rank < 14; rank++)
{
deck[index]=new Card(suit,rank);
index++;
}
}
return deck;
}
public static int findCard(Card[] deck, Card c)
{
for (int i = 0; i <deck.length;i++)
{
if(sameCard(c,deck[i]))
{
return i;
}
}
return -1;
}
public static int findBisect(Card[] deck, Card c, int low, int high)
{
if(low>high)
{
return -1;
}
int mid =(low+high)/2;
int comp = compareCard(c,deck[mid]);
if (comp == 0)
{
return mid;
}
if ( comp == 1)
{
return findBisect(deck,c,mid+1,high);
}
if (comp == -1)
{
return findBisect(deck,c,low,mid-1);
}
return -1;
}
public static int handScore(Card[] blackJackHand)
{
int score = 0;
for (int i = 0; i < blackJackHand.length; i++)
{
if (blackJackHand[i].rank<11)
{
score += blackJackHand[i].rank;
}
else
{
score += 10;
}
}
return score;
}
public static int[] suitHist (Card[] pokerHand)
{
int []counts = new int[4];
for (int i = 0; i<pokerHand.length; i++)
{
counts[pokerHand[i].suit]++;
}
return counts;
}
public static boolean hasFlush(Card[] pokerHand)
{
for (int i = 0; i < suitHist(pokerHand).length; i++)
{
if (suitHist(pokerHand)[i]>=5)
{
return true;
}
}
return false;
}
public static void main(String[] args)
{
Card test = new Card(3,12);
Card testA = new Card();
testA.rank = 3;
printCard(test);
Card[] cards = new Card[52];
if (cards[0]==null)
{
System.out.println("You have no cards yet");
}
Card[] deck = makeDeck();
System.out.println(findCard(deck,new Card(2,3)));
printCard(deck[findCard(deck, new Card(2,3))]);
System.out.println(findBisect(deck, new Card(2,3), 0, deck.length));
}
}
<file_sep>/Missing Assignments/src/Checker.java
public class Checker {
public static boolean StringChecker(String s, String let)
{
System.out.print("Looking for: " + let);
if(s.indexOf(let) > -1)
{
System.out.print(" " + true);
return true;
}
System.out.print(" " + false);
return false;
}
public static void main(String[] args)
{
StringChecker("<NAME>","az");
}
}
<file_sep>/hello_world_other/src/hello_world_other/hello_world_other.java
package hello_world_other;
import javax.swing.JOptionPane;
public class hello_world_other {
public static void main(String[] args) {
// TODO Auto-generated method stub
JOptionPane myIO = new JOptionPane();
JOptionPane.showMessageDialog(null, "Hello World!");
}
}
<file_sep>/KarelJRobot/Field612.java
import kareltherobot.*;
public class Field612 implements Directions {
public static void task()
{
HarvesterBot karel = new HarvesterBot(5, 2, East, 40);
karel.move();
karel.harvestBeepers();
karel.move();
karel.harvestBeepers();
karel.faceEast();
karel.move();
karel.harvestBeepers();
karel.move();
karel.harvestBeepers();
karel.faceEast();
karel.move();
karel.harvestBeepers();
karel.turnOff();
}
public static void main(String[] args)
{
World.setDelay(5);
World.readWorld("field612.txt");
World.setVisible();
task();
}
}
<file_sep>/Projects/src/ATMMachine.java
import java.util.*;
public class ATMMachine {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
double withdraw ;
double deposit ;
double balance = 5423;
// double checkBalance ;
int option ;
int exit = 1 ;
while (exit == 1)
{
System.out.println("Welcome to Goliath National Bank what would you like to do?");
System.out.println("Press 1 to withdraw, 2 to deposit, 3 to check your balance, and 4 to exit ");
option = reader.nextInt();
if (option == 1)
{
System.out.println("How much would you like to withdraw? ");
withdraw = reader.nextDouble();
balance -= withdraw;
System.out.println("Your new balance is: " + balance);
System.out.println("Thank you for doing your banking at GNB");
}
if (option == 2)
{
System.out.println("How much would you like to deposit? ");
deposit = reader.nextDouble();
balance += deposit;
System.out.println("Your new balance is: " + balance);
System.out.println("Thank you for doing your banking at GNB");
}
if (option == 3)
{
System.out.println("Your current balance is: " + balance); // this might be messed up
System.out.println("Thank you for doing your banking at GNB");
}
if (option == 4)
{
exit = 2;
System.out.println("Have a nice day! ");
}
}
reader.close();
}
}
<file_sep>/Baseball Programs/src/QuadraticFormula.java
public class QuadraticFormula
{
static double a = 1 ;
static double b = 3 ;
static double c = 4 ;
public static void main(String[] args)
{
b = Math.abs(b) * - 1;
double bSquared = b * b;
double fourA = 4 * a;
double fourC = 4 * c;
double ac = fourA + fourC;
double divider = 2 * a;
double squareRootOfB = Math.sqrt(bSquared) ;
double squareRootOfAC = Math.sqrt(ac);
System.out.println();
System.out.println((squareRootOfB - squareRootOfAC) / divider);
}
}
<file_sep>/Projects/src/Calculator.java
public class Calculator
{
String name;
double number;
double number2;
void add()
{
double output = number + number2;
System.out.println(output);
}
void multiply()
{
double output = number * number2;
System.out.println(output);
}
void division()
{
double output = number/number2;
System.out.println(output);
}
void squareRoot()
{
double output = Math.sqrt(number);
System.out.println(output);
}
void square()
{
double output = number * number;
System.out.println(output);
}
}
<file_sep>/Think Java/src/power.java
public class power {
public static double pow(double x,double n)
{
if (n == 0)
{
return 1;
}
if (n > 0)
{
return x*pow(x, n-1);
}
else if (n < 0)
{
return 1/x * pow(1/x, n -n -1);
}
return 0;
}
public static void main(String[] args)
{
System.out.println(pow(3,-1));
}
}
<file_sep>/Baseball Programs/src/obp.java
import java.util.*;
public class obp {
public static void main(String[] args) {
// TODO Auto-generated method stub
int h ;
int bb ;
int hbp ;
int ab ;
int sf ;
Scanner reader = new Scanner(System.in);
System.out.println("Insert how many hits he had: ");
h = reader.nextInt();
System.out.println("Insert how many walks he had: ");
bb = reader.nextInt();
System.out.println("Insert how many times he was hit by a pitch: ");
hbp = reader.nextInt();
System.out.println("Insert how many at bats he had: ");
ab = reader.nextInt();
System.out.println("Insert how many sac flies he had: ");
sf = reader.nextInt();
int ob1 = h + bb + hbp;
int ob2 = ab + bb + hbp + sf;
float obp = (float)ob1 / (float)ob2;
System.out.println(obp);
reader.close();
}
}<file_sep>/KarelJRobot/Hello_writing.java
import kareltherobot.*;
public class Hello_writing implements Directions {
public static void task()
{
letterwriter karel = new letterwriter(1, 1, North, infinity);
karel.printH();
karel.turnAround();
karel.move_three();
karel.move();
karel.turnLeft();
karel.move_two();
karel.turnLeft();
karel.printE();
karel.turnAround();
karel.move_three();
karel.putBeeper();
karel.turnLeft();
karel.move4_put_4();
karel.turnAround();
karel.move_four();
karel.turnLeft();
karel.move2_put_2();
karel.turnLeft();
karel.turnLeft();
karel.printL();
karel.printO();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
World.setDelay(2);
World.readWorld("blank.TXT");
World.setVisible();
task();
}
}
<file_sep>/Projects2/src/numbers/NextPrime.java
package numbers;
public class NextPrime
{
public static boolean isPrime(int x)
{
// every composite number can be made from 2, 3, or 11 genius moment!
if ((x == 2) || (x==3) || (x==11))
{
return true;
}
if ((x%2 == 0) || (x%3 == 0) || (x%7 == 0) || (x%11 == 0))
{
return false;
}
return true;
}
public static int getNextPrime(int x)
{
// only gets if from even numbers
while(isPrime(x) == false)
{
x++;
}
return x;
}
public static void main(String[] args)
{
System.out.println(isPrime(103));
System.out.println(getNextPrime(135));
}
}
<file_sep>/HelloWorld/src/countdown.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class countdown {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println( sdf.format(cal.getTime()));
}
}
| 011cab0c7734a00ee5b3154e54660969c45d89f4 | [
"Java"
] | 17 | Java | thekidfromyesterday/ap_java | c83f5024c4fd38c8bac540d85b4acf0ea464074d | 08174d6fcda4e8ab8a56e4113eaddbc97c80f1b0 |
refs/heads/master | <file_sep>#!/bin/sh
KUBE_API_URL=https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT_HTTPS/api
KUBE_TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
CA_CERT_FILE=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
AUTH_HEADER="Authorization: Bearer $KUBE_TOKEN"
# kubernetesのAPIを叩く
function callK8sApi {
METHOD="$1"
ENDPOINT="${2##/}"
shift
shift
URL="$KUBE_API_URL/$ENDPOINT"
CURL_OPTS="-s --cacert '$CA_CERT_FILE' -H '$AUTH_HEADER' "
if [ "$METHOD" == "GET" ]; then
CURL_OPTS="$CURL_OPTS -G"
for param in "$@"; do
CURL_OPTS="$CURL_OPTS --data-urlencode '$param'"
done
elif [ "$METHOD" == "POST" ]; then
CURL_OPTS="$CURL_OPTS -H 'Content-Type: application/json'"
for param in "$@"; do
CURL_OPTS="$CURL_OPTS -d '$param' "
done
fi
cmd="curl $CURL_OPTS '$URL'"
echo "cmd: $cmd" >&2
echo "$(eval $cmd)"
}
# ノード一覧を取得し、名前を取り出してランダムに1つ抽出する
function getRandomNode {
echo "$(callK8sApi "GET" "/v1/nodes" | jq -r '.items[].metadata.name' | shuf -n 1)"
}
# NodeNameが入っていない(アサインされていない)かつスケジューラの名前がrandom-schedulerのPodを取り出す
function getUnassignedPods {
echo "$(callK8sApi "GET" "/v1/pods" "fieldSelector=spec.nodeName=" "fieldSelector=spec.schedulerName=random-scheduler" | jq -r '.items[].metadata | .namespace + "\t" + .name')"
}
function assignPodToNode {
NAMESPACE=$1
POD=$2
NODE=$3
JSONBODY=$(cat <<JSON
{
"apiVersion": "v1",
"kind": "Binding",
"metadata": {
"name": "$POD"
},
"target": {
"apiVersion": "v1",
"kind": "Node",
"name": "$NODE"
}
}
JSON
)
echo "$(callK8sApi "POST" "/v1/namespaces/$NAMESPACE/pods/$POD/binding" "$JSONBODY")"
}
function main {
while true; do
# 未アサインのpod取得
PODS=$(getUnassignedPods)
# podがなければスリープして再取得
if [ -z "$PODS" ]; then
sleep 1
continue
fi
# podがあるときは1つずつノードをランダムに選んで配置していく
local IFS=$'\n'
for POD in $PODS; do
NODE=$(getRandomNode)
NAMESPACE=$(echo $POD | cut -f 1)
PODNAME=$(echo $POD | cut -f 2)
echo "'${NAMESPACE}:${PODNAME}' -> '$NODE'"
# PodをNodeにアサインする
assignPodToNode "$NAMESPACE" "$PODNAME" "$NODE"
done
sleep 1
done
}
main
<file_sep>FROM alpine:3.12.0
USER root
RUN echo 'alias ll="ls -al"' >> /etc/profile.d/ashrc.sh && \
apk --no-cache add curl jq && \
apk --no-cache add vim
COPY ./random-scheduler.sh /
CMD ["/bin/sh", "/random-scheduler.sh"]
| e628e070f300bd51255701dc4e9d0624b06308fe | [
"Dockerfile",
"Shell"
] | 2 | Shell | miyachi000/random-scheduler | 1f56ecb4775053c7d30a9599b312c9903d4dcdcf | 2a72ebafc13e2be65f352efeb31e0abbd4d76370 |
refs/heads/master | <file_sep>/**
* Created by zemoso on 4/7/17.
*/
public class DividedByNegative extends Exception{
public String getMessage()
{
return "Don't divide with negative numbers";
}
}
<file_sep>
/**
* Created by zemoso on 4/7/17.
*/
public class Exception_Handling {
/**
* @param a a is used to throw exceptions here
* @throws DividedByOne this exception is thrown when a =1
* @throws DividedByZeroException this exception is thrown when a =0
* @throws DividedByNegative this exception is thrown when a < 0
*/
static void divide (int a) throws DividedByOne,DividedByZeroException,DividedByNegative
{
if(a==0)
throw new DividedByZeroException();
else if(a<0)
throw new DividedByNegative();
else if(a==1)
throw new DividedByOne();
}
}
<file_sep>/**
* Created by zemoso on 4/7/17.
*/
public class ExceptionTest {
/**
* This is used to repeatedly take inputs from the main class and throw a null pointer exception when a =-1
* @param a this is used to pass the value to Exception_Handling
*/
public void tester(int a){
try {
if(a!=-1) {
Exception_Handling.divide(a);
}
else {
throw new NullPointerException();
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
finally{
System.out.println("Finally part always gets executed");
}
}
public static void main(String args[])
{
ExceptionTest et=new ExceptionTest();
et.tester(0);
et.tester(1);
et.tester(-3);
et.tester(-1);
}
}
<file_sep>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by zemoso on 12/7/17.
*/
public class KycForm {
private SimpleDateFormat form = new SimpleDateFormat("dd-MM-yyyy");
private Calendar anniversary = Calendar.getInstance();
private Calendar beginningOfRange;
private Calendar endOfRange;
/**
* This method sets the Anniversary Date and the beginning of the range and end of the range.
* @param signUp signUp gives the signUp date of the customer
* @param current current gives the current date the customer is in
*/
private void setAnniversary(Calendar signUp, Calendar current) {
anniversary.set(Calendar.DATE, signUp.get(Calendar.DATE));
anniversary.set(Calendar.MONTH, signUp.get(Calendar.MONTH));
anniversary.set(Calendar.YEAR, current.get(Calendar.YEAR));
beginningOfRange = (Calendar) anniversary.clone();
endOfRange = (Calendar) anniversary.clone();
beginningOfRange.add(Calendar.DATE, -30);
endOfRange.add(Calendar.DATE, +30);
}
/**
* This method sets the beginning of the range.
*
* @param yearValue The yearValue takes the value of how many years u want to move back/front.
* @param monthValue The monthValue takes the value of how many months u want to move back/front.
* @return this method returns the beginning of the range
*/
private Calendar setRangeBeginning(int yearValue, int monthValue) {
Calendar beginningOfRange1;
beginningOfRange1 = (Calendar) beginningOfRange.clone();
beginningOfRange1.add(Calendar.YEAR, +yearValue);
beginningOfRange1.add(Calendar.DATE, +monthValue);
return beginningOfRange1;
}
/**
* @param yearValue The yearValue takes the value of how many years u want to move back/front.
* @param mothValue The monthValue takes the value of how many months u want to move back/front.
* @return returns the ending of the range
*/
private Calendar setRangeEnding(int yearValue, int mothValue) {
Calendar endOfRange1 = (Calendar) endOfRange.clone();
endOfRange1.add(Calendar.YEAR, +yearValue);
endOfRange1.add(Calendar.DATE, +mothValue);
return endOfRange1;
}
/**
* This method prints out the range of dates the customer can fill on the form
*
* @param signUpDate This takes string mentioning the signUp date of the customer.
* @param currentDate This takes string mentioning the current date the customer is in.
* @throws ParseException throws an exception when date is entered wrong or in wrong format.
*/
public String getRange(String signUpDate, String currentDate) throws ParseException {
Calendar signUp = Calendar.getInstance();
Calendar current = Calendar.getInstance();
signUp.setTime(form.parse(signUpDate));
current.setTime(form.parse(currentDate));
if (signUp.after(current)) {
return "No range";
//System.exit(0);
}
setAnniversary(signUp, current);
if (current.after(beginningOfRange) && current.before(endOfRange))
{
return form.format(beginningOfRange.getTime()) + " " + form.format(current.getTime());
}
else if (current.after(endOfRange))
{
Calendar beginningOfRangeOfNextYear = setRangeBeginning(+1, -30);
if (current.after(beginningOfRangeOfNextYear))
return form.format(setRangeBeginning(+1, 0).getTime()) +
" " + form.format(setRangeEnding(+1, +30).getTime());
else {
return form.format(beginningOfRange.getTime()) + " " + form.format(endOfRange.getTime());
}
}
else if(current.before(beginningOfRange))
{
Calendar beginningOfRangeMinusThirty = setRangeBeginning(+0, -30);
if (current.after(beginningOfRangeMinusThirty))
return form.format(beginningOfRange.getTime()) + " " +
form.format(setRangeEnding(+0, +30).getTime());
else {
Calendar previousYearRangeBeginning = setRangeBeginning(-1, 0);
Calendar previousYearRangeEnding = setRangeEnding(-1, 0);
if (previousYearRangeBeginning.before(signUp)) {
return "No range";
}
return form.format(previousYearRangeBeginning.getTime()) + " " +
form.format(previousYearRangeEnding.getTime());
}
}
else
return form.format(current.getTime())+" "+
form.format(current.getTime());
}
}
<file_sep>import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by zemoso on 13/7/17.
*/
public class PingTest {
private Ping p = new Ping("ping -c5 123google.com", 5, "123google.com");
@Test
public void testingIfThereIsNoPacketLoss() {
ArrayList<Double> arrayList = new ArrayList(Arrays.asList(16.3, 15.7, 14.6, 25.00, 36.00));
assertEquals("The median is 16.3", p.median(arrayList));
}
@Test
public void testingIfThereIsPacketLoss() {
ArrayList<Double> arrayList = new ArrayList<>(Arrays.asList(16.3, 15.7, 14.6, 25.00));
assertEquals("There is packet loss, Ping again to get the correct value.The median is 16.0", p.median(arrayList));
}
@Test
public void testingIfThereIsNoReplyFromHost() {
ArrayList<Double> arrayList = new ArrayList<>();
assertEquals("There is a no reply from this host", p.median(arrayList));
}
@Test //this is not working should check again.
public void testingWhenEnteredHostDoesntExist() {
try {
p.runCommand();
}
catch (Exception e)
{
assertTrue(e.getClass() == IOException.class); //Exception is thrown, so assert true gives success.
}
}
}
<file_sep>/**
* Created by zemoso on 13/7/17.
*/
public class AllLettersChecker {
/**
* This method takes the input string and creates a boolean array with value=true for the index of (ASCII value-97)
* only for letters between a-z. Then we check the boolean array to know whether all letters are present or not..
* @param input This takes the input string that needs to be checked.
* @return returns the statement whether or not the string has all letters of the alphabet a-z case insensitive.
*/
public String checkingAllLetters(String input) {
int lengthOfString = input.length();
if (lengthOfString < 26)
return ("Doesn't Contain all letters");
boolean checkerArray[] = new boolean[26];
String lowerCaseString = input.toLowerCase();
char characterArray[] = lowerCaseString.toCharArray();
for (int i : characterArray) {
if (i >= 97 && i <= 122) checkerArray[i - 97] = true;
}
for (boolean i : checkerArray) {
if (!i)
return "Doesn't Contain all letters";
}
return "Contain all letters";
}
}
<file_sep>/**
* Created by zemoso on 3/7/17.
*/
class Cycle {
public Cycle()
{
System.out.println("Hi, I am cycle");
}
public void balance()
{
System.out.println("Balancing cycle");
}
}
class Unicycle extends Cycle
{
public Unicycle()
{
System.out.println("I have one wheel");
}
public void balance()
{
System.out.println("Please help me balance");
}
}
class Bicycle extends Cycle
{
public Bicycle()
{
System.out.println("I have two wheels");
}
public void balance()
{
System.out.println("I need a stand to balance");
}
}
class Tricycle extends Cycle
{
public Tricycle()
{
System.out.println("I have three wheels");
}
}
class Demo{
public static void main(String args[])
{
Unicycle u = new Unicycle();
Bicycle b = new Bicycle();
Tricycle t = new Tricycle();
Cycle c[] = {u,b,t}; // upcasting
System.out.println("\n After Upcasting: \n");
for(Cycle i : c)
{
i.balance();
}
// Down-casting
System.out.println("\n After Downcasting: \n");
u = (Unicycle)c[0];
b = (Bicycle) c[1];
t= (Tricycle) c[2];
u.balance();
b.balance();
t.balance();
}
}<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by zemoso on 5/7/17.
*/
public class RegExp {
static String pattern = "^\\p{Upper}.*\\.$"; //pattern to match the sentence starting with capital letter
static Pattern p = Pattern.compile(pattern);
/**
* This method checks if the given string matches with our specified pattern and returns true or false.
* @param input takes string read from a file as input
* @return returns a Boolean value
*/
public static Boolean checkString(String input)
{
Matcher m = p.matcher(input);
return m.find();
}
public static void main(String args[]) throws IOException {
try {
//Reading Input From a file input.txt.
BufferedReader inputStream = new BufferedReader(new FileReader("input.txt"));
String input;
while ((input = inputStream.readLine()) != null) {
System.out.println("Does the string " + input + " matches the given pattern?\n" + checkString(input));
}
}
catch (Exception e)
{
System.out.println("file not found, please create a file named input.txt in the current working directory");
}
}
}
<file_sep>package raju.DefaultInitializationAssignment.data;
/**
* Created by zemoso on 29/6/17.
*/
public class Data {
private int a; // This is a class field which gets initialised automatically
private char b; // This is a class field which gets initialised automatically
public void print()
{
System.out.println(a);
System.out.println(b);
}
public void print2()
{
int c,d; // These are method fields which does't get initialised automatically
/*System.out.println(c); //This code doesn't execute because fields c & d were not initialised
System.out.println(d);*/ // Fields inside a class gets initialised automatically but not fields
// fields in the methods.
}
}
<file_sep>import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by zemoso on 11/7/17.
*/
class Ping {
private String command;
protected int count;
private String websiteAddress;
//private ArrayList<Float> timeArray = new ArrayList<>();
/**
* This method initialises the arguments.
* @param command This takes the command to be run in the process
* @param count This takes the number of times the user want to ping
* @param websiteAddress This takes the address of the host the user want to ping
*/
public Ping(String command, int count, String websiteAddress)
{
this.command = command;
this.count = count;
this.websiteAddress = websiteAddress;
}
/**
* This method runs the command and takes the value of the time by verifying the string start and end with 64 bytes
* and ms respectively and add it into a timeArray ArrayList.
* @throws IOException When a host is unreachable it throws IOException or when the process cannot execute
* the command.
* @return returns an ArrayList<Double> which contains the time values of each ping.
*/
protected ArrayList<Double> runCommand() throws IOException {
ArrayList<Double> timeArray = new ArrayList<>();
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
if (errorStream.readLine() != null) // If there is no error the s==NUll.
throw new IOException();
String s;
while ((s = inputStream.readLine()) != null) {
if (s.endsWith("ms") && s.startsWith("64 bytes")) {
int index = s.indexOf("time");
if (index != -1) {
Double time = Double.parseDouble(s.substring(index + 5, s.length() - 2));
timeArray.add(time);
}
}
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Unable to reach Host"+" "+ websiteAddress);
}
return timeArray;
}
/**
* This method is used to calculate the median of the ping times which are stored in timeArray.
* It also checks if there is no reply from the host by checking the timeArray size and packet loss by comparing
* the timeArray size with count.
* @throws IndexOutOfBoundsException When we are trying to access the index of timeArray that is not yet been
* initialised , this error is thrown.
* @return returns the median value
*/
protected String median(ArrayList<Double> timeArray) throws IndexOutOfBoundsException
{
String s ="";
if(timeArray.size()==0)
return ("There is a no reply from this host");
if(count!=timeArray.size()) {
s = "There is packet loss, Ping again to get the correct value.";
// return (((float) (count - timeArray.size()) / (float) (count)) * 100);
}
Collections.sort(timeArray);
if (timeArray.size() % 2 == 0) {
return s+"The median is "+((timeArray.get(timeArray.size() / 2) + timeArray.get(timeArray.size() / 2 - 1)) / 2);
}
else
{
return s+"The median is "+(timeArray.get((timeArray.size() - 1) / 2));
}
}
/**
* This method is used to take inputs from the user and build a command string and pass on it to the rumCommand
* method and then finding its median by calling a median method.
* This method also takes care when user enters wrong inputs by catching a InputMismatchException
* @param args arguments for the main method
* @throws IOException This error is thrown when runCommand method is called and an error occurs there
*/
public static void main(String[] args) throws IOException{
try {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the websiteAddress address you want to ping:");
String websiteAddress = scan.nextLine();
System.out.println("How many times do u want to ping?");
int count = scan.nextInt();
Ping p = new Ping("ping -c" + count + " " + websiteAddress,count,websiteAddress);
ArrayList<Double> timeArray = p.runCommand();
if(timeArray.size()==0) {
//System.out.println("auishd");
System.exit(0);
}
System.out.println(p.median(timeArray));
}
catch(InputMismatchException e)
{
System.out.println("Please enter an integer for number of times to ping");
}
}
}
| c59e84066793ac12d9f3f86c37f32ad625185814 | [
"Java"
] | 10 | Java | Bhupathi-Raju/JAVA | 31a61954c82665f6c4163308c14c25da1fef24d9 | 90be911cd4e9e3ef2e96a01c2498bdb56597626c |
refs/heads/master | <file_sep>//! A safe binary tree.
//!
//! The `binary tree` allows inserting, removing and is naturally sorted.
//!
//! NOTE: This was written for a learning purpose.
use super::stack::Stack;
use std::cmp::Ordering;
/// A binary tree build from Nodes. This struct represents a binary tree
/// holding a root node.
pub struct BinaryTree<T> {
head: Link<T>,
}
/// A Link between Nodes.
type Link<T> = Option<Box<Node<T>>>;
/// A Node in a binary tree which holds a reference to the left and right Nodes as well as a value.
#[derive(Debug, Eq, PartialEq)]
struct Node<T> {
left: Link<T>,
right: Link<T>,
value: T,
}
/// The Iterator for a binary tree, containing a stack with all nodes that should be visited.
/// Instances are created by [`BinaryTree::iter()`]. See its
/// documentation for more.
pub struct Iter<'a, T: 'a> {
visited: Box<Stack<&'a Box<Node<T>>>>,
}
impl<T: Eq + std::cmp::Ord> BinaryTree<T> {
/// Creates a new and empty `BinaryTree`.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::<()>::new();
/// assert!(binary_tree.is_empty());
///```
pub fn new() -> Self {
BinaryTree { head: None }
}
/// Inserts a new element into the tree. The tree alway keeps an ordered structure by
/// making sure that the left child node is always "bigger" than the right child node.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(1);
/// binary_tree.insert(2);
///
/// assert!(binary_tree.contains(1));
/// assert!(binary_tree.contains(2));
/// ```
pub fn insert(&mut self, value: T) -> bool {
if self.is_empty() {
self.head = Some(Box::new(Node::new(value)));
return true;
}
self.head.as_mut().unwrap().insert(value)
}
/// Checks if the tree is empty.
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
/// Searches for an element in the tree and returns whether the tree contains the element
/// or not. As the tree is always ordered, this happens relatively fast. (As long as it's not)
/// super unordered.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(1);
///
/// assert!(binary_tree.contains(1));
/// ```
pub fn contains(&self, value: T) -> bool {
match self.head.as_ref() {
Some(node) => match value.cmp(&node.value) {
Ordering::Equal => true,
Ordering::Greater => match node.right.as_ref() {
Some(node) => node.contains(value),
None => false,
},
Ordering::Less => match node.left.as_ref() {
Some(node) => node.contains(value),
None => false,
},
},
None => false,
}
}
/// Traverses the tree inorder. That means it goes through the tree and recursively
/// visites the leftmost child, the root and then the rightmost child.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(10);
/// binary_tree.insert(8);
/// binary_tree.insert(11);
/// binary_tree.insert(9);
/// binary_tree.insert(12);
///
/// assert_eq!(binary_tree.inorder(), vec![&8, &9, &10, &11, &12]);
/// ```
pub fn inorder(&self) -> Vec<&T> {
match &self.head {
Some(node) => node.inorder(),
None => Vec::new(),
}
}
/// Traverses the tree preorder. That means it goes through the tree and recursively
/// visites the root, the leftmost child, and then the rightmost child.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(10);
/// binary_tree.insert(8);
/// binary_tree.insert(11);
/// binary_tree.insert(9);
/// binary_tree.insert(12);
///
/// assert_eq!(binary_tree.preorder(), vec![&10, &8, &9, &11, &12]);
/// ```
pub fn preorder(&self) -> Vec<&T> {
match &self.head {
Some(node) => node.preorder(),
None => Vec::new(),
}
}
/// Traverses the tree postorder. That means it goes through the tree and recursively
/// visites the the leftmost child, the righmost child and then the root node.
/// # Example
/// ```rust
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(10);
/// binary_tree.insert(8);
/// binary_tree.insert(11);
/// binary_tree.insert(9);
/// binary_tree.insert(12);
///
/// assert_eq!(binary_tree.preorder(), vec![&10, &8, &9, &11, &12]);
/// ```
pub fn postorder(&self) -> Vec<&T> {
match &self.head {
Some(node) => node.postorder(),
None => Vec::new(),
}
}
/// Returns an `Iterator` over the elements of a tree. First the root node is returned,
/// than an ordering from the lowest to the highest element.
/// # Example
/// ```
/// use data_structure_with_colin::binary_tree::BinaryTree;
/// let mut binary_tree = BinaryTree::new();
/// binary_tree.insert(10);
/// binary_tree.insert(8);
/// binary_tree.insert(11);
///
/// for elem in binary_tree.iter() {
/// println!("{}", elem);
/// }
/// ```
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
let mut visited = Box::new(Stack::new());
visited.push(self.head.as_ref().unwrap());
Iter { visited: visited }
}
}
impl<T: Eq + std::cmp::Ord> Node<T> {
pub fn new(value: T) -> Self {
Node {
left: None,
right: None,
value,
}
}
pub fn insert(&mut self, value: T) -> bool {
match value.cmp(&self.value) {
Ordering::Less => match &mut self.left {
Some(node) => node.insert(value),
None => {
self.left = Some(Box::new(Node::new(value)));
return true;
}
},
Ordering::Equal => return false,
Ordering::Greater => match &mut self.right {
Some(node) => node.insert(value),
None => {
self.right = Some(Box::new(Node::new(value)));
return true;
}
},
}
}
fn contains(&self, value: T) -> bool {
match value.cmp(&self.value) {
Ordering::Equal => true,
Ordering::Greater => match self.right.as_ref() {
Some(node) => node.contains(value),
None => false,
},
Ordering::Less => match self.left.as_ref() {
Some(node) => node.contains(value),
None => false,
},
}
}
pub fn inorder(&self) -> Vec<&T> {
let mut result = vec![];
match self.left.as_ref() {
Some(node) => {
let mut left_vec = node.inorder();
result.append(left_vec.as_mut());
}
None => (),
}
result.push(&self.value);
match self.right.as_ref() {
Some(node) => {
let mut right_vec = node.inorder();
result.append(right_vec.as_mut());
}
None => (),
}
result
}
pub fn postorder(&self) -> Vec<&T> {
let mut result = vec![];
match self.left.as_ref() {
Some(node) => {
let mut vec_left = node.postorder();
result.append(vec_left.as_mut());
}
None => (),
}
match self.right.as_ref() {
Some(node) => {
let mut right_vec = node.postorder();
result.append(right_vec.as_mut());
}
None => (),
}
result.push(&self.value);
result
}
pub fn preorder(&self) -> Vec<&T> {
let mut result = vec![];
result.push(&self.value);
match self.left.as_ref() {
Some(node) => {
let mut vec_left = node.preorder();
result.append(vec_left.as_mut());
}
None => (),
}
match self.right.as_ref() {
Some(node) => {
let mut right_vec = node.preorder();
result.append(right_vec.as_mut());
}
None => (),
}
result
}
}
impl<'a, T: std::cmp::Eq> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.visited.is_empty() {
return None;
}
let node = self.visited.pop();
match (
node.unwrap().as_ref().left.as_ref(),
node.unwrap().as_ref().right.as_ref(),
) {
(None, None) => (),
(leaf @ Some(_), None) | (None, leaf @ Some(_)) => self.visited.push(&leaf.unwrap()),
(Some(left), Some(right)) => {
self.visited.push(right);
self.visited.push(left);
}
}
return Some(&node.unwrap().as_ref().value);
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_insert() {
let mut sut = BinaryTree::new();
assert!(sut.insert(42));
assert!(sut.insert(41));
assert!(sut.insert(43));
}
#[test]
fn test_traversal() {
let mut sut = BinaryTree::new();
sut.insert(10);
sut.insert(8);
sut.insert(11);
sut.insert(9);
sut.insert(12);
assert_eq!(sut.inorder(), vec![&8, &9, &10, &11, &12]);
assert_eq!(sut.preorder(), vec![&10, &8, &9, &11, &12]);
assert_eq!(sut.postorder(), vec![&9, &8, &12, &11, &10]);
}
#[test]
fn test_contains() {
let mut sut = BinaryTree::new();
sut.insert(10);
sut.insert(8);
sut.insert(11);
sut.insert(9);
sut.insert(12);
assert!(sut.contains(10));
assert!(sut.contains(8));
assert!(sut.contains(11));
assert!(sut.contains(9));
assert!(sut.contains(12));
}
#[test]
fn test_iter_count() {
let mut sut = BinaryTree::new();
sut.insert(10);
sut.insert(8);
sut.insert(11);
sut.insert(9);
sut.insert(12);
assert_eq!(sut.iter().count(), 5);
}
#[test]
fn test_iter_elementwise() {
let mut sut = BinaryTree::new();
sut.insert(10);
sut.insert(8);
sut.insert(11);
sut.insert(9);
sut.insert(12);
let mut iter = sut.iter();
assert_eq!(iter.next(), Some(&10));
assert_eq!(iter.next(), Some(&8));
assert_eq!(iter.next(), Some(&9));
assert_eq!(iter.next(), Some(&11));
assert_eq!(iter.next(), Some(&12));
}
}
<file_sep>pub mod binary_tree;
pub mod hash_map;
pub mod linked_list;
pub mod avl_tree;
pub mod stack;
<file_sep>use std::cmp::max;
use std::mem::{replace, swap};
#[derive(Debug, PartialEq, Clone)]
pub struct AVLNode<T: Ord> {
pub value: T,
pub left: AVLTree<T>,
pub right: AVLTree<T>,
pub height: usize,
}
pub type AVLTree<T> = Option<Box<AVLNode<T>>>;
impl<'a, T: 'a + Ord> AVLNode<T> {
// Overflow precautions
pub fn balance_factor(&self) -> i8 {
let left_height = self.left_height();
let right_height = self.right_height();
if left_height >= right_height {
(left_height - right_height) as i8
} else {
-((right_height - left_height) as i8)
}
}
pub fn update_height(&mut self) {
self.height = 1 + max(self.left_height(), self.right_height())
}
fn left_height(&self) -> usize {
self.left.as_ref().map_or(0, |left| left.height)
}
fn right_height(&self) -> usize {
self.right.as_ref().map_or(0, |right| right.height)
}
fn rotate_right(&mut self) {
if self.left.is_none() {
return;
}
let new_center = self.left.as_mut().unwrap();
let new_left = new_center.left.take();
let left_of_new_right = new_center.right.take();
let mut new_right = replace(&mut self.left, new_left);
swap(&mut self.value, &mut new_right.as_mut().unwrap().value);
let right_tree = self.right.take();
let new_right_node = new_right.as_mut().unwrap();
new_right_node.left = left_of_new_right;
new_right_node.right = right_tree;
self.right = new_right;
if let Some(node) = self.right.as_mut() {
node.update_height();
}
self.update_height();
}
fn rotate_left(&mut self) {
if self.right.is_none() {
return;
}
let new_center = self.right.as_mut().unwrap();
let new_right = new_center.right.take();
let right_of_new_left = new_center.left.take();
let mut new_left = replace(&mut self.right, new_right);
swap(&mut self.value, &mut new_left.as_mut().unwrap().value);
let left_tree = self.left.take();
let new_left_node = new_left.as_mut().unwrap();
new_left_node.left = left_tree;
new_left_node.right = right_of_new_left;
self.left = new_left;
if let Some(node) = self.left.as_mut() {
node.update_height();
}
self.update_height();
}
pub fn rebalance(&mut self) {
match self.balance_factor() {
-2 => {
let right_node = self.right.as_mut().unwrap();
if right_node.balance_factor() == 1 {
right_node.rotate_right();
}
self.rotate_left();
}
2 => {
let left_node = self.left.as_mut().unwrap();
if left_node.balance_factor() == -1 {
left_node.rotate_left();
}
self.rotate_right();
}
_ => return,
}
}
}
<file_sep>//! A safe linked list.
//!
//! The `LinkedList` allows inserting, removing and iterating it's elements.
//!
//! NOTE: This was written for a learning purpose.
use std::convert::From;
/// A linked list build from Nodes. This struct represents a linked list
/// with a head and it's length.
#[derive(Debug, Eq, PartialEq)]
pub struct LinkedList<T> {
head: Link<T>,
len: usize,
}
/// A Link between Nodes.
type Link<T> = Option<Box<Node<T>>>;
/// A Node in a linked list which holds a reference to the next Node as well as a value.
#[derive(Debug, Eq, PartialEq)]
struct Node<T> {
next: Link<T>,
value: T,
}
/// The Iterator for a linked list, containing the head as well as the size of the list.
/// Instances are created by [`LinkedList::iter()`]. See its
/// documentation for more.
pub struct Iter<'a, T: 'a> {
head: &'a Link<T>,
len: usize,
}
/// An owning Iteraror the elements of a linked list.
/// Instances are created by [`LinkedList::into_iter()`]. See its
/// documentation for more.
pub struct IntoIter<T: Eq> {
list: LinkedList<T>,
}
impl<T> LinkedList<T>
where
T: Eq + Ord,
{
/// Creates a new and empty `LinkedList`.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::<()>::new();
/// assert!(linked_list.is_empty());
///```
#[inline]
pub fn new() -> Self {
LinkedList { head: None, len: 0 }
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Appends a new element to the list.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::new();
/// linked_list.append(1);
/// linked_list.append(2);
///
/// assert!(linked_list.contains(1));
/// assert!(linked_list.contains(2));
/// ```
pub fn append(&mut self, val: T) -> bool {
match &mut self.head {
Some(first) => {
self.len += 1;
first.append(val)
}
None => {
self.head = Some(Box::new(Node::new(val)));
self.len += 1;
true
}
}
}
/// Checks if a `LinkedList` contains a given element.
pub fn contains(&self, val: T) -> bool {
match &self.head {
Some(first) => first.contains(val),
None => false,
}
}
/// Removes an element at the given index from the list.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::new();
/// linked_list.append(1);
/// linked_list.append(2);
///
/// assert!(linked_list.contains(1));
/// assert!(linked_list.contains(2));
///
/// linked_list.remove(0);
///
/// assert!(!linked_list.contains(1));
/// ```
pub fn remove(&mut self, index: usize) -> bool {
if index >= self.len {
false
} else if index == 0 {
let mut old_head = self.head.take().unwrap();
if let Some(new) = old_head.next.take() {
self.head = Some(new);
}
self.len -= 1;
true
} else {
match &mut self.head {
Some(val) => {
self.len -= 1;
val.remove(index, 0)
}
None => false,
}
}
}
pub fn is_sorted(&self) -> bool {
match &self.head {
Some(head) => head.is_sorted(),
None => false,
}
}
/// Why Merge-Sort?
///
/// Quick sort works well for sorting in-place.
/// In particular, most of the operations can be defined in terms of swapping pairs of elements
/// in an array. To do that, however, you normally "walk" through the array with two pointers
/// (or indexes, etc.) One starts at the beginning of the array and the other at the end.
/// Both then work their way toward the middle (and you're done with a particular partition step
/// when they meet). That's expensive with files, because files are oriented primarily toward reading
/// in one direction, from beginning to end. Starting from the end and seeking backwards is usually
/// relatively expensive.
/// At least in its simplest incarnation, merge sort is pretty much the opposite.
/// The easy way to implement it only requires looking through the data in one direction,
/// but involves breaking the data into two separate pieces, sorting the pieces,
/// then merging them back together.
/// With a linked list, it's easy to take (for example) alternating elements in one linked list,
/// and manipulate the links to create two linked lists from those same elements instead.
/// With an array, rearranging elements so alternating elements go into separate arrays is easy
/// if you're willing to create a copy as big as the original data, but otherwise rather more
/// non-trivial.
/// Likewise, merging with arrays is easy if you merge elements from the source arrays
/// into a new array with the data in order -- but to do it in place without creating a whole
/// new copy of the data is a whole different story. With a linked list, merging elements together
/// from two source lists into a single target list is trivial -- again, you just manipulate links,
/// without copying elements.
/// As for using Quicksort to produce the sorted runs for an external merge sort,
/// it does work, but it's (decidedly) sub-optimal as a rule. To optimize a merge-sort,
/// you normally want to maximize the lengths of each sorted "run" as you produce it.
/// If you simply read in the data that will fit in memory, Quicksort it and write it out,
/// each run will be restricted to (a little less than) the size of the available memory.
/// You can do quite a bit better than that as a rule though.
/// You start by reading in a block of data, but instead of using a Quicksort on it, you build a heap.
/// Then, as you write each item out from the heap into the sorted "run" file, you read another item
/// in from your input file. If it's larger than the item you just wrote to disk, you insert it into
/// your existing heap, and repeat.
/// Items that are smaller (i.e., belong before items that have already been written) you keep
/// separate, and build into a second heap. When (and only when) your first heap is empty,
/// and the second heap has taken over all the memory, you quit writing items to the existing "run" file,
/// and start on a new one.
/// Exactly how effective this will be depends on the initial order of the data.
/// In the worst case (input sorted in inverse order) it does no good at all. In the best case
/// (input already sorted) it lets you "sort" the data in a single run through the input.
/// In an average case (input in random order) it lets you approximately double the length of
/// each sorted run, which will typically improve speed by around 20-25%
/// (though the percentage varies depending on how much larger your data is than the available memory).
#[inline]
pub fn sort(&mut self) {
if self.head.is_none() {
return;
}
let (mut front, mut back) = self.split();
if front.len > 1 {
front.sort();
}
if back.len > 1 {
back.sort();
}
self.head = Some(Box::new(Node::from(LinkedList::merge(
&mut front, &mut back,
))));
}
#[inline]
fn split(&mut self) -> (LinkedList<T>, LinkedList<T>) {
let back = self
.head
.as_mut()
.unwrap()
.get_back(self.len / 2, 0)
.unwrap();
let front = self.head.take().unwrap();
(LinkedList::from(*front), LinkedList::from(*back))
}
#[inline]
fn merge(front: &mut LinkedList<T>, back: &mut LinkedList<T>) -> Self {
let mut result: Node<T>;
if front.head.is_none() {
return LinkedList::from(*back.head.take().unwrap());
} else if back.head.is_none() {
return LinkedList::from(*front.head.take().unwrap());
}
if front.head.as_ref().unwrap().value <= back.head.as_ref().unwrap().value {
result = Node::new(front.pop_front().unwrap());
} else {
result = Node::new(back.pop_front().unwrap());
}
result.set_next(Node::from(LinkedList::merge(front, back)));
LinkedList::from(result)
}
/// Removes the head and returns it as an Option.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::new();
/// linked_list.append(1);
/// linked_list.append(2);
///
/// assert_eq!(linked_list.pop_front(), Some(1))
/// ```
pub fn pop_front(&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
let mut old_head = self.head.take().unwrap();
let res = Some(old_head.value);
if let Some(next) = old_head.next.take() {
self.head = Some(next);
}
self.len -= 1;
res
}
}
/// Returns an `Iterator` over the elements of a list.
/// # Example
/// ```
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::new();
/// linked_list.append(1);
/// linked_list.append(2);
/// for elem in linked_list.iter() {
/// println!("{}", elem);
/// }
/// ```
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
Iter {
head: &self.head,
len: self.len,
}
}
/// Reverses the linked list.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let mut linked_list = LinkedList::new();
/// linked_list.append(1);
/// linked_list.append(2);
/// linked_list.append(3);
/// linked_list.append(4);
///
/// let reversed = linked_list.reverse();
/// ```
pub fn reverse(&mut self) -> Self {
if self.is_empty() {
return LinkedList::new();
}
let mut cur = self.head.take().unwrap();
if cur.next.is_none() {
return LinkedList::from(*cur);
}
let mut next = cur.next.take().unwrap();
// return in case the list does not have more than two elements
if next.next.is_none() {
next.next = Some(cur);
return LinkedList::from(*next);
}
while next.next.is_some() {
let look_ahead = next.next.take().unwrap();
next.next = Some(cur);
cur = next;
next = look_ahead;
}
next.next = Some(cur);
LinkedList::from(*next)
}
}
impl<T: Eq + Ord> IntoIterator for LinkedList<T> {
type Item = T;
type IntoIter = IntoIter<T>;
/// Consumes the list into an iterator over the lists values.
fn into_iter(self) -> Self::IntoIter {
IntoIter { list: self }
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
/// Returns the next element of a list iterator.
fn next(&mut self) -> Option<Self::Item> {
if self.len == 0 {
return None;
}
self.head.as_ref().map(|head| {
self.len -= 1;
self.head = &head.next;
&head.value
})
}
/// Returns the length of an iterator.
fn count(self) -> usize {
self.len
}
}
impl<'a, T: Eq + Ord> Iterator for IntoIter<T> {
type Item = T;
/// Returns the next element of a IntoIter.
fn next(&mut self) -> Option<Self::Item> {
self.list.pop_front()
}
}
impl<T> Node<T>
where
T: Eq + Ord,
{
#[inline]
fn set_next(&mut self, new: Node<T>) {
self.next = Some(Box::new(new));
}
#[inline]
fn get_back(&mut self, index: usize, mut cur: usize) -> Option<Box<Node<T>>> {
if cur + 1 == index {
self.next.take()
} else {
cur += 1;
self.next.as_mut().unwrap().get_back(index, cur)
}
}
fn is_sorted(&self) -> bool {
let look = self;
match &look.next {
Some(val) => {
if look.value <= val.value {
return val.is_sorted();
} else {
return false;
}
}
None => true,
}
}
fn new(value: T) -> Self
where
T: Ord,
{
Node { next: None, value }
}
#[inline]
fn append(&mut self, val: T) -> bool {
match &mut self.next {
Some(iter) => iter.append(val),
None => {
self.set_next(Node::new(val));
true
}
}
}
#[inline]
fn contains(&self, val: T) -> bool {
if val == self.value {
true
} else {
match &self.next {
Some(iter) => iter.contains(val),
None => false,
}
}
}
#[inline]
fn remove(&mut self, index: usize, mut cur: usize) -> bool {
if cur + 1 == index {
let mut garbage = self.next.take().unwrap();
match garbage.next.take() {
None => true,
Some(new_link) => {
self.set_next(*new_link);
true
}
}
} else {
cur += 1;
self.next.as_mut().unwrap().remove(index, cur)
}
}
fn get_length(&self) -> usize {
let mut count = 1;
let mut walk = Some(self);
while walk.unwrap().next.is_some() {
walk = walk.unwrap().next.as_deref();
count += 1;
}
count
}
}
/// Macro for creating a list with given elements. Works like the Vec![] Macro.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let linked_list = list![1, 2, 3];
///
/// assert!(linked_list.contains(1));
/// assert!(linked_list.contains(2));
/// assert!(linked_list.contains(3));
/// ```
macro_rules! list {
() => {
LinkedList::new();
};
($elem:expr) => {{
let mut res = LinkedList::new();
res.append($elem);
res
}};
($($elem:expr),+) => {{
let mut res = LinkedList::new();
$(res.append($elem);)+
res
}};
}
/// Creates a `LinkedList` from a `Vec`.
/// # Example
/// ```rust
/// use data_structure_with_colin::linked_list::LinkedList;
/// let v = vec![1, 2, 3];
/// let linked_list = LinkedList::from(v);
///
/// assert!(linked_list.contains(1));
/// assert!(linked_list.contains(2));
/// assert!(linked_list.contains(3));
///```
impl<T> From<Vec<T>> for LinkedList<T>
where
T: Eq + Ord,
{
fn from(list: Vec<T>) -> Self {
let mut result = list![];
for elem in list {
result.append(elem);
}
result
}
}
impl<T> From<LinkedList<T>> for Node<T>
where
T: Eq + Ord,
{
fn from(list: LinkedList<T>) -> Self {
*list.head.unwrap()
}
}
impl<T> From<Node<T>> for LinkedList<T>
where
T: Eq + Ord,
{
fn from(node: Node<T>) -> Self {
let length = node.get_length();
LinkedList {
head: Some(Box::new(node)),
len: length,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_new() {
let sut = LinkedList::<bool>::new();
assert_eq!(sut.head, None);
assert_eq!(sut.is_empty(), true);
}
#[test]
fn test_append() {
let mut sut = LinkedList::<i32>::new();
assert_eq!(&sut.append(1), &true);
assert_eq!(sut.head.unwrap().value, (1 as i32));
}
#[test]
fn test_multiple_append() {
let mut sut = LinkedList::new();
sut.append(3453);
sut.append(342);
for i in 0..10 {
sut.append(i);
}
for i in 0..10 {
assert_eq!(sut.contains(i), true);
}
assert_eq!(sut.contains(342), true);
assert_eq!(sut.contains(3453), true);
}
#[test]
fn test_empty_contains() {
let sut = LinkedList::<i32>::new();
assert_eq!(sut.contains(42), false);
}
#[test]
fn test_contains() {
let mut sut = LinkedList::<i32>::new();
assert_eq!(sut.contains(42), false);
sut.append(42);
assert_eq!(sut.contains(42), true);
}
#[test]
fn test_to_list() {
let vector = vec![1, 2, 3];
let sut = LinkedList::from(vector);
assert_eq!(sut.head.unwrap().value, 1);
let vector = vec![1, 2, 3];
let sut = LinkedList::from(vector);
assert_eq!(sut.head.unwrap().next.unwrap().value, 2);
let vector = vec![1, 2, 3];
let sut = LinkedList::from(vector);
assert_eq!(sut.head.unwrap().next.unwrap().next.unwrap().value, 3);
}
#[test]
fn test_macro() {
let sut: LinkedList<u32> = list![];
assert_eq!(sut.head, None);
let sut = list![2];
assert_eq!(sut.head.unwrap().value, 2);
let sut = list![1, 2, 3];
assert_eq!(sut.contains(1), true);
assert_eq!(sut.contains(2), true);
assert_eq!(sut.contains(3), true);
}
#[test]
fn test_remove_simple() {
let mut sut: LinkedList<u32> = list![];
assert_ne!(true, sut.remove(0));
sut.append(45);
assert!(sut.contains(45));
sut.remove(0);
assert!(!sut.contains(45))
}
#[test]
fn test_remove_more() {
let mut sut: LinkedList<u32> = list![];
sut.append(45);
sut.append(56);
sut.append(234);
sut.append(4345);
sut.append(3532);
sut.append(43234);
assert_eq!(sut.len, 6);
sut.remove(5);
assert!(!sut.contains(43234));
assert_eq!(sut.len, 5);
sut.remove(2);
assert!(!sut.contains(234));
assert_eq!(sut.len, 4);
}
#[test]
fn test_is_sorted() {
let mut sut = list![];
sut.append(4);
sut.append(3);
sut.append(5);
assert!(!sut.is_sorted());
sut.remove(0);
assert!(sut.is_sorted());
}
#[test]
fn test_remove_head() {
let mut sut: LinkedList<u32> = list![];
sut.append(45);
sut.append(56);
sut.append(234);
sut.append(4345);
sut.append(3532);
sut.append(43234);
assert_eq!(sut.len, 6);
assert!(sut.contains(45));
sut.remove(0);
assert!(!sut.contains(45));
let val = sut.head.unwrap().value;
assert_eq!(val, 56);
assert_eq!(sut.len, 5);
println!("{}", val);
}
#[test]
fn test_get_length() {
let mut sut: LinkedList<u32> = list![1, 2, 4, 5, 6];
let head = sut.head.take().unwrap();
let test = LinkedList::from(*head);
assert_eq!(test.len, 5)
}
#[test]
fn test_pop_front() {
let mut sut = LinkedList::new();
sut.append(1);
sut.append(2);
assert_eq!(sut.pop_front(), Some(1))
}
#[test]
fn test_iter_count() {
let sut = list![1, 2, 3, 4, 5];
assert_eq!(sut.iter().count(), 5);
}
#[test]
fn test_iter_loop() {
let sut = list![1, 2, 3, 4, 5];
let mut iter_sut = sut.iter();
assert_eq!(iter_sut.next(), Some(&1));
assert_eq!(iter_sut.next(), Some(&2));
assert_eq!(iter_sut.next(), Some(&3));
assert_eq!(iter_sut.next(), Some(&4));
assert_eq!(iter_sut.next(), Some(&5));
}
#[test]
fn test_into_iter() {
let sut = list![1, 2, 3, 4, 5];
let mut iter_sut = sut.into_iter();
assert_eq!(iter_sut.next(), Some(1));
assert_eq!(iter_sut.next(), Some(2));
assert_eq!(iter_sut.next(), Some(3));
assert_eq!(iter_sut.next(), Some(4));
assert_eq!(iter_sut.next(), Some(5));
}
#[test]
fn test_sort() {
let mut sut = list![5, 4, 3, 2, 1];
assert!(!sut.is_sorted());
sut.sort();
assert!(sut.is_sorted());
let mut iter_sut = sut.iter();
assert_eq!(iter_sut.next(), Some(&1));
assert_eq!(iter_sut.next(), Some(&2));
assert_eq!(iter_sut.next(), Some(&3));
assert_eq!(iter_sut.next(), Some(&4));
assert_eq!(iter_sut.next(), Some(&5));
}
#[test]
fn test_sort_advanced() {
let mut sut = list![1938, 234, 239842, 28, 32, 2, 4, 2382, 1093482, 23, 34, 89, 2];
assert!(!sut.is_sorted());
sut.sort();
assert!(sut.is_sorted());
}
#[test]
fn test_list_reverse() {
let mut sut = list![1, 2, 3, 4];
let should = list![4, 3, 2, 1];
let reversed = sut.reverse();
let mut iter_should = should.iter();
let mut iter_reversed = reversed.iter();
for item in iter_reversed {
let should = iter_should.next().unwrap();
assert_eq!(item, should)
}
}
#[test]
fn test_list_reverse_short() {
let mut sut = list![1, 2];
let should = list![2, 1];
let reversed = sut.reverse();
let mut iter_should = should.iter();
let mut iter_reversed = reversed.iter();
assert_eq!(iter_should.next(), iter_reversed.next())
}
}
<file_sep>pub mod set;
mod tree;
<file_sep># Data structures in Rust
Small collection of common datastructures (and algorithms), implemented for the purpose of learning the language Rust.
<file_sep>//! A safe stack.
//!
//! The `Stack` allows inserting, removing and iterating it's elements.
//!
//! NOTE: This was written for a learning purpose.
use super::linked_list::LinkedList;
use std::iter::FromIterator;
/// A Stack build from Nodes. This struct represents a Stack with a head node and a size.
pub struct Stack<T> {
first: Link<T>,
size: i32,
}
/// A link between Nodes.
type Link<T> = Option<Box<Node<T>>>;
/// A node in a stack which holds some value of Type T.
/// It also saves the next node in the stack.
struct Node<T> {
next: Link<T>,
value: T,
}
/// An Iter struct for iterating over the stacks elements.
/// Instances are created by [`Stack::iter()`].
pub struct Iter<'a, T: 'a> {
head: &'a Link<T>,
}
/// An owning Iterator of the stacks elements.
/// Instances are created by [`Stack::into_iter()`]. See its
/// documentation for more.
pub struct IntoIter<T: Eq> {
stack: Stack<T>,
}
impl<T: Eq> Stack<T> {
/// Creates a new empty stack.
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::<()>::new();
/// assert!(stack.is_empty());
/// ```
pub fn new() -> Self {
Stack {
first: None,
size: 0,
}
}
/// Inserts into a stack. Remember that a stack works in the 'last in first out' principle.
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::new();
/// stack.push(1);
/// assert!(!stack.is_empty());
/// ```
pub fn push(&mut self, elem: T) {
if self.is_empty() {
self.first = Some(Box::new(Node::new(elem)));
self.size += 1;
} else {
let mut new_node = Box::new(Node::new(elem));
new_node.next = self.first.take();
self.first = Some(new_node);
self.size += 1;
}
}
/// Returns the size (depth) of the stack. It iterates over all elements to do so and is therefore not super fast.
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::new();
/// stack.push(1);
/// stack.push(2);
/// assert_eq!(stack.size(), 2);
/// ```
pub fn size(&self) -> i32 {
self.size
}
/// Checks if a stack contains a specific element. It iterates over the elements until it finds the searched one
/// or the end is reached.
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::new();
/// stack.push(1);
/// assert!(!stack.contains(2));
/// assert!(stack.contains(1));
/// ```
pub fn contains(&self, value: T) -> bool {
return if self.is_empty() {
false
} else if self.first.as_ref().unwrap().value == value {
true
} else {
self.first.as_ref().unwrap().contains(value)
};
}
/// Pops the first element of a stack. Remember that the stacks first element is always the last one that got inserted (LIFO-Principle).
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::new();
/// stack.push(2);
/// stack.push(1);
/// assert_eq!(stack.pop(), Some(1));
/// assert!(!stack.is_empty());
/// ```
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None;
} else {
let mut old_head = self.first.take();
self.first = old_head.as_mut().unwrap().next.take();
self.size -= 1;
Some(old_head.unwrap().value)
}
}
/// Checks if the current stack is empty or not.
/// ```rust
/// use data_structure_with_colin::stack::Stack;
/// let mut stack = Stack::new();
/// assert!(stack.is_empty());
/// stack.push(1);
/// assert!(!stack.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.first.is_none()
}
/// Returns a non-owning iterator for the stack which iterates over the element in the LIFO way.
pub fn iter(&self) -> Iter<T> {
Iter { head: &self.first }
}
}
impl<T: Eq> Default for Stack<T> {
/// Creates an empty `LinkedList<T>`.
#[inline]
fn default() -> Self {
Stack::new()
}
}
impl<T: Eq + Ord> From<LinkedList<T>> for Stack<T> {
fn from(list: LinkedList<T>) -> Self {
list.into_iter().collect()
}
}
impl<T: Eq> FromIterator<T> for Stack<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut result = Stack::new();
for elem in iter {
result.push(elem);
}
result
}
}
impl<T: Eq> Node<T> {
#[inline]
fn new(value: T) -> Self {
Node { next: None, value }
}
#[inline]
fn contains(&self, value: T) -> bool {
return if self.value == value {
true
} else {
match &self.next {
Some(node) => node.contains(value),
None => false,
}
};
}
}
impl<T: Eq> IntoIterator for Stack<T> {
type Item = T;
type IntoIter = IntoIter<T>;
/// Consumes the list into an iterator over the lists values.
fn into_iter(self) -> Self::IntoIter {
IntoIter { stack: self }
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
/// Returns the next element of a stack.
fn next(&mut self) -> Option<Self::Item> {
self.head.as_ref().map(|node| {
self.head = &node.next;
&node.value
})
}
}
impl<'a, T: Eq> Iterator for IntoIter<T> {
type Item = T;
/// Returns the next element of a IntoIter.
fn next(&mut self) -> Option<Self::Item> {
self.stack.pop()
}
}
macro_rules! stack {
() => {
Stack::new();
};
($($elem:expr),+) => {{
let mut res = Stack::new();
$(res.push($elem);)+
res
}};
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_new_stack() {
let sut = Stack::<()>::new();
assert!(sut.is_empty());
}
#[test]
fn test_push() {
let mut sut = Stack::new();
sut.push(1);
assert!(!sut.is_empty());
}
#[test]
fn test_push_1_2_3() {
let mut sut = Stack::new();
sut.push(1);
sut.push(2);
sut.push(3);
assert!(!sut.is_empty());
assert_eq!(sut.size(), 3);
}
#[test]
fn test_pop() {
let mut sut = Stack::new();
assert_eq!(sut.pop(), None);
sut.push(1);
assert_eq!(sut.pop(), Some(1));
sut.push(2);
sut.push(3);
sut.push(4);
sut.push(5);
assert_eq!(sut.pop(), Some(5));
assert_eq!(sut.size(), 3);
}
#[test]
fn test_contains() {
let mut sut = Stack::new();
assert_eq!(sut.contains(42), false);
sut.push(42);
assert_eq!(sut.contains(42), true);
sut.push(43);
sut.push(44);
sut.push(45);
sut.push(46);
assert_eq!(sut.contains(43), true);
assert_eq!(sut.contains(44), true);
assert_eq!(sut.contains(45), true);
assert_eq!(sut.contains(46), true);
assert_eq!(sut.contains(47), false);
}
#[test]
fn test_iter_count() {
let sut = stack![1, 2, 3, 4];
assert_eq!(sut.iter().count(), 4);
}
#[test]
fn test_iter_loop() {
let sut = stack![1, 2, 3, 4];
let mut iter_sut = sut.iter();
assert_eq!(iter_sut.next(), Some(&4));
assert_eq!(iter_sut.next(), Some(&3));
assert_eq!(iter_sut.next(), Some(&2));
assert_eq!(iter_sut.next(), Some(&1));
}
#[test]
fn test_into_iter() {
let sut = stack![1, 2, 3, 4];
let mut iter_sut = sut.into_iter();
assert_eq!(iter_sut.next(), Some(4));
assert_eq!(iter_sut.next(), Some(3));
assert_eq!(iter_sut.next(), Some(2));
assert_eq!(iter_sut.next(), Some(1));
}
#[test]
fn test_size() {
let mut sut = stack![1, 2, 3, 4];
assert_eq!(sut.size(), 4);
sut.pop();
assert_eq!(sut.size(), 3);
}
#[test]
fn test_default() {
let sut: Stack<()> = Default::default();
assert!(sut.is_empty());
assert_eq!(sut.size(), 0);
}
#[test]
fn test_from() {
let mut list = LinkedList::new();
list.append(12);
list.append(13);
list.append(14);
let mut sut = Stack::from(list);
assert!(sut.contains(12));
assert!(sut.contains(13));
assert!(sut.contains(14));
assert_eq!(sut.pop(), Some(14));
}
}
<file_sep>use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::mem;
const INITIAL_SIZE: usize = 7;
type Bucket<K, V> = Option<Vec<(K, V)>>;
pub struct HashMap<K, V> {
buckets: Vec<Bucket<K, V>>,
}
impl<K, V> HashMap<K, V>
where
K: Hash + Ord,
V: Ord,
{
/// Creates an instance
///
/// # Example
/// ```rust
/// use data_structure_with_colin::hash_map::HashMap;
/// let map = HashMap::<(), ()>::new();
///
/// assert!(map.is_empty());
/// ```
pub fn new() -> Self {
// seven buckets for the start
HashMap {
buckets: Vec::new(),
}
}
/// Resizes the map. This could have multiple reasons:
/// - the map is not yet initialize -> create the a list of buckets which
/// contains INITIAL_SIZE elements (currently seven).
/// - the list of buckets doesn't contain enough buckets and therefore the
/// size needs to be doubled. In that case the current content of the
/// buckets should be redistributed.
fn resize(&mut self) {
let mut target_size: usize = INITIAL_SIZE;
if self.buckets.len() != 0 {
target_size = self.buckets.len() * 2;
}
let mut new_buckets = Vec::with_capacity(target_size);
new_buckets.extend((0..target_size).map(|_| None));
//TODO: Copying existing values
let _ = mem::replace(&mut self.buckets, new_buckets);
}
/// Checks if a map is currently empty.
///
/// # Example
/// ```rust
/// use data_structure_with_colin::hash_map::HashMap;
/// let map = HashMap::<(), ()>::new();
///
/// assert!(map.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.buckets.len() == 0
}
/// Returns the bucket for a certain key. As the key needs to implement
/// the Hash trait, we're able to hash it with the DefaultHasher.
/// Afterwards the bucket is retrieved by calculating the remainder of
/// the hash with the number of buckets.
fn get_bucket(&self, key: &K) -> usize {
// this call is only legal if the map is not empty
// empty checks should be done in every method befor
// evaluating the bucket
assert!(!self.is_empty());
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
let hash = hasher.finish();
// TODO check if the cast is necessary
return (hash % self.buckets.capacity() as u64) as usize;
}
/// Inserts a tuple into the HashMap.
///
/// # Example
/// ```rust
/// use data_structure_with_colin::hash_map::HashMap;
/// let mut map = HashMap::new();
/// map.insert(1, "Hello World");
///
/// assert!(!map.is_empty());
/// ```
pub fn insert(&mut self, key: K, value: V) {
//TODO: or too small
if self.is_empty() {
self.resize()
}
let bucket = self.get_bucket(&key);
match &mut self.buckets[bucket] {
Some(vector) => vector.push((key, value)),
None => {
self.buckets[bucket] = Some(Vec::with_capacity(10));
self.buckets[bucket].as_mut().unwrap().push((key, value));
}
}
}
/// Returns whether a map contains a certain key.
///
/// # Example
/// ```rust
/// use data_structure_with_colin::hash_map::HashMap;
/// let mut map = HashMap::new();
/// map.insert(42, "Hello World");
///
/// assert!(map.contains_key(42));
/// ```
pub fn contains_key(&self, key: K) -> bool {
if self.is_empty() {
return false;
}
let bucket = self.get_bucket(&key);
match self.buckets[bucket].as_ref() {
Some(vector) => vector.iter().find(|tuple| tuple.0 == key).is_some(),
None => false,
}
}
/// Returns a value for a given key.
///
/// # Example
/// ```rust
/// use data_structure_with_colin::hash_map::HashMap;
/// let mut map = HashMap::new();
/// map.insert(42, 607);
///
/// assert_eq!(map.get(42), Some(&607));
/// ```
pub fn get(&mut self, key: K) -> Option<&V> {
if self.is_empty() {
return None;
}
let bucket = self.get_bucket(&key);
return match &self.buckets[bucket] {
Some(vec) => vec
.into_iter()
.find(|k| k.0 == key)
.map_or(None, |tuple| Some(&tuple.1)),
None => None,
};
}
/// Put this here to test my credentials and to create
/// the necesessary method head.
pub fn remove(&mut self, key: K) -> Option<V> {
if self.is_empty() {
return None;
}
let bucket = self.get_bucket(&key);
return match self.buckets[bucket].take() {
Some(vec) => vec
.into_iter()
.find(|k| k.0 == key)
.take()
.map_or(None, |tuple| Some(tuple.1)),
None => None,
};
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_insert() {
let mut sut = HashMap::new();
sut.insert(1, "Colin ist dof");
assert!(!sut.is_empty());
}
#[test]
fn test_get_bucket() {
let mut sut = HashMap::<i64, ()>::new();
// insert something to hold is_empty invariant
sut.insert(42, ());
assert_eq!(sut.get_bucket(&1), sut.get_bucket(&1));
assert_eq!(sut.get_bucket(&11201020120), sut.get_bucket(&11201020120));
let mut sut = HashMap::<String, ()>::new();
// insert something to hold is_empty invariant
sut.insert(String::from("Test"), ());
assert_eq!(
sut.get_bucket(&String::from("Rust is nice")),
sut.get_bucket(&String::from("Rust is nice"))
);
}
#[test]
fn test_get() {
let mut sut = HashMap::new();
sut.insert(1, "Colin ist dof");
assert_eq!(sut.get(1), Some(&"Colin ist dof"));
assert!(!sut.is_empty());
}
#[test]
fn test_get_int() {
let mut sut = HashMap::new();
sut.insert(1, 42);
assert_eq!(sut.get(1), Some(&42));
assert_eq!(sut.get(2), None);
assert!(!sut.is_empty());
}
#[test]
fn test_remove() {
let mut sut = HashMap::new();
sut.insert(45, "value");
sut.insert(98, "sec_value");
assert_eq!(sut.get(45), Some(&"value"));
sut.remove(45);
assert_eq!(sut.get(45), None);
}
}
<file_sep>extern crate rand;
use crate::avl_tree::tree::*;
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::mem::replace;
use std::{cmp::Ordering, iter::FromIterator};
#[derive(Debug, PartialEq, Clone)]
pub struct AVLTreeSet<T: Ord> {
root: AVLTree<T>,
}
impl<'a, T: 'a + Ord> AVLTreeSet<T> {
fn new() -> Self {
Self { root: None }
}
fn insert(&mut self, value: T) -> bool {
let mut prev_ptrs = Vec::<*mut AVLNode<T>>::new();
let mut current = &mut self.root;
while let Some(current_node) = current {
prev_ptrs.push(&mut **current_node);
match current_node.value.cmp(&value) {
Ordering::Less => current = &mut current_node.right,
Ordering::Equal => return false,
Ordering::Greater => current = &mut current_node.left,
}
}
*current = Some(Box::new(AVLNode {
value,
left: None,
right: None,
height: 1,
}));
for node_ptr in prev_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr };
node.update_height();
node.rebalance();
}
true
}
pub fn take(&mut self, value: &T) -> Option<T> {
let mut prev_ptrs = Vec::<*mut AVLNode<T>>::new();
let mut current_tree = &mut self.root;
let mut target_value = None;
while let Some(current_node) = current_tree {
match current_node.value.cmp(&value) {
Ordering::Less => {
prev_ptrs.push(&mut **current_node);
current_tree = &mut current_node.right;
}
Ordering::Equal => {
target_value = Some(&mut **current_node);
break;
}
Ordering::Greater => {
prev_ptrs.push(&mut **current_node);
current_tree = &mut current_node.left;
}
}
}
// Target does not exist in tree
if target_value.is_none() {
return None;
}
let target_node = target_value.unwrap();
// 3 Cases: No children, left child, right child
let taken = if target_node.left.is_none() || target_node.right.is_none() {
// Left child
if let Some(left_node) = target_node.left.take() {
replace(target_node, *left_node).value
}
// Right child
else if let Some(right_node) = target_node.right.take() {
replace(target_node, *right_node).value
}
// No children
else if let Some(prev_ptr) = prev_ptrs.pop() {
let prev_node = unsafe { &mut *prev_ptr };
// Determine which node to take
let inner_value = if let Some(left_node) = prev_node.left.as_ref() {
// Target was left node from parent
if left_node.value == target_node.value {
prev_node.left.take().unwrap().value
}
// Target was right node from parent
else {
prev_node.right.take().unwrap().value
}
}
// Target was right all along, since left is None
else {
prev_node.right.take().unwrap().value
};
prev_node.update_height();
prev_node.rebalance();
inner_value
}
// Fourth boring case: Tree is root
else {
self.root.take().unwrap().value
}
}
// Find Inorder-Successor
else {
AVLTreeSet::find_inorder_succesor(target_node)
};
// Update for every touched Node
for node_ptr in prev_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr };
node.update_height();
node.rebalance();
}
Some(taken)
}
fn find_inorder_succesor(target_node: &mut AVLNode<T>) -> T {
let right_tree = &mut target_node.right;
// Left tree of right is None, take first right
if right_tree.as_ref().unwrap().left.is_none() {
let mut right_node = right_tree.take().unwrap();
let inner_value = replace(&mut target_node.value, right_node.value);
let _ = replace(&mut target_node.right, right_node.right.take());
target_node.update_height();
target_node.rebalance();
inner_value
}
// Take leftest(^^) left node
else {
let mut next_tree = right_tree;
let mut left_ptrs = Vec::<*mut AVLNode<T>>::new();
// iterate to leftest
while let Some(next_left_node) = next_tree {
if next_left_node.left.is_some() {
left_ptrs.push(&mut **next_left_node);
}
next_tree = &mut next_left_node.left;
}
let parent_leftest_node = unsafe { &mut *left_ptrs.pop().unwrap() };
let mut leftest_node = parent_leftest_node.left.take().unwrap();
// Taken node is now filled with leftest value
let inner_value = replace(&mut target_node.value, leftest_node.value);
// Leftest node is now the right child of former leftest,
// because leftest has no left child and if right child is none, then thats the end of this tree
let _ = replace(&mut parent_leftest_node.left, leftest_node.right.take());
// Start at the bottom with updating
parent_leftest_node.update_height();
parent_leftest_node.rebalance();
// Up to the children of target
// Rev because into iter starts at the first inserted item, we need the last inserted first
for node_ptr in left_ptrs.into_iter().rev() {
let node = unsafe { &mut *node_ptr };
node.update_height();
node.rebalance();
}
// At last of course target node to update
target_node.update_height();
target_node.rebalance();
inner_value
}
}
pub fn remove(&mut self, value: &T) -> bool {
self.take(value).is_some()
}
pub fn contains(&self, value: &T) -> bool {
self.get(value).is_some()
}
pub fn get(&self, value: &T) -> Option<&T> {
let mut current_tree = &self.root;
while let Some(current_node) = current_tree {
match current_node.value.cmp(&value) {
Ordering::Less => {
current_tree = ¤t_node.right;
}
Ordering::Equal => {
return Some(¤t_node.as_ref().value);
}
Ordering::Greater => {
current_tree = ¤t_node.left;
}
}
}
None
}
}
impl<T: Ord> FromIterator<T> for AVLTreeSet<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut set = Self::new();
for i in iter {
set.insert(i);
}
set
}
}
/// Iterator
impl<'a, T: 'a + Ord> AVLTreeSet<T> {
fn iter(&'a self) -> AVLTreeSetNodeIter<'a, T> {
AVLTreeSetNodeIter {
prev_nodes: Vec::new(),
current_tree: &self.root,
}
}
}
#[derive(Debug)]
struct AVLTreeSetNodeIter<'a, T: Ord> {
prev_nodes: Vec<&'a AVLNode<T>>,
current_tree: &'a AVLTree<T>,
}
impl<'a, T: 'a + Ord> Iterator for AVLTreeSetNodeIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
loop {
match *self.current_tree {
None => match self.prev_nodes.pop() {
None => return None,
Some(ref prev_node) => {
self.current_tree = &prev_node.right;
return Some(&prev_node.value);
}
},
Some(ref current_node) => {
if current_node.left.is_some() {
self.prev_nodes.push(¤t_node);
self.current_tree = ¤t_node.left;
continue;
}
if current_node.right.is_some() {
self.current_tree = ¤t_node.right;
return Some(¤t_node.value);
}
self.current_tree = &None;
return Some(¤t_node.value);
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::BTreeSet;
#[test]
fn test_avl_insert_and_remove_basic() {
let mut tree = AVLTreeSet::new();
tree.insert(50);
tree.insert(70);
tree.insert(90);
assert_eq!(tree.insert(90), false);
assert_eq!(tree.contains(&50), true);
assert_eq!(tree.contains(&70), true);
assert_eq!(tree.contains(&90), true);
tree.remove(&70);
assert_eq!(tree.contains(&70), false);
assert_eq!(tree.get(&50).unwrap(), &50);
assert_eq!(tree.root.unwrap().value, 90);
}
#[test]
fn test_insert_randomly() {
let avl = (1..50 as u8).collect::<AVLTreeSet<_>>();
let btree = (1..50 as u8).collect::<BTreeSet<_>>();
for it in avl.iter().zip(btree.iter()) {
let (a, b) = it;
assert_eq!(a, b)
}
}
#[test]
fn test_delete_somehow_randomly() {
let mut avl = (1..100 as u16).collect::<AVLTreeSet<_>>();
let mut btree = (1..100 as u16).collect::<BTreeSet<_>>();
avl.remove(&45);
avl.remove(&12);
avl.remove(&36);
avl.remove(&73);
avl.remove(&75);
avl.remove(&80);
btree.remove(&45);
btree.remove(&12);
btree.remove(&36);
btree.remove(&73);
btree.remove(&75);
btree.remove(&80);
assert_eq!(avl.contains(&90), true);
assert_eq!(avl.get(&90).unwrap(), &90);
for it in avl.iter().zip(btree.iter()) {
let (a, b) = it;
assert_eq!(a, b)
}
}
#[test]
fn test_insert() {
let mut avl = AVLTreeSet::new();
let mut btree = BTreeSet::new();
avl.insert(10);
avl.insert(9);
avl.insert(4);
btree.insert(10);
btree.insert(9);
btree.insert(4);
for it in avl.iter().zip(btree.iter()) {
let (a, b) = it;
assert_eq!(a, b)
}
}
#[test]
fn truly_random_insert() {
let mut vec: Vec<u32> = (0..10000).collect();
vec.shuffle(&mut thread_rng());
let avl = vec.iter().collect::<AVLTreeSet<_>>();
let btree = vec.iter().collect::<BTreeSet<_>>();
for it in avl.iter().zip(btree.iter()) {
let (a, b) = it;
assert_eq!(a, b)
}
}
#[test]
fn random_remove() {
let mut vec: Vec<u32> = (0..100000).collect();
vec.shuffle(&mut thread_rng());
let mut avl = vec.iter().collect::<AVLTreeSet<_>>();
let mut btree = vec.iter().collect::<BTreeSet<_>>();
let mut remove: Vec<u32> = (0..10000).collect();
remove.shuffle(&mut thread_rng());
for item in remove.iter() {
avl.remove(&item);
btree.remove(&item);
}
for it in avl.iter().zip(btree.iter()) {
let (a, b) = it;
assert_eq!(a, b)
}
}
}
<file_sep>.PHONY: build test clippy format
build:
@cargo build --verbose
test:
@cargo test --verbose --all
clippy:
@cargo clippy --verbose
format:
@cargo fmt --all -- --check
checks: build test clippy format
@echo "### Don't forget to add untracked files! ###"
@git status
@echo "### Awesome work! 😍 ###""" | c65b440ec2e8a1f0fd5e9b6ef6b9b728a78cb77a | [
"Markdown",
"Rust",
"Makefile"
] | 10 | Rust | 1c3t3a/rust-data-structures | d42ea11c38289dea1fc798a8b8d82ba17d3d2284 | fb5a0ec489e1fb02efff9058794eb43267cf3ce6 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 15:49:47 2017
@author: mumar
"""
import twitter_sentiment as ts
x, y = ts.pre()
# Let us consider CountVectorizer from sklearn
# CountVectorizer, TfidfVectorizer, Word Embeddings, Word2Vec
X_vec = ts.countVectorizer(x)
y_encoded = ts.labelEncoding(y)
# Now, the dataset should be split in to train and test sets
X_train, X_test, y_train, y_test = ts.splitTestTrain(X_vec, y_encoded)
#kfold validation
#X_train, X_test, y_train, y_test = kFold(X_vec, y_encoded)
#plot Labels of Dataset
ts.plotLabels(y)
#precison, recall and f-measure of all the six classifiers
naiveBayesPrecision, naiveBayesRecall, naiveBayesFMeasure = ts.applyNaiveBayesClassifier(X_train, y_train, X_test, y_test)
svmPrecision, svmRecall, svmFMeasure = ts.applySVMClassifier(X_train, y_train, X_test, y_test)
randomForestPrecision, randomForestRecall, randomForestFMeasure = ts.applyRandomForestClassifier(X_train, y_train, X_test, y_test)
logisticRegressionPrecision, logisticRegressionRecall, logisticRegressionFMeasure = ts.applyLogisticRegressionClassifier(X_train, y_train, X_test, y_test)
sgdPrecision, sgdRecall, sgdFMeasure = ts.applySGDClassifier(X_train, y_train, X_test, y_test)
decisionTreePrecision, decisionTreeRecall, decisionTreeFMeasure = ts.applyDecisionTreeClassifier(X_train, y_train, X_test, y_test)
#Plot Precision-Recall comparison graph
ts.plotPreRec(naiveBayesRecall, naiveBayesPrecision, svmRecall, svmPrecision, randomForestRecall, randomForestPrecision, logisticRegressionRecall, logisticRegressionPrecision, sgdRecall, sgdPrecision)
#plot FMeasure comparison graph
ts.plotAcuuracyComaprisonGraph(naiveBayesFMeasure, svmFMeasure, randomForestFMeasure, logisticRegressionFMeasure, sgdFMeasure)<file_sep># TwitterSentimentAnalysis
Twitter Sentiment Analysis project uses twitter data as a corpus and perform sentiment analysis on this data.
| 4132642a181964259c5d52f1001509a20b9aa59c | [
"Markdown",
"Python"
] | 2 | Python | leoking90/TwitterSentimentAnalysis | 965a45983e6ff05e6cea99d8bed215e915c316a4 | 75252b1dcc24804ad6d9e8552c71259259daef83 |
refs/heads/master | <file_sep>import httplib, urllib, base64, urllib2, json
def face_api_call(link):
print "\nFACE FEATURES API\n"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<KEY>',
}
params = urllib.urlencode({
'returnFaceId': 'true',
'returnFaceLandmarks': 'false',
'returnFaceAttributes': 'age,gender,smile',
})
try:
url = '{ "url" : "' + link + '"}'
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/face/v1.0/detect?%s" % params, url, headers)
response = conn.getresponse()
data = response.read()
print(data), "\n"
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
def face_emotion_call(link):
print "\nFACE EMOTION API \n"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<KEY>',
}
try:
url = '{ "url" : "' + link + '"}'
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/emotion/v1.0/recognize", url, headers)
response = conn.getresponse()
data = response.read()
print(data), "\n"
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
def search_ocr_call(query):
print "\nQUERY SEARCH AND OCR API \n"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<KEY>',
}
params = urllib.urlencode({
'language': 'unk',
'detectOrientation ': 'true',
})
search_type = "Image"
key= '<KEY>'
query = urllib.quote(query)
credentials = (':%s' % key).encode('base64')[:-1]
auth = 'Basic %s' % credentials
url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/'+search_type+'?Query=%27'+query+'%27&$top=10&$format=json'
request = urllib2.Request(url)
request.add_header('Authorization', auth)
request_opener = urllib2.build_opener()
response = request_opener.open(request)
response_data = response.read()
json_result = json.loads(response_data)
#print json_result
for i in json_result['d']['results']:
url = '{ "url" : "' + str(i['MediaUrl'].encode('ascii', 'ignore')) + '"}'
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/vision/v1/ocr?%s" % params, url, headers)
response = conn.getresponse()
data = response.read()
json_result = json.loads(data)
output = ''
for r in json_result['regions']:
for l in r['lines']:
for w in l['words']:
output += w['text']
output += " "
print output, "\n"
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
def get_clarifai_tags(url):
print "\nCLARIFAI API\n"
method = "POST"
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
param = '{ "url" :"' + url + '"}'
data = urllib.urlencode(param)
request = urllib2.Request('https://api.clarifai.com/v1/tag', data)
request.add_header('Authorization', 'Bearer <KEY>')
request.get_method = lambda: method
try:
connection = opener.open(request)
except urllib2.HTTPError,e:
connection = e
if connection.code == 200:
data = connection.read()
data = json.loads(data)
classList = data["results"][0]["result"]["tag"]["classes"]
print classList + "\n"
def img_tag_category_call(link):
print "\nFEATURES - TAGS AND CATEGORIES \n"
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<KEY>',
}
params = urllib.urlencode({
'visualFeatures': 'All',
})
try:
url = '{ "url" : "' + link + '"}'
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/vision/v1/analyses?%s" % params, url, headers)
response = conn.getresponse()
data = response.read()
print(data), "\n"
conn.close()
get_clarifai_tags(link)
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
link = "http://akonthego.com/blog/wp-content/uploads/2012/07/DSC_5129.jpg"
face_api_call(link)
face_emotion_call(link)
search_ocr_call("Funny <NAME> quotes")
img_tag_category_call(link)
| bb567c94d7cf906a66466dce1d4d7eccc47887cb | [
"Python"
] | 1 | Python | aniketvp/hacktech | ec2a3e1f966038aa6d0b79b5bd576255bc30fd49 | e1eae8790e5554c140d3cd3c06f2c0e57ca45e25 |
refs/heads/master | <file_sep>import Vuex from 'vuex'
export default new Vuex.Store({
state: {
articles: undefined,
article: undefined,
comments: undefined,
active_tab: undefined,
},
getters: {
get_articles(state) {
return state.articles
},
get_article(state) {
return state.article
}
},
mutations: {
set_articles(state, articles) {
state.articles = articles
},
set_article(state, article) {
state.article = article
},
set_comments(state, comments) {
state.comments = comments
},
set_active_tab(state, active_tab) {
state.active_tab = active_tab
}
}
})<file_sep>export default {
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
username: {
message: '用户名验证失败',
validators: {
notEmpty: {
message: '用户名不能为空'
},
stringLength: {
min: 6,
max: 18,
message: '长度必须在6~18位之间'
},
regexp: {
regexp: /^[a-zA-Z0-9_]+$/,
message: '用户名只能包含英文大小写字母、数字和下划线'
}
}
},
email: {
validators: {
notEmpty: {
message: '邮箱地址不能为空'
},
emailAddress: {
message: '邮箱地址格式有误'
}
}
},
password: {
message: '密码验证失败',
validators: {
notEmpty: {
message: '密码不能为空'
},
stringLength: {
min: 8,
max: 20,
message: '长度必须在8~20位之间'
},
different: {
field: 'username',
message: '密码不能和用户名相同'
},
regexp: {
regexp: /^[a-zA-Z0-9_]+$/,
message: '密码只能包含英文大小写字母、数字和下划线'
}
}
},
confirm_password: {
message: '密码确认失败',
validators: {
notEmpty: {
message: '两次密码不一致'
},
identical: {
field: 'password',
message: '两次密码不一致'
},
}
},
code: {
message: '邀请码格式错误',
validators: {
notEmpty: {
message: '邀请码不能为空'
},
regexp: {
regexp: /^([0-9]{4,6}-[A-Z]{6,8}-[0-9]{3,6}[1-9])|test$/,
message: '邀请码格式错误'
}
}
}
}
}<file_sep>let url = '//192.168.1.102/ajax';
export default function (callback) {
let data = {type: 'article'};
$.get(url, data, callback)
}
export function get_comments(id, callback) {
let data = {type: 'comment', id: id};
$.get(url, data, callback)
}
// data => {
// that.$store.commit('set_articles', JSON.parse(data));
// if (a) {
// that.$store.commit('set_article', JSON.parse(data)[that.$route.params.id - 1]);
// data = {
// 'type': 'comment',
// 'id': that.$store.state.article.id,
// };
// $.get(url, data, data => {
// let comments = JSON.parse(data);
// for (let i = 0; i < comments.length; i++) {
// if (!comments[i].avatar) {
// comments[i].avatar = window.localStorage.getItem('avatar')
// }
// }
// that.$store.commit('set_comments', comments);
// }<file_sep>import sha256_digest from '../tools/my_sha256'
export default function (data, register, callback) {
data.pwd_256 = sha256_digest(data.password);
delete data.password;
console.log(data);
register = register ? 'register' : 'login';
let url = '//192.168.1.102/' + register;
$.post(url, data, callback)
}<file_sep>import VueRouter from 'vue-router'
import Home from './view/Home'
import Article from './view/Article'
import Picture from './view/Picture'
import Video from './view/Video'
import Music from './view/Music'
import Article_item from './view/Article_item'
import NotFount from './view/Error'
import Login from './view/Login'
import Game from './view/Game'
import JSTest from './view/JSTest'
export default new VueRouter({
routes: [
{
path: '/', name: 'home', component: Home
}, {
path: '/article', name: 'article', component: Article
}, {
path: '/picture', name: 'picture', component: Picture
}, {
path: '/video', name: 'video', component: Video
}, {
path: '/music', name: 'music', component: Music
}, {
path: '/article/:id(\\d+)', name: 'article_item', component: Article_item
}, {
path: '/login', name: 'login', component: Login
}, {
path: '/game', name: 'game', component: Game
}, {
path: '/jstest', name: 'jstest', component: JSTest
}
, {
path: '*', name: '404', component: NotFount
}
]
}) | 7d8e95e381e7835fdaf641164fef5ca6b2229a93 | [
"JavaScript"
] | 5 | JavaScript | zhantan2015/frontend | d70c091b2982204234062e3dbd5a0b77f576e93c | 074296820343be9fb269d21f24a73ad90a196fd7 |
refs/heads/master | <file_sep>- 前端新手,使用WeUI开发的一个demo,旨在熟悉前端,为以后webapp的开发打点基础。代码质量肯定不高,
能为像我一样的新手提供一点参考就好
- 忽略导航栏的文题不符
- 效果截图:





- 感谢:[jQuery WeUI](https://jqweui.com/)
<file_sep>/**
* Created by cyq7on on 2016/8/24 0024.
*/
$().ready(function () {
$("#login").on("click", function () {
var url = "http://172.16.58.3:8080/LuZhouFire/login";
var account = $("#account").val();
var psw = $("#password").val();
if (account.length == 0 || psw.length == 0) {
$.toast("请输入完整信息", "forbidden");
return;
}
$.showLoading();
location.href = "home.html";
$.hideLoading();
// $("#submit").submit();
/*$.ajax({
type:"post",
url:url,
data:{tel:account,password:psw},
datatype:"json",
success:function (data) {
console.log(data);
},
error:function () {
}
});*/
});
});<file_sep>/**
* Created by cyq7on on 2016/8/24 0024.
*/
$().ready(function () {
getNews("top");
showSwiper();
// $(".weui_tab_bd").pullToRefresh();
$(".weui_tab_bd").pullToRefresh().on("pull-to-refresh", function () {
setTimeout(function () {
$(".weui_tab_bd").pullToRefreshDone();
}, 2000);
});
//初始化滚动加载
var loading = false; //状态标记
$('.weui_tab_bd').infinite();
$('.weui_tab_bd').infinite().on("infinite", function () {
if (loading) return;
loading = true;
setTimeout(function () {
$("#content").append("<p> 我是新加载的内容 </p><p> 我是新加载的内容 </p><p> 我是新加载的内容 </p><p> 我是新加载的内容 </p><p> 我是新加载的内容 </p>");
loading = false;
}, 1500); //模拟延迟
});
// var a = $(".weui_tabbar_item");
// var img = a.find("img");
// img[0].src = "img/icon_shopping_mall_selected.png";
// a.on("click", function () {
// img[0].src = "img/icon_shopping_mall_normal.png";
// img[1].src = "img/icon_alarm_information_normal.png";
// img[2].src = "img/icon_device_manager_normal.png";
// img[3].src = "img/icon_my_normal.png";
// var imgSrc = $(this).data('selected');
// $(this).find("img").attr('src', imgSrc);
// });
});
function getNews(type) {
var urlPre = "http://cors.itxti.net/?";
var url = "http://v.juhe.cn/toutiao/index";
var appKey = "<KEY>92a9c";
$.getJSON("data.json", function (data){
$.each(data.result.data, function (i, item) {
var html = '<div class="weui_cell">'+
'<div data-id="'+ i+'">'+
'<img src="' + item.thumbnail_pic_s + '" style="width: 100px ;height: 75px ; padding-top: 10px">' +
'</div> ' +
'<span style="height: 82px">'+
'<p class="weui_cell_p">' + item.title + '</p>' +
'<p class="weui_cell_p">' + item.date + '</p>' +
'</span> ' +
'</div>';
$("#content").append(html);
})
$("#content").on("click","div",function () {
var id = $(this).find("div").data("id");
// $.toast("你选择了第" + id + "项", "text");
location.href = "detail.html?id=" + id;
});
});
// $.getJSON(url, {key: appKey, type: type}, function (data) {
// $.each(data.result.data, function (i, item) {
// var html = '<div class="weui_cell">'+
// '<div class="weui_cell_hd" data-id="'+ i+'">'+
// '<img src="' + item.thumbnail_pic_s + '" width="120px" height="100px">' +
// '</div> <span>'+
// '<p style="width: 280px;position: relative;top: -15px">' + item.title + '</p>' +
// '<p>' + item.date + '</p>' +
// '</span> </div>';
// $("#content").append(html);
// })
// $("#content").on("click","div",function () {
// var id = $(this).find("div").data("id");
// // $.toast("你选择了第" + id + "项", "text");
// location.href = "detail.html?id=" + id;
// });
// })
}
function showSwiper() {
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
spaceBetween: 30,
autoplay: 1500,
});
$(".swiper-slide").on("click", function () {
$.toptip("点击了第" + (swiper.clickedIndex + 1) + "张图片", 1000, "success");
});
} | fad0c8839120e20e3e8ae79f6a81983ab278f6d5 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | cyq7on/WeUIDemo | 54df786e62fe351ea8af50185edce3b1a5c9abe1 | b934529d1e2f7a0545eb677e2cf7d56c9e9d67c0 |
refs/heads/master | <file_sep>using LojaEF.Entidades;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LojaEF
{
class Program
{
static void Main(string[] args)
{
var contexto = new EntidadesContext();
Produto produto = new Produto()
{
Nome = "Impressora",
Preco = 100.0m
};
contexto.Produtos.Add(produto);
contexto.SaveChanges();
}
}
}
| 93e802db61d8b5014a2df546d4f92906c732e8c6 | [
"C#"
] | 1 | C# | gabsferreira/LojaEF | 278d25d27edf69618d27235c1607012b2fb7a957 | 006ed6678828ac3ce9bb9040a702aa7a68d12690 |
refs/heads/master | <file_sep>package org.fraarson.models;
import java.time.LocalDate;
public class Task {
private long id;
private String taskName;
private String content;
private LocalDate creationDate;
private LocalDate deadlineDate;
private LocalDate executedDate;
private String executor_name;
private String taskgiver_name;
public void setId(long id) {
this.id = id;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public void setContent(String content) {
this.content = content;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate = creationDate;
}
public void setDeadlineDate(LocalDate deadlineDate) {
this.deadlineDate = deadlineDate;
}
public void setExecutedDate(LocalDate executedDate) {
this.executedDate = executedDate;
}
public void setExecutor_name(String executor_name) {
this.executor_name = executor_name;
}
public void setTaskgiver_name(String taskgiver_name) {
this.taskgiver_name = taskgiver_name;
}
public long getId() {
return id;
}
public String getTaskName() {
return taskName;
}
public String getContent() {
return content;
}
public LocalDate getCreationDate() {
return creationDate;
}
public LocalDate getDeadlineDate() {
return deadlineDate;
}
public LocalDate getExecutedDate() {
return executedDate;
}
public String getExecutor_name() {
return executor_name;
}
public String getTaskgiver_name() {
return taskgiver_name;
}
}
<file_sep>package org.fraarson.repositories;
import javafx.collections.FXCollections;
import javafx.collections.ObservableArray;
import javafx.collections.ObservableList;
import org.fraarson.models.Executor;
import org.fraarson.models.Task;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class TaskRepository {
private static final String CREATE_TASK_QUERY = "INSERT INTO task (name, content, creation_date, deadline_date," +
" executed_date, executor_name, taskgiver_name) VALUES (?, ?, ?, ?, ?, ?, ?);";
private static final String READ_TASK_BY_TASKGIVER_QUERY = "SELECT * FROM task WHERE taskgiver_name = ?;";
private static final String READ_TASK_BY_EXECUTOR_QUERY = "SELECT * FROM task WHERE executor_name = ?;";
private static final String UPDATE_TASK_BY_ID_QUERY = "UPDATE task SET executed_date = ? WHERE id = ?;";
private static final String UPDATE_TASK_QUERY = "UPDATE task SET name = ?, content = ?, deadline_date =?," +
" executor_name = ? WHERE id = ?;";
public void createTask(String name, String content, LocalDate creationDate, LocalDate deadlineDate, LocalDate executedDate,
String executorName, String taskgiverName) throws SQLException{
Connection connection = SessionUtils.getDbConnection();
try(PreparedStatement statement = connection.prepareStatement(CREATE_TASK_QUERY)){
statement.setString(1, name);
statement.setString(2, content);
if(executedDate == null) {
statement.setDate(5, null);
}else {
statement.setDate(5, java.sql.Date.valueOf(executedDate));
}
statement.setDate(3, java.sql.Date.valueOf(creationDate));
statement.setDate(4, java.sql.Date.valueOf(deadlineDate));
statement.setString(6, executorName);
statement.setString(7, taskgiverName);
statement.execute();
}catch (SQLException e){
throw new SQLException();
}
}
public ObservableList<Task> readAllTaskByTaskgiver(String taskgiver){
Connection connection = SessionUtils.getDbConnection();
ObservableList<Task> resultList = FXCollections.observableArrayList();
try(PreparedStatement statement = connection.prepareStatement(READ_TASK_BY_TASKGIVER_QUERY)){
statement.setString(1, taskgiver);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
Task task = new Task();
task.setId(resultSet.getLong(1));
task.setTaskName(resultSet.getString(2));
task.setContent(resultSet.getString(3));
task.setCreationDate(resultSet.getDate(4).toLocalDate());
task.setDeadlineDate(resultSet.getDate(5).toLocalDate());
if(resultSet.getDate(6) != null) {
task.setExecutedDate(resultSet.getDate(6).toLocalDate());
}else {
task.setExecutedDate(null);
}
task.setExecutor_name(resultSet.getString(7));
task.setTaskgiver_name(resultSet.getString(8));
resultList.add(task);
}
}catch (SQLException e){
e.printStackTrace();
}
return resultList;
}
public void updateTask(long id, String name, String content, LocalDate deadline, String executor){
Connection connection = SessionUtils.getDbConnection();
try(PreparedStatement statement = connection.prepareStatement(UPDATE_TASK_QUERY)){
statement.setString(1, name);
statement.setString(2, content);
statement.setString(4, executor);
statement.setLong(5, id);
statement.setDate(3, java.sql.Date.valueOf(deadline));
statement.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
public ObservableList<Task> readTaskByExecutor(String executorName){
Connection connection = SessionUtils.getDbConnection();
ObservableList<Task> resultList = FXCollections.observableArrayList();
try(PreparedStatement statement = connection.prepareStatement(READ_TASK_BY_EXECUTOR_QUERY)){
statement.setString(1, executorName);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
Task task = new Task();
task.setId(resultSet.getLong(1));
task.setTaskName(resultSet.getString(2));
task.setContent(resultSet.getString(3));
task.setCreationDate(resultSet.getDate(4).toLocalDate());
task.setDeadlineDate(resultSet.getDate(5).toLocalDate());
if(resultSet.getDate(6) != null) {
task.setExecutedDate(resultSet.getDate(6).toLocalDate());
}else {
task.setExecutedDate(null);
}
task.setExecutor_name(resultSet.getString(7));
task.setTaskgiver_name(resultSet.getString(8));
resultList.add(task);
}
}catch (SQLException e){
e.printStackTrace();
}
return resultList;
}
public void updateTaskById(Long id, LocalDate executedDate){
Connection connection = SessionUtils.getDbConnection();
try(PreparedStatement statement = connection.prepareStatement(UPDATE_TASK_BY_ID_QUERY)){
statement.setLong(2, id);
statement.setDate(1, java.sql.Date.valueOf(executedDate));
statement.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
}
<file_sep>package org.fraarson.repositories;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.fraarson.models.Task;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DepartmentRepository {
private static final String READ_DEPARTMENT_QUERY = "SELECT * FROM department;";
public ObservableList<String> readDepartmentNames(){
Connection connection = SessionUtils.getDbConnection();
ObservableList<String> resultList = FXCollections.observableArrayList();
try(PreparedStatement statement = connection.prepareStatement(READ_DEPARTMENT_QUERY)){
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
resultList.add(resultSet.getString(1));
}
}catch (SQLException e){
e.printStackTrace();
}
return resultList;
}
}
<file_sep># javafx-task-manager
Simple javafx application with h2 database. Task manager.
| 8bd50a2d6923e011f3702f8d52a7fd525d00ced5 | [
"Markdown",
"Java"
] | 4 | Java | poorvajappja/javafx-task-manager | 0a7a39986ce06a1941270cae3d3b6736fac2a48d | 4ebe9a34374a3f9c5340f43ac2e7709a94c13ab5 |
refs/heads/master | <repo_name>SoumyajeetNayak/Tutorials<file_sep>/Vega-Used Car Sale System/Migrations/20181118134900_added-feature-model.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace VegaUsedCarSaleSystem.Migrations
{
public partial class addedfeaturemodel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
<file_sep>/Vega-Used Car Sale System/Mapping/MappingProfile.cs
using AutoMapper;
using Vega_Used_Car_Sale_System.Controllers.Resources;
using Vega_Used_Car_Sale_System.Models;
namespace Vega_Used_Car_Sale_System.Mapping
{
public class MappingProfile :Profile
{
public MappingProfile()
{
CreateMap<Make, MakeResource>();
CreateMap<Model, ModelResource>();
CreateMap<Feature, FeatureResource>();
}
}
}<file_sep>/Vega-Used Car Sale System/Persistence/VegaDbContext.cs
using Microsoft.EntityFrameworkCore;
using Vega_Used_Car_Sale_System.Models;
namespace Vega_Used_Car_Sale_System.Persistence
{
public class VegaDbContext: DbContext
{
public VegaDbContext(DbContextOptions<VegaDbContext> options)
:base(options)
{
}
public DbSet<Make> Makes { get; set; }
public DbSet<Feature> Features {get; set;}
}
}<file_sep>/README.md
# Tutorials
Tutorials related to <NAME> and others
1. Restify Customer API.
2. Angular CRUD Operation with ASP.NET WebApi and SQL Server BackEnd.
3. Angular With ASP.NET Core WebApi and EntityFramework Core.
| c5bfb0f9f9748c3c28c4bdc40465ab6b20027f49 | [
"Markdown",
"C#"
] | 4 | C# | SoumyajeetNayak/Tutorials | ca2168549b6198ea332b1de7dcbdaa90c4f858e3 | fad1c19e3ef1248c36685668a40e6ecc2e4849dd |
refs/heads/master | <file_sep>using Styx;
using Styx.Common;
using Styx.CommonBot;
using Styx.Helpers;
using Styx.Plugins;
using Styx.WoWInternals;
using System;
using System.Windows.Media;
namespace ChatLogger
{
public class ChatLogger : HBPlugin
{
public override string Author { get { return "zstyblik"; } }
public override string Name { get { return "ChatLogger"; } }
public override void OnButtonPress() { }
public override void Pulse() { }
public override Version Version { get { return new Version(0, 1); } }
public override bool WantButton { get { return false; } }
public override void OnEnable() {
//Chat.Say += Chat_Say;
//Chat.Yell += Chat_Yell;
Chat.Whisper += Chat_Whisper;
Chat.Party += Chat_Party;
Chat.PartyLeader += Chat_Party;
Chat.Guild += Chat_Guild;
Chat.Emote += Chat_Emote;
Chat.Battleground += Chat_BG;
Chat.BattlegroundLeader += Chat_BG;
Chat.Raid += Chat_Raid;
Chat.RaidLeader += Chat_Raid;
Chat.Officer += Chat_Officer;
Lua.Events.AttachEvent("CHAT_MSG_BN_WHISPER", BNetWhisper);
Lua.Events.AttachEvent("GMRESPONSE_RECEIVED", GMResponse);
}
public override void OnDisable()
{
//Chat.Say -= Chat_Say;
//Chat.Yell -= Chat_Yell;
Chat.Whisper -= Chat_Whisper;
Chat.Party -= Chat_Party;
Chat.PartyLeader -= Chat_Party;
Chat.Guild -= Chat_Guild;
Chat.Emote -= Chat_Emote;
Chat.Battleground -= Chat_BG;
Chat.BattlegroundLeader -= Chat_BG;
Chat.Raid -= Chat_Raid;
Chat.RaidLeader -= Chat_Raid;
Chat.Officer -= Chat_Officer;
Lua.Events.DetachEvent("CHAT_MSG_BN_WHISPER", BNetWhisper);
Lua.Events.DetachEvent("GMRESPONSE_RECEIVED", GMResponse);
}
private void BNetWhisper(object sender, LuaEventArgs args)
{
if (((string)args.Args[0]).StartsWith("OQ,0Z,")) {
return;
}
// This has been commented out due to fear of "lag" during the
// lookup. It might come handy one day. We'll see.
//string friendname = Styx.WoWInternals.Lua.GetReturnVal<string>(string.Format("return BNGetFriendInfoByID({0})", author), 4);
//string chat_from = string.Format("({0}){1}", author,friendname.ToString());
PrintChatMessage((string)args.Args[0], (string)args.Args[12].ToString(), "BNet");
}
private void GMResponse(object sender, LuaEventArgs args)
{
PrintChatMessage((string)args.Args[0], (string)args.Args[1], args.ToString());
}
private void Chat_Officer(Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Raid(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_BG(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Emote(Styx.CommonBot.Chat.ChatAuthoredEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Party(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Whisper(Styx.CommonBot.Chat.ChatWhisperEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Yell(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Say(Styx.CommonBot.Chat.ChatLanguageSpecificEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void Chat_Guild(Styx.CommonBot.Chat.ChatGuildEventArgs e)
{
PrintChatMessage(e.Message, e.Author, e.EventName);
}
private void PrintChatMessage(string message, string author = "", string type = "")
{
Logging.Write(Colors.Green,
string.Format("[@ChatLogger] Chat From: {0} Message: {1} Type: {2} EOM",
author, message, type));
}
}
}
| 716f6542c564f76cc07719291dcc3ff0dad20393 | [
"C#"
] | 1 | C# | zstyblik/wow-chat-logger | 776afd5a70756cbc3d3cb31107053fd920a5c132 | ce755af5657b9a539200644166d7bdd518fd09bc |
refs/heads/master | <file_sep># Scratch
basic programs of python
<file_sep>import sys
import tkinter as tk
import time
def times():
current_time=time.strftime("%H:%M:%S")
clock.config(text=current_time)
clock.after(200,times)
root=tk.Tk()
root.geometry('500x250')
root.title("Clock")
clock=tk.lable(root,font=("times",50,"bold"),bg="white")
#clock.grid(row=2,column=2,pady=25,padx=100)
times()
digi=tk.lable(root,text="Digital Clock",font=("times",50,"bold"))
clock.grid(row=0,column=2)
nota=tk.lable(root,text="hours minutes seconds", font="times 15 bold")
nota.grid(row=3,column=2)
root.mainloop()<file_sep>from tkinter import *
window = Tk()
class Calci():
def __init__(self):
self.result = []
self.resultprice = []
self.x = 0
self.products = []
self.prices = []
self.row = 1
window.title = "Calculator"
self.v = IntVar()
Radiobutton(window, text="List", variable=self.v, value=1).grid(row=0,column = 1)
Radiobutton(window, text="Calci", variable=self.v, value=2).grid(row=0, column =3)
label1 = Label(window, text="Enter Product name")
label1.grid(row=1, sticky=W)
label2 = Label(window, text="Enter Price")
label2.grid(row=2)
self.string = StringVar()
self.entry = Entry(window, textvariable=self.string, font="Helvetica 17 bold")
self.entry.grid(row=2,column=1, columnspan=5)
#self.txt = StringVar()
#self.output_screen = Label(window, textvariable=self.txt)
#self.output_screen.grid(row=2, column=8, columnspan=10, rowspan=6, sticky=N)
self.string_name = StringVar()
self.entry_name = Entry(window, textvariable=self.string_name, font="Helvetica 17 bold")
self.entry_name.grid(row=1,column=1, columnspan=5)
self.entry_name.focus()
but_7 = Button(window, height=2, width=2, padx=10, pady=10, text="7",
command=lambda txt="7": self.addchar(txt))
but_7.grid(row=3,column=0, padx=1, pady=1,sticky = E)
but_8 = Button(window, height=2, width=2, padx=10, pady=10, text="8",
command=lambda: self.addchar('8'))
but_8.grid(row=3,column=1, padx=1, pady=1)
but_9 = Button(window, height=2, width=2, padx=10, pady=10, text="9",
command=lambda: self.addchar('9'))
but_9.grid(row=3,column=2, padx=1, pady=1)
but_div = Button(window, height=2, width=2, padx=10, pady=10, text="/",
command=lambda: self.addchar("/"))
but_div.grid(row=3,column=3, padx=1, pady=1)
but_clear = Button(window, height=2, width=2, padx=10, pady=10, text="clr",
command=lambda: self.cleartext())
but_clear.grid(row=3,column=4, padx=1, pady=1)
but_del = Button(window, height=2, width=2, padx=10, pady=10, text="<-",
command=lambda: self.delete())
but_del.grid(row=3, column=5, padx=1, pady=1)
but_4 = Button(window, height=2, width=2, padx=10, pady=10, text="4",
command=lambda: self.addchar("4"))
but_4.grid(row=4,column=0, padx=1, pady=1,sticky = E)
but_5 = Button(window, height=2, width=2, padx=10, pady=10, text="5",
command=lambda: self.addchar("5"))
but_5.grid(row=4,column=1, padx=1, pady=1)
but_6 = Button(window, height=2, width=2, padx=10, pady=10, text="6",
command=lambda: self.addchar("6"))
but_6.grid(row=4,column=2, padx=1, pady=1)
but_multiply = Button(window, height=2, width=2, padx=10, pady=10, text="*",
command=lambda: self.addchar("*"))
but_multiply.grid(row=4,column=3, padx=1, pady=1)
but_openbrace = Button(window, height=2, width=2, padx=10, pady=10, text="(",
command=lambda: self.addchar("("))
but_openbrace.grid(row=4,column=4, padx=1, pady=1)
but_closebrace = Button(window, height=2, width=2, padx=10, pady=10, text=")",
command=lambda: self.addchar(")"))
but_closebrace.grid(row=4,column=5, padx=1, pady=1)
but_1 = Button(window, height=2, width=2, padx=10, pady=10, text="1",
command=lambda: self.addchar("1"))
but_1.grid(row=5,column=0, padx=1, pady=1,sticky = E)
but_2 = Button(window, height=2, width=2, padx=10, pady=10, text="2",
command=lambda: self.addchar("2"))
but_2.grid(row=5,column=1, padx=1, pady=1)
but_3 = Button(window, height=2, width=2, padx=10, pady=10, text="3",
command=lambda: self.addchar("3"))
but_3.grid(row=5,column=2, padx=1, pady=1)
but_subtract = Button(window, height=2, width=2, padx=10, pady=10, text="-",
command=lambda: self.addchar("-"))
but_subtract.grid(row=5,column=3, padx=1, pady=1)
but_0 = Button(window, height=2, width=2, padx=10, pady=10, text="0",
command=lambda: self.addchar("0"))
but_0.grid(row=6,column=0, padx=1, pady=1,sticky = E)
but_dot = Button(window, height=2, width=2, padx=10, pady=10, text=".",
command=lambda: self.addchar("."))
but_dot.grid(row=6,column=1, padx=1, pady=1)
but_per = Button(window, height=2, width=2, padx=10, pady=10, text="%",
command=lambda: self.addchar("%"))
but_per.grid(row=6,column=2, padx=1, pady=1)
but_add = Button(window, height=2, width=2, padx=10, pady=10, text="+",
command=lambda: self.addchar("+"))
but_add.grid(row=6,column=3, padx=1, pady=1)
but_equals = Button(window, height=2, width=8, padx=10, pady=10, text="=",
command=lambda: self.equals())
but_equals.grid(row=6,column=4, columnspan=2, padx=1, pady=1)
but_list = Button(window, height=2, width=8, padx=10, pady=10, text="Add to List",
command=lambda: self.list())
but_list.grid(row=5,column=4, columnspan=2, padx=1, pady=1)
window.mainloop()
def addchar(self, char):
self.string.set(self.string.get() + (str(char)))
def cleartext(self):
self.string.set('')
self.string_name.set('')
def delete(self):
if self.entry.focus_get():
self.string.set(self.string.get()[0:-1])
elif self.entry_name.focus_get():
self.string_name.set(self.string_name.get()[0:-1])
def list(self):
if self.v.get() == 1:
try:
#self.result.append(self.string_name.get() + " " + self.string.get())
#self.resultprice.append(self.string.get())
#self.string.set('')
#self.string_name.set('')
#self.products.append(self.string_name.get())
output_heading = Label(window, text="Product" + " " + "Price")
output_heading.grid(row=0, column=7, sticky=N)
self.prices.append(self.string.get())
productlabel = Label(window, text = self.string_name.get())
productlabel.grid(row = self.row, column = 7)
pricelabel = Label(window, text = self.string.get())
pricelabel.grid(row =self.row, column = 8)
self.row +=1
self.string.set('')
self.string_name.set('')
except:
self.error = True
result = "Error"
# self.string.set(result)
#self.txt.set(self.result)
elif self.v.get() == 2:
self.entry.focus()
self.string_name = ''
result = ''
try:
result = eval(self.string.get())
except:
self.error = True
result = "Error"
self.string.set(result)
def equals(self):
if self.v.get() == 1:
finaloutputprice = 0
try:
for num in self.prices:
finaloutputprice = float(num) + finaloutputprice
#finaloutputprice = eval(self.prices)
except:
self.error = True
result = "Error"
self.string_name = ("Total Price =")
self.string.set(finaloutputprice)
elif self.v.get()==2:
self.entry.focus()
self.string_name = ''
result = ''
try:
result = eval(self.string.get())
except:
self.error = True
result = "Error"
self.string.set(result)
Calci()
<file_sep>from tkinter import *
master = Tk()
def callback():
print("click!")
def test1():
print("its show time")
b = Button(master, text="OK", command=test1)
b.pack()
mainloop() | dda1064805bb719e0a350c972e6591e7474595a7 | [
"Markdown",
"Python"
] | 4 | Markdown | hr4official/Scratch | 92e2dfe45a1d5bdc3475eb19c9b0eb3455676b6e | f7d5864ab4c3bf430dac0fce2a866df53d7cfda6 |
refs/heads/master | <repo_name>EduardoPedrosa/Trabalho1_SD<file_sep>/server_Vazao.py
#!/usr/bin/env python
import socket
import threading
def createTCPSocket(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #UDP
s.bind((ip, port))
s.listen(1)
return s
def receiveMessages(conn):
while(True):
data = conn.recv(1024)
if(not data):
break
conn.close()
def main():
IP = '127.0.0.1'
PORT = 5007
s = createTCPSocket(IP, PORT)
while True:
conn, addr = s.accept()
receiveMessagesThread = threading.Thread(target=receiveMessages, args=(conn,))
receiveMessagesThread.start()
main()<file_sep>/server_RTTePerda.py
#!/usr/bin/env python
import socket
IP = '127.0.0.1'
PORT = 5006
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #UDP
s.bind((IP, PORT))
while True:
message, addr = s.recvfrom(1024)
s.sendto(message, addr)
s.close()
<file_sep>/README.md
# Métricas para avaliação de rede
<NAME> - 201710145 <br>
<NAME> - 201710770 <br>
Link do repositório:
https://github.com/EduardoPedrosa/Trabalho1_SD
| 9f367b8b359251c42fc0441634563ef0bfee8161 | [
"Markdown",
"Python"
] | 3 | Python | EduardoPedrosa/Trabalho1_SD | bb5d9fe9218f2c828403060d5c5b897636a41e20 | 57a095c0b9042643e95c362e0c87acd1a923ddae |
refs/heads/master | <repo_name>Nelvake/Lucene<file_sep>/Lucene/Program.cs
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using System;
using System.IO;
using System.Linq;
namespace Lucene
{
class Program
{
static void Main(string[] args)
{
using (LuceneService lucene = new LuceneService())
{
lucene.AddIndex(@"D:/image.jpg");
lucene.AddIndex(@"D:/image.jpg");
lucene.AddIndex(@"D:/image1.jpg");
lucene.AddIndex(@"D:/image1.jpg");
}
Search();
}
public static void Search()
{
var strIndexDir = @"C:\Index";
var phrase = new FuzzyQuery(new Term("Name", "image"));
using (Net.Store.Directory indexDir = FSDirectory.Open(new DirectoryInfo(strIndexDir)))
using (var searcher = new IndexSearcher(indexDir))
{
var hits = searcher.Search(phrase, 20).ScoreDocs;
foreach (var hit in hits)
{
var foundDoc = searcher.Doc(hit.Doc);
var list = foundDoc.GetFields().ToList();
foreach (var item in list)
{
if (item.Name == "Path")
Console.WriteLine(item.StringValue);
}
}
}
}
}
}
<file_sep>/Lucene/LuceneService.cs
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Lucene
{
public class LuceneService : IDisposable
{
private readonly string strIndexDir;
private readonly IndexWriter writer;
private readonly Net.Store.Directory indexDir;
private readonly Analyzer std;
public LuceneService()
{
strIndexDir = @"C:\Index";
indexDir = FSDirectory.Open(new DirectoryInfo(strIndexDir));
std = new StandardAnalyzer(Net.Util.Version.LUCENE_30);
writer = new IndexWriter(indexDir, std, true, IndexWriter.MaxFieldLength.UNLIMITED);
}
public void AddIndex(string path)
{
//Create an Index writer object.
Document doc = new Document();
Field fldName = new Field("Name", Path.GetFileNameWithoutExtension(path), Field.Store.YES, Field.Index.ANALYZED);
Field fldPath = new Field("Path", Path.GetFullPath(path), Field.Store.YES, Field.Index.ANALYZED);
doc.Add(fldName);
doc.Add(fldPath);
writer.AddDocument(doc);
writer.Flush(true,true,true);
}
public void Dispose()
{
writer.Optimize();
writer.Commit();
writer.Dispose();
std.Dispose();
indexDir.Dispose();
}
}
}
| 6c3b8a6d1000e482bae1cf5de1a180b0e11eb85a | [
"C#"
] | 2 | C# | Nelvake/Lucene | 5841551f2dbfaf4b08c9a68f87076904953fc960 | 8f185d139f0563987556f8f74cc63867a4beb341 |
refs/heads/main | <file_sep>//
// SelectView.swift
// App
//
// Created by ggamangmuri on 2021/05/26.
//
import SwiftUI
struct selectButton: View{
private var str: String
init(str: String){
self.str = str
}
var body: some View{
Text("\(str)")
.frame(width: 250, height: 100)
.background(Color.green)
.cornerRadius(10.0)
.foregroundColor(.white)
.font(.largeTitle)
.padding()
}
}
struct SelectView: View {
var body: some View {
NavigationView{
VStack{
NavigationLink(destination: Text("캘린더확인페이지")){
selectButton(str: "캘린더")}
NavigationLink(
destination: EnvelopeView()
){selectButton(str: "챌린지")}
NavigationLink(destination: MenuView()){
selectButton(str: "메뉴")}
}
.navigationBarHidden(true)
}
}
}
struct SelectView_Previews: PreviewProvider {
static var previews: some View {
SelectView()
}
}
<file_sep>//
// MessageView.swift
// page
//
// Created by ggamangmuri on 2021/05/25.
//
import SwiftUI
struct MessageView: View{
var isClick: Bool = false
@State private var noActive = false
@State private var yesActive = false
var body: some View{
NavigationView{
ZStack{
RoundedRectangle(cornerRadius: 10).fill(Color.white)
//RoundedRectangle(cornerRadius: 10).stroke().padding() // 테두리
RoundedRectangle(cornerRadius: 10)
.stroke(Color.black)
.frame(width:350, height: 350)
NavigationLink(destination: Text("no page"), isActive : $noActive){}
NavigationLink(destination: Text("yes page"), isActive : $yesActive){}
VStack{
Text("챌린지 내용")
.font(Font.largeTitle)
.padding(15)
HStack(content: {
Button(action:{
noActive = true
}){
Text("No")
.frame(width: 150, height: 70)
.background(Color.black)
.cornerRadius(10)
}
Button(action:{
self.yesActive = true
}){
Text("Yes")
.frame(width: 150, height: 70)
.background(Color.blue)
.cornerRadius(10)
}
})//HStack
.foregroundColor(Color.white)
}//VStack
}
}
.navigationBarHidden(true)
}
}
struct MessageView_Previews: PreviewProvider {
static var previews: some View {
MessageView()
}
}
<file_sep>//
// Button.swift
// page
//
// Created by ggamangmuri on 2021/05/25.
//
import SwiftUI
struct envelopeButton: View{
@State var isClicked = false
var body: some View{
NavigationLink(destination: MessageView(), isActive:$isClicked){
ZStack{
RoundedRectangle(cornerRadius: 10)
.fill(Color.gray)
.frame(width: 200, height:150)
Button(action:{isClicked=true}){
Image(systemName: "heart.fill")
.font(.system(size:80))
.foregroundColor(Color.pink)
}
}
}
}
}
<file_sep>//
// EnvelopeView.swift
// page
//
// Created by ggamangmuri on 2021/05/25.
//
import SwiftUI
struct EnvelopeView: View {
var body: some View{
NavigationView{
VStack{
Text("오늘의 챌린지가 도착했습니다 !\n\n")
envelopeButton()
}
}
}
}
struct EnvelopeView_Previews: PreviewProvider {
static var previews: some View {
EnvelopeView()
}
}
| 80b9fb7383e3cc7407e09b00f85f0e611dfba321 | [
"Swift"
] | 4 | Swift | dhraudwn/moapp2 | d1087359ecb6ff2adb4426a3b824a2b224bb32d2 | cfa03a8bde68d58ccef7db5faced5ed4b48f8a62 |
refs/heads/master | <file_sep>#!/usr/bin/python
infile = open ('harddrive.in','r')
_ = int(infile.readline())
parts = [int(x) for x in infile.readline().split()]
def function (parts):
turns = -1
backturn = set()
for part in parts:
if (part - 1) not in backturn:
turns += 1
backturn.add(part)
return turns
result = function(parts)
#print result
infile.close()
with open('harddrive.out', 'w') as outfile:
outfile.write(str(result))<file_sep>import sys
sys.setrecursionlimit(100000)
input_file = open('pathsg.in', 'r')
output_file = open('pathsg.out', 'w')
nodes, edges = [int(i) for i in input_file.readline().split()]
dist = []
dist = [[None for i in range(nodes)] for j in range(nodes)]
def get_dist (dist,nodes):
cumulative_w = 0
for j in range (edges):
x,y,z = [int (w) for w in input_file.readline().split()]
dist [x-1][y-1] = z
cumulative_w += z
for j in range (nodes):
for i in range (nodes):
if j == i:
dist[j][i] = 0
elif dist[j][i] is None:
dist [j][i] = cumulative_w +1
return dist
def F_W (nodes, dist):
for i in range (nodes):
for j in range (nodes):
for x in range (nodes):
if dist[j][i] + dist[i][x] < dist [j][x]:
dist [j][x] = dist [j][i] + dist [i][x]
return dist
get_dist (dist,nodes)
F_W (nodes,dist)
for line in dist:
output_file.write(' '.join(str(i) for i in line) + '\n' )
input_file.close()
output_file.close()
<file_sep>#!/usr/bin/python
import numpy
yz = [1, 3, 2]
xz = [1, 2, 3]
xmatrix = [float(x) for x in xz]
print numpy.matrix(xmatrix).shape
x_matrix = numpy.matrix(xmatrix)
ymatrix = [ float(y) for y in yz]
print numpy.matrix(ymatrix).shape
y_matrix = numpy.matrix(ymatrix)
from scipy import stats
import numpy as np
#linregress - This computes a least-squares regression for two sets of measurements.
slope, intercept, r_value, p_value, std_err = stats.linregress(xmatrix,ymatrix)
print "slope:", slope
print "intercept:", intercept
print "standard error:", std_err
print "Coefficient of determination (R-squared):", r_value**2
print "p-value:", p_value
from scipy import polyfit
coefficients = polyfit(xz, yz, 1)[::-1]
print "coefficients (same as slope, intercept):", coefficients
#let us use the CHI-SQUARED TEST
def Sum (y_matrix, yz, xz, coefficients):
for i in range (y_matrix.shape[0]):
a = (sum([yz[i] - coefficients[1]*xz[i] - coefficients[0]])**2)*6
return a
a = Sum(y_matrix, yz, xz, coefficients)
#count p-value
from scipy import stats
p_value = stats.chi2.cdf(a,3)
print "chi-squared, P-value:", p_value
<file_sep>#!/usr/bin/python
import scipy
import numpy
xfile = open ('x.txt', 'r')
yfile = open ('y.txt','r')
xmatrix = [[float(x) for x in row.split()] for row in xfile]
print numpy.matrix(xmatrix).shape
x_matrix = numpy.matrix(xmatrix)
ymatrix = [[ float(y) ] for y in yfile]
print numpy.matrix(ymatrix).shape
y_matrix = numpy.matrix(ymatrix)
add_column = numpy.matrix([1]*x_matrix.shape[0]).T
new_x = numpy.hstack((add_column, x_matrix))
#matrices multiplication
step_one = numpy.dot (new_x.T, new_x)
step_two = numpy.linalg.pinv(step_one)
step_three = numpy.dot(step_two, new_x.T)
coeffs = numpy.dot(step_three, y_matrix)
errors = y_matrix - numpy.dot(new_x, coeffs)
print coeffs
#the model is too complicated (multidimentional)
#are errors distributed normally? if yes, then the model is accurate
import numpy as np
import numpy.ma as ma
from scipy.stats import mstats
x = np.array(errors)
z,pval = mstats.normaltest(x) #Tests whether a sample differs from a normal distribution.
#This function tests the null hypothesis that a sample comes from a normal distribution
print "Z-score:", z
print "P-value:", pval
if(pval < 0.055):
print "Not normal distribution"
if (pval >= 0.055):
print "This seems to be a normal distribution! Our model is good"<file_sep>#!/usr/bin/python
from __future__ import division
with open("airplane.in") as infile:
M, N, alpha = [int(x) for x in infile.readline().split()]
passenger_mass = sum(int(x) for x in infile.readline().split())
mass_on_empty = M + passenger_mass
if alpha == 1000:
result = "Impossible"
else:
result = mass_on_empty * alpha / (1000 - alpha)
with open("airplane.out", "w") as outfile:
outfile.write(str(result))<file_sep>#!/usr/bin/python
import numpy, scipy
from math import sqrt
from scipy import stats
import matplotlib.pyplot as plot
import random
%matplotlib inline
x = numpy.linspace(0, 2, 1000)
y = 2 * x + 1
noise = scipy.randn(y.size)
y_noise = y + noise
X_full = numpy.array(x).T
y_full = numpy.array(y_noise).T
print (X_full.shape)
print (y_full.shape)
TRAIN_SIZE = 800
from sklearn.utils import shuffle
x, y_noise = shuffle(x, y_noise, random_state=1)
x_train = x[:TRAIN_SIZE]
y_train = y_noise[:TRAIN_SIZE]
x_test = x[TRAIN_SIZE:]
y_test = y_noise[TRAIN_SIZE:]
X_train = numpy.asmatrix(x_train).T
Y_train = numpy.asmatrix(y_train).T
Train_set = numpy.hstack((X_train, Y_train))
print (Train_set.shape)
X_test = numpy.asmatrix(x_test).T
Y_test = numpy.asmatrix(y_test).T
Test_set = numpy.hstack((X_test,Y_test))
print (Test_set.shape)
betas = scipy.polyfit(x, y_noise, 1)[::-1] # 1 is order (max degree of x)
print ("betas:", betas)
print ("original model: y = 2 * x + 1")
print ("proposed model: y = 1.99725967*x + 1.03406303")
_ = plot.plot(x, y_noise, "r.", label = "full set")
_ = plot.plot(x, betas[0] + betas[1]*x, color="blue", label = "model")
plot.xlabel('X')
plot.ylabel('Y')
_ = plot.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0)
from sklearn import linear_model
regr = linear_model.LinearRegression()
regr.fit(X_train, Y_train)
print(regr.coef_)
print(regr.intercept_)
regr.fit(X_test, Y_test)
print (regr.coef_)
print (regr.intercept_)
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y_noise)
print ("Full set r-squared (determination coefficient):", r_value**2)
print ("standard error = ", std_err)
train_set_error = sqrt(numpy.sum(((slope*x_train+intercept) - y_train)**2)/len(y_train))
print ('Residual sum of squares, train:', train_set_error)
test_set_error = sqrt(numpy.sum(((slope*x_test+intercept) - y_test)**2)/len(y_test))
print ('Residual sum of squares, test:', test_set_error)
from scipy.stats import pearsonr
print ("Correlation coefficient:")
pearsonr(x, y_noise) #correlation coefficient x1
print ("Correlation coefficient array:")
numpy.corrcoef(x,y_noise) #correlation coefficient x2
_ = plot.plot(x_train, y_train, "r.", label = "train")
_ = plot.plot(x_test,y_test, "b.", label = "test")
_ = plot.plot(x, betas[0] + betas[1]*x, color="green", linewidth = 3, label = "model")
plot.xlabel('X')
plot.ylabel('Y')
_ = plot.legend(bbox_to_anchor = (1.05, 1), loc = 2, borderaxespad = 0)
model_function = lambda x: betas[0] + betas[1]*x
ok = []
too_far = []
for tx, ty in numpy.vstack((X_full, y_full)).T.tolist():
if (model_function(tx) - ty)**2 < std_err:
ok.append([tx, ty])
else:
too_far.append([tx, ty])
ok_points = numpy.array(ok)
too_far = numpy.array(too_far)
print (ok_points.shape)
print (too_far.shape)
_ = plot.plot(x, betas[0] + betas[1]*x, color="blue", linewidth = 1, label = "model")
_ = plot.plot(ok_points[:, 0], ok_points[:, 1], "g.", label = "ok points (dist. < std)")
_ = plot.plot(too_far[:, 0], too_far[:, 1], "r.", label = "points, that are too far (dist.>std)")
_ = plot.legend(bbox_to_anchor = (1.05, 1),loc = "best",borderaxespad = 0)
<file_sep>#!/usr/bin/python
outdata = open("allvectors.out", "w")
def gen_bin(vector, position):
if position < len(vector):
for nextvalue in ["0", "1"]:
vector[position] = nextvalue
gen_bin(vector, position + 1)
else:
outdata.write("".join(vector) + "\n")
with open("allvectors.in", "r") as indata:
n = int(indata.readline().strip())
gen_bin(["0"] * n, 0)
<file_sep>import sys
sys.setrecursionlimit(200000)
from collections import deque
from collections import defaultdict
input_file = open('pathbge1.in', 'r')
output_file = open('pathbge1.out', 'w')
def function():
pass
n_vertices, n_edges = [int(i) for i in input_file.readline().split()]
vertices = []
edges = []
for i in range(1, n_vertices+1):
vertices.append (i)
i += 1
for j in range (n_edges):
edges.append ([int(j) for j in input_file.readline().split()])
adj = defaultdict (lambda: defaultdict(lambda: 0))
for x, y in edges:
adj[x][y] += 1
adj [y][x] += 1
distances = {1:0}
def BFS ():
queue = deque ([1])
while len (queue):
for i in adj[queue[0]]:
if i not in distances:
distances[i] = distances[queue[0]] + 1
queue.append(i)
queue.popleft()
return distances
BFS ()
answer = distances.values()
for i in answer:
output_file.write(str(i)+ " ")
input_file.close ()
output_file.close ()
<file_sep>infile = open ("permutations.in","r")
outfile = open ("permutations.out",'w')
n = int (infile.readline().strip())
def generate_permutations (seq, loc):
if loc < len (seq):
for i in range (1, n+1):
if i not in seq:
seq[loc] = i
generate_permutations (seq, loc+1)
seq[loc] = 0
else:
outfile.write(" ".join([str(i) for i in seq]) + "\n")
generate_permutations (["0"] * n, 0)
<file_sep>import sys
from collections import defaultdict
sys.setrecursionlimit(200000)
from collections import deque
input_file = open('components.in', 'r')
output_file = open('components.out', 'w')
n_vertices, n_edges = [int(i) for i in input_file.readline().split()]
vertices = []
edges = []
for i in range(1, n_vertices+1):
vertices.append (i)
i += 1
for j in range (n_edges):
edges.append ([int(j) for j in input_file.readline().split()])
adj = defaultdict (lambda: defaultdict(lambda: 0))
for x, y in edges:
adj[x][y] += 1
adj [y][x] += 1
def search_df ():
conn_comp = {}
coconut = 0
for i in vertices:
if i not in conn_comp:
coconut += 1
conn_comp[i] = coconut
queue = deque ([i])
while len(queue) > 0:
for j in adj[queue[0]]:
if j not in conn_comp:
conn_comp[j] = coconut
queue.append (j)
queue.popleft ()
output_file.write(str(coconut)+"\n")
for i in conn_comp.values ():
output_file.write(str(i)+" ")
search_df()
input_file.close()
output_file.close ()
<file_sep>#!/usr/bin/python
with open("maxpiece.in") as infile:
n, m, k = [int(x) for x in infile.readline().split()]
xcuts = [0, n]
ycuts = [0, m]
for line in infile:
t, v = [int(x) for x in line.split()]
if t == 0:
xcuts.append(v)
else:
ycuts.append(v)
xcuts.sort()
xsizes = []
for i, _ in enumerate(xcuts):
if i > 0:
xsizes.append(xcuts[i] - xcuts[i-1])
ycuts.sort()
ysizes = []
for i, _ in enumerate(ycuts):
if i > 0:
ysizes.append(ycuts[i] - ycuts[i-1])
biggest_square = min(max(xsizes), max(ysizes))
with open("maxpiece.out", "w") as outfile:
outfile.write(str(biggest_square))<file_sep>#!/usr/bin/python
with open('nextchoose.in') as infile:
number, n = [int(x) for x in infile.readline().split()]
combination = [int(x) for x in infile.readline().split()]
def mk_choice(number, n, combination):
for x in range(n):
if combination [ n - x - 1 ] < number - x:
combination [ n - x -1 ] += 1
for y in range ( n - x, n ):
combination [y] = combination [ y - 1 ] + 1
return combination
return [-1]
result = mk_choice (number, n, combination)
#print result
with open ('nextchoose.out', 'w') as outfile:
outfile.write(" ".join(str(x) for x in result)) <file_sep>#!/usr/bin/python
infile = open ("choose.in",'r')
outfile = open ("choose.out",'w')
n, k = (int(x) for x in infile.readline().split())
variants = []
def gener_comb (combination, position, n):
if position < k:
for i in range (1, n+1):
if i not in combination:
if position > 0 and i < combination[position-1]:
pass
else:
combination[position] = i
gener_comb (combination, position+1, n)
combination[position] = 0
else:
variants.append(combination[:])
return variants
gener_comb ([0]*k, 0, n)
for v in variants:
outfile.write(" ".join([str(x) for x in v]) + "\n")
<file_sep>#!/usr/bin/python
#I chose to perform the classification task using the KNN method
import sys
import numpy as np
import scipy
from sklearn.utils import shuffle
import matplotlib.pyplot as plot
from sklearn.neighbors import KNeighborsClassifier
blue = np.loadtxt("./blue.txt")
red = np.loadtxt("./red.txt")
#Visualize data (this doesn't work outside ipython), but we get something
#like an ellipse.... (pic attached)
#_ = plot.plot(blue[:, 0], blue[:, 1], "b.")
#_ = plot.plot(red[:, 0], red[:, 1], "r.")
#Create the classifying function
red_points = np.hstack ((red, [[1]] * len (red) ))
blue_points = np.hstack ((blue, [[0]] * len (blue) ))
all_points = np.concatenate((red_points, blue_points), axis=0)
x = all_points[:, :-1]
y = all_points[:, 2]
x, y = shuffle(x, y, random_state=1)
train_set=all_points.shape[0] *0.6
Xtrainset = x[:train_set]
Ytrainset = y[:train_set]
Xtestset = x[train_set:]
Ytestset = y[train_set:]
knearest = KNeighborsClassifier(n_neighbors=5)
knearest.fit(Xtrainset, Ytrainset)
print('Training set score:', knearest.score(Xtrainset, Ytrainset))
print('Test set score:', knearest.score(Xtestset, Ytestset))
#Prediction function
def classify (x,y):
if knearest.predict([x,y]) == 0:
print("must be blue...")
else:
print("must be red...")
#propose some coordinates :)
print('what will be your x?')
x = raw_input()
print('and y?')
y = raw_input()
classify (x,y)
<file_sep>#!/usr/bin/python
def nextvector (seq):
result = seq[:]
for x,y in reversed(list(enumerate(seq))):
if y == '0':
result[x] = '1'
return result
else:
result[x] = '0'
return ['-']
def previousvector (seq):
result = seq[:]
for x,y in reversed(list(enumerate(seq))):
if y == '1':
result[x] = '0'
return result
else:
result[x] = '1'
return ['-']
with open ('nextvector.in', 'r') as infile:
seq = list(infile.readline().strip())
preceding = previousvector(seq)
following = nextvector(seq)
with open ('nextvector.out', 'w') as outfile:
outfile.write(''.join(preceding) + '\n')
outfile.write(''.join(following) + '\n')
<file_sep>infile = open ('subsets.in', 'r')
outfile = open ('subsets.out', 'w')
n = int(infile.readline().strip())
limit = range (1, n+1)
subsets = []
def generate_subsets(x, y):
subsets.append(' '.join(str(i) for i in x))
for val in limit:
if val > y:
generate_subsets(x + [val], val)
return subsets
string = []
output = generate_subsets(string, 0)
outfile.write('\n'.join(output))
infile.close()
outfile.close()<file_sep>#!/usr/bin/python
infile = open ("tower.in",'r')
inlines = infile.readlines()
#print inlines
def peop_lang(inlines):
lang_vars = {}
population = {}
for someone, line in list(enumerate(inlines))[1:]:
population[someone] = [int(x) for x in line.split()[1:]]
for variant in population[someone]:
lang_vars[variant] = lang_vars.get(variant, []) + [someone]
return population, lang_vars
def thinker_f(start, uzd):
uzd[start] = True
for variant in population[start]:
for neighbor in lang_vars[variant]:
if not uzd[neighbor]:
thinker_f(neighbor, uzd)
population, lang_vars = peop_lang(inlines)
uzd = {someone: False for someone in population.keys()}
start = 1
uzd = uzd
thinker_f (start,uzd)
outfile = open ("tower.out", "w")
outfile.write(str(uzd.values().count(True)))
outfile.close()
infile.close()<file_sep>import sys
sys.setrecursionlimit(100000)
#from collections import deque
infile = open('pathmgep.in', 'r')
outfile = open('pathmgep.out', 'w')
dimensions = [int(i) for i in infile.readline().split()]
n_vertices = dimensions[0]
start = dimensions[1]
end = dimensions[2]
scope = []
def get_matrix (scope, infile, n_vertices):
for i in range(n_vertices):
y = [int(i) for i in infile.readline().split()]
scope.append(y)
return scope
get_matrix (scope, infile, n_vertices)
distances = {} #distance dict
def get_dist (distances, n_vertices):
for i in range(1, n_vertices+1):
distances[i] = -1
return distances
get_dist (distances, n_vertices)
#the main algorithm
vertices = []
def dijkstra_alg (distances,start,end):
distances[start] = 0
for y in range(n_vertices-1):
vertices.append(start)
for i in range(n_vertices):
if scope[start-1][i] != -1:
if distances[i+1] != -1:
distances[i+1] = min(distances[i+1], (distances[start]+scope[start-1][i]))
else:
distances[i+1] = scope[start-1][i]+distances[start]
assist = {}
for key in distances:
if key not in vertices and distances[key] != -1:
assist[key] = distances[key]
if len(assist) == 0:
break
start = min(assist, key=lambda k: assist[k])
return distances
dijkstra_alg (distances,start,end)
outfile.write(str(distances[end]))
infile.close()
outfile.close()<file_sep>#!/usr/bin/python
indata = open ("vectors.in","r")
outdata = open ("vectors.out",'w')
n = int (indata.readline().strip())
vectors = []
def gener_vect (vector, position):
if position < len (vector):
for next in ["0","1"]:
if position > 0 and next == "1" and vector[position-1] == "1":
pass
else:
vector[position] = next
gener_vect(vector, position + 1)
else :
vectors.append (vector[:])
return vectors
gener_vect (["0"] * n, 0)
outdata.write (str(len(vectors))+"\n")
for vector in vectors:
outdata.write("".join(vector) + "\n")<file_sep>k = 3
def gen_perm (a,p,k):
if p<k:
for i in range (1, k+1):
if i not in a:
a[p] = i
gen_perm (a, p+1, k)
a[p] = 0
else:
print (a)
gen_perm ([0 for i in range (k)],0,k)
<file_sep>
#!/usr/bin/python
infile = open("olympic.in", "r")
_ = (infile.readline().strip())
participants = {}
record = [0, 0, 0]
win_country = ""
top_three =[]
def fill_dict(infile, participants):
for winners in infile:
first, second, third = winners.strip().split()
for participant, index in zip((first, second, third), (0, 1, 2)):
if participant not in participants:
participants[participant] = [0, 0, 0]
participants[participant][index] += 1
##print participants
top_three = sorted(list(participants.keys()))
return top_three
def find_winner (top_three, win_country, record):
for score in top_three:
if participants[score] > record:
record = participants[score]
win_country = score
return win_country
top_three = fill_dict (infile, participants)
win_country = find_winner(top_three, win_country,record)
outfile = open("olympic.out", "w")
outfile.write(win_country + "\n")
outfile.close()<file_sep>k = 3
def gen_bin (a,p):
if p<k:
a[p] = 0
gen_bin(a, p+1)
a[p] = 1
gen_bin (a, p+1)
else:
print (a)
gen_bin ([0 for i in range (k)], 0)
| ed2fa0498fed9d964d82ee485b2cd1fde6e16907 | [
"Python"
] | 22 | Python | sofiiako/bii-14s | b2cbcbb3c3aba261e3249dd084aa612c8e812a06 | 4a57419c711b92f80f4f30aba12cee26ce1ad330 |
refs/heads/master | <file_sep>#!/usr/bin/env python
#
# read_snes_ksp_data
#
def read_snes_ksp_data(file):
import re
# max readin
nmax = 10000
# read file, parse and store
kspiter = 0
ksplist = []
snesidx = []
sneslist = []
f = open(file, "r")
for line in f:
# SNES
snesmatch = re.search(r"^\s+(\d+) SNES Function norm (\d+.\d+e[+-]\d+)", line)
if snesmatch:
snesidx.append(kspiter)
sneslist.append(snesmatch.groups()[1])
# KSP
kspmatch = re.search(r"^\s+(\d+) KSP Residual norm (\d+.\d+e[+-]\d+)", line)
if kspmatch:
ksplist.append(kspmatch.groups()[1])
kspiter = kspiter + 1
if kspiter >= nmax:
break
f.close()
return snesidx, sneslist, kspiter, ksplist
#
# create_figures
#
def create_figures():
import sys
import numpy as np
import math as m
# create figures
print "# Creating figures ..."
# ew params
gammas = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5]
gammas = np.array(gammas[::-1])
alphas = [(1.0 + m.sqrt(5.0))/2.0, 1.5, 1.4, 1.3, 1.2, 1.1]
alphas = np.array(alphas[::-1])
ngamma = len(gammas)
nalpha = len(alphas)
# data to plot
ksp2d = np.zeros(shape=(ngamma, nalpha))
snes2d = np.zeros(shape=(ngamma, nalpha))
# files
sneskspdata = []
for gidx in range(0, ngamma):
for aidx in range(0, nalpha):
astr = "{0:.5f}".format(alphas[aidx])
gstr = "{0:1.1f}".format(gammas[gidx])
file = "../work/NK-" + gstr + "-" + astr + ".out.txt"
# print file
snesidx, sneslist, kspiter, ksplist = read_snes_ksp_data(file)
ksp2d[gidx, aidx] = kspiter
snes2d[gidx, aidx] = len(snesidx)
# print gstr, astr, len(snesidx), kspiter
# plot
create_plot(alphas, gammas, ksp2d, snes2d)
#
# create_plot
#
def create_plot(alphas, gammas, ksp2d, snes2d):
import numpy as np
import matplotlib
matplotlib.rc("font", **{"family" : "sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex = True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# grid
X, Y = np.meshgrid(alphas, gammas)
ngamma = len(gammas)
nalpha = len(alphas)
# view
elev = 30
azi = 65
# KSP
fig = plt.figure(1)
ax = Axes3D(fig)
ax.plot_surface(X, Y, ksp2d, lw = 0.1, rstride = 1, cstride = 1, cmap = plt.cm.bone_r, alpha = 0.5)
ax.plot_wireframe(X, Y, ksp2d, color = "k", linewidth = 1.0)
# axes
ax.set_xlim([1.01, 1.69])
ax.set_ylim([0.41, 1.09])
ax.set_zlim([401, 699])
# labels
ax.set_xlabel(r"Alpha ($\alpha$)")
ax.set_ylabel(r"Gamma ($\gamma$)")
ax.set_zlabel("Model years")
ax.set_xticklabels(["%.1f" % alpha for alpha in alphas])
ax.set_yticklabels(["%.1f" % gamma for gamma in gammas])
ax.set_zticklabels(["450", "500", "550", "600", "650"])
# view
ax.view_init(elev, azi)
# save
from matplotlib.transforms import Bbox
b = Bbox.from_bounds(0.25, 0, 7.25, 5.75)
plt.savefig("eisenstat-walker-ksp.pdf", bbox_inches = b)
# SNES
fig = plt.figure(2)
ax = Axes3D(fig)
# plot
ax.plot_surface(X, Y, snes2d, lw = 0.1, rstride = 1, cstride = 1, cmap = plt.cm.bone_r, alpha = 0.5)
ax.plot_wireframe(X, Y, snes2d, color = "k", linewidth = 1.0)
# axes
ax.set_xlim([1.01, 1.69])
ax.set_ylim([0.41, 1.09])
ax.set_zlim([8.01, 21.9])
# labels
ax.set_xlabel(r"Alpha ($\alpha$)")
ax.set_ylabel(r"Gamma ($\gamma$)")
ax.set_zlabel(r"Newton steps")
ax.set_xticklabels(["%.1f" % alpha for alpha in alphas])
ax.set_yticklabels(["%.1f" % gamma for gamma in gammas])
ax.set_zticklabels(["10", "12", "14", "16", "18", "20"])
# view
ax.view_init(elev, azi)
# save
from matplotlib.transforms import Bbox
b = Bbox.from_bounds(0.25, 0, 7.25, 5.75)
plt.savefig("eisenstat-walker-snes.pdf", bbox_inches = b)
#
# main
#
if __name__ == "__main__":
create_figures()
<file_sep>#!/usr/bin/env python
import os
import sys
import re
import numpy as np
#
# read_monitor_data
#
def read_monitor_data(filepath):
# debug
# print 'read_monitor_data ...', filepath
# read file, parse and store
splist = []
f = open(filepath, 'r')
for line in f:
spmatch = re.search(r"^\s+(\d+.\d+)s \d+ Spinup Function norm \d+.\d+e[+-]\d+ \d+.\d+e[+-]\d+", line)
if spmatch:
# print line,
splist.append(float(spmatch.groups()[0]))
f.close()
# return values
return np.array(splist)
#
# create table
#
def create_table(models, data):
# debug
print("create table ...")
for i in range(0, len(models)):
# debug
# print models[i], data[i]
# model
print("%-15s" % models[i]),
# min, max, avg, std
min = data[i][0]
max = data[i][1]
avg = data[i][2]
std = data[i][3]
print(r''' & '''),
print("%8.2f" % min),
print(r'''\unit{s} '''),
print(r''' & '''),
print("%8.2f" % max),
print(r'''\unit{s} '''),
print(r''' & '''),
print("%8.2f" % avg),
print(r'''\unit{s} '''),
print(r''' & '''),
print("%8.2f" % std),
print(r''' & '''),
print("%8.2f" % (min/(i+1))),
print(r'''\unit{s} '''),
# row end
print(r''' \\''')
# print(r'''
# %tab:norms
# \begin{table*}
# \setlength{\tabcolsep}{10pt}
# \caption{\label{tab:norms}
# Difference in Euclidean norm ...}
# \vspace{0.3cm}
# \small
# \centering
# \begin{tabular}{l S S}
# \tophline
# Model & {$\| \mathbf{y}_{\mathrm{SP}} - \mathbf{y}_{\mathrm{NK}} \|_2$} & {$\| \mathbf{y}_{\mathrm{SP}} - \mathbf{y}_{\mathrm{NK}} \|_{2, \Omega}$} \\
# \middlehline''')
# # go through models
# for i in range(0, len(modellist)):
# # combine volumes and tracer vectors
# vols = np.tile(vol, len(tracerlist[i]))
# tracer = np.concatenate(vlist[i])
# # debug
# print("%-15s" % modellist[i]),
# print(r'''& '''),
# # print(r'''& \num{'''),
# # print("vector lengths: %d, %d" % (len(vols), len(tracer)))
# # compute 2-norm
# norm = np.linalg.norm(tracer)
# # debug
# print("%.3e" % norm),
# print(r''' & '''),
# # print(r'''} & \num{'''),
# # compute weighted norm
# normw = np.linalg.norm(tracer * np.sqrt(vols))
# # debug
# print("%.3e" % normw),
# print(r''' \\''')
# # print(r'''} \\''')
# print(r'''\bottomhline
# \end{tabular}
# \end{table*}
# ''')
#
# read_all_data
#
def read_all_data(modeldirs):
data = []
for dir in modeldirs:
# construct file path
filepath = "%s/work/profile.%s.out" % (dir, dir)
# read monitor data
monitordata = read_monitor_data(filepath)
# debug
# print monitordata
# compute min, max, avg, std
min = np.min(monitordata)
max = np.max(monitordata)
avg = np.mean(monitordata)
std = np.std(monitordata)
# debug
# print "%.2f s" % min, "%.2f s" % max, "%.2f s" % avg, "%.2f" % std
# append to data
data.append([min, max, avg, std])
# return values
return data
#
# main
#
if __name__ == "__main__":
# no arguments?
if not (len(sys.argv) == 1):
# print usage and exit with code 1
print("usage: ./create-table.py")
sys.exit(1)
# model directories
modeldirs = ["N", "N-DOP", "NP-DOP", "NPZ-DOP", "NPZD-DOP"]
# debug
print("using %s models" % modeldirs)
# read all data
data = read_all_data(modeldirs)
# debug
# print data
# create table
create_table(modeldirs, data)
###
### DUMP
###
# create profile plot
# create_profile_figure(modeldir)
#
# read_profile_data
#
# def read_profile_data(filepath):
# # debug
# print 'read profile data ...', filepath
# # read file, parse and store
# lines = []
# starthere = 0
# f = open(filepath, "r")
# for line in f:
# # look for starting point
# linematch = re.search(r"--- Event Stage 0: Main Stage", line)
# if linematch:
# starthere = 1
# if starthere == 1:
# linematch = re.search(r"------------------------------------------------------------------------------------------------------------------------", line)
# if linematch:
# break
# lines.append(line)
# f.close()
# # print lines
#
# # post process
# data = []
# total = 0.0
# for line in lines:
# datamatch = re.search(r"^(\S+)\s+\d+\s\S+\s(\d+.\d+e[+-]\d+)", line)
# if datamatch:
# groups = datamatch.groups()
# if groups[0] in ["BGCStep", "MatCopy", "MatScale", "MatAXPY", "MatMult"]:
# data.append(datamatch.groups())
# if groups[0] in ["TimeStepPhi"]:
# total = float(groups[1])
# # return values
# return total, data
# read profile data
# profiledata = read_profile_data(filepath)
# print profiledata
<file_sep>#!/usr/bin/env python
#
# write_job_file
#
def write_job_file(gamma, alpha):
gstr = "{0:1.1f}".format(gamma)
astr = "{0:.5f}".format(alpha)
filltext = gstr + "-" + astr
# job file
jobfile = "job/NK-" + filltext + ".nesh-fe.job.txt"
# job text
jobtext = ""
jobtext += "#PBS -N NK-" + filltext + "\n"
jobtext += "#PBS -j o" + "\n"
jobtext += "#PBS -o work/NK-" + filltext + ".out.txt" + "\n"
jobtext += "#PBS -b 4" + "\n"
jobtext += "#PBS -l cpunum_job=16" + "\n"
jobtext += "#PBS -l elapstim_req=02:00:00" + "\n"
jobtext += "#PBS -l memsz_job=32gb" + "\n"
jobtext += "#PBS -T mpich" + "\n"
jobtext += "#PBS -q clmedium" + "\n"
jobtext += "cd $PBS_O_WORKDIR" + "\n"
jobtext += ". job/de.uni-kiel.rz.nesh-fe.petsc-3.3-p5.opt.txt" + "\n"
jobtext += "mpirun -n 64 -r ssh $NQSII_MPIOPTS ./metos3d-simpack-MITgcm-PO4-DOP.exe option/NK-" + filltext + ".option.txt" + "\n"
jobtext += "qstat -f ${PBS_JOBID/0:/}" + "\n"
# store
f = open(jobfile, "w")
f.write(jobtext)
f.close()
#
# write_option_file
#
def write_option_file(gamma, alpha):
gstr = "{0:1.1f}".format(gamma)
astr = "{0:.5f}".format(alpha)
filltext = gstr + "-" + astr
# opt file
optfile = "option/NK-" + filltext + ".option.txt"
# opt text
opttext = ""
opttext += "-Metos3DDebugLevel 0" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DGeometryType Profile" + "\n"
opttext += "-Metos3DProfileInputDirectory data/TMM/2.8/Geometry/" + "\n"
opttext += "-Metos3DProfileIndexStartFile gStartIndices.bin" + "\n"
opttext += "-Metos3DProfileIndexEndFile gEndIndices.bin" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DTracerCount 2" + "\n"
opttext += "-Metos3DTracerInitValue 2.17e+0,1.e-4" + "\n"
opttext += "-Metos3DTracerOutputDirectory work/" + "\n"
opttext += "-Metos3DTracerOutputFile PO4.petsc,DOP.petsc" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DParameterCount 7" + "\n"
opttext += "-Metos3DParameterValue 0.5,2.0,0.67,0.5,30.0,0.02,0.858" + "\n"
# boundary data
opttext += "" + "\n"
opttext += "-Metos3DBoundaryConditionCount 2" + "\n"
opttext += "-Metos3DBoundaryConditionInputDirectory data/TMM/2.8/Forcing/BoundaryCondition/" + "\n"
opttext += "-Metos3DBoundaryConditionName Latitude,IceCover" + "\n"
opttext += "-Metos3DLatitudeCount 1" + "\n"
opttext += "-Metos3DLatitudeFileFormat latitude.petsc" + "\n"
opttext += "-Metos3DIceCoverCount 12" + "\n"
opttext += "-Metos3DIceCoverFileFormat fice_$02d.petsc" + "\n"
# domain data
opttext += "" + "\n"
opttext += "-Metos3DDomainConditionCount 2" + "\n"
opttext += "-Metos3DDomainConditionInputDirectory data/TMM/2.8/Forcing/DomainCondition/" + "\n"
opttext += "-Metos3DDomainConditionName LayerDepth,LayerHeight" + "\n"
opttext += "-Metos3DLayerDepthCount 1" + "\n"
opttext += "-Metos3DLayerDepthFileFormat z.petsc" + "\n"
opttext += "-Metos3DLayerHeightCount 1" + "\n"
opttext += "-Metos3DLayerHeightFileFormat dz.petsc" + "\n"
# transport
opttext += "" + "\n"
opttext += "-Metos3DTransportType Matrix" + "\n"
opttext += "-Metos3DMatrixInputDirectory data/TMM/2.8/Transport/Matrix5_4/1dt/" + "\n"
opttext += "-Metos3DMatrixCount 12" + "\n"
opttext += "-Metos3DMatrixExplicitFileFormat Ae_$02d.petsc" + "\n"
opttext += "-Metos3DMatrixImplicitFileFormat Ai_$02d.petsc" + "\n"
# time step
opttext += "" + "\n"
opttext += "-Metos3DTimeStepStart 0.0" + "\n"
opttext += "-Metos3DTimeStepCount 2880" + "\n"
opttext += "-Metos3DTimeStep 0.0003472222222222" + "\n"
# solver
opttext += "-Metos3DSolverType Newton" + "\n"
opttext += "-Metos3DNewton_snes_type ls" + "\n"
opttext += "-Metos3DNewton_snes_atol 9.008823302130e-04" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_gamma " + gstr + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_alpha " + astr + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_alpha2 " + astr + "\n"
opttext += "-Metos3DNewton_snes_monitor" + "\n"
opttext += "-Metos3DNewton_ksp_type gmres" + "\n"
opttext += "-Metos3DNewton_ksp_atol 9.008823302130e-04" + "\n"
opttext += "-Metos3DNewton_ksp_max_it 300" + "\n"
opttext += "-Metos3DNewton_ksp_gmres_modifiedgramschmidt" + "\n"
opttext += "-Metos3DNewton_ksp_monitor" + "\n"
# store
f = open(optfile, "w")
f.write(opttext)
f.close()
#
# create_job_option
#
def create_job_option():
import math as m
# ew params
gammas = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5]
alphas = [(1 + m.sqrt(5))/2, 1.5, 1.4, 1.3, 1.2, 1.1]
# files
for gamma in gammas:
for alpha in alphas:
write_job_file(gamma, alpha)
write_option_file(gamma, alpha)
#
# main
#
if __name__ == "__main__":
create_job_option()
<file_sep>#!/usr/bin/env python -W ignore
import os
import sys
import re
import numpy as np
import matplotlib
matplotlib.rc("font", **{"family" : "sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex = True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gsp
#
# read_nk_convergence_data
#
def read_nk_convergence_data(nmax, filepath):
# debug
print 'read Newton-Krylov convergence data ...'
# read file, parse and store
kspiter = 0
kspidx = []
ksplist = []
snesidx = []
sneslist = []
f = open(filepath, 'r')
for line in f:
# SNES
snesmatch = re.search(r"^\s+(\d+) SNES Function norm (\d+.\d+e[+-]\d+)", line)
if snesmatch:
# print snesmatch.groups()
snesidx.append(kspiter)
sneslist.append(snesmatch.groups())
# KSP
kspmatch = re.search(r"^\s+(\d+) KSP Residual norm (\d+.\d+e[+-]\d+)", line)
if kspmatch:
# print kspmatch.groups()
kspidx.append(kspiter)
ksplist.append(kspmatch.groups())
kspiter = kspiter + 1
if kspiter >= nmax:
break
f.close()
# debug
print("read in %d data points ..." % kspiter)
# retrieve values
kspval = map(lambda x: x[1], ksplist)
snesval = map(lambda x: x[1], sneslist)
# return values
return [kspidx, kspval, snesidx, snesval]
#
# read_sp_convergence_data
#
def read_sp_convergence_data(nmax, filepath):
# debug
print 'read spin-up convergence data ...'
# read file, parse and store
spiter = 0
spidx = []
splist = []
f = open(filepath, 'r')
for line in f:
spmatch = re.search(r"^\s+\d+.\d+s (\d+) Spinup Function norm (\d+.\d+e[+-]\d+) (\d+.\d+e[+-]\d+)", line)
if spmatch:
# print line,
spidx.append(spiter)
splist.append(spmatch.groups())
spiter = spiter + 1
if spiter >= nmax:
break
else:
continue
break
f.close()
# debug
print("read in %d data points ..." % spiter)
# retrieve values
spval = map(lambda x: x[1], splist)
spvalw = map(lambda x: x[2], splist)
# return values
return [spidx, spval, spvalw]
#
# create_convergence_figure
#
def create_convergence_figure(modeldir, prefix):
# debug
print "create convergence figure ..."
# set max data points
nmax = 10000
# read convergence data
(kspidx, kspval, snesidx, snesval) = read_nk_convergence_data(nmax, "%s/work/%s%s.out" % (modeldir, prefix, modeldir))
# spinup
(spidx, spval, spvalw) = read_sp_convergence_data(nmax, "%s/work/spinup.%s.out" % (modeldir, modeldir))
# set dimensions
# plot
xrange = range(0, nmax)
# subplot
nsplit = 1000
ax1l, ax1r = (0, nsplit)
ax2l, ax2r = (nsplit, nmax)
# subplots
figid = 1
f = plt.figure(figid)
gs = gsp.GridSpec(1, 2, width_ratios=[2,1])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
# spinup
p1, = ax1.semilogy(spidx[ax1l:ax1r], spval[ax1l:ax1r], "k-", linewidth = 1.0)
ax2.semilogy(spidx[ax2l:ax2r], spval[ax2l:ax2r], "k-", linewidth = 1.0)
# KSP
p2, = ax1.semilogy(kspidx[ax1l:ax1r], kspval[ax1l:ax1r], "k-", linewidth = 1.0)
ax2.semilogy(kspidx[ax2l:ax2r], kspval[ax2l:ax2r], "k-", linewidth = 1.0)
# SNES
if max(snesidx) >= nsplit:
# get index lists first NK
idxlow = np.where(np.array(snesidx)<nsplit)[0]
idxhigh = np.where(np.array(snesidx)>=nsplit)[0]
# set arrays first NK
snesidxlow = [snesidx[i] for i in idxlow]
snesidxhigh = [snesidx[i] for i in idxhigh]
snesvallow = [snesval[i] for i in idxlow]
snesvalhigh = [snesval[i] for i in idxhigh]
# plot
ax1.semilogy(snesidxlow, snesvallow, marker = "D", ms = 4.0, mfc = "None", mec = "k", mew = 1.0, linewidth = 0)
ax2.semilogy(snesidxhigh, snesvalhigh, marker = "D", ms = 4.0, mfc = "None", mec = "k", mew = 1.0, linewidth = 0)
else:
ax1.semilogy(snesidx, snesval, marker = "D", ms = 4.0, mfc = "None", mec = "k", mew = 1.0, linewidth = 0)
# x
ax1xmaj = range(0, 1000, 100)
ax1.set_xticks(ax1xmaj)
ax1.set_xticklabels(ax1xmaj)
ax2xmaj = range(1000, nmax+1, 1000)
ax2.set_xticks(ax2xmaj)
ax2.set_xticklabels(ax2xmaj, **{"rotation":55.0, "rotation_mode":"anchor", "x":0.005, "y":0.005, "ha":"right"})
# common x label
f.suptitle("Model years", y = 0.035)
# y
ax1.set_ylim([10e-7, 10e+2])
ytext = [r"10\textsuperscript{%d}" % i for i in range(-7, 4)]
ax1.set_ylabel("Norm [$\mathrm{m\,mol\,P / m^3}$]")
ax1.set_yticklabels(ytext)
ax2.set_yticklabels([])
ax2.set_ylim([10e-7, 10e+2])
# grid
ax1.grid(True, which='major', axis='both', color='0.25', linestyle=':')
ax2.grid(True, which='major', axis='both', color='0.25', linestyle=':')
ax2.grid(True, which='minor', axis='x', color='0.25', linestyle=':')
# legend
leg1 = r"Spin-up"
leg2 = r"Newton-Krylov"
l1 = plt.figlegend([p1, p2], [leg1, leg2], 1, numpoints = 3, bbox_to_anchor = (0.862, 0.899), prop={'size':15})
ll1 = l1.get_lines()[1]
ll1.set_marker("D")
ll1.set_ms(4.0)
ll1.set_mfc("None")
ll1.set_mew(1.0)
# adjust subplots
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.00, hspace=None)
# write to file
plt.savefig("figures/convergence.%s.pdf" % modeldir, bbox_inches="tight")
#
# main
#
if __name__ == "__main__":
# no arguments?
if len(sys.argv) == 1:
# print usage and exit with code 1
print("usage: %s [MODELNAME...] [PREFIX...]" % sys.argv[0])
sys.exit(1)
# model directory does not exist?
modeldir = sys.argv[1]
if not (os.path.exists(modeldir) and os.path.isdir(modeldir)):
# print error message and exit with code 2
print("### ERROR ### '%s' does not exist or is no directory." % modeldir)
sys.exit(2)
# strip trailing slash if any
modeldir = os.path.normpath(modeldir)
# check if we have a *given* prefix
if len(sys.argv) == 3:
prefix = sys.argv[2]
else:
prefix = "newton."
# debug
print("using '%s' model" % modeldir)
print("using prefix ... '%s'" % prefix)
# create convergence plot
create_convergence_figure(modeldir, prefix)
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 4
#PBS -l cpunum_job=16
#PBS -l elapstim_req=12:00:00
#PBS -l memsz_job=10gb
#PBS -N spinup.NPZ-DOP
#PBS -o work/spinup.NPZ-DOP.out
#PBS -e work/spinup.NPZ-DOP.out
#PBS -q clfocean
#
module load intel intelmpi
module load petsc-3.3-p4-intel
#
cd $PBS_O_WORKDIR
#
mpirun $NQSII_MPIOPTS -np 64 ./metos3d-simpack-NPZ-DOP.exe option/spinup.NPZ-DOP.option
<file_sep>### Latin Hypercube Sampling
Generated samples using MATLAB's `lhsdesign` routine:
m = 100;
n = 7;
xx = lhsdesign(m, n);
lb = [0.25, 1.5, 0.05, 0.25, 10.0, 0.01, 0.7];
ub = [0.75, 200.0, 0.95, 1.50, 50.0, 0.05, 1.5];
x = bsxfun(@plus, lb, bsxfun(@times, xx, (ub-lb)))
#### Written to disk using MATLAB:
fid = fopen('LHS-samples.bin', 'wb', 'ieee-be')
fwrite(fid, m, 'integer*4')
fwrite(fid, n, 'integer*4')
fwrite(fid, x, 'real*8')
fclose(fid)
#### Read in using Python:
import numpy as np
fid = open('LHS-samples.bin', 'rb')
m, = np.fromfile(fid, dtype = '>i4', count = 1)
n, = np.fromfile(fid, dtype = '>i4', count = 1)
x = np.fromfile(fid, dtype = '>f8', count = m * n)
fid.close()
#### Reshaped:
x = np.reshape(x, (n, m))
### Setup:
$> . job/de.uni-kiel.rz.nesh-fe.petsc-3.3-p5.opt.txt
$> metos3d simpack MITgcm-PO4-DOP
### Run:
$> for i in $(ls job/sample.*); do qsub $i; done;
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 1
#PBS -l cpunum_job=24
#PBS -l elapstim_req=01:00:00
#PBS -l memsz_job=10gb
#PBS -N profile.N
#PBS -o work/profile.N.out
#PBS -e work/profile.N.out
#PBS -q clfo2
#
cd $PBS_O_WORKDIR
#
. ../petsc-3.3-p4.env
#
mpirun $NQSII_MPIOPTS -np 1 ./metos3d-simpack-N.exe option/profile.N.option -log_summary
<file_sep>#### Spin-up and Newton-Krylov solver
Setup PETSc environment:
$> . petsc-3.3-p4.env.txt
Compile model and run experiment (submit job):
- ``MITgcm-PO4-DOP`` model:
$> cd MITgcm-PO4-DOP/
$> metos3d simpack MITgcm-PO4-DOP
$> qsub job/newton.MITgcm-PO4-DOP.job
$> qsub job/spinup.MITgcm-PO4-DOP.job
- ``N`` model:
$> cd N/
$> metos3d simpack N
$> qsub job/newton.N.job
$> qsub job/spinup.N.job
...
- ``NPZD-DOP`` model:
$> cd NPZD-DOP/
$> metos3d simpack NPZD-DOP
$> qsub job/newton.NPZD-DOP.job
$> qsub job/sinpup.NPZD-DOP.job
Create figures:
- ``MITgcm-PO4-DOP`` model:
$> ./create-figures.py MITgcm-PO4-DOP/
- ``N`` model:
$> ./create-figures.py N/
...
- ``NPZD-DOP`` model:
$> ./create-figures.py NPZD-DOP/
<file_sep>#!/usr/bin/env python
import os
import sys
import numpy as np
import numpy.random as npr
#
# read_PETSc_vec
#
def read_PETSc_vec(filepath):
# debug
print "reading in PETSc vector ...", filepath
# open file
f = open(filepath, "rb")
# omit header
np.fromfile(f, dtype = ">i4", count = 1)
# read length
nvec = np.fromfile(f, dtype = ">i4", count = 1)
# read values
v = np.fromfile(f, dtype = ">f8", count = nvec)
# close file
f.close()
# return vector
return v
#
# write_PETSc_vec
#
def write_PETSc_vec(v, filepath):
# debug
print "writing PETSc vector ...", filepath
# open file
f = open(filepath, "wb")
# write PETSc vector header
np.array(1211214, dtype = ">i4").tofile(f)
# write length
np.array(len(v), dtype = ">i4").tofile(f)
# write values
np.array(v, dtype = ">f8").tofile(f)
# close file
f.close()
#
# read_PETSc_mat
#
def read_PETSc_mat(filepath):
# debug
print "reading in PETSc matrix ...", filepath
# open file
f = open(filepath, "rb")
# omit header
np.fromfile(f, dtype = ">i4", count = 1)
# read dims
nx = np.fromfile(f, dtype = ">i4", count = 1)
ny = np.fromfile(f, dtype = ">i4", count = 1)
# read no of non zeros
nnz = np.fromfile(f, dtype = ">i4", count = 1)
# non zeros per row
nrow = np.fromfile(f, dtype = ">i4", count = nx)
# column indices
colidx = np.fromfile(f, dtype = ">i4", count = nnz)
# values
val = np.fromfile(f, dtype = ">f8", count = nnz)
# close file
f.close()
# create full matrix (default np.float64)
mat = np.zeros(shape = (nx, ny))
offset = 0
for i in range(nx):
if not nrow[i] == 0.0:
for j in range(nrow[i]):
mat[i, colidx[offset]] = val[offset]
offset = offset + 1
# return matrix
return mat
#
# create_samples_read_data
#
def create_samples_read_data():
# debug
print "read data ..."
# set file paths
lsmpath = m3dprefix + "/data/data/TMM/2.8/Geometry/landSeaMask.petsc"
volpath = m3dprefix + "/data/data/TMM/2.8/Geometry/volumes.petsc"
# read in land sea mask and volumes
# convert lsm to a matrix of ints
lsm = read_PETSc_mat(lsmpath)
lsm = lsm.astype(int)
vol = read_PETSc_vec(volpath)
# return data
return lsm, vol
#
# create_samples
#
def create_samples(m3dprefix, argv):
# debug
print "create samples ..."
# retrieve mass
mass = float(sys.argv[1])
# debug
print "using mass ...", mass, "mmol P m^(-3)"
# retrieve tracers
tracers = sys.argv[2:]
ntracer = len(tracers)
# debug
print "using tracer(s) ...", tracers
# read data
lsm, vol = create_samples_read_data()
# normalize volumes
volnorm = vol / sum(vol)
# divide mass by no of tracers
masstracer = mass / ntracer
# loop over tracers
for itracer in range(ntracer):
# get random values
val = 0.5 + 0.25 * npr.ranf(vol.shape)
# scale
val = masstracer * val / sum(val * volnorm)
# debug
# print val
# print min(val), max(val)
# print sum(val * volnorm)
# save vector
filepath = "init.%s.petsc" % tracers[itracer]
write_PETSc_vec(val, filepath)
#
# main
#
if __name__ == "__main__":
# no arguments?
if len(sys.argv) <= 2:
# print usage and exit with code 1
print("usage: ./create-samples.py [MASS...] [TRACERS...]")
print("example:")
print(" $> ./create-samples.py 2.17 N P Z D DOP")
sys.exit(1)
# determine path prefix for geometry data
m3dprefix = os.path.expanduser("~/.metos3d")
# create samples
create_samples(m3dprefix, sys.argv)
<file_sep>#!/usr/bin/env python -W ignore
import os
import sys
import re
import numpy as np
import matplotlib
matplotlib.rc("font", **{"family" : "sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex = True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gsp
from mpl_toolkits.basemap import Basemap
#
# read_PETSc_vec
#
def read_PETSc_vec(file):
# open file
# omit header
# read length
# read values
# close file
f = open(file, "rb")
np.fromfile(f, dtype=">i4", count=1)
nvec = np.fromfile(f, dtype=">i4", count=1)
v = np.fromfile(f, dtype=">f8", count=nvec)
f.close()
return v
#
# read_PETSc_mat
#
def read_PETSc_mat(file):
# open file
f = open(file, "rb")
# omit header
np.fromfile(f, dtype=">i4", count=1)
# read dims
nx = np.fromfile(f, dtype=">i4", count=1)
ny = np.fromfile(f, dtype=">i4", count=1)
nnz = np.fromfile(f, dtype=">i4", count=1)
nrow = np.fromfile(f, dtype=">i4", count=nx)
colidx = np.fromfile(f, dtype=">i4", count=nnz)
val = np.fromfile(f, dtype=">f8", count=nnz)
# print "dims"
# print nx, ny
# print "nnz"
# print nnz
# print "nrow"
# print nrow
# print "colidx"
# print colidx
# print "val"
# print val
# close file
f.close()
# create full matrix
matfull = np.zeros(shape=(nx, ny), dtype = float)
offset = 0
for i in range(nx):
if not nrow[i] == 0.0:
for j in range(nrow[i]):
matfull[i, colidx[offset]] = val[offset]
offset = offset + 1
return matfull
#
# read_data
#
def read_data(m3dprefix, modeldir, prefix, tracer):
# debug
print("reading data ... %s" % tracer)
# v1d, z, dz, lsm (land sea mask)
v1dsp = read_PETSc_vec("%s/work/spinup.%s.petsc" % (modeldir, tracer))
v1dnk = read_PETSc_vec("%s/work/%s%s.petsc" % (modeldir, prefix, tracer))
v1d = np.fabs(v1dsp - v1dnk)
z = read_PETSc_vec("%s/data/data/TMM/2.8/Forcing/DomainCondition/z.petsc" % m3dprefix)
dz = read_PETSc_vec("%s/data/data/TMM/2.8/Forcing/DomainCondition/dz.petsc" % m3dprefix)
lsm = read_PETSc_mat("%s/data/data/TMM/2.8/Geometry/landSeaMask.petsc" % m3dprefix)
lsm = lsm.astype(int)
# dims
nx, ny = lsm.shape
nz = 15
# v3d
v3d = np.zeros(shape=(3, nx, ny, nz), dtype = float)
v3d[:,:,:,:] = np.nan
# v1d -> (v3d, z, dz)
offset = 0
for ix in range(nx):
for iy in range(ny):
length = lsm[ix, iy]
if not length == 0:
v3d[0, ix, iy, 0:length] = v1d[offset:offset+length]
v3d[1, ix, iy, 0:length] = z[offset:offset+length]
v3d[2, ix, iy, 0:length] = dz[offset:offset+length]
offset = offset + length
return v3d
#
# create_figure_surface
#
def create_figure_surface(figid, aspect, xx, yy, cmin, cmax, levels, slices, v3d):
print "# Creating surface ..."
# data
vv = v3d[0,:,:,0]
# shift
vv = np.roll(vv, 64, axis=1)
# plot surface
plt.figure(figid)
# colormap
cmap = plt.cm.bone_r
# contour fill
p1 = plt.contourf(xx, yy, vv, cmap=cmap, levels=levels, origin="lower")
# contour lines
p2 = plt.contour(p1, levels=levels, linewidths = (1,), colors="k")
# slices
s1 = xx[np.mod(slices[0]+64, 128)]
s2 = xx[np.mod(slices[1]+64, 128)]
s3 = xx[np.mod(slices[2]+64, 128)]
# print s1, s2, s3
plt.vlines([s1, s2, s3], -90, 90, color='k', linestyles='--')
# set aspect ratio of axes
plt.gca().set_aspect(aspect)
# colorbar
cbar = plt.colorbar(p1, format = '%.1e', fraction = 0.024, pad = 0.03)
# basemap
m = Basemap(projection="cyl")
m.drawcoastlines(linewidth = 0.5)
# xticks
plt.xticks(range(-180, 181, 45), range(-180, 181, 45))
plt.xlim([-180, 180])
plt.xlabel("Longitude [degrees]", labelpad=8)
# yticks
plt.yticks(range(-90, 91, 30), range(-90, 91, 30))
plt.ylim([-90, 90])
plt.ylabel("Latitude [degrees]")
#
# create_figure_slice
#
def create_figure_slice(figid, aspect, yy, yl, yr, slice, title, yvisible, cmin, cmax, levels, v3d):
# create figure
print "# Creating slice ..."
# data
vv = v3d[0,yl:yr,slice,:]
# depths, heights, mids
vzz = np.nanmax(v3d[1, :, slice, :], axis = 0)
vdz = np.nanmax(v3d[2, :, slice, :], axis = 0)
vdzz = vzz - 0.5*vdz
# print vzz, vdz, vdzz
# plot slice
plt.figure(figid)
# colormap
cmap = plt.cm.bone_r
# contour fill
p1 = plt.contourf(yy[yl:yr], vdzz, vv.T, cmap=cmap, levels=levels, origin="upper")
plt.clim(cmin, cmax)
# x
plt.xticks([-60, -30, 0, 30, 60], [-60, -30, 0, 30, 60])
plt.xlabel("Latitude [degrees]", labelpad=8)
# y
plt.ylim([0, 5200])
plt.yticks(vzz, ("50", "", "", "360", "", "790", "1080", "1420", "1810", "2250", "2740", "3280", "3870", "4510", "5200"))
plt.yticks(visible=yvisible)
if yvisible: plt.ylabel("Depth [m]")
# title
t1 = plt.title(title)
t1.set_y(1.02)
# contour lines
p2 = plt.contour(yy[yl:yr], vdzz, vv.T, levels=p1.levels, linewidths = (1,), colors="k")#, hold="on")
# axes transform
plt.gca().invert_yaxis()
plt.gca().set_aspect(aspect)
# colorbar
cbar = plt.colorbar(p1, format = '%.1e', fraction = 0.027, pad = 0.03)
#
# create_figures
#
def create_figures(m3dprefix, modeldir, tracer, v3d):
# create figures
print "# Creating figures ..."
# longitude
dx = 2.8125
xx = np.concatenate([np.arange(-180 + 0.5 * dx, 0, dx), np.arange(0 + 0.5 * dx, 180, dx)])
# latitude
dy = 2.8125
yy = np.arange(-90 + 0.5 * dy, 90, dy)
# print xx
# print yy
# min, max of v3d data, just info
vmin = np.nanmin(v3d[0,:,:,:])
vmax = np.nanmax(v3d[0,:,:,:])
vavg = np.nanmean(v3d[0,:,:,:])
vstd = np.nanstd(v3d[0,:,:,:])
print("min: %e, max: %e, avg: %e, std: %e" % (vmin, vmax, vavg, vstd))
# levels
levels = np.arange(vmin, vmax, vstd)
print levels
# color range
cmin, cmax = [vmin, vmax]
# print cmin, cmax
#
# slices
#
# range of latitude
yl, yr = [6, 58]
# aspect of axes
aspect = (yy[yr] - yy[yl] + 1) / 5200.0 / 1.8
# print yl, yr
# print aspect
slices = [73, 117, 32]
title = "Pacific"
yvisible = True
create_figure_slice(1, aspect, yy, yl, yr, slices[0], title, yvisible, cmin, cmax, levels, v3d)
# write to file
plt.savefig("figures/slice-%s-%s-diff-%s.pdf" % (modeldir, tracer, title), bbox_inches = "tight")
title = "Atlantic"
yvisible = True
create_figure_slice(2, aspect, yy, yl, yr, slices[1], title, yvisible, cmin, cmax, levels, v3d)
# write to file
plt.savefig("figures/slice-%s-%s-diff-%s.pdf" % (modeldir, tracer, title), bbox_inches = "tight")
title = "Indian"
yvisible = True
create_figure_slice(3, aspect, yy, yl, yr, slices[2], title, yvisible, cmin, cmax, levels, v3d)
# write to file
plt.savefig("figures/slice-%s-%s-diff-%s.pdf" % (modeldir, tracer, title), bbox_inches = "tight")
#
# surface
#
aspect = 1.0
create_figure_surface(4, aspect, xx, yy, cmin, cmax, levels, slices, v3d)
# write to file
plt.savefig("figures/surface-%s-diff-%s.pdf" % (modeldir, tracer), bbox_inches = "tight")
#
# main
#
if __name__ == "__main__":
# no arguments?
if len(sys.argv) <= 2:
# print usage and exit with code 1
print("usage: %s [MODELNAME...] [TRACER...] [PREFIX...]" % sys.argv[0])
sys.exit(1)
# model directory does not exist?
modeldir = sys.argv[1]
if not (os.path.exists(modeldir) and os.path.isdir(modeldir)):
# print error message and exit with code 2
print("### ERROR ### '%s' does not exist or is no directory." % modeldir)
sys.exit(2)
# strip trailing slash if any
modeldir = os.path.normpath(modeldir)
# debug
print("using %s model" % modeldir)
# set prefix for data
m3dprefix = os.path.expanduser('~/.metos3d')
# set tracer
tracer = sys.argv[2]
# check if we have a *given* prefix
if len(sys.argv) == 4:
prefix = sys.argv[3]
else:
prefix = "newton."
# debug
print("using prefix ... '%s'" % prefix)
# read data
v3d = read_data(m3dprefix, modeldir, prefix, tracer)
# create figure
create_figures(m3dprefix, modeldir, tracer, v3d)
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 1
#PBS -l cpunum_job=24
#PBS -l elapstim_req=01:00:00
#PBS -l memsz_job=10gb
#PBS -N profile.NPZD-DOP
#PBS -o work/profile.NPZD-DOP.out
#PBS -e work/profile.NPZD-DOP.out
#PBS -q clfo2
#
cd $PBS_O_WORKDIR
#
. ../petsc-3.3-p4.env
#
mpirun $NQSII_MPIOPTS -np 1 ./metos3d-simpack-NPZD-DOP.exe option/profile.NPZD-DOP.option -log_summary
<file_sep>#!/usr/bin/env python
#
# write_option_file
#
def write_option_file(option, u, file):
# option text
opttext = ""
opttext += "-Metos3DDebugLevel 0" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DGeometryType Profile" + "\n"
opttext += "-Metos3DProfileInputDirectory data/TMM/2.8/Geometry/" + "\n"
opttext += "-Metos3DProfileIndexStartFile gStartIndices.bin" + "\n"
opttext += "-Metos3DProfileIndexEndFile gEndIndices.bin" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DTracerCount 2" + "\n"
opttext += "-Metos3DTracerInitValue 2.17e+0,1.e-4" + "\n"
opttext += "-Metos3DTracerOutputDirectory work/" + "\n"
opttext += "-Metos3DTracerOutputFile PO4.petsc,DOP.petsc" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DParameterCount 7" + "\n"
opttext += "-Metos3DParameterValue " + ",".join(["%.16e" % ui for ui in u]) + "\n"
opttext += "" + "\n"
opttext += "-Metos3DBoundaryConditionCount 2" + "\n"
opttext += "-Metos3DBoundaryConditionInputDirectory data/TMM/2.8/Forcing/BoundaryCondition/" + "\n"
opttext += "-Metos3DBoundaryConditionName Latitude,IceCover" + "\n"
opttext += "-Metos3DLatitudeCount 1" + "\n"
opttext += "-Metos3DLatitudeFileFormat latitude.petsc" + "\n"
opttext += "-Metos3DIceCoverCount 12" + "\n"
opttext += "-Metos3DIceCoverFileFormat fice_$02d.petsc" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DDomainConditionCount 2" + "\n"
opttext += "-Metos3DDomainConditionInputDirectory data/TMM/2.8/Forcing/DomainCondition/" + "\n"
opttext += "-Metos3DDomainConditionName LayerDepth,LayerHeight" + "\n"
opttext += "-Metos3DLayerDepthCount 1" + "\n"
opttext += "-Metos3DLayerDepthFileFormat z.petsc" + "\n"
opttext += "-Metos3DLayerHeightCount 1" + "\n"
opttext += "-Metos3DLayerHeightFileFormat dz.petsc" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DTransportType Matrix" + "\n"
opttext += "-Metos3DMatrixInputDirectory data/TMM/2.8/Transport/Matrix5_4/1dt/" + "\n"
opttext += "-Metos3DMatrixCount 12" + "\n"
opttext += "-Metos3DMatrixExplicitFileFormat Ae_$02d.petsc" + "\n"
opttext += "-Metos3DMatrixImplicitFileFormat Ai_$02d.petsc" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DTimeStepStart 0.0" + "\n"
opttext += "-Metos3DTimeStepCount 2880" + "\n"
opttext += "-Metos3DTimeStep 0.0003472222222222" + "\n"
opttext += "" + "\n"
opttext += "-Metos3DSolverType Newton" + "\n"
opttext += "-Metos3DNewton_snes_type ls" + "\n"
opttext += "-Metos3DNewton_snes_atol 9.008823302130e-04" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_gamma 1.0" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_alpha 1.2" + "\n"
opttext += "-Metos3DNewton_snes_ksp_ew_alpha2 1.2" + "\n"
opttext += "-Metos3DNewton_snes_monitor" + "\n"
opttext += "-Metos3DNewton_ksp_type gmres" + "\n"
opttext += "-Metos3DNewton_ksp_atol 9.008823302130e-04" + "\n"
opttext += "-Metos3DNewton_ksp_gmres_modifiedgramschmidt" + "\n"
opttext += "-Metos3DNewton_ksp_monitor" + "\n"
# write file
f = open(file, "w")
f.write(opttext)
f.close()
#
# write_job_file
#
def write_job_file(job, file):
# job text
jobtext = ""
jobtext += "#PBS -N sample." + job + "\n"
jobtext += "#PBS -b 4" + "\n"
jobtext += "#PBS -l cpunum_job=16" + "\n"
jobtext += "#PBS -l elapstim_req=01:00:00" + "\n"
jobtext += "#PBS -l memsz_job=32gb" + "\n"
jobtext += "#PBS -T mpich" + "\n"
jobtext += "#PBS -j o" + "\n"
jobtext += "#PBS -o work/metos3d.nesh-fe.sample." + job + ".out.txt" + "\n"
jobtext += "#PBS -q clfocean" + "\n"
jobtext += "cd $PBS_O_WORKDIR" + "\n"
jobtext += ". job/de.uni-kiel.rz.nesh-fe.petsc-3.3-p5.opt.txt" + "\n"
jobtext += "mpirun -r ssh $NQSII_MPIOPTS -n 64 ./metos3d-simpack-MITgcm-PO4-DOP.exe option/sample." + job + ".option.txt" + "\n"
jobtext += "qstat -f ${PBS_JOBID/0:/}" + "\n"
# write file
f = open(file, "w")
f.write(jobtext)
f.close()
#
# create_job_nesh_fe
#
def create_job_nesh_fe(samples):
import numpy as np
print "# Creating job files ..."
# shape
(n ,m) = samples.shape
# generate m job files
for i in range(0, m):
job = "%02d" % i
file = "job/sample." + job + ".job.txt"
# print job, file
write_job_file(job, file)
#
# create_option
#
def create_option(samples):
import numpy as np
print "# Creating option files ..."
# shape
(n ,m) = samples.shape
# generate m option files
for i in range(0, m):
option = "%02d" % i
file = "option/sample." + option + ".option.txt"
# print option, file
write_option_file(option, samples[:,i], file)
#
# create_job_option_nesh_fe
#
def create_job_option_nesh_fe(samples):
create_job_nesh_fe(samples)
create_option(samples)
#
# read_samples
#
def read_samples():
import numpy as np
print "# Reading samples ..."
# read
fid = open('LHS-samples.bin', 'rb')
m = np.fromfile(fid, dtype = '>i4', count = 1)
n = np.fromfile(fid, dtype = '>i4', count = 1)
x = np.fromfile(fid, dtype = '>f8', count = m * n)
fid.close()
# reshape
x = np.reshape(x, (n, m))
return x
#
# main
#
if __name__ == '__main__':
samples = read_samples()
create_job_option_nesh_fe(samples)
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 4
#PBS -l cpunum_job=16
#PBS -l elapstim_req=12:00:00
#PBS -l memsz_job=10gb
#PBS -N newton.2.NPZ-DOP
#PBS -o work/newton.2.NPZ-DOP.out
#PBS -e work/newton.2.NPZ-DOP.out
#PBS -q clfocean
#
module load intel intelmpi
module load petsc-3.3-p4-intel
#
cd $PBS_O_WORKDIR
#
mpirun $NQSII_MPIOPTS -np 64 ./metos3d-simpack-NPZ-DOP.exe option/newton.2.NPZ-DOP.option
<file_sep>#!/usr/bin/env python -W ignore
import os
import sys
import numpy as np
# set model list
modellist = ['MITgcm-PO4-DOP', 'N', 'N-DOP', 'NP-DOP', 'NPZ-DOP', 'NPZD-DOP']
tracerlist = [['PO4', 'DOP'], ['N'], ['N', 'DOP'], ['N', 'P', 'DOP'], ['N', 'P', 'Z', 'DOP'], ['N', 'P', 'Z', 'D', 'DOP']]
#
# read_PETSc_vec
#
def read_PETSc_vec(filepath):
# debug
# print "reading in PETSc vector ...", filepath
# open file
f = open(filepath, "rb")
# omit header
np.fromfile(f, dtype = ">i4", count = 1)
# read length
nvec = np.fromfile(f, dtype = ">i4", count = 1)
# read values
v = np.fromfile(f, dtype = ">f8", count = nvec)
# close file
f.close()
# return vector
return v
#
# read_PETSc_mat
#
def read_PETSc_mat(filepath):
# debug
# print "reading in PETSc matrix ...", filepath
# open file
f = open(filepath, "rb")
# omit header
np.fromfile(f, dtype = ">i4", count = 1)
# read dims
nx = np.fromfile(f, dtype = ">i4", count = 1)
ny = np.fromfile(f, dtype = ">i4", count = 1)
# read no of non zeros
nnz = np.fromfile(f, dtype = ">i4", count = 1)
# non zeros per row
nrow = np.fromfile(f, dtype = ">i4", count = nx)
# column indices
colidx = np.fromfile(f, dtype = ">i4", count = nnz)
# values
val = np.fromfile(f, dtype = ">f8", count = nnz)
# close file
f.close()
# create full matrix (default np.float64)
mat = np.zeros(shape = (nx, ny))
offset = 0
for i in range(nx):
if not nrow[i] == 0.0:
for j in range(nrow[i]):
mat[i, colidx[offset]] = val[offset]
offset = offset + 1
# return matrix
return mat
#
# create table
#
def create_table(vlist, vol):
# debug
# print("create table ...")
print(r'''
%tab:norms
\begin{table*}
\setlength{\tabcolsep}{10pt}
\caption{\label{tab:norms}
Difference in Euclidean norm ...}
\vspace{0.3cm}
\small
\centering
\begin{tabular}{l S S}
\tophline
Model & {$\| \mathbf{y}_{\mathrm{SP}} - \mathbf{y}_{\mathrm{NK}} \|_2$} & {$\| \mathbf{y}_{\mathrm{SP}} - \mathbf{y}_{\mathrm{NK}} \|_{2, \Omega}$} \\
\middlehline''')
# go through models
for i in range(0, len(modellist)):
# combine volumes and tracer vectors
vols = np.tile(vol, len(tracerlist[i]))
tracer = np.concatenate(vlist[i])
# debug
print("%-15s" % modellist[i]),
print(r'''& '''),
# print(r'''& \num{'''),
# print("vector lengths: %d, %d" % (len(vols), len(tracer)))
# compute 2-norm
norm = np.linalg.norm(tracer)
# debug
print("%.3e" % norm),
print(r''' & '''),
# print(r'''} & \num{'''),
# compute weighted norm
normw = np.linalg.norm(tracer * np.sqrt(vols))
# debug
print("%.3e" % normw),
print(r''' \\''')
# print(r'''} \\''')
print(r'''\bottomhline
\end{tabular}
\end{table*}
''')
#
# main
#
if __name__ == "__main__":
# debug
# print("comparing models ... " + str.join(', ', modellist))
# set prefix for newton experiments
if len(sys.argv) == len(modellist)+1:
prefixlist = sys.argv[1:len(modellist)+1]
else:
prefixlist = ('newton. '*len(modellist)).split(' ')
prefixlist.pop()
# debug
# print("using given prefix for model ... %s" % prefixlist)
# read in data
# print("read in data ...")
# diffs
vlist = []
for i in range(0, len(modellist)):
modeldir = modellist[i]
# print("model: %s tracer: %s" % (modeldir, str.join(', ', tracerlist[i])))
# add new empty list
vlist.append([])
for j in range(0, len(tracerlist[i])):
tracer = tracerlist[i][j]
# read vectors
vsp = read_PETSc_vec("%s/work/spinup.%s.petsc" % (modeldir, tracer))
vnk = read_PETSc_vec("%s/work/%s%s.petsc" % (modeldir, prefixlist[i], tracer))
# compute diff
vdiff = vsp - vnk
# add to list
vlist[i].append(vdiff)
# volumes
# print("read in volumes ...")
# determine path prefix for geometry data
m3dprefix = os.path.expanduser("~/.metos3d")
volpath = m3dprefix + "/data/data/TMM/2.8/Geometry/volumes.petsc"
vol = read_PETSc_vec(volpath)
# create table
create_table(vlist, vol)
<file_sep>#### Setup:
$> . job/de.uni-kiel.rz.nesh-fe.petsc-3.3-p5.opt.txt
$> metos3d simpack MITgcm-PO4-DOP
#### Run:
$> for i in $(ls job/NK-*); do qsub $i; done;
<file_sep>#### Profiling experiments
Setup PETSc environment:
$> . petsc-3.3-p4.env.txt
Compile model and run experiment (submit job):
- ``MITgcm-PO4-DOP`` model:
$> cd MITgcm-PO4-DOP/
$> metos3d simpack MITgcm-PO4-DOP
$> qsub job/profile.MITgcm-PO4-DOP.job
- ``N`` model:
$> cd N/
$> metos3d simpack N
$> qsub job/profile.N.job
...
- ``NPZD-DOP`` model:
$> cd NPZD-DOP/
$> metos3d simpack NPZD-DOP
$> qsub job/profile.NPZD-DOP.job
Create figures:
- ``MITgcm-PO4-DOP`` model:
$> ./create-figures.py MITgcm-PO4-DOP/
- ``N`` model:
$> ./create-figures.py N/
...
- ``NPZD-DOP`` model:
$> ./create-figures.py NPZD-DOP/
<file_sep>#!/usr/bin/env python
import os
import sys
import re
import numpy as np
import matplotlib
matplotlib.rc("font", **{"family" : "sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex = True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
#
# read_profile_data
#
def read_profile_data(filepath):
# debug
print 'read profile data ...'
# read file, parse and store
lines = []
starthere = 0
f = open(filepath, "r")
for line in f:
# look for starting point
linematch = re.search(r"--- Event Stage 0: Main Stage", line)
if linematch:
starthere = 1
if starthere == 1:
linematch = re.search(r"------------------------------------------------------------------------------------------------------------------------", line)
if linematch:
break
lines.append(line)
f.close()
# print lines
# post process
data = []
total = 0.0
for line in lines:
datamatch = re.search(r"^(\S+)\s+\d+\s\S+\s(\d+.\d+e[+-]\d+)", line)
if datamatch:
groups = datamatch.groups()
if groups[0] in ["BGCStep", "MatCopy", "MatScale", "MatAXPY", "MatMult"]:
data.append(datamatch.groups())
if groups[0] in ["TimeStepPhi"]:
total = float(groups[1])
# return values
return total, data
#
# create_profile_figure
#
def create_profile_figure(modeldir):
# debug
print "create profile figure ..."
# read in profile data
(total, data) = read_profile_data("%s/work/profile.%s.out" % (modeldir, modeldir))
# print total, data
# sort
order = ["BGCStep", "MatCopy", "MatScale", "MatAXPY", "MatMult"]
def new_order(t1, t2):
return order.index(t1[0]) - order.index(t2[0])
data = sorted(data, cmp = new_order)
# print data
# sum
sum = 0.0
for tuple in data:
sum = sum + float(tuple[1])
# print sum
# split lists, add other
dataname = []
datatime = []
for tuple in data:
dataname.append(tuple[0])
datatime.append(float(tuple[1]))
dataname.append('Other')
datatime.append(total-sum)
# print dataname, datatime
# plot
fig = plt.figure(1)
ax = fig.add_subplot(111, aspect = "equal")
colors = plt.cm.bone(np.linspace(0.2, 1, 6))
patches, texts, autotexts = ax.pie(datatime, labels = dataname, autopct = "%1.1f\,\%%", colors = colors)
for text in autotexts:
text.set_bbox(dict(edgecolor = "k", facecolor = "w"))
# save
plt.savefig("figures/profile.%s.pdf" % modeldir, bbox_inches = "tight")
#
# main
#
if __name__ == "__main__":
# no arguments?
if len(sys.argv) == 1:
# print usage and exit with code 1
print("usage: ./create-figure.py [MODELNAME...]")
sys.exit(1)
# model directory does not exist?
modeldir = sys.argv[1]
if not (os.path.exists(modeldir) and os.path.isdir(modeldir)):
# print error message and exit with code 2
print("### ERROR ### '%s' does not exist or is no directory." % modeldir)
sys.exit(2)
# strip trailing slash if any
modeldir = os.path.normpath(modeldir)
# debug
print("using %s model" % modeldir)
# create profile plot
create_profile_figure(modeldir)
<file_sep>#!/usr/bin/env python -W ignore
import os
import re
import sys
import numpy as np
import matplotlib
matplotlib.rc("font",**{"family":"sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex=True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
#
# figure_error
#
def figure_error(message):
print "#"
print "# ERROR:", message
print "#"
print "# Quitting ..."
sys.exit(0)
#
# figure_read_nesh_fe_data
#
def figure_read_nesh_fe_data():
# number of tests
# number of runs per test
# number of timed model years per run
ntest = 10
nrun = 16*16
nyear = 3
# create array
data = np.empty(shape=(nrun*nyear, ntest), dtype=float)
# read nesh-fe data
print "# Reading nesh-fe files ..."
for itest in range(0, ntest):
filename = "work/metos3d.nesh-fe.out.MITgcm-PO4-DOP-" + str(itest) + ".txt"
print "# ", filename
# read, parse
f = open(filename, "r")
# data1
fiter = 0
for line in f:
matches = re.search(r"^\s+(\d+.\d+)s (\d+) Spinup Function norm (\d+.\d+e[+-]\d+)", line)
if matches:
# print line,
[time, iter, norm] = matches.groups()
data[fiter, itest] = time
fiter = fiter + 1
f.close()
if not fiter == nrun*nyear:
figure_error("Mismatch: fiter = " + str(fiter) + ", nrun * nyear = " + str(nrun*nyear) )
# post process
mindata = np.empty(shape=(nrun), dtype=float)
for irun in range(0, nrun):
mindata[irun] = np.amin(data[irun*nyear:(irun+1)*nyear, :])
# seq
data = np.empty(shape=(nyear), dtype=float)
filename = "work/metos3d.nesh-fe.out.MITgcm-PO4-DOP-seq.txt"
f = open(filename, "r")
dataiter = 0
print "# ", filename
for line in f:
matches = re.search(r"^\s+(\d+.\d+)s (\d+) Spinup Function norm (\d+.\d+e[+-]\d+)", line)
if matches:
[time, iter, norm] = matches.groups()
data[dataiter] = time
dataiter = dataiter + 1
f.close()
# post process
minseqdata = np.amin(data)
# set t1
mindata[0] = np.minimum(mindata[0], minseqdata)
# return data
return mindata
#
# figure_read_spk_data
#
def figure_read_spk_data():
# debug
print("Reading TMM data ...")
# read, parse
f = open("work/spkwall.out", "r")
# go through lines
nrun = 5
irun = 1
mintime = 1.e+300
spkdata = []
for line in f:
matches = re.search(r"^Wall clock time:\s+(\d+.\d+)", line)
if matches:
time = float(matches.groups()[0])
# print irun, irun % nrun, mintime, time
mintime = np.minimum(mintime, time)
if irun % nrun == 0:
# print "append"
spkdata.append(mintime)
irun = 1
mintime = 1.e+300
continue
irun = irun + 1
# close
f.close()
# return data
return spkdata
#
# figure_create_plot_speedup
#
def figure_create_plot_speedup(nesh_fe_data, spk_data, load_data):
# create figure
print "# Creating speedup figure ..."
# create plot
plt.figure(1)
# set range
nmax = 260
xrange = np.arange(1, nmax+1)
# ticks
plt.xticks(np.arange(0, nmax+1, 20), np.arange(0, nmax+1, 20))
plt.yticks(np.arange(0, nmax+1, 20), np.arange(0, nmax+1, 20))
# axis
plt.axis([0, nmax, 0, nmax])
# grid
plt.grid(True, which="major", axis="both", color="0.25", linestyle=":")
# axis title
xlab = plt.xlabel("Number of processes", labelpad=10)
ylab = plt.ylabel("Speedup factor", labelpad=10)
# ideal speedup, load balance
p1, = plt.plot(xrange, xrange, "--", lw=1, color="0.0")
p2, = plt.plot(xrange, xrange * load_data, "-", lw=1, color="0.0")
# compute and plot speedup
nesh_fe_data = nesh_fe_data[0] / nesh_fe_data
spk_data = spk_data[0] / spk_data
p3, = plt.plot(xrange[0:256], nesh_fe_data, "-", lw=1, color="0.5")
p4, = plt.plot(xrange[0:192], spk_data, "-", lw=1, color="0.7")
# legend
leg1 = r"Ideal"
leg2 = r"Theoretical"
leg3 = r"Metos3D (Intel$^{\mbox{\textregistered}}$ Sandy Bridge EP)"
leg4 = r"TMM (Intel$^{\mbox{\textregistered}}$ Sandy Bridge EP)"
plt.legend([p1,p2,p3,p4],[leg1,leg2,leg3,leg4], loc=2, numpoints=1, fontsize = 12.0)
# save
plt.figure(1)
plt.savefig("figures/speedup.pdf", bbox_inches="tight")
#
# figure_create_plot_efficiency
#
def figure_create_plot_efficiency(nesh_fe_data, spk_data, load_data):
# create figure
print "# Creating efficiency figure ..."
# create plot
plt.figure(2)
# range
nmax = 260
neffmax = 140
xrange = np.arange(1, nmax+1)
# axis
plt.axis([0, nmax, 0, neffmax])
# ticks
plt.xticks(np.arange(0, nmax+1, 20), np.arange(0, nmax+1, 20))
plt.yticks(np.arange(0, neffmax+1, 10), np.arange(0, neffmax+1, 10))
# grid
plt.grid(True, which="major", axis="both", color="0.25", linestyle=":")
# axis title
xlab = plt.xlabel("Number of processes", labelpad=10)
ylab = plt.ylabel(r"Efficiency [\%]", labelpad=10)
# ideal and theoretical efficiency
p1, = plt.plot(xrange, np.repeat(100.0, nmax), "--", lw=1, color="0.0")
p2, = plt.plot(xrange, load_data * 100.0, "-", lw=1, color="0.0")
# compute and plot efficiency
nesh_fe_data = 100.0 * nesh_fe_data[0] / nesh_fe_data / xrange[0:256]
spk_data = 100.0 * spk_data[0] / spk_data / xrange[0:192]
# plot
p3, = plt.plot(xrange[0:256], nesh_fe_data, "-", lw=1, color="0.5")
p4, = plt.plot(xrange[0:192], spk_data, "-", lw=1, color="0.7")
# save
plt.figure(2)
plt.savefig("figures/efficiency.pdf", bbox_inches="tight")
#
# figure_compute_load
#
def figure_compute_load(m3dprefix):
print "# Computing load balancing ..."
import numpy
# read profile data
# read starts
filename = "%s/data/data/TMM/2.8/Geometry/gStartIndices.bin" % m3dprefix
print "#", filename
f = open(filename, "rb")
nprof = numpy.fromfile(f, dtype=">i4", count=1)
starts = numpy.fromfile(f, dtype=">i4", count=nprof)
f.close()
# read ends
filename = "%s/data/data/TMM/2.8/Geometry/gEndIndices.bin" % m3dprefix
print "#", filename
f = open(filename, "rb")
nprof = numpy.fromfile(f, dtype=">i4", count=1)
ends = numpy.fromfile(f, dtype=">i4", count=nprof)
f.close()
# compute lengths
lengths = ends-starts+1
veclength = numpy.sum(lengths)
# compute theoretical load balancing
nprocs = 260
theory = numpy.zeros(shape=(nprocs), dtype=float)
# prepare index computation
idxwork = (starts - 1 + 0.5 * lengths)/veclength
# compute load for all procs from 1 to nprocs
for iproc in range(1, nprocs+1):
# optimal vectorlength
optlength = veclength/float(iproc)
# storage for all lengths
profbucket = numpy.zeros(shape=(iproc), dtype=">i4")
# indices for iproc
idx = numpy.floor(idxwork*iproc)
# compute balanced load for iproc
for iprof in range(0, nprof):
intidx = int(idx[iprof])
profbucket[intidx] = profbucket[intidx] + lengths[iprof]
# take worst case
theory[iproc-1] = veclength / float(numpy.amax(profbucket)*iproc)
return theory
#
# figure_main
#
if __name__ == "__main__":
# read data
nesh_fe_data = figure_read_nesh_fe_data()
# print nesh_fe_data
spk_data = figure_read_spk_data()
# print spk_data
# set prefix for data
m3dprefix = os.path.expanduser('~/.metos3d')
# compute load balancing
load_data = figure_compute_load(m3dprefix)
# create figures
figure_create_plot_speedup(nesh_fe_data, spk_data, load_data)
figure_create_plot_efficiency(nesh_fe_data, spk_data, load_data)
<file_sep>#!/usr/bin/env python
#
# read_snes_ksp_data
#
def read_snes_ksp_data(file):
import re
# max readin
nmax = 10000
# read file, parse and store
kspiter = 0
ksplist = []
snesidx = []
sneslist = []
f = open(file, "r")
for line in f:
# SNES
snesmatch = re.search(r"^\s+(\d+) SNES Function norm (\d+.\d+e[+-]\d+)", line)
if snesmatch:
snesidx.append(kspiter)
sneslist.append(snesmatch.groups()[1])
# KSP
kspmatch = re.search(r"^\s+(\d+) KSP Residual norm (\d+.\d+e[+-]\d+)", line)
if kspmatch:
ksplist.append(kspmatch.groups()[1])
kspiter = kspiter + 1
if kspiter >= nmax:
break
f.close()
return snesidx, sneslist, kspiter, ksplist
#
# read_data
#
def read_data():
import numpy as np
print "# Reading data ..."
# read all samples
data = []
nsample = 100
for isample in range(0, nsample):
filename = "../work/metos3d.nesh-fe.sample.%02d.out.txt" % isample
# print filename
sampledata = read_snes_ksp_data(filename)
# number of Newton steps, number of model years
data.append((len(sampledata[0]), sampledata[2]))
return np.array(data)
#
# create_figures
#
def create_figures(data):
import numpy as np
print "# Creating figure ..."
# prepare matplotlib
import matplotlib
matplotlib.rc("font",**{"family":"sans-serif"})
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rc("text", usetex=True)
matplotlib.use("PDF")
import matplotlib.pyplot as plt
# KSP
plt.figure(1)
n, bins, patches = plt.hist(data[:, 1], bins = 50, fc = "k", ec = "w")
plt.xticks(range(300, 1001, 100), range(300, 1001, 100))
plt.yticks(range(0, 17, 2), range(0, 17, 2))
plt.xlabel("Model years")
plt.ylabel("Occurrence")
plt.savefig("parameterrange-ksp", bbox_inches = "tight")
# SNES
plt.figure(2)
n, bins, patches = plt.hist(data[:, 0], bins = 50, fc = "k", ec = "w")
plt.xticks(range(5, 46, 5), range(5, 46, 5))
plt.yticks(range(0, 15, 2), range(0, 15, 2))
plt.xlabel("Newton steps")
plt.ylabel("Occurrence")
plt.savefig("parameterrange-snes", bbox_inches = "tight")
#
# main
#
if __name__ == "__main__":
data = read_data()
create_figures(data)
<file_sep>#!/bin/env python
header = '''#!/bin/bash
#PBS -T intmpi
#PBS -b 8
#PBS -l cpunum_job=24
#PBS -l elapstim_req=24:00:00
#PBS -l memsz_job=10gb
#PBS -N speedtest
#PBS -o speedtest.out
#PBS -e speedtest.out
#PBS -q clfo2
cd $PBS_O_WORKDIR
. ../../petsc/petsc-3.4.5.env
'''
mpicmd = '''mpirun $NQSII_MPIOPTS -n %d ./tmmmitgchemdic -numtracers 6 -i dicini.petsc,alkini.petsc,po4ini.petsc,dopini.petsc,o2ini.petsc,feini.petsc \
-me Ae -mi Ai -t0 0.0 -iter0 0 -deltat_clock 0.0013888888888889 -max_steps 720 -write_steps 7200000 -o dic.petsc,alk.petsc,po4.petsc,dop.petsc,o2.petsc,fe.petsc \
-external_forcing -use_profiles -biogeochem_deltat 43200.0 -periodic_matrix -matrix_cycle_period 1.0 -matrix_cycle_step 0.0833333333333333 \
-periodic_biogeochem_forcing -periodic_biogeochem_cycle_period 1.0 -periodic_biogeochem_cycle_step 0.0833333333333333 '''
print header
for i in range(0,192):
for j in (1,2,3,4,5):
print mpicmd % (i+1)
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 1
#PBS -l cpunum_job=24
#PBS -l elapstim_req=01:00:00
#PBS -l memsz_job=10gb
#PBS -N profile.NPZ-DOP
#PBS -o work/profile.NPZ-DOP.out
#PBS -e work/profile.NPZ-DOP.out
#PBS -q clfo2
#
cd $PBS_O_WORKDIR
#
. ../petsc-3.3-p4.env
#
mpirun $NQSII_MPIOPTS -np 1 ./metos3d-simpack-NPZ-DOP.exe option/profile.NPZ-DOP.option -log_summary
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 1
#PBS -l cpunum_job=24
#PBS -l elapstim_req=01:00:00
#PBS -l memsz_job=10gb
#PBS -N profile.NP-DOP
#PBS -o work/profile.NP-DOP.out
#PBS -e work/profile.NP-DOP.out
#PBS -q clfo2
#
cd $PBS_O_WORKDIR
#
. ../petsc-3.3-p4.env
#
mpirun $NQSII_MPIOPTS -np 1 ./metos3d-simpack-NP-DOP.exe option/profile.NP-DOP.option -log_summary
<file_sep># 2016-GMD-Metos3D
### Setup, experiments and results for the corresponding GMD paper
http://www.geosci-model-dev.net/9/3729/2016/
-
### [convergence-control/](convergence-control/)
Newton solver convergence control experiments
### [parameter-samples/](parameter-samples/)
Newton solver parameter samples experiments
### [profile/](profile/)
Profiling experiments
### [solver/](solver/)
Spin-up and Newton-Krylov solver experiments
### [speed-up/](speed-up/)
Speed-up experiments
<file_sep>#!/bin/bash
#PBS -T intmpi
#PBS -b 4
#PBS -l cpunum_job=16
#PBS -l elapstim_req=12:00:00
#PBS -l memsz_job=10gb
#PBS -N spinup.N-DOP
#PBS -o work/spinup.N-DOP.out
#PBS -e work/spinup.N-DOP.out
#PBS -q clfocean
#
module load intel intelmpi
module load petsc-3.3-p4-intel
#
cd $PBS_O_WORKDIR
#
mpirun $NQSII_MPIOPTS -np 64 ./metos3d-simpack-N-DOP.exe option/spinup.N-DOP.option
| 64d1f64849b9522ec452c4e3977eb3af6c2cee37 | [
"Markdown",
"Python",
"Shell"
] | 24 | Python | metos3d/2016-GMD-Metos3D | 5fa1ed51d83d691d4a08d025880d06b8964e9634 | 82c7f87b5f37aff11b8cc1a8c398a5a24db6e054 |
refs/heads/master | <repo_name>DAPountain/machine-learning<file_sep>/Assignment.Rmd
---
title: "Assignment Writeup: Human Activity Recognition"
author: "<NAME>"
date: "August 14, 2016"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,message=FALSE,warning=FALSE)
```
## Introduction
The purpose of this assignment was to predict activity given sensor data. In this case we are predicting correct vs incorrect execution of an excercise. The data for this assignment is taken from the **Qualitative Activity Recognition of Weight Lifting Exercises** (Velloso et al 2013)
## The Code
### Load the libraries used
The caret package was used for this assignment. The doParallel package is used to take advantage of the multiple cores on the machine where code is executed.
```{r libraries}
library(caret)
library(doParallel)
#set the seed
set.seed(8675)
```
### Configure for Parallel Processing
```{r ConfigureParallel}
cluster<- makeCluster(detectCores())
registerDoParallel(cluster)
```
### Load the data ###
For the purpose of this assigment, data was downloaded from links provided on assignment description:
<https://d396qusza40orc.cloudfront.net/predmachlearn/pml-training.csv>
```{r LoadData}
pmlData <- read.csv("pml-training.csv",stringsAsFactors=TRUE, na.strings=c("NA"))
```
### Feature Selection ###
After analyzing the activity dataset, fields with low/no predictability were identified and removed.
Note: normally, we might consider replacing NA with column mean, but after experimenation, we were still able
to create a highly accurate predictive model by simply excluding columns containing NA values.
```{r FeatureSelection}
#Remove first 5 columns (no predictability from these: name, timestamp, etc.)
pmlData <- pmlData[,-(1:5)]
#Remove columns with low variability
pmlData <- pmlData[,-nearZeroVar(pmlData)]
#Remove columns with NA content
pmlData <- pmlData[,colSums(is.na(pmlData)) == 0]
```
### Partition the provided training set###
The training data provided was split into training and testing data sets (70/30 split).
```{r partition}
inTrain <- createDataPartition(pmlData$classe, p=0.7, list=FALSE)
trainData <- pmlData[inTrain,]
testData <- pmlData[-inTrain,]
```
### Train the predictive model###
A random forest model using 5-fold cross validation was trained using the training data.
The *classe* variable was predicted using all remaining features (post-selection) as predictors.
```{r modelTrain}
# using Random Forest model, using cross-validation with 5 folds
trainControl <-trainControl(method = "cv", number = 5, allowParallel = TRUE)
rfModel <- train(classe ~. , data=trainData, method="rf" , preProcess=c("center","scale"), trControl=trainControl )
```
### Test accuracy of model ###
We calcultated both in-sample and out-of-sample accuracy statistics.
In sample:
```{r predictInSample}
# predict the out of sample accuracy using our held out test set
rfTrain <- predict(rfModel, trainData)
confusionMatrix(rfTrain, trainData$classe)
```
Out of sample:
```{r predictOutOfSample}
# predict the out of sample accuracy using our held out test set
rfTesting <- predict(rfModel, testData)
confusionMatrix(rfTesting, testData$classe)
```
### Predict on the supplied test set ###
```{r predictHoldout}
holdout<-read.csv("pml-testing.csv", stringsAsFactors=TRUE )
holdout$classe <- predict(rfModel, holdout)
matrix(holdout$classe)
```
## Summary
Above, we see that the model is very successful at predicting the activity, with the following error statistics:
**In sample**: 100% accuracy (0% error )
**Out of sample**: 99.88% accuracy (0.22% error).
**"Holdout" (pml-testing.csv data)**: 100% accuracy (based on quiz submission results)
## References
<NAME>.; <NAME>.; <NAME>.; <NAME>.; <NAME>. Qualitative Activity Recognition of Weight Lifting Exercises. Proceedings of 4th International Conference in Cooperation with SIGCHI (Augmented Human '13) . Stuttgart, Germany: ACM SIGCHI, 2013.
<file_sep>/Assignment.R
setwd("~/Documents/Coursera/Data Science/Machine Learning/Week 4/Assignment")
set.seed(8675)
ggplot2
library(caret)
library(doParallel)
#setup parallel processing
cluster<- makeCluster(detectCores())
registerDoParallel(cluster)
pmlData <- read.csv("pml-training.csv",stringsAsFactors=TRUE, na.strings=c("NA"))
#### FEATURE SELECTION ####
#Remove first 5 columns (no predictability from these: name, timestamp, etc.)
pmlData <- pmlData[,-(1:5)]
#Remove columns with low variability
pmlData <- pmlData[,-nearZeroVar(pmlData)]
#Remove columns with NA content
pmlData <- pmlData[,colSums(is.na(pmlData)) == 0]
#### CREATE TRAIN AND TEST SETS ####
inTrain <- createDataPartition(pmlData$classe, p=0.7, list=FALSE)
trainData <- pmlData[inTrain,]
testData <- pmlData[-inTrain,]
#### TRAIN THE MODEL ####
# using Random Forest model using 5 fold cross-validation
trainControl <-trainControl(method = "cv", number = 5, allowParallel = TRUE)
rfModel <- train(classe ~. , data=trainData, method="rf" , preProcess=c("center","scale"), trControl=trainControl )
#### PREDICT RESERVED TEST SET USING TRAINED MODEL ####
rfTesting <- predict(rfModel, testData)
confusionMatrix(rfTesting, testData$classe)
#### PREDICT HELDOUT DATA SET (Quiz Data) ####
holdout<-read.csv("pml-testing.csv", stringsAsFactors=TRUE )
holdout$classe <- predict(rfModel, holdout)
matrix(holdout$classe)
| d73fbf692f1deda590b61ce7ac04e5763c31f313 | [
"R",
"RMarkdown"
] | 2 | RMarkdown | DAPountain/machine-learning | 46a273b915e03edc6e8198968840d148f037ab5b | 0f3b3fdcd6e3e005b8bb06b4a9002d8ccd19e6ca |
refs/heads/master | <repo_name>gilles1986/tdd-kurs<file_sep>/Gruntfile.js
module.exports = function(grunt) {
'use strict';
var npmTasksArray = [
'grunt-contrib-clean',
'grunt-contrib-watch',
'grunt-contrib-concat',
'grunt-contrib-copy',
'grunt-karma',
'grunt-contrib-connect'
];
// DON'T TOUCH THE CONFIG BELOW IF YOU DON'T KNOW WHAT YOU DO
for(var i = 0; i < npmTasksArray.length; i++) {
grunt.loadNpmTasks(npmTasksArray[i]);
}
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
scripts: [
'web/includes/js/*'
],
project: [
'bower_components',
'reports'
]
},
concat: {
scripts: {
src: [
'assets/javascript/dev/_tmp/dev.js',
'assets/javascript/scripts/*.js'
],
dest: 'assets/javascript/_work/scripts.js'
},
libs: {
src: [
"assets/javascript/lib/base/jquery.min.js",
"assets/javascript/lib/base/bootstrap.min.js",
"assets/javascript/lib/base/enquire.min.js",
"assets/javascript/lib/base/bowser.min.js",
"assets/javascript/lib/base/is.min.js",
"assets/javascript/lib/base/AbstractComponent.js",
"assets/javascript/lib/base/AbstractResponsiveComponent.js",
"assets/javascript/lib/base/bootstrapMediaquerys.js",
"assets/javascript/lib/*.js"
],
dest: 'assets/javascript/_work/libs.js'
}
},
copy: {
jstoweb: {
files: [
// includes files within path and its sub-directories
{
expand: true,
src: ['js/src/**.js'],
dest: 'web/includes/js/',
filter: 'isFile',
flatten: true
},
{
expand: true,
src: ['js/lib/**/*.js'],
dest: 'web/includes/js/lib',
filter: 'isFile',
flatten: true
}
]
}
},
watch: {
scripts: {
files: [
'js/src/**/*.js'
],
tasks: ['js']
},
libs: {
files: [
'js/libs/**/*.js'
],
tasks: ['js']
},
options: {
debounceDelay: 5000,
atBegin: true,
"livereload" : false
}
},
karma: {
unit: {
configFile: 'karmaconfig.js',
singleRun: true,
browsers: ["PhantomJS"]
},
debug: {
configFile: 'karmaconfig.js',
singleRun: false,
browsers: ["Chrome"],
preprocessors: {'js/test/html_fixtures/*.html': []}
}
},
connect: {
server: {
options: {
port: 9000,
base: 'web',
open: true,
keepalive: true
}
}
}
});
// Eigene Tasks
grunt.registerTask('default', [ "js"]);
grunt.registerTask('project-clean', 'clean:project');
grunt.registerTask('js', ["runTests", "clean", "copy"]);
grunt.registerTask('runTests', ['karma:unit']);
grunt.registerTask("html-server", "connect:server");
grunt.registerTask('watchJS', ['watch']);
};<file_sep>/README.md
# TDD Übung
## Aufgabe
Die Aufgabe zum TDD Kurs kann [hier](https://docs.google.com/document/d/1KWR9JhnjsoQ8_KU2lGmVEwCeiRl9eZ95DoI-XXuFLkY/edit?usp=sharing) gefunden werden:
## Technische Anforderungen
Folgende Programme müssen installiert sein und eventuell in der Path Variable sein:
- Node JS
- NPM
- Grunt (*npm install grunt -g* und *npm install grunt-cli -g*)
- Phantom JS (*npm install -g phantomjs*)
## Installation
Im Root Folder einmal *npm update* durchführen. Fertig!
## Wichtigste Grunt Tasks
- html-server : Lässt auf Port 9000 einen Webserver laufen, welcher als Root den web-Ordner des Projektes hat
- js : Kopiert das geschriebene JS in den Web Ordner
- runTests : Unit Tests ausführen lassen
- watchJS : Sobald eine Datei im JS Ordner geändert wird, wird der js-Task ausgeführt
Ansonsten bleibt nur noch eins zu sagen:

| 6029042a669557d6ed1da24695482398c9959612 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | gilles1986/tdd-kurs | a72e84d0d31136f74f6031fbe94bc55d5ae1067b | d6cec0603c3362840eab965e5a1728b47c9886f5 |
refs/heads/master | <repo_name>ahraz2016/tinyurl<file_sep>/HelloWorld.py
print "helloworld"
print "yogi hahdh ji"
print "123 456 789"
print "yogi ji hello ji"
| b19878f2ddb5733180928487bbd417831d028529 | [
"Python"
] | 1 | Python | ahraz2016/tinyurl | 7fa30aeec611008b8cfda5b9f08af1c587918e3d | 345fd8d5897788062fc5d99d759992a2f7d954cc |
refs/heads/master | <repo_name>raoshruti16/RestAssured-API<file_sep>/src/test/java/Reqres/ListUser.java
package Reqres;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.sun.xml.xsom.impl.scd.Iterators.Map;
import static io.restassured.RestAssured.*;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
import java.util.HashMap;
import static io.restassured.matcher.RestAssuredMatchers.*;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
public class ListUser {
@Given("^the api is up and running$")
public void the_api_is_up_and_running() throws Throwable{
System.out.println(GetHelper.getUser());
System.out.println(GetHelper.getUserPage2());
}
@And("^I count the number of users$")
public void I_count_the_number_of_users() throws Throwable{
JSONObject response1 = ResponseBean.getResponse();
int count1 = response1.getJSONArray("data").length();
System.out.println("Users in page 1 are " + count1);
JSONObject response2 = ResponseBean.getResponsePg2();
int count2 = response2.getJSONArray("data").length();
System.out.println("Users in page 2 are " + count2);
int userCount = response1.getInt("total");
Assert.assertEquals((count1+count2), userCount);
}
@Then("^I verify the number of users$")
public void I_verify_the_number_of_users() throws Throwable{
JSONObject response = ResponseBean.getResponse();
int userCount = response.getInt("total");
Assert.assertEquals(userCount, 12);
}
}
| 51978931d8a333c5946a949d6d67ceabda8d69fe | [
"Java"
] | 1 | Java | raoshruti16/RestAssured-API | 877e51b9aca8f30c639154fe61c046b49116b8ea | 25025579dc1ea86135c6c1838c62723fe63980ee |
refs/heads/master | <repo_name>tmnguyen8/open-weather-api<file_sep>/weather.js
var inputCity = "";
var weatherAPI = "";
function displayWeather () {
$.getJSON(`https://api.openweathermap.org/data/2.5/weather?q=${inputCity},us&units=imperial&appid=a14b5cd39920b60f089d913e4253e5f5`,
function(data){
console.log(data);
let icon = `https://api.openweathermap.org/img/w/${data.weather[0].icon}.png`;
$(".icon").attr("src", icon);
$(".city").html(data.name);
$(".description").html(data.weather[0].description);
$(".temp").html(`${Math.floor(data.main.temp)} °F`)
}
);
};
// when submit button is pressed
$("#submit").click(function() {
inputCity = $("#cityInput").val();
weatherAPI = `https://api.openweathermap.org/data/2.5/weather?q=${inputCity},us&units=imperial&appid=a14b5cd39920b60f089d913e4253e5f5`;
displayWeather();
});
// when the enter key is pressed
$('#cityInput').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
inputCity = $("#cityInput").val();
weatherAPI = `https://api.openweathermap.org/data/2.5/weather?q=${inputCity},us&units=imperial&appid=a14b5cd39920b60f089d913e4253e5f5`;
displayWeather();
}
});
| 1880ff82331e2a1c92df3517c3bf2dd8ccfc8f24 | [
"JavaScript"
] | 1 | JavaScript | tmnguyen8/open-weather-api | 325029cde8a8cafde12ab44b3ceaaf143c5de05a | 140bdf6729724fcc1c6e926c3cbdec014fc359e7 |
refs/heads/main | <file_sep>1. Create an object called books and array myLibrary.
books object contains the following items: title, author, pages, read_status.
2. Create a button 'Add Books'. When the user presses this button, a pop-up form appears.
This form has input fields for following parameters: title, author, pages, read_status.
When 'the pop up form is submitted, a new instance of books object is created and the data from pop up form is updated in the new object instance.
This new object is then pushed to myLibrary array.
3. Create a function display. This function is used to display all object instances in the myLibrary array.
Learnings:
1. How to create a pop up form.
2. How to get the data from pop up form into javascript.
3.Usage of 'this' in DOM manipulation.
4. Usage of objects and instantiation.
5.How to add local storage
---------------------------------------------------------------------
Rework the entire javascript code to make it modular.
Try to follow DRY (Dont Repeat Your code).
<file_sep>//Class to create book
const book = class book{
constructor(title, author, pages, status){
this.title = title;
this.author = author;
this.pages = pages;
this.status = status;
}
get getTitle(){
return this.title;
}
get getAuthor(){
return this.author;
}
get getPages(){
return this.pages;
}
get getStatus(){
return this.status;
}
set setStatus(str){
this.status = str;
}
}
//This module contains the methods for modifying the list of books in the library
const myLibrary = (()=>{
let bookList = [];
this.mainHeader = document.querySelector(".main-header").getElementsByTagName('*');
this.input = Array.from(mainHeader).filter((item=>item.tagName == 'INPUT'));
this.buttons = Array.from(mainHeader).filter((item=>item.tagName == 'BUTTON'));
function addBook(obj){
let nBook = new book();
console.log(obj);
for(const prop in nBook){
if(prop == 'status'){
//console.log(obj.status || input.filter(item=>item.name=='readStatus' && item.checked == true)[0].value);
nBook[prop] = obj ? obj[prop] : input.filter(item=>item.name=='readStatus' && item.checked == true)[0].value; //if correct obj is passed then take that as input. Otherwise, use html element
//nBook[prop] = obj[prop] || statusArray.filter(item => item.checked==true)[0].value;
}
else{
nBook[prop] = obj ? obj[prop] : input.filter(item=>item.id==prop)[0].value; //if correct obj is passed then take that as input. Otherwise, use html element
//console.log(input.filter(item=>item.id==prop)[0].value)
}
};
bookList.push(nBook);
console.log(bookList);
displayControl.render(bookList);
}
function removeBook(event){
bookList.splice(Number(this.id.replace(/^\D+/g,'')),1);
displayControl.render(bookList);
}
function updateBook(event){
console.log(this.id);
let bookIndex = Number(this.id.replace(/^\D+/g,'')); //get index of the book from id
if(bookList[bookIndex].getStatus === 'read'){
bookList[bookIndex].setStatus = 'unread';
}
else{
bookList[bookIndex].setStatus = 'read';
}
displayControl.render(bookList);
}
function init(){
addBook({title:'Title', author:'Author',pages:'Pages',status:'Status'}); //This is added just to create a header
buttons.forEach(element=>{ //add event listeners to all static html buttons
element.addEventListener('click',function(e){
console.log(`${element.id} btn clicked`);
Array.from(mainHeader).filter(item=>item.id == 'myForm')[0].style.display = (element.id == 'add'?'block':'none');
if(this.id == 'submit')
addBook();
});
});
}
return{init, removeBook, updateBook}
})();
const displayControl = (()=>{
const headArray = ['No.', 'title', 'author', 'pages', 'Status','readStatus','delete'];
const mainContainer = document.querySelector('.main-container');
const handler = { //create mapping of eventListeners corresponding to each class
['remove-btn']: myLibrary.removeBook,
['read-btn']: myLibrary.updateBook,
}
function addBlock(obj){
let handle = document.createElement(obj['type']);
handle.id = obj['id'];
if(obj['class'])
handle.classList.add(obj['class']);
handle.textContent = obj['value'];
console.log(handle);
mainContainer.appendChild(handle);
if(obj['type'] == 'button'){
handle.addEventListener('click',handler[obj['class']]);
}
}
function clear(){
while(mainContainer.firstChild)
mainContainer.removeChild(mainContainer.firstChild);
}
function render(bookArray){
clear();
bookArray.forEach(item=>{ //Iterate through each book
console.log(item);
addBlock({type:'div',id:`serial${bookArray.indexOf(item)}`,class:bookArray.indexOf(item)==0 ? 'head':(item.getStatus == 'read'? 'read':'unread'),value:(bookArray.indexOf(item)==0 ? 'Sr.No' : `${bookArray.indexOf(item)}`)});
addBlock({type:'div',id:`title${bookArray.indexOf(item)}`,class:bookArray.indexOf(item)==0 ? 'head':(item.getStatus == 'read'? 'read':'unread'),value:`${item.getTitle}`});
addBlock({type:'div',id:`author${bookArray.indexOf(item)}`,class:bookArray.indexOf(item)==0 ? 'head':(item.getStatus == 'read'? 'read':'unread'),value:`${item.getAuthor}`});
addBlock({type:'div',id:`pages${bookArray.indexOf(item)}`,class:bookArray.indexOf(item)==0 ? 'head':(item.getStatus == 'read'? 'read':'unread'),value:`${item.getPages}`});
addBlock({type:'div',id:`status${bookArray.indexOf(item)}`,class:bookArray.indexOf(item)==0 ? 'head':(item.getStatus == 'read'? 'read':'unread'),value:`${item.getStatus}`});
if(bookArray.indexOf(item)>0){
addBlock({type:'button',id:`readBtn${bookArray.indexOf(item)}`,class:'read-btn',value:'Read/Unread'});
addBlock({type:'button',id:`deleteBtn${bookArray.indexOf(item)}`,class:'remove-btn',value:'Delete'});
}
else{ //empty div added to maintain symmetry
addBlock({type:'div',id:`readBtn${bookArray.indexOf(item)}`,class:'',value:''});
addBlock({type:'div',id:`readBtn${bookArray.indexOf(item)}`,class:'',value:''});
}
});
}
return {render}
})();
myLibrary.init();
<file_sep># library_app
Demo: https://faisal-523.github.io/library_app/
The Odin Project: A simple library App in javascript
| 8cbf7016ffb1b727d75fadc03c2c2b232dbe9427 | [
"JavaScript",
"Text",
"Markdown"
] | 3 | Text | Faisal-523/library_app | 86f648bd713ca8b9503621d5388473006f7cac8b | c8f8ea087b8c3681c289c648ba3618e19c99f80c |
refs/heads/master | <file_sep>const css = require('../style/style.sass');
<file_sep># fulfil-ui
CSS library for Fulfil's design language.
## Setup
* Clone the Repo.
* Run ```npm install```.
## Usage
* Run ```npm run start``` to compile and run the server.
* View Documentation on localhost http://localhost:8080/ or mentioned otherwise.
* Run ```npm run build``` to compile only in production mode.
* All the compiled style can be found in /dist/fulfil-ui.js
| 24e6fcd57aea8b3de56f946d10b89ccbc195c475 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | arwwwind/Personal | 3a43a20e4c68b4c4025f9eace50b47b230a497a9 | 7661cc1561d8699d699eb429236ea3646ea8f44d |
refs/heads/master | <file_sep>package com.jun.dialogqueue.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.jun.dialogqueue.R;
import com.jun.dialogqueue.util.DialogQueue2;
import com.jun.dialogqueue.util.DialogQueue2.Element;
import com.jun.dialogqueue.util.DialogQueueManager;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_ACTIVITY;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_ADVISE_UPGRADE;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_COMPLETE_DATA;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_CUSTOMER;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_LIVE;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_MEETING;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_ME_FRAGMENT_GUIDE1;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_ME_FRAGMENT_GUIDE2;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_REMIND_AUTH;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_SELECT_DOCTOR_ROLE;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_UNION_INVITE;
import static com.jun.dialogqueue.util.DialogQueueManager.TYPE_UNREAD_CARDS;
public class DialogQueueActivity2 extends AppCompatActivity implements DialogQueue2.DialogQueueChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog_queue);
DialogQueueManager.getInstance().init(new DialogQueue2(this));
getConfig();
getType1();
getType2();
getType3();
getType4();
getType5();
getType6();
getType7();
getType8();
getType9();
getType10();
}
@Override
protected void onDestroy() {
super.onDestroy();
DialogQueueManager.getInstance().release();
}
private void getConfig() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getConfig() finish");
DialogQueueManager.getInstance().config(4, 5000);
DialogQueueManager.getInstance().countDown();
}
}, 0);
}
private void getType1() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "获取角色接口finish");
DialogQueueManager.getInstance().register(TYPE_SELECT_DOCTOR_ROLE, null);
}
}, 0);
}
private void getType2() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType2() finish");
DialogQueueManager.getInstance().register(TYPE_REMIND_AUTH, null);
}
}, 0);
}
private void getType3() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType4() finish");
DialogQueueManager.getInstance().register(TYPE_COMPLETE_DATA, null);
}
}, 0);
}
private void getType4() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType6() finish");
DialogQueueManager.getInstance().register(TYPE_ADVISE_UPGRADE, null);
}
}, 0);
}
private void getType5() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
DialogQueueManager.getInstance().register(TYPE_CUSTOMER, null);
}
}, 0);
}
private void getType6() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType3() finish");
DialogQueueManager.getInstance().register(TYPE_LIVE, null);
}
}, 0);
}
private void getType7() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType5() finish");
DialogQueueManager.getInstance().register(TYPE_ACTIVITY, null);
}
}, 0);
}
private void getType8() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType7() finish");
DialogQueueManager.getInstance().register(TYPE_MEETING, null);
}
}, 0);
}
private void getType9() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType8() finish");
DialogQueueManager.getInstance().register(TYPE_UNION_INVITE, null);
}
}, 0);
}
private void getType10() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.i("iiiiiiiiii", "getType1() finish");
DialogQueueManager.getInstance().register(TYPE_UNREAD_CARDS, null);
}
}, 0);
}
private AlertDialog showDialog(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 设置参数
builder.setTitle(message).setIcon(R.mipmap.ic_launcher)
.setMessage(message)
.setPositiveButton(message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setNegativeButton(message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return alertDialog;
}
@Override
public void onDialogQueueChanged(Element element) {
final int type = element.type;
switch (type) {
case TYPE_UNION_INVITE:
DialogQueueManager.getInstance().showing();
showDialog(String.valueOf(type)).setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
DialogQueueManager.getInstance().register(TYPE_ME_FRAGMENT_GUIDE1, null);
DialogQueueManager.getInstance().dismissAndNext();
}
});
break;
case TYPE_ME_FRAGMENT_GUIDE1:
DialogQueueManager.getInstance().showing();
showDialog(String.valueOf(type)).setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
DialogQueueManager.getInstance().register(TYPE_ME_FRAGMENT_GUIDE2, null);
DialogQueueManager.getInstance().dismissAndNext();
}
});
break;
default:
DialogQueueManager.getInstance().showing();
showDialog(String.valueOf(type)).setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
DialogQueueManager.getInstance().dismissAndNext();
}
});
break;
}
}
// private void blockApp() {
// try {
// DialogQueueManager.getInstance().setHasBlockAppDialog(true);
// Object currentDialog = DialogQueueManager.getInstance().getCurrentDialog();
// if (currentDialog != null) {
// if (currentDialog instanceof Dialog) {
// if (((Dialog) currentDialog).isShowing())
// ((Dialog) currentDialog).dismiss();
// } else if (currentDialog instanceof DialogFragment) {
// if (((DialogFragment) currentDialog).getDialog() != null && ((DialogFragment) currentDialog).getDialog().isShowing())
// ((DialogFragment) currentDialog).dismiss();
// } else if (currentDialog instanceof ForceLookAliveView) {
// ((ForceLookAliveView) currentDialog).dismiss();
// } else if (currentDialog instanceof ActivityAnimDialog) {
// ((ActivityAnimDialog) currentDialog).dismiss();
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// DialogQueueManager.getInstance().setDialogQueue(null);
// }
} | 67ac7d3dff85403c12a5408cf439fc5d33be3759 | [
"Java"
] | 1 | Java | tino1101/DialogQueue | 801077516040c08f1cc8e9a8792413f48e057ba4 | 4be3c182cff414dc9466cfcdb2a6973d4351fd26 |
refs/heads/master | <repo_name>go-audio/riff<file_sep>/chunk_test.go
package riff
import (
"bytes"
"fmt"
"os"
"path/filepath"
"testing"
)
func TestWavNextChunk(t *testing.T) {
path, _ := filepath.Abs("fixtures/sample.wav")
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
c := New(f)
if err := c.ParseHeaders(); err != nil {
t.Fatal(err)
}
// fmt
ch, err := c.NextChunk()
if err != nil {
t.Fatal(err)
}
if ch.ID != FmtID {
t.Fatalf("Expected the next chunk to have an ID of %q but got %q", FmtID, ch.ID)
}
if ch.Size != 16 {
t.Fatalf("Expected the next chunk to have a size of %d but got %d", 16, ch.Size)
}
ch.Done()
//
ch, err = c.NextChunk()
if err != nil {
t.Fatal(err)
}
if ch.ID != DataFormatID {
t.Fatalf("Expected the next chunk to have an ID of %q but got %q", DataFormatID, ch.ID)
}
if ch.Size != 53958 {
t.Fatalf("Expected the next chunk to have a size of %d but got %d", 53958, ch.Size)
}
if int(c.Size) != (ch.Size + 36) {
t.Fatal("Looks like we have some extra data in this wav file?")
}
}
func TestNextChunk(t *testing.T) {
path, _ := filepath.Abs("fixtures/sample.wav")
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
c := New(f)
if err := c.ParseHeaders(); err != nil {
t.Fatal(err)
}
ch, err := c.NextChunk()
if err != nil {
t.Fatal(err)
}
ch.DecodeWavHeader(c)
ch, err = c.NextChunk()
if err != nil {
t.Fatal(err)
}
nextSample := func() []byte {
var s = make([]byte, c.BlockAlign)
if err := ch.ReadLE(s); err != nil {
t.Fatal(err)
}
return s
}
firstSample := nextSample()
if ch.Pos != int(c.BlockAlign) {
t.Fatal("Chunk position wasn't moved as expected")
}
expectedSample := []byte{0, 0}
if bytes.Compare(firstSample, expectedSample) != 0 {
t.Fatalf("First sample doesn't seem right, got %q, expected %q", firstSample, expectedSample)
}
desideredPos := 1541
bytePos := desideredPos * 2
for ch.Pos < bytePos {
nextSample()
}
s := nextSample()
expectedSample = []byte{0xfe, 0xff}
if bytes.Compare(s, expectedSample) != 0 {
t.Fatalf("1542nd sample doesn't seem right, got %q, expected %q", s, expectedSample)
}
}
func ExampleParser_NextChunk() {
// Example showing how to access the sound data
path, _ := filepath.Abs("fixtures/sample.wav")
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
c := New(f)
if err := c.ParseHeaders(); err != nil {
panic(err)
}
var chunk *Chunk
for err == nil {
chunk, err = c.NextChunk()
if err != nil {
panic(err)
}
if chunk.ID == FmtID {
chunk.DecodeWavHeader(c)
} else if chunk.ID == DataFormatID {
break
}
chunk.Done()
}
soundData := chunk
nextSample := func() []byte {
s := make([]byte, c.BlockAlign)
if err := soundData.ReadLE(&s); err != nil {
panic(err)
}
return s
}
// jump to a specific sample since first samples are blank
desideredPos := 1541
bytePos := desideredPos * 2
for i := 0; soundData.Pos < bytePos; i++ {
nextSample()
if i > soundData.Size {
panic(fmt.Errorf("%+v read way too many bytes, we're out of bounds", soundData))
}
}
sample := nextSample()
fmt.Printf("1542nd sample: %#X %#X\n", sample[0], sample[1])
// Output:
// 1542nd sample: 0XFE 0XFF
}
<file_sep>/go.mod
module github.com/go-audio/riff
go 1.12
<file_sep>/riff.go
package riff
import (
"errors"
"io"
"sync"
"time"
)
var (
RiffID = [4]byte{'R', 'I', 'F', 'F'}
FmtID = [4]byte{'f', 'm', 't', ' '}
// To align RIFF chunks to certain boundaries (i.e. 2048bytes for CD-ROMs) the RIFF specification includes a JUNK chunk.
// Its contents are to be skipped when reading. When writing RIFFs, JUNK chunks should not have odd number as Size.
junkID = [4]byte{'J', 'U', 'N', 'K'}
WavFormatID = [4]byte{'W', 'A', 'V', 'E'}
// DataFormatID is the Wave Data Chunk ID, it contains the digital audio sample data which can be decoded using the format
// and compression method specified in the Wave Format Chunk. If the Compression Code is 1 (uncompressed PCM), then the Wave Data contains raw sample values.
DataFormatID = [4]byte{'d', 'a', 't', 'a'}
rmiFormatID = [4]byte{'R', 'M', 'I', 'D'}
aviFormatID = [4]byte{'A', 'V', 'I', ' '}
// ErrFmtNotSupported is a generic error reporting an unknown format.
ErrFmtNotSupported = errors.New("format not supported")
// ErrUnexpectedData is a generic error reporting that the parser encountered unexpected data.
ErrUnexpectedData = errors.New("unexpected data content")
)
// New creates a parser wrapper for a reader.
// Note that the reader doesn't get rewinded as the container is processed.
func New(r io.Reader) *Parser {
return &Parser{r: r, Wg: &sync.WaitGroup{}}
}
// Duration returns the time duration of the passed reader if the sub format is supported.
func Duration(r io.Reader) (time.Duration, error) {
c := New(r)
if err := c.ParseHeaders(); err != nil {
return 0, err
}
return c.Duration()
}
<file_sep>/chunk.go
package riff
import (
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"sync"
)
// Chunk represents the header and containt of a sub block
// See https://tech.ebu.ch/docs/tech/tech3285.pdf to see how
// audio content is stored in a BWF/WAVE file.
type Chunk struct {
ID [4]byte
Size int
Pos int
R io.Reader
okChan chan bool
Wg *sync.WaitGroup
}
func (ch *Chunk) DecodeWavHeader(p *Parser) error {
if ch == nil {
return fmt.Errorf("can't decode a nil chunk")
}
if ch.ID == FmtID {
p.wavHeaderSize = uint32(ch.Size)
if err := ch.ReadLE(&p.WavAudioFormat); err != nil {
return err
}
if err := ch.ReadLE(&p.NumChannels); err != nil {
return err
}
if err := ch.ReadLE(&p.SampleRate); err != nil {
return err
}
if err := ch.ReadLE(&p.AvgBytesPerSec); err != nil {
return err
}
if err := ch.ReadLE(&p.BlockAlign); err != nil {
return err
}
if err := ch.ReadLE(&p.BitsPerSample); err != nil {
return err
}
// if we aren't dealing with a PCM file, we advance to reader to the
// end of the chunck.
if ch.Size > 16 {
extra := make([]byte, ch.Size-16)
ch.ReadLE(&extra)
}
}
return nil
}
// Done signals the parent parser that we are done reading the chunk
// if the chunk isn't fully read, this code will do so before signaling.
func (ch *Chunk) Done() {
if !ch.IsFullyRead() {
ch.Drain()
}
if ch.Wg != nil {
ch.Wg.Done()
}
}
// IsFullyRead checks if we're finished reading the chunk
func (ch *Chunk) IsFullyRead() bool {
if ch == nil || ch.R == nil {
return true
}
return ch.Size <= ch.Pos
}
// Read implements the reader interface
func (ch *Chunk) Read(p []byte) (n int, err error) {
if ch == nil || ch.R == nil {
return 0, errors.New("nil chunk/reader pointer")
}
n, err = ch.R.Read(p)
ch.Pos += n
return n, err
}
// ReadLE reads the Little Endian chunk data into the passed struct
func (ch *Chunk) ReadLE(dst interface{}) error {
if ch == nil || ch.R == nil {
return errors.New("nil chunk/reader pointer")
}
if ch.IsFullyRead() {
return io.EOF
}
ch.Pos += binary.Size(dst)
return binary.Read(ch.R, binary.LittleEndian, dst)
}
// ReadBE reads the Big Endian chunk data into the passed struct
func (ch *Chunk) ReadBE(dst interface{}) error {
if ch.IsFullyRead() {
return io.EOF
}
ch.Pos += binary.Size(dst)
return binary.Read(ch.R, binary.LittleEndian, dst)
}
// ReadByte reads and returns a single byte
func (ch *Chunk) ReadByte() (byte, error) {
if ch.IsFullyRead() {
return 0, io.EOF
}
var r byte
err := ch.ReadLE(&r)
return r, err
}
// Drain discards the rest of the chunk
func (ch *Chunk) Drain() {
bytesAhead := ch.Size - ch.Pos
for bytesAhead > 0 {
readSize := int64(bytesAhead)
if _, err := io.CopyN(ioutil.Discard, ch.R, readSize); err != nil {
return
}
bytesAhead -= int(readSize)
}
}
<file_sep>/README.md
# Resource Interchange File Format parser
[](http://godoc.org/go-audio/riff)
[](https://travis-ci.org/go-audio/riff)
The [RIFF](https://en.wikipedia.org/wiki/Resource_Interchange_File_Format) container format is used to store chunks of data in media files, especially in wav files hence this package inside under the go-audio organization.
<file_sep>/parser.go
package riff
import (
"encoding/binary"
"errors"
"fmt"
"io"
"sync"
"time"
)
// Parser is a struct containing the overall container information.
type Parser struct {
r io.Reader
// Chan is an Optional channel of chunks that is used to parse chunks
Chan chan *Chunk
// ChunkParserTimeout is the duration after which the main parser keeps going
// if the dev hasn't reported the chunk parsing to be done.
// By default: 2s
ChunkParserTimeout time.Duration
// The waitgroup is used to let the parser that it's ok to continue
// after a chunk was passed to the optional parser channel.
Wg *sync.WaitGroup
// Must match RIFF
ID [4]byte
// This size is the size of the block
// controlled by the RIFF header. Normally this equals the file size.
Size uint32
// Format name.
// The representation of data in <wave-data>, and the content of the <format-specific-fields>
// of the ‘fmt’ chunk, depend on the format category.
// 0001h => Microsoft Pulse Code Modulation (PCM) format
// 0050h => MPEG-1 Audio (audio only)
Format [4]byte
// WAV stuff
// size of the wav specific fmt header
wavHeaderSize uint32
// A number indicating the WAVE format category of the file. The content of the
// <format-specific-fields> portion of the ‘fmt’ chunk, and the interpretation of
// the waveform data, depend on this value.
// PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
WavAudioFormat uint16
// The number of channels represented in the waveform data: 1 for mono or 2 for stereo.
// Audio: Mono = 1, Stereo = 2, etc.
// The EBU has defined the Multi-channel Broadcast Wave
// Format [4] where more than two channels of audio are required.
NumChannels uint16
// The sampling rate (in sample per second) at which each channel should be played.
// 8000, 44100, etc.
SampleRate uint32
// The average number of bytes per second at which the waveform data should be
// transferred. Playback software can estimate the buffer size using this value.
// SampleRate * NumChannels * BitsPerSample/8
AvgBytesPerSec uint32
// BlockAlign = SignificantBitsPerSample / 8 * NumChannels
// It is the number of bytes per sample slice. This value is not affected by the number of channels and can be calculated with the formula:
// NumChannels * BitsPerSample/8 The number of bytes for one sample including
// all channels.
// The block alignment (in bytes) of the waveform data. Playback software needs
// to process a multiple of <nBlockAlign> bytes of data at a time, so the value of
// <BlockAlign> can be used for buffer alignment.
BlockAlign uint16
// BitsPerSample 8, 16, 24...
// Only available for PCM
// This value specifies the number of bits used to define each sample. This value is usually 8, 16, 24 or 32.
// If the number of bits is not byte aligned (a multiple of 8) then the number of bytes used per sample is
// rounded up to the nearest byte size and the unused bytes are set to 0 and ignored.
// The <nBitsPerSample> field specifies the number of bits of data used to represent each sample of
// each channel. If there are multiple channels, the sample size is the same for each channel.
BitsPerSample uint16
}
// ParseHeaders reads the header of the passed container and populat the container with parsed info.
// Note that this code advances the container reader.
func (c *Parser) ParseHeaders() error {
id, size, err := c.IDnSize()
if err != nil {
return err
}
c.ID = id
if c.ID != RiffID {
return fmt.Errorf("%s - %s", c.ID, ErrFmtNotSupported)
}
c.Size = size
if err := binary.Read(c.r, binary.BigEndian, &c.Format); err != nil {
return err
}
return nil
}
// Duration returns the time duration for the current RIFF container
// based on the sub format (wav etc...)
func (c *Parser) Duration() (time.Duration, error) {
if c == nil {
return 0, errors.New("can't calculate the duration of a nil pointer")
}
if c.ID == [4]byte{} || c.AvgBytesPerSec == 0 {
err := c.Parse()
if err != nil {
return 0, nil
}
}
switch c.Format {
case WavFormatID:
return c.wavDuration()
default:
return 0, ErrFmtNotSupported
}
}
// String implements the Stringer interface.
func (c *Parser) String() string {
out := fmt.Sprintf("Format: %s - ", c.Format)
if c.Format == WavFormatID {
out += fmt.Sprintf("%d channels @ %d / %d bits - ", c.NumChannels, c.SampleRate, c.BitsPerSample)
d, _ := c.Duration()
out += fmt.Sprintf("Duration: %f seconds", d.Seconds())
}
return out
}
// NextChunk returns a convenient structure to parse the next chunk.
// If the container is fully read, io.EOF is returned as an error.
func (c *Parser) NextChunk() (*Chunk, error) {
if c == nil {
return nil, errors.New("can't calculate the duration of a nil pointer")
}
id, size, err := c.IDnSize()
if err != nil {
return nil, err
}
// all RIFF chunks (including WAVE "data" chunks) must be word aligned.
// If the data uses an odd number of bytes, a padding byte with a value of zero must be placed at the end of the sample data.
// The "data" chunk header's size should not include this byte.
if size%2 == 1 {
size++
}
ch := &Chunk{
ID: id,
Size: int(size),
R: c.r,
}
return ch, nil
}
// IDnSize returns the next ID + block size
func (c *Parser) IDnSize() ([4]byte, uint32, error) {
var ID [4]byte
var blockSize uint32
if err := binary.Read(c.r, binary.BigEndian, &ID); err != nil {
return ID, blockSize, err
}
if err := binary.Read(c.r, binary.LittleEndian, &blockSize); err != err {
return ID, blockSize, err
}
return ID, blockSize, nil
}
// Parse parses the content of the file and populate the useful fields.
// If the parser has a chan set, chunks are sent to the channel.
func (p *Parser) Parse() error {
if p == nil {
return errors.New("can't calculate the wav duration of a nil pointer")
}
if p.Size == 0 {
id, size, err := p.IDnSize()
if err != nil {
return err
}
p.ID = id
if p.ID != RiffID {
return fmt.Errorf("%s - %s", p.ID, ErrFmtNotSupported)
}
p.Size = size
if err := binary.Read(p.r, binary.BigEndian, &p.Format); err != nil {
return err
}
}
var chunk *Chunk
var err error
for err == nil {
chunk, err = p.NextChunk()
if err != nil {
break
}
if chunk.ID == FmtID {
chunk.DecodeWavHeader(p)
} else {
if p.Chan != nil {
if chunk.Wg == nil {
chunk.Wg = p.Wg
}
chunk.Wg.Add(1)
p.Chan <- chunk
// the channel has to release otherwise the goroutine is locked
chunk.Wg.Wait()
}
}
// BFW: bext chunk described here
// https://tech.ebu.ch/docs/tech/tech3285.pdf
if !chunk.IsFullyRead() {
chunk.Drain()
}
}
if p.Wg != nil {
p.Wg.Wait()
}
if p.Chan != nil {
close(p.Chan)
}
if err == io.EOF {
return nil
}
return err
}
// WavDuration returns the time duration of a wav container.
func (p *Parser) wavDuration() (time.Duration, error) {
if p.Size == 0 || p.AvgBytesPerSec == 0 {
return 0, fmt.Errorf("can't extract the duration due to the file not properly parsed")
}
duration := time.Duration((float64(p.Size) / float64(p.AvgBytesPerSec)) * float64(time.Second))
return duration, nil
}
// jumpTo advances the reader to the amount of bytes provided
func (p *Parser) jumpTo(bytesAhead int) error {
var err error
for bytesAhead > 0 {
readSize := bytesAhead
if readSize > 4000 {
readSize = 4000
}
buf := make([]byte, readSize)
err = binary.Read(p.r, binary.LittleEndian, &buf)
if err != nil {
return nil
}
bytesAhead -= readSize
}
return nil
}
<file_sep>/doc.go
/*
Package riff is package implementing a simple Resource Interchange File Format
(RIFF) parser with basic support for sub formats such as WAV.
The goal of this package is to give all the tools needed for a developer
to implement parse any kind of file formats using the RIFF container format.
Support for PCM wav format was added so the headers are parsed, the duration and the raw sound data
of a wav file can be easily accessed (See the examples below) .
For more information about RIFF:
https://en.wikipedia.org/wiki/Resource_Interchange_File_Format
*/
package riff
<file_sep>/riff_test.go
package riff
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
)
func TestDuration(t *testing.T) {
expectations := []struct {
input string
dur time.Duration
}{
{"fixtures/sample.wav", time.Duration(612176870)},
}
for _, exp := range expectations {
path, _ := filepath.Abs(exp.input)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
d, err := Duration(f)
if err != nil {
t.Fatal(err)
}
if d != exp.dur {
t.Fatalf("%s of %s didn't match %f, got %f", "Duration", exp.input, exp.dur.Seconds(), d.Seconds())
}
}
}
func ExampleDuration() {
path, _ := filepath.Abs("fixtures/sample.wav")
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
d, err := Duration(f)
if err != nil {
panic(err)
}
fmt.Printf("File with a duration of %f seconds", d.Seconds())
// Output:
// File with a duration of 0.612177 seconds
}
<file_sep>/parser_test.go
package riff
import (
"bytes"
"io"
"os"
"path/filepath"
"testing"
"time"
)
func TestParseHeader(t *testing.T) {
expectations := []struct {
input string
id [4]byte
size uint32
format [4]byte
}{
{"fixtures/sample.rmi", RiffID, 29632, rmiFormatID},
{"fixtures/sample.wav", RiffID, 53994, WavFormatID},
{"fixtures/sample.avi", RiffID, 230256, aviFormatID},
}
for _, exp := range expectations {
path, _ := filepath.Abs(exp.input)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
c := New(f)
err = c.ParseHeaders()
if err != nil {
t.Fatal(err)
}
if c.ID != exp.id {
t.Fatalf("%s of %s didn't match %s, got %s", "ID", exp.input, exp.id, c.ID)
}
if c.Size != exp.size {
t.Fatalf("%s of %s didn't match %d, got %d", "BlockSize", exp.input, exp.size, c.Size)
}
if c.Format != exp.format {
t.Fatalf("%s of %s didn't match %q, got %q", "Format", exp.input, exp.format, c.Format)
}
}
}
func TestParseWavHeaders(t *testing.T) {
expectations := []struct {
input string
headerSize uint32
format uint16
numChans uint16
sampleRate uint32
byteRate uint32
blockAlign uint16
bitsPerSample uint16
}{
// mono audio files
{"fixtures/sample.wav", 16, 1, 1, 44100, 88200, 2, 16},
// sterep audio files with junk, bext and more headers
{"fixtures/junkKick.wav", 40, 1, 2, 44100, 176400, 4, 16},
}
for _, exp := range expectations {
path, _ := filepath.Abs(exp.input)
t.Log(path)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
c := New(f)
if err := c.ParseHeaders(); err != nil {
t.Fatalf("%s for %s when parsing headers", err, path)
}
ch, err := c.NextChunk()
if err != nil {
t.Fatal(err)
}
for ; ch != nil; ch, err = c.NextChunk() {
if err != nil {
if err != io.EOF {
t.Fatal(err)
}
break
}
if bytes.Compare(ch.ID[:], FmtID[:]) == 0 {
ch.DecodeWavHeader(c)
} else {
ch.Done()
}
}
if c.wavHeaderSize != exp.headerSize {
t.Fatalf("%s didn't match %d, got %d", "header size", exp.headerSize, c.wavHeaderSize)
}
if c.WavAudioFormat != exp.format {
t.Fatalf("%s didn't match %d, got %d", "audio format", exp.format, c.WavAudioFormat)
}
if c.NumChannels != exp.numChans {
t.Fatalf("%s didn't match %d, got %d", "# of channels", exp.numChans, c.NumChannels)
}
if c.SampleRate != exp.sampleRate {
t.Fatalf("%s didn't match %d, got %d", "SampleRate", exp.sampleRate, c.SampleRate)
}
if c.AvgBytesPerSec != exp.byteRate {
t.Fatalf("%s didn't match %d, got %d", "ByteRate", exp.byteRate, c.AvgBytesPerSec)
}
if c.BlockAlign != exp.blockAlign {
t.Fatalf("%s didn't match %d, got %d", "BlockAlign", exp.blockAlign, c.BlockAlign)
}
if c.BitsPerSample != exp.bitsPerSample {
t.Fatalf("%s didn't match %d, got %d", "BitsPerSample", exp.bitsPerSample, c.BitsPerSample)
}
}
}
func TestContainerDuration(t *testing.T) {
expectations := []struct {
input string
dur time.Duration
}{
{"fixtures/sample.wav", time.Duration(612176870)},
}
for _, exp := range expectations {
path, _ := filepath.Abs(exp.input)
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
c := New(f)
d, err := c.Duration()
if err != nil {
t.Fatal(err)
}
if d != exp.dur {
t.Fatalf("Container duration of %s didn't match %f, got %f", exp.input, exp.dur.Seconds(), d.Seconds())
}
}
}
| c0bc5054aefdc30acaeee19dbc23ffcdf9597d82 | [
"Markdown",
"Go Module",
"Go"
] | 9 | Go | go-audio/riff | 6dc8fb4eb0bbea9d5966890969cccbdf89d6c268 | 4f22ddc3e91ba6c62da0995ea9260305196be47d |
refs/heads/master | <file_sep>package pgpwords
import (
"encoding/hex"
"testing"
)
func TestEncodeWords(t *testing.T) {
var tst16 = []struct {
in uint16
out string
}{
{0xE582, "topmost Istanbul"},
{0x82E5, "miser travesty"},
{0xFFFF, "Zulu Yucatán"},
}
for _, tt := range tst16 {
if enc := Encode16(tt.in); enc != tt.out {
t.Errorf("Encode16(%d) failed: got '%v' expected '%v'", tt.in, enc, tt.out)
}
}
var tst32 = []struct {
in uint32
out string
}{
{0xE58282E5, "topmost Istanbul miser travesty"},
{0xFFFFFFFF, "Zulu Yucatán Zulu Yucatán"},
}
for _, tt := range tst32 {
if enc := Encode32(tt.in); enc != tt.out {
t.Errorf("Encode32(%d) failed: got '%v' expected '%v'", tt.in, enc, tt.out)
}
}
}
func TestEncode(t *testing.T) {
in, _ := hex.DecodeString("E58294F2E9A22748")
out := `topmost Istanbul Pluto vagabond treadmill Pacific brackish dictator`
if enc := Encode(in); enc != out {
t.Errorf("Encode(% 02x) failed: got '%v' expected '%v'", in, enc, out)
}
}
| 7b55524fa8ef110eb8ec911439cc12d54a4b6290 | [
"Go"
] | 1 | Go | pombredanne/go-pgpwords | 7279cce56e03393fa3692e0b380c3a8ad9bd2ba9 | be27ed0faaa89d9689a3e92dc9b5677482a59f21 |
refs/heads/master | <repo_name>filsmagalhaes/projetoIbratec<file_sep>/distribuidora(PHP)/indexVendedor.php
<?php
// allow requests from other applications
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
require('classes/Vendedor.php');
// listar (um) vendedor
if(isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['idVendedor'])) {
$vendedor = new vendedor();
echo json_encode($vendedor->listarItem($_GET['idVendedor']));
}
// Listar (todos) os vendedores
if(!isset($_GET['action'])) {
$vendedor = new vendedor();
echo json_encode($vendedor->listarTudo());
}
// Novo vendedor
if(isset($_POST['action']) && $_POST['action'] == 'inserir') {
$vendedor = new vendedor();
echo json_encode($vendedor->inserir($_POST));
return;
}
// Atualizar vendedor
if(isset($_POST['action']) && $_POST['action'] == 'atualizar') {
$vendedor = new vendedor();
if($vendedor->atualizar($_POST)) {
echo 'Atualizado!';
}
return;
}
// Remover vendedor
if(isset($_GET['action']) && $_GET['action'] == 'deletar' && isset($_GET['idVendedor'])) {
$vendedor = new vendedor();
if($vendedor->deletar($_GET['idVendedor'])) {
echo 'Vendedor excluído!';
}
return;
}
<file_sep>/distribuidora(PHP)/db.sql
<?php
$conn = 'mysql:host=localhost;dbname=distribuidora';
try{
$db = new PDO($conn, 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
if($e->getCode) == 1049){
echo "Banco de dados errado.";
}else{
echo $e->getMessage();
}
}<file_sep>/distribuidora(PHP)/distribuidora/classes/Cliente.php
<?php
require('banco/Conexao.php');
class Cliente {
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM cliente';
$cliente = $this->connection->prepare($sql);
$cliente->execute();
return $cliente->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - cliente específico
*
* @param int $cnpj
* @return object
*/
public function listarItem($cnpj)
{
$sql = 'SELECT * FROM cliente WHERE cnpj = :cnpj';
$cliente = $this->connection->prepare($sql);
$cliente->bindValue(':cnpj', $cnpj, PDO::PARAM_INT);
$cliente->execute();
return $cliente->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO cliente (cnpj, nome, telefone, email) ';
$sql .= 'VALUES (:cnpj, :nome, :telefone, :email)';
$cliente = $this->connection->prepare($sql);
$cliente->bindValue(':cnpj', $dados['cnpj'], PDO::PARAM_STR);
$cliente->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$cliente->bindValue(':telefone', $dados['telefone'], PDO::PARAM_STR);
$cliente->bindValue(':email', $dados['email'], PDO::PARAM_STR);
$cliente->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE cliente SET cnpj = :cnpj, nome = :nome, telefone = :telefone, email = :email WHERE cnpj = :cnpj';
$cliente = $this->connection->prepare($sql);
$cliente->bindValue(':cnpj', $dados['cnpj'], PDO::PARAM_INT);
$cliente->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$cliente->bindValue(':telefone', $dados['telefone'], PDO::PARAM_STR);
$cliente->bindValue(':email', $dados['email'], PDO::PARAM_STR);
return $cliente->execute();
}
/**
* DELETE
*
* @param int $cnpj
* @return object
*/
public function deletar($cnpj)
{
$sql = 'DELETE FROM cliente WHERE cnpj = :cnpj';
$cliente = $this->connection->prepare($sql);
$cliente->bindValue(':cnpj', $cnpj, PDO::PARAM_INT);
return $cliente->execute();
}
}<file_sep>/distribuidora(PHP)/classes/Pedido.php
<?php
require('core/Database.php');
class Pedido {
// n uso o sublme mas como ver teus arquivos aqui?
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM pedido';
$pedido = $this->connection->prepare($sql);
$pedido->execute();
return $pedido->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - produto específico
*
* @param int $id
* @return object
*/
public function listarItem($idPedido)
{
$sql = 'SELECT * FROM pedido WHERE idPedido = :idPedido';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':idPedido', $idPedido, PDO::PARAM_INT);
$pedido->execute();
return $pedido->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO pedido (quantidade, forma_pagamento, fk_idCliente, fk_idProduto) ';
$sql .= 'VALUES (:quantidade, :forma_pagamento, :fk_idCliente, :fk_idProduto)';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':quantidade', $dados['quantidade'], PDO::PARAM_INT);
$pedido->bindValue(':forma_pagamento', $dados['forma_pagamento'], PDO::PARAM_STR);
$pedido->bindValue(':fk_idCliente', $dados['fk_idCliente'], PDO::PARAM_INT);
$pedido->bindValue(':fk_idProduto', $dados['fk_idProduto'], PDO::PARAM_INT);
$pedido->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE pedido SET quantidade = :quantidade, forma_pagamento = :forma_pagamento, ';
$sql .= ' fk_idCliente = :fk_idCliente, fk_idProduto = :fk_idProduto ';
$sql .= ' WHERE idPedido = :idPedido';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':idPedido', $dados['idPedido'], PDO::PARAM_INT);
$pedido->bindValue(':quantidade', $dados['quantidade'], PDO::PARAM_STR);
$pedido->bindValue(':forma_pagamento', $dados['forma_pagamento'], PDO::PARAM_STR);
$pedido->bindValue(':fk_idCliente', $dados['fk_idCliente'], PDO::PARAM_INT);
$pedido->bindValue(':fk_idProduto', $dados['fk_idProduto'], PDO::PARAM_INT);
return $pedido->execute();
}
/**
* DELETE
*
* @param int $idPedido
* @return object
*/
public function deletar($idPedido)
{
$sql = 'DELETE FROM pedido WHERE idPedido = :idPedido';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':idPedido', $idPedido, PDO::PARAM_INT);
return $pedido->execute();
}
}<file_sep>/distribuidora(PHP)/classes/Produto.php
<?php
require('core/Database.php');
class Produto {
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM produto';
$produto = $this->connection->prepare($sql);
$produto->execute();
return $produto->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - produto específico
*
* @param int $id
* @return object
*/
public function listarItem($idProduto)
{
$sql = 'SELECT * FROM produto WHERE idProduto = :idProduto';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':idProduto', $idProduto, PDO::PARAM_INT);
$produto->execute();
return $produto->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO produto ( nome, valor, descricao) ';
$sql .= 'VALUES (:nome, :valor, :descricao)';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$produto->bindValue(':valor', $dados['valor'], PDO::PARAM_INT);
$produto->bindValue(':descricao', $dados['descricao'], PDO::PARAM_STR);
$produto->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE produto SET nome = :nome, valor = :valor, descricao = :descricao WHERE idProduto = :idProduto';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':idProduto', $dados['idProduto'], PDO::PARAM_INT);
$produto->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$produto->bindValue(':valor', $dados['valor'], PDO::PARAM_STR);
$produto->bindValue(':descricao', $dados['descricao'], PDO::PARAM_STR);
return $produto->execute();
}
/**
* DELETE
*
* @param int $idProduto
* @return object
*/
public function deletar($idProduto)
{
$sql = 'DELETE FROM produto WHERE idProduto = :idProduto';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':idProduto', $idProduto, PDO::PARAM_INT);
return $produto->execute();
}
}<file_sep>/BD_FlashLog.sql
create database distribuidora;
use distribuidora;
select * from pedido;
create table cliente (
idCliente int primary key auto_increment,
cnpj varchar(30),
nome varchar (255) not null,
telefone varchar (50),
email varchar (255) not null
);
create table vendedor (
idVendedor int primary key auto_increment,
cpf varchar(20),
nome varchar (255) not null,
telefone varchar (50),
email varchar (255) not null
);
create table produto (
idProduto int primary key auto_increment ,
nome varchar (255) not null,
valor decimal (10,2) not null,
descricao varchar (512),
fk_idVendedor int,
FOREIGN KEY (fk_idVendedor) REFERENCES vendedor (idVendedor)
);
create table pedido (
idPedido int auto_increment primary key,
quantidade int not null,
forma_pagamento varchar (255) not null,
fk_idCliente int,
fk_idProduto int,
FOREIGN KEY (fk_idCliente) REFERENCES cliente (idCliente),
FOREIGN KEY (fk_idProduto) REFERENCES produto (idProduto)
);
INSERT INTO vendedor (cpf, nome, telefone, email)
VALUES ('123123123', ':nome', '8657568', ':email')
INSERT INTO pedido (quantidade, forma_pagamento, fk_idCliente,fk_idProduto)
VALUES (100, ':forma_pagamento', 1, 1);
insert into produto (idProduto,nome, valor, descricao)
values ( 1 ,'dog', 12, 'quente');
INSERT INTO cliente (cnpj, nome, telefone, email)
VALUES ("874562131894651", "Moura", "98465165", "<EMAIL>");
INSERT INTO cliente (cnpj, nome, telefone, email)
VALUES ("984651324651215", "Shell", "98465132", "<EMAIL>");
INSERT INTO cliente (cnpj, nome, telefone, email)
VALUES ("874562142524534", "Heliar", "894561236", "<EMAIL>");
INSERT INTO produto (nome, valor, descricao)
VALUES ("agua", "20", "agua sanitaria");
INSERT INTO vendedor (cpf, nome, telefone, email)
VALUES ("87423432656", "Marcos", "28951236", "<EMAIL>");<file_sep>/distribuidora(PHP)/indexPedido.php
<?php
// allow requests from other applications
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
require('classes/Pedido.php');
// listar (um) pedido
if(isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['idPedido'])) {
$pedido = new Pedido();
echo json_encode($pedido->listarItem($_GET['idPedido']));
}
// Novo pedido
if(isset($_POST['action']) && $_POST['action'] == 'inserir') {
$pedido = new Pedido();
echo json_encode($pedido->inserir($_POST));
return;
}
// Atualizar pedido
if(isset($_POST['action']) && $_POST['action'] == 'atualizar') {
$pedido = new Pedido();
if($pedido->atualizar($_POST)) {
echo 'Atualizado!';
}
return;
}
// Remover pedido
if(isset($_GET['action']) && $_GET['action'] == 'deletar' && isset($_GET['idPedido'])) {
$pedido = new Pedido();
if($pedido->deletar($_GET['idPedido'])) {
echo 'Pedido excluído!';
}
return;
}
// Todos pedidos
if(!isset($_GET['action'])) {
$pedido = new Pedido();
echo json_encode($pedido->listarTudo());
}<file_sep>/distribuidora(PHP)/distribuidora/classes/Pedido.php
<?php
require('banco/Conexao.php');
class Pedido {
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM pedido';
$pedido = $this->connection->prepare($sql);
$pedido->execute();
return $pedido->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - produto específico
*
* @param int $id
* @return object
*/
public function listarItem($id)
{
$sql = 'SELECT * FROM pedido WHERE id = :id';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':id', $id, PDO::PARAM_INT);
$pedido->execute();
return $pedido->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO pedido (id, quantidade, forma_pagamento, cnpj) ';
$sql .= 'VALUES (:id, :quantidade, :forma_pagamento)';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':id', $dados['id'], PDO::PARAM_STR);
$pedido->bindValue(':quantidade', $dados['quantidade'], PDO::PARAM_STR);
$pedido->bindValue(':forma_pagamento', $dados['forma_pagamento'], PDO::PARAM_STR);
$pedido->bindValue(':fk_cnpj', $dados['fk_cnpj'], PDO::PARAM_STR);
$pedido->bindValue(':fk_id', $dados['fk_id'], PDO::PARAM_STR);
$pedido->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE pedido SET id = :id, quantidade = :quantidade, forma_pagamento = :forma_pagamento WHERE id = :id';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':id', $dados['id'], PDO::PARAM_INT);
$pedido->bindValue(':quantidade', $dados['quantidade'], PDO::PARAM_STR);
$pedido->bindValue(':forma_pagamento', $dados['forma_pagamento'], PDO::PARAM_STR);
$pedido->bindValue(':fk_cnpj', $dados['fk_cnpj'], PDO::PARAM_STR);
$pedido->bindValue(':fk_id', $dados['fk_id'], PDO::PARAM_STR);
return $pedido->execute();
}
/**
* DELETE
*
* @param int $id
* @return object
*/
public function deletar($id)
{
$sql = 'DELETE FROM pedido WHERE id = :id';
$pedido = $this->connection->prepare($sql);
$pedido->bindValue(':id', $id, PDO::PARAM_INT);
return $pedido->execute();
}
}<file_sep>/distribuidora(PHP)/distribuidora/rotas/Produto.php
<?php
// allow requests from other applications
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
require('classes/Pedido.php');
// listar (um) produto
if(isset($_GET['action']) && $_GET['action'] == 'listarItem' && isset($_GET['idProduto'])) {
$produto = new Produto();
echo json_encode($produto->listarItem($_GET['idProduto']));
}
// Listar (todos) os produto
if(!isset($_GET['action'])) {
$produto = new Produto();
echo json_encode($produto->listarTudo());
}
// Novo produto
if(isset($_POST['action']) && $_POST['action'] == 'inserir') {
$produto = new Produto();
echo json_encode($produto->inserir($_POST));
return;
}
// Atualizar produto
if(isset($_POST['action']) && $_POST['action'] == 'atualizar') {
$produto = new Produto();
if($produto->atualizar($_POST)) {
echo 'Atualizado!';
}
return;
}
// Remover produto
if(isset($_GET['action']) && $_GET['action'] == 'deletar' && isset($_GET['idProduto'])) {
$produto = new Produto();
if($produto->deletar($_GET['idProduto'])) {
echo 'Produto excluído!';
}
return;
}
// Todos produtos
if(!isset($_GET['action'])) {
$produto = new Produto();
echo json_encode($produto->findAll());
}<file_sep>/FlashLog(Quasar)/src/router/routes.js
const routes =
[
{
path: '/clientes',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/clientes/Index.vue')
}]
},
{
path: '/clientes/criar/',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/clientes/Criar.vue')
}]
},
{
path: '/clientes/:idCliente/',
component: () =>
import ('layouts/MeuLayoutEditarCliente.vue'),
children: [{
path: '',
component: () =>
import ('pages/clientes/Editar.vue')
}]
},
{
path: '/pedidos',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/pedidos/index.vue')
}]
},
{
path: '/pedidos/Criar',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/pedidos/Criar.vue')
}]
},
{
path: '/pedidos/:idPedido',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/pedidos/Editar.vue')
}]
},
{
path: '/produtos',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/produtos/index.vue')
}]
},
{
path: '/produtos/Criar',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/produtos/Criar.vue')
}]
},
{
path: '/produtos/:idProduto',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/produtos/Editar.vue')
}]
},
{
path: '/vendedor',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/vendedor/index.vue')
}]
},
{
path: '/vendedor/Criar',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/vendedor/Criar.vue')
}]
},
{
path: '/vendedor/:idVendedor',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/vendedor/Editar.vue')
}]
},
{
path: '/',
component: () =>
import ('layouts/MyLayout.vue'),
children: [{
path: '',
component: () =>
import ('pages/Index.vue')
}]
}
]
// Always leave this as last one
if (process.env.MODE !== 'ssr') {
routes.push({
path: '*',
component: () =>
import ('pages/Error404.vue')
})
}
export default routes<file_sep>/distribuidora(PHP)/distribuidora/classes/Vendedor.php
<?php
require('banco/Conexao.php');
class Vendedor {
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM vendedor';
$vendedor = $this->connection->prepare($sql);
$vendedor->execute();
return $vendedor->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - vendedor específico
*
* @param int $cnpj
* @return object
*/
public function listarItem($cnpj)
{
$sql = 'SELECT * FROM vendedor WHERE cpf = :cpf';
$vendedor = $this->connection->prepare($sql);
$vendedor->bindValue(':cpf', $cpf, PDO::PARAM_INT);
$vendedor->execute();
return $vendedor->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO vendedor (cpf, nome, telefone, email) ';
$sql .= 'VALUES (:cpf, :nome, :telefone, :email)';
$cliente = $this->connection->prepare($sql);
$cliente->bindValue(':cpf', $dados['cpf'], PDO::PARAM_STR);
$cliente->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$cliente->bindValue(':telefone', $dados['telefone'], PDO::PARAM_STR);
$cliente->bindValue(':email', $dados['email'], PDO::PARAM_STR);
$cliente->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE vendedor SET cpf = :cpf, nome = :nome, telefone = :telefone, email = :email WHERE cpf = :cpf';
$vendedor = $this->connection->prepare($sql);
$vendedor->bindValue(':cpf', $dados['cpf'], PDO::PARAM_INT);
$vendedor->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$vendedor->bindValue(':telefone', $dados['telefone'], PDO::PARAM_STR);
$vendedor->bindValue(':email', $dados['email'], PDO::PARAM_STR);
return $vendedor->execute();
}
/**
* DELETE
*
* @param int $cpf
* @return object
*/
public function deletar($cpf)
{
$sql = 'DELETE FROM vendedor WHERE cpf = :cpf';
$vendedor = $this->connection->prepare($sql);
$vendedor->bindValue(':cpf', $cpf, PDO::PARAM_INT);
return $vendedor->execute();
}
}<file_sep>/distribuidora(PHP)/indexCliente.php
<?php
// allow requests from other applications
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
require('classes/Cliente.php');
// listarr (um) cliente
if(isset($_GET['action']) && $_GET['action'] == 'show' && isset($_GET['idCliente'])) {
$cliente = new Cliente();
echo json_encode($cliente->listarItem($_GET['idCliente']));
}
// Listar (todos) os clientes
// Novo cliente
if(isset($_POST['action']) && $_POST['action'] == 'inserir') {
$cliente = new Cliente();
echo json_encode($cliente->inserir($_POST));
return;
}
// Atualizar cliente
if(isset($_POST['action']) && $_POST['action'] == 'atualizar') {
$cliente = new Cliente();
if($cliente->atualizar($_POST)) {
echo 'Atualizado!';
}
return;
}
// Remover cliente
if(isset($_GET['action']) && $_GET['action'] == 'deletar' && isset($_GET['idCliente'])) {
$cliente = new Cliente();
echo 'Cliente excluído!';
if($cliente->deletar($_GET['idCliente'])) {
echo 'Cliente excluído!';
}
return;
}
// Todos clientes
if(!isset($_GET['action'])) {
$cliente = new Cliente();
echo json_encode($cliente->listarTudo());
}<file_sep>/distribuidora(PHP)/distribuidora/classes/Produto.php
<?php
require('banco/Conexao.php');
class Produto {
/**
* Connection instance
* @var Database $connection
*/
private $connection;
/**
* Intialize object with connection
*
* @return void
*/
public function __construct()
{
$this->connection = (new Database())->connect();
}
/**
* SELECT - tudo
*
* @return array
*/
public function listarTudo()
{
$sql = 'SELECT * FROM produto';
$produto = $this->connection->prepare($sql);
$produto->execute();
return $produto->fetchAll(PDO::FETCH_OBJ);
}
/**
* SELECT - produto específico
*
* @param int $id
* @return object
*/
public function listarItem($id)
{
$sql = 'SELECT * FROM produto WHERE id = :id';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':id', $id, PDO::PARAM_INT);
$produto->execute();
return $produto->fetch(PDO::FETCH_OBJ);
}
/**
* INSERT
*
* @param array $dados
* @return int
*/
public function inserir($dados)
{
$sql = 'INSERT INTO produto (id, nome, valor, descricao) ';
$sql .= 'VALUES (:id, :nome, :valor, :descricao)';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':id', $dados['id'], PDO::PARAM_STR);
$produto->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$produto->bindValue(':valor', $dados['valor'], PDO::PARAM_STR);
$produto->bindValue(':descricao', $dados['descricao'], PDO::PARAM_STR);
$produto->bindValue(':fk_cpf', $dados['fk_cpf'], PDO::PARAM_STR);
$produto->execute();
return $this->connection->lastInsertId();
}
/**
* Update
*
* @param array $dados
* @return object
*/
public function atualizar($dados)
{
$sql = 'UPDATE produto SET id = :id, nome = :nome, valor = :valor, descricao = :descricao WHERE id = :id';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':id', $dados['id'], PDO::PARAM_INT);
$produto->bindValue(':nome', $dados['nome'], PDO::PARAM_STR);
$produto->bindValue(':valor', $dados['valor'], PDO::PARAM_STR);
$produto->bindValue(':descricao', $dados['descricao'], PDO::PARAM_STR);
$produto->bindValue(':fk_cpf', $dados['fk_cpf'], PDO::PARAM_STR);
return $produto->execute();
}
/**
* DELETE
*
* @param int $id
* @return object
*/
public function deletar($id)
{
$sql = 'DELETE FROM produto WHERE id = :id';
$produto = $this->connection->prepare($sql);
$produto->bindValue(':id', $id, PDO::PARAM_INT);
return $produto->execute();
}
} | 68733cd4140d5698b975f5111f807ffc36568f4d | [
"JavaScript",
"SQL",
"PHP"
] | 13 | PHP | filsmagalhaes/projetoIbratec | e9c8892f094d05a2089134e69fc186c2ba2132b7 | 2a4a48a76408cd3194f3b05e82547156158015db |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/*
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Express server listening on port " + port + ".");
});
}
*/
router.post('/api/getEmpInfoByEmpNo/:empNo', function(req, res, next) {
let user = req.params.empNo;
console.log ("getEmpInfo.js >>>>>1 " + user)
conn.executeQueryTx("SELECT * FROM IO_EMP WHERE EMP_NO = ?", user, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getEmpInfo', function(req, res, next) {
console.log ("getEmpInfo.js::: /api/getEmpInfo >>>>>1 ")
conn.executeQuery("SELECT * FROM IO_EMP", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
/*
router.get('/', function(req, res, next) {
conn.executeQuery('SELECT * FROM TEST', function(result){
console.log("*********************");
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
});
});
router.get('/getEmpInfoAll', function(req, res, next) {
conn.executeQuery('SELECT * FROM IO_EMP', function(result){
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
res.send(JSON.stringify(result));
});
});
router.get('/getEmpInfoByEmpNo/:empNo', function(req, res, next) {
let empNo = req.params.empNo;
conn.executeQuery('SELECT * FROM IO_EMP WHERE EMP_NO = ?', [empNo], function(result){
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
res.send(JSON.stringify(result));
});
});
router.put('/putEmpInfoByEmpNo/:empNo', function(req, res, next) {
let empNo = req.params.empNo;
let NAME = req.body.NAME,
EMP_GBN = req.body.EMP_GBN,
EMAIL_ADDR = req.body.EMAIL_ADDR,
PHONE_NO = req.body.PHONE_NO;
conn.executeQuery('INSERT INTO IO_EMP(EMP_NO, NAME, EMP_GBN, EMAIL_ADDR, PHONE_NO ) VALUES (?,?,?,?,?) ', [empNo,NAME, EMP_GBN, EMAIL_ADDR, PHONE_NO], function(result){
if(err) throw err;
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
res.send(JSON.stringify(res[0]));
});
});
router.post('/postEmpInfoByEmpNo/:empNo', function(req, res, next) {
let empNo = req.params.empNo;
let NAME = req.body.NAME,
EMP_GBN = req.body.EMP_GBN,
EMAIL_ADDR = req.body.EMAIL_ADDR,
PHONE_NO = req.body.PHONE_NO;
conn.executeQuery('UPDATE IO_EMP SET NAME = ?, EMP_GBN =? , EMAIL_ADDR = ?, PHONE_NO =? ) WHERE EMP_NO = ? ', [NAME, EMP_GBN, EMAIL_ADDR, PHONE_NO, empNo], function(result){
if(err) throw err;
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
res.send(JSON.stringify(res[0]));
});
});
router.delete('/deleteEmpInfoByEmpNo/:empNo', function(req, res, next) {
let empNo = req.params.empNo;
conn.executeQuery('DELETE FROM IO_EMP WHERE EMP_NO = ? ', [empNo], function(result){
if(err) throw err;
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
res.send(JSON.stringify(res[0]));
});
});
*/
/*
var type = 'C';
var tb_code = 'TB001';
var field = 'IO_NO,NAME,GENDER,JC_CD,JUMIN_NO';
var value = "'H001','김상화','F','AA',''";
var condition = '';
*/
//호출 방법1
//var queryStr = common_query.fn_makeCommonQuery(type,tb_code,field,value,condition);
/* 기석 과장 소스
//호출 방법3
var queryStr = common_query.fn_makeCommonQuery_callSP("procedure_test","'123','ABC'");
router.get('/', function(req, res, next) {
//호출 방법2
//var queryStr = common_query.fn_makeCommonQuery_req(req);
conn.executeQuery(queryStr, function(result){
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express1' });
});
});
*/
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/* GET home page. */
router.put('/empInfo', function(req, res, next) {
conn.executeQuery('SELECT * FROM TEST', function(result){
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/*
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Express server listening on port " + port + ".");
});
}
*/
router.get('/api/getProcessCodeAll', function(req, res, next) {
console.log ("getProcessCode.js /api/PROJECT_Master >>>>>1 ")
conn.executeQuery("SELECT IO_CODE_SEQ AS ID, IO_CODE_D_NM AS CODENAME FROM C_CODE_D where IO_CODE_M = 'P001' AND USE_YN ='Y'", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getProcessCodeByProject/:projectCode', function(req, res, next) {
let projectCode = req.params.projectCode
console.log ("getProcessCode.js /api/PROCESS_Master >>>>>1 ")
conn.executeQueryTx("SELECT IO_CODE_SEQ AS ID, IO_CODE_D_NM AS CODENAME FROM C_CDOE_D WHERE IO_CODE_CD IN (SELECT PROCESS_CD FROM PROCESS_MASTER where PROJECT_CD = ?)", [projectCode], function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.post('/api/getProcessCodeByDateInfo', function(req, res, next) {
console.log ("getProcessCode.js /api/getProcessCodeByDateInfo >>>>> startDate ")
// let startDate = req.param.getDateInfo.startDate;
// let endDate = req.param.getDateInfo.endDate;
var dateInfo = req.body;
var searchStartDate = null
var searchEndDate = null
/* const event = new Date.now()
if(dateInfo.startDate == null) {
searchStartDate = event.toISOString()
searchEndDate = event.toISOString()
} else { */
searchStartDate = dateInfo.startDate
searchEndDate = dateInfo.endDate
// }
console.log ("getProcessCode.js /api/getProcessCodeByDateInfo startDate>>>>>1 " + searchStartDate)
console.log ("getProcessCode.js /api/getProcessCodeByDateInfo endDate>>>>>1 " + searchEndDate)
/// let startDate = getDateInfo.startDate;
///let endDate = getDateInfo.endDate;
//router.get('/api/getProcessCodeByDateInfo', function(req, res, next) {
// conn.executeQueryTx("SELECT PROJECT_CD FROM PROJECT_MASTER WHERE DATE_FORMAT(CRT_DTM,'%Y-%m-%d') BETWEEN ? and ?", [dateInfo], function(result){
conn.executeQueryTx("SELECT PROJECT_CD FROM PROJECT_MASTER WHERE DATE_FORMAT(CRT_DTM,'%Y-%m-%d') BETWEEN ? and ?", [searchStartDate,searchEndDate], function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getProcessCodeByProjectId/:projectCode', function(req, res, next) {
console.log ("getProcessCode.js /api/getProcessCodeByProjectId >>>>> projectId ")
// var pBody = req.body;
// var projectId = pBody.s_projectId;
let projectCode = req.params.projectCode
console.log ("getProcessCode.js /api/getProcessCodeByProjectId projectId>>>>>1 " + projectCode)
conn.executeQueryTx("SELECT PROCESS_CD AS ID, PROCESS_NM AS CODENAME , true AS isCodeReg FROM PROCESS_PLAN_DESC WHERE PROJECT_CD = ?", [projectCode], function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.post('/api/getProcessRealInfoByProjectId', function(req, res, next) {
console.log ("getProcessCode.js /api/getProcessRealInfoByProjectId >>>>> projectId ")
var processInfo = req.body;
console.log ("getProcessCode.js /api/getProcessRealInfoByProjectId projectId>>>>>1 " + processInfo.projectId)
console.log ("getProcessCode.js /api/getProcessRealInfoByProjectId processCodeId>>>>>1 " + processInfo.processCodeId)
console.log ("getProcessCode.js /api/getProcessRealInfoByProjectId processCodeName>>>>>1 " + processInfo.processCodeName)
conn.executeQueryTx("SELECT PPD.NO, PPD.PROCESS_CD, PPD.PROCESS_NM, PPD.SEQ_PROCESS_NO, \
PPD.WORK_CD, FNC_GET_C_CODE_D_NM(SUBSTR(PM.WORK_CD,1,4),PM.WORK_CD) AS WORK_NM, PM.COMPRESS_RATE, \
PPD.PROJECT_CD, FNC_GET_PROJECT_NM(PPD.PROJECT_CD) AS PROJECT_NM, \
PM.EQUIPMENT_CD , FNC_GET_EQUIPMENT_NM(PM.EQUIPMENT_CD) AS EQUIPMENT_NM, \
PM.MATERIAL_CD , FNC_GET_MATERIAL_NM(PM.MATERIAL_CD)AS MATERIAL_NM, PM.PART_CD,\
FNC_GET_PART_NM(PM.PART_CD) AS PART_NM, PM.CAVITY, FNC_GET_C_CODE_D_NM(SUBSTR(PM.CAVITY,1,4),PM.CAVITY) AS CAVITY_NM, \
PPD.PLAN_WORK_COUNT, PPD.PLAN_START_DT, PPD.PLAN_FINISH_DT, \
PPD.PLAN_USE_HOUR, PPD.PROCESS_UNIT, \
PPD.OTHER_PROCESS_HOUR, PPD.OTHER_PROCESS_MIN, \
PPD.SELF_PROCESS_HOUR, PPD.SELF_PROCESS_MIN, \
PPD.ATTRIBUTE, PPD.SORT_ORDER, PPD.PRICE_PER_HOUR, PPD.CRT_BY, \
PPD.CRT_DTM, PPD.MOD_BY, PPD.MOD_DTM \
FROM MES.PROCESS_PLAN_DESC PPD, MES.PROCESS_MASTER PM \
WHERE PPD.PROJECT_CD = PM.PROJECT_CD AND PPD.PROCESS_CD = PM.PROCESS_CD \
AND PPD.PROJECT_CD = ? AND PPD.PROCESS_CD = ? AND PPD.PROCESS_NM = ?", [processInfo.projectId,processInfo.processCodeId,processInfo.processCodeName], function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.get('/api/getMaterialInfoSearch', function(req, res, next) {
console.log ("getMaterialInfoSearch.js /api/getMaterialInfoSearch >>>>>1 ")
conn.executeQuery("SELECT NO, MATERIAL_CD, MATERIAL_NM, SERIAL_NO, MODEL_NO, MATERIAL_SPEC, UNIT, MGR_EMP_NO,\
PURCHASE_NO, ATTRIBUTE, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM \
FROM MES.MATERIAL_MASTER", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>* token 생성 라이브러리
npm install --save jsonwebtoken
npm install --save passport-strategy
npm i --save passport
npm i --save passport-jwt<file_sep>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require("body-parser");
var logger = require('morgan');
var cors = require('cors');
var dateFormat = require('dateformat');
var config = require('./routes/util/config');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var admKeyRouter = require('./routes/admKey');
var loginRouter = require('./routes/loginInfo/login');
var commRouter = require('./routes/common/commCode');
var getProjectRouter = require('./routes/projectInfo/getProjectInfo');
var putProjectRouter = require('./routes/projectInfo/putProjectInfo');
var vendorRouter = require('./routes/vendor/index');
var purchaseRouter = require('./routes/purchaseInfo/getPurchaseInfo'); //kks 20191109
//발주처-고객 관리
var customerRouter = require('./routes/customerInfo/getCustomerInfo');
var getProcessRouter = require('./routes/processCodeInfo/getProcessCode'); //hsk
var putProcessRouter = require('./routes/processCodeInfo/putProcessCode'); //hsk
//재료 Material Info
var getMaterialRouter = require('./routes/materialInfo/getMaterialInfo'); //hsk
//재료 Material Info
var getWorkRouter = require('./routes/workInfo/getWorkInfo'); //hsk
//부품명 Info
var getPartRouter = require('./routes/partInfo/getPartInfo'); //hsk
//장비명 Info
var getEquipmentRouter = require('./routes/equipmentInfo/getEquipmentInfo'); //hsk
//CAM 담당자 Info
var getCamRouter = require('./routes/camInfo/getCamInfo'); //hsk
//CAD 담당자 Info
var getCadRouter = require('./routes/cadInfo/getCadInfo'); //hsk
//프로젝트별 작업 일정 기간
var pjtStatRouter = require('./routes/dayStatis/getPjtStatInfo'); //hsk
// 사원정보 관리
var rEmpInfo = require('./routes/empInfo/getEmpInfo'); //./routes/customerInfo/index.js
var cEmpInfo = require('./routes/empInfo/setEmpInfo'); //./routes/customerInfo/users.js
var uEmpInfo = require('./routes/empInfo/updEmpInfo'); //./routes/customerInfo/users.js
var dEmpInfo = require('./routes/empInfo/delEmpInfo'); //./routes/customerInfo/users.js
// 공통 쿼리
var callDirectQuery = require('./routes/common/callDirectQuery'); //./routes/common/callDirectQuery.js
const passport = require('passport');
//require('./passport');
require('./passport');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set the secret key variable for jwt
app.set('jwt-secret', config.secret)
app.use(cors()); // Access-Control-Allow-Origin 헤더를 설정해줄 수 있는 cors npm 모듈
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(dateFormat);
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', passport.authenticate('jwt', {session: false}), loginRouter);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api/admKey', admKeyRouter);
app.use('/', rEmpInfo);
app.use('/', commRouter);
// app.use('/api/empInfo/setEmpInfo', cEmpInfo);
// app.use('/api/empInfo/updEmpInfo', uEmpInfo);
// app.use('/api/empInfo/delEmpInfo', dEmpInfo);
app.use('/', getProjectRouter);
app.use('/', putProjectRouter);
app.use('/', customerRouter);
app.use('/', purchaseRouter);
app.use('/', getProcessRouter);
app.use('/', putProcessRouter);
app.use('/', loginRouter);
app.use('/api/vendor', vendorRouter);
app.use('/', pjtStatRouter);
app.use('/', getMaterialRouter);
app.use('/', getWorkRouter);
app.use('/', getPartRouter);
app.use('/', getEquipmentRouter);
app.use('/', getCamRouter);
app.use('/', getCadRouter);
app.use('/api/common/callDirectQuery', callDirectQuery);
//http:localhost:3000/api
//http:localhost:3000/api/users
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
console.log('app.js payload received');
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Express server listening on port " + port + ".");
});
}
module.exports = app;<file_sep>var queryStr = '';
var TB_Map = new Map();
TB_Map.set('TB001','io_emp');
TB_Map.set('TB002','io_common_code');
//request를 파라미터로 전달시 사용
function fn_makeCommonQuery_req(req){
var type = req.query.type;
var tb_code = req.query.tb_code;
var field = req.query.field;
var value = req.query.value;
var condition = req.query.condition;
return fn_makeCommonQuery(type, tb_code, field, value, condition);
}
function fn_makeCommonQuery(type, tb_code, field, value, condition) {
/*
var param1 = 'C';
var param2 = 'TB001';
var param3 = 'IO_NO,NAME,GENDER,JC_CD';
//var param4 = 'AD003,최비서,100000003,,F,비서,관리,123457,서울,서초구,1234567';
//var param3 = '';
var param4 = 'AD001,김기석,M,팀장'; // 날짜 curdate()
var param5 = "io_no='AD001'"; //where 절
*/
//value = "'cj'";
//condition = "io_no='AD001'";//get 방식으로는 '가 포함되어 오류 발생하기 때문에 하드코딩으로 테스트
/*
type = param1;
tb_code = param2;
field = param3;
value = param4;
condition = param5;
*/
//http://localhost:3000/api/empInfo/getEmpInfo?type=C&tb_code=TB001&field=IO_NO,NAME,GENDER,JC_CD&value=AD001,kks,M,tj&condition=
//http://localhost:3000/api/empInfo/getEmpInfo?type=C&tb_code=TB001&field=IO_NO,NAME,GENDER,JC_CD&value=AD002,kyk,M,tj&condition=
//http://localhost:3000/api/empInfo/getEmpInfo?type=R&tb_code=TB001&field=IO_NO,NAME,GENDER,JC_CD&value=&condition=io_no='AD001'
//http://localhost:3000/api/empInfo/getEmpInfo?type=U&tb_code=TB001&field=JC_CD&value=cj&condition=io_no=AD001
//http://localhost:3000/api/empInfo/getEmpInfo?type=D&tb_code=TB001&field=&value=&condition=io_no=AD001
value = value.replace(/'/g, "\'");
condition = condition.replace(/'/g, "\'");
var paramArray = '';
var paramArray2 = '';
switch (type) {
case 'C' :
queryStr = ' insert into ' + TB_Map.get(tb_code);
//스키마 변경을 고려해서 필드 값은 필수로 있어야 하지만, 예외 case는 만들어 놓음
if(field !=''){
queryStr += '(';
paramArray = field.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ') ';
}
queryStr += ' values (';
paramArray = value.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ') ';
break;
case 'R' :
queryStr = ' select ';
paramArray = field.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ' from ' + TB_Map.get(tb_code) + ' ';
if(condition != ""){
queryStr += " where " + condition;
}
break;
case 'U' :
queryStr = ' update ' + TB_Map.get(tb_code);
queryStr += ' set ';
paramArray = field.split(',');
paramArray2 = value.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i] + "=" + paramArray2[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
if(condition != ""){
queryStr += " where " + condition;
} else {
//update에 조건이 없이 수행되는 case를 방지
queryStr = "select 1 from dual "
}
break;
case 'D' :
queryStr = ' delete from ' + TB_Map.get(tb_code);
if(condition != ""){
queryStr += " where " + condition;
} else {
//delete에 조건이 없이 수행되는 case를 방지
queryStr = "select 1 from dual "
}
break;
defualt : break;
}
console.log("queryStr : " + queryStr);
return queryStr;
}
function fn_makeCommonQuery_callSP(sp_name, param) {
param = param.replace(/'/g, "\'");
var paramArray = '';
var queryStr = ' call ' + sp_name;
queryStr += '(';
if(param !=''){
paramArray = param.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ') ';
}
console.log("queryStr : " + queryStr);
return queryStr;
}
module.exports = {
fn_makeCommonQuery_req: fn_makeCommonQuery_req,
fn_makeCommonQuery: fn_makeCommonQuery,
fn_makeCommonQuery_callSP: fn_makeCommonQuery_callSP
}<file_sep>const mysql = require("mysql"),
util = require("util"),
Promise = require("bluebird");
Promise.promisifyAll(mysql);
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
const DB_INFO = {
host : 'localhost:3306',
user : 'huetech',
password : '!<PASSWORD>',
database : 'MES',
multipleStatements : true,
connectionLimit : 10,
waitForConnections : false
};
module.exports = class {
constructor(dbinfo) {
dbinfo = dbinfo || DB_INFO;
this.pool = mysql.createPool(dbinfo);
}
connect() {
return this.pool.getConnectionAsync().disposer( conn => {
return conn.release();
});
}
end() {
this.pool.end( function(err) {
util.log(">>>>>>>>>>>>>>>>>>>>>>> End of Pool !!!!");
if(err)
util.log("ERR POOL Ending !!!");
});
}
};
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.get('/api/getCamInfoSearch', function(req, res, next) {
console.log ("getCamInfoSearch.js /api/getCamInfoSearch >>>>>1 ")
conn.executeQuery("SELECT IO_CODE_SEQ AS NO, IO_CODE_D AS CAM_MGR_CD, IO_CODE_D_NM AS CAM_MGR_NM, \
IO_ATTRIBUTE \
FROM MES.C_CODE_D WHERE IO_CODE_M = 'B001' AND USE_YN = 'Y' ", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>var queryStr = '';
var TB_Map = new Map();
TB_Map.set('TB001','io_emp');
TB_Map.set('TB002','io_common_code');
function commonQuery(type,tb_code,field,value,condition) {
var param1 = 'R';
var param2 = 'TB001';
var param3 = 'IO_NO,NAME,JUMIN_NO,PASSPORT_NO,GENDER,JC_CD,JW_CD,DEPT_ID,ADDRESS,ADDRESS2,POST_NO';
//var param4 = 'AD003,최비서,100000003,,F,비서,관리,123457,서울,서초구,1234567';
//var param3 = '';
var param4 = 'AD003,권용경,100000003,,M,대표,대표,123456,경기도,우리집,123456,,,,,curdate(),,null,null,null';
var param5 = "io_no='AD001'"; //where 절
type = param1;
tb_code = param2;
field = param3;
value = param4;
condition = param5;
condition = condition.replace(/g//','/'');
var paramArray = '';
switch (type) {
case 'C' :
queryStr = ' insert into ' + TB_Map.get(tb_code);
//스키마 변경을 고려해서 필드 값은 필수로 있어야 하지만, 예외 case는 만들어 놓음
if(param3 !=''){
queryStr += '(';
paramArray = field.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ') ';
}
queryStr += ' values (';
paramArray = value.split(',');
for(var i=0;i<paramArray.length; i++){
if(paramArray[i].indexOf('(') > -1 || paramArray[i]=='null'){
queryStr += paramArray[i];
} else {
queryStr += "'" + paramArray[i] + "'";
}
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ') ';
break;
case 'R' :
queryStr = ' select ';
paramArray = field.split(',');
for(var i=0;i<paramArray.length; i++){
queryStr += paramArray[i];
if(i < paramArray.length-1){
queryStr += ',';
}
}
queryStr += ' from ' + TB_Map.get(tb_code) + ' ';
queryStr += " where " + condition;
//+ TB_Map.get(tb_code);
break;
defualt : break;
}
return queryStr;
}
module.exports = {
commonQuery: commonQuery
}<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/*
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Express server listening on port " + port + ".");
});
}
*/
router.get('/api/getPurchaseInfo', function(req, res, next) {
console.log ("getEmpInfo.js /api/purchase_master >>>>>1 ")
conn.executeQuery("SELECT * FROM purchase_master", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>module.exports = Object.const({
MES: '공정관리프로그램',
MENU: 'Menu',
SEARCH: '검색',
INPUT: '입력'
});<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/* 고객정보 모두 가져오기 */
router.get('/api/get_customer_desc_all', function(req, res, next) {
conn.executeQuery('SELECT * FROM customer_desc', function(result){
console.log("In Index : " + JSON.stringify(result));
res.render('index', { title: 'Express' });
});
});
/* 고객의 고유코드 가져오기 */
router.get('/api/get_customer_masterCode', function(req, res, next) {
conn.executeQuery("SELECT CONCAT(substr(replace(CUSTOMER_NM,\' \',\'\'),1,3), LEGAL_NO) as customerCode FROM mes.customer_master", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
/* 고객의 회사명 가져오기 */
router.get('/api/get_customer_masterName', function(req, res, next) {
conn.executeQuery("SELECT CUSTOMER_NM as customerName FROM mes.customer_master", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
/* 공통 코드 상세 정보 가져오기 */
router.post('/api/getCommCode/:codeNo', function(req, res, next) {
let M_CODE = req.params.codeNo;
console.log ("getCommCode/:codeNo.js >>>>>1 " + M_CODE)
conn.executeQueryTx("SELECT CM.IO_CODE_NM, CD.IO_CODE_D, CD.IO_CODE_D_NM FROM C_CODE_D CD, C_CODE_M CM WHERE CD.IO_CODE_M = CM.IO_CODE_M AND CM.IO_CODE_M = ? AND CD.USE_YN='Y' ORDER BY CD.IO_CODE_SEQ ASC ", M_CODE, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
/* 코드값에 의한 코드명 가져오기 */
router.post('/api/getCommCodeName/:codeNo', function(req, res, next) {
let M_CODE = req.params.codeNo;
console.log ("getCommCodeName/:codeNo.js >>>>>1 " + M_CODE)
conn.executeQueryTx("SELECT CM.IO_CODE_NM FROM C_CODE_D CD, C_CODE_M CM WHERE CD.IO_CODE_M = CM.IO_CODE_M AND CM.IO_CODE_M = ? AND CD.USE_YN='Y' ORDER BY CD.IO_CODE_SEQ ASC ", M_CODE, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
/*
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Express server listening on port " + port + ".");
});
}
*/
router.get('/api/getProjectInfo', function(req, res, next) {
console.log ("getProjectInfo.js /api/getProjectInfo >>>>>1 ")
conn.executeQuery("SELECT NO, PROJECT_CD, PROJECT_NM, MODEL_NM, ATTRIBUTE, \
SORT_ORDER, PROJECT_EMP_NO, PROJECT_CUSTOMER_ID, \
CAVITY, CAD AS CAD_MGR_NM, CAM AS CAM_MGR_NM, PROJECT_MATERIAL, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM, PROJECT_IMG \
FROM MES.PROJECT_MASTER ", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getProjectInfo/:projectCd', function(req, res, next) {
let projectCd = req.params.projectCd;
//console.log ("getProjectInfo/:projectCd.js >>>>>1 " + projectCd)
conn.executeQueryTx("SELECT A.*, B.* FROM PROJECT_MASTER A, PROJECT_DESC B WHERE A.PROJECT_CD = B.PROJECT_CD AND A.PROJECT_CD = ? ", projectCd, function(result){
console.log("In Index projectInfo : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.get('/api/getWorkInfoSearch', function(req, res, next) {
console.log ("getWorkNmSearch.js /api/getWorkInfoSearch >>>>>1 ")
conn.executeQuery("SELECT IO_CODE_SEQ AS NO, IO_CODE_D AS WORK_CD , IO_CODE_D_NM AS WORK_NM, \
IO_ATTRIBUTE \
FROM MES.C_CODE_D WHERE IO_CODE_M = 'P003' AND USE_YN = 'Y' ", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
var common_query = require('../common/common_query.js');
router.post('/', function(req, res, next) {
var type = req.param('type');
var tb_code = req.param('tb_code');
var field = req.param('field');
var value = req.param('value');
var condition = req.param('condition');
var queryStr = common_query.fn_makeCommonQuery(type,tb_code,field,value,condition);
conn.executeQuery(queryStr, function(result){
console.log("In Index1 : " + JSON.stringify(result));
//res.render('index', { title: 'Express1' });
res.send(JSON.stringify(result));
/*
res.send(body), res.send(status, body) : 클라이언트에 응답을 보냄. 상태 코드는 옵션. 기본 콘텐츠 타입은 text/html이므로 text/plain을 보내려면 res.set(‘Content-Type’, ‘text/plain’)을 먼저 호출 해야한다. JSON을 보낼거면 res.json을 쓰자.
res.json(json), res.json(status, json) : 클라이언트로 JSON 값을 보냄.
*/
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
function defualtCallbackFunction(result){
if(result){
res.send(JSON.stringify(result));
}else{
res.send("FAIL");
}
}
router.get('/getVendorInfo', function(req, res, next) {
console.log(req);
conn.executeQuery("SELECT * FROM VENDOR_MASTER WHERE VENDOR_CD = 1" , function(result){
console.log(result);
res.send(JSON.stringify(result));
});
});
router.get('/getVendorList', function(req, res, next){
console.log("getVendorList *********************");
conn.executeQuery("SELECT VENDOR_NM AS Name, BOSS_NM AS Boss, MAIN_ADDR AS Addr, TEL_NO AS Tel, MGR_HP_NO AS Mgr FROM VENDOR_MASTER", function(result){
console.log("########## vendor list");
res.send(JSON.stringify(result));
});
});
router.post('/insertVendor', function(req, res, next){
var sql = "";
console.log("vendor insert");
// conn.executeQuery(sql, function(result){
// res.send(JSON.stringify(result));
// });
});
router.put('/putVendorInfo', function(req, res, next){
console.log("**** in putVendorInfo");
console.log("**** req : " + req);
var query = "INSERT INTO VENDOR_MASTER (VENDOR_CD, VENDOR_NM, LEGAL_NO, BOSS_NM, ATTRIBUTE, MAIN_ADDR, SUB_ADDR, "
+ "TEL_NO, FAX_NO, EMAIL_ADDR, MGR_HP_NO, MGR_TEL_NO, MGR_EMAIL_ADDR, VENDOR_GBN, USE_YN, CRT_BY, CRT_DTM) "
+ "VALUES "
+ "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// conn.executeQuery(queyr, param, function(result){
// res.send("success");
// };
res.send("OK");
});
router.get('/updateVendorInfo', function(req, res, next){
});
module.exports = router;<file_sep>/* const Promise = require("bluebird");
const pool = require("./config");
module.exports = {
constructor(pool){
this.pool = pool;
},
executeQuery(fn) {
Promise.using(this.pool.connect(), conn => {
fn(conn);
})
},
executeQueryTx(fn) {
Promise.using(this.pool.connect(), conn => {
conn.beginTransaction(txerr => {
fn(conn);
})
})
}
}
*/
let mysql = require('mysql');
let config = require('./config');
let conn = null;
function executeQuery(query, callback){
if(conn == null){
conn = mysql.createConnection(config.dbInfo);
}
console.log(query);
conn.query(query, function(err, rows, fields){
if(err) throw err;
callback(rows);
});
}
function executeQueryTx(query, param, callback){
if(conn == null){
conn = mysql.createConnection(config.dbInfo);
}
console.log(query);
conn.query(query, param, function(err, rows, fields){
if(err) throw err;
callback(rows);
});
}
module.exports = {
executeQuery: executeQuery,
executeQueryTx: executeQueryTx
} <file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.post('/api/putProcessCodeByProjectId', function(req, res, next) {
console.log ("putProcessCode.js /api/putProcessCodeByProjectId >>>>>1 >> ");
//cry_by / crt_dtm 은 추가해야함. mod_by, mod_dtm
// id Sequence 로직 수행 이후 적용
var processCodeInfo = req.body;
//project Id get
//array list
console.log ("/api/putProcessCodeSaveByProjectId : ");
console.log ("projectId : " + processCodeInfo.projectId + ":");
console.log ("processId : " + processCodeInfo.processCodeId+ ":");
console.log ("processName : " + processCodeInfo.processCodeName+ ":");
//mes.get_seq('seq_processIdByProjectId')
//INSERT INTO mes.process_real_desc
//(`NO`, PROCESS_CD, PROCESS_NM, seq_process_no, WORK_CD, PROJECT_CD, real_work_count, real_start_dt, real_finish_dt, process_hour, PROCESS_min, other_process_hour, other_process_min, self_process_hour, self_process_min, `ATTRIBUTE`, finish_stat, start_yn, finish_yn, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM)
//VALUES(0, '', '', 0, '', '', 0, '', '', 0, 0, 0, 0, 0, 0, '', '', '', '', '', '', '', '');
conn.executeQueryTx("INSERT INTO mes.process_plan_desc \
(`NO`, PROCESS_CD, PROCESS_NM, PROJECT_CD, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM ) \
VALUES (mes.get_seq('seq_processIdByProjectId'), ?, ?, ?, ?, now(), ?, now() ) ",
[ processCodeInfo.processCodeId, processCodeInfo.processCodeName, processCodeInfo.projectId ,'SYSTEM','SYSTEM'],
function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.post('/api/delProcessCodeRealByProjectId', function(req, res, next) {
console.log ("putProcessCode.js /api/delProcessCodeRealByProjectId >>>>>1 >> ");
//cry_by / crt_dtm 은 추가해야함. mod_by, mod_dtm
// id Sequence 로직 수행 이후 적용
var processCodeInfo = req.body;
//project Id get
//array list
console.log ("/api/delProcessCodeRealByProjectId : ");
console.log ("projectId : " + processCodeInfo.projectId + ":");
console.log ("processId : " + processCodeInfo.processCodeId+ ":");
console.log ("processName : " + processCodeInfo.processCodeName+ ":");
//mes.get_seq('seq_processIdByProjectId')
//INSERT INTO mes.process_real_desc
//(`NO`, PROCESS_CD, PROCESS_NM, seq_process_no, WORK_CD, PROJECT_CD, real_work_count, real_start_dt, real_finish_dt, process_hour, PROCESS_min, other_process_hour, other_process_min, self_process_hour, self_process_min, `ATTRIBUTE`, finish_stat, start_yn, finish_yn, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM)
//VALUES(0, '', '', 0, '', '', 0, '', '', 0, 0, 0, 0, 0, 0, '', '', '', '', '', '', '', '');
conn.executeQueryTx(" DELETE FROM mes.process_plan_desc \
WHERE PROCESS_CD = ? AND PROJECT_CD = ? ",
[ processCodeInfo.processCodeId, processCodeInfo.projectId ],
function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.post('/api/putProcessMasterByProjectId', function(req, res, next) {
console.log ("putProcessMaster.js /api/putProcessCodeByProjectId >>>>>1 >> ");
//cry_by / crt_dtm 은 추가해야함. mod_by, mod_dtm
// id Sequence 로직 수행 이후 적용
var processCodeInfo = req.body;
//project Id get
//array list
console.log ("/api/putProcessMasterSaveByProjectId : ");
console.log ("projectId : " + processCodeInfo.projectId + ":");
console.log ("processId : " + processCodeInfo.processCodeId+ ":");
console.log ("processName : " + processCodeInfo.processCodeName+ ":");
//mes.get_seq('seq_processIdByProjectId')
//INSERT INTO mes.process_real_desc
//(`NO`, PROCESS_CD, PROCESS_NM, seq_process_no, WORK_CD, PROJECT_CD, real_work_count, real_start_dt, real_finish_dt, process_hour, PROCESS_min, other_process_hour, other_process_min, self_process_hour, self_process_min, `ATTRIBUTE`, finish_stat, start_yn, finish_yn, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM)
//VALUES(0, '', '', 0, '', '', 0, '', '', 0, 0, 0, 0, 0, 0, '', '', '', '', '', '', '', '');
conn.executeQueryTx("INSERT INTO mes.process_master \
(`NO`, PROCESS_CD, PROCESS_NM, SEQ_PROCESS_NO, WORK_CD, \
PROJECT_CD, `DEPTH`, PROCESS_GBN, PROCESS_REQ_NO, \
PROCESS_EMP_NO, PROCESS_COMP_NO, PROCESS_COMP_GBN, \
START_DT, FINISH_DT, EQUIPMENT_CD, MATERIAL_CD, \
PART_CD, COMPRESS_RATE, CAVITY, MOD_BY, MOD_DTM ) \
ON DUPLICATE KEY UPDATE \
VALUES (mes.get_seq('seq_processIdByProjectId'), ?, ?, ?, ?, now(), ?, now() \
'NO'= ? , PROCESS_CD=?, PROCESS_NM=?, SEQ_PROCESS_NO = mes.get_seq('seq_processIdByProjectId'), \
PROCESS_EMP_NO =? ",
[ processCodeInfo.processCodeId, processCodeInfo.processCodeName, processCodeInfo.projectId ,'SYSTEM','SYSTEM'],
function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.post('/api/putProcessPlanByProjectId', function(req, res, next) {
console.log ("putProcessPlan.js /api/putProcessPlanByProjectId >>>>>1 >> ");
//cry_by / crt_dtm 은 추가해야함. mod_by, mod_dtm
// id Sequence 로직 수행 이후 적용
var processCodeInfo = req.body;
//project Id get
//array list
console.log ("/api/putProcessPlanByProjectId : ");
console.log ("projectId : " + processCodeInfo.projectId + ":");
console.log ("processId : " + processCodeInfo.processCodeId+ ":");
console.log ("processName : " + processCodeInfo.processCodeName+ ":");
//mes.get_seq('seq_processIdByProjectId')
//INSERT INTO mes.process_real_desc
//(`NO`, PROCESS_CD, PROCESS_NM, seq_process_no, WORK_CD, PROJECT_CD, real_work_count, real_start_dt, real_finish_dt, process_hour, PROCESS_min, other_process_hour, other_process_min, self_process_hour, self_process_min, `ATTRIBUTE`, finish_stat, start_yn, finish_yn, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM)
//VALUES(0, '', '', 0, '', '', 0, '', '', 0, 0, 0, 0, 0, 0, '', '', '', '', '', '', '', '');
conn.executeQueryTx("INSERT INTO mes.process_plan_desc \
(`NO`, PROCESS_CD, PROCESS_NM, PROJECT_CD, CRT_BY, CRT_DTM, MOD_BY, MOD_DTM ) \
VALUES (mes.get_seq('seq_processIdByProjectId'), ?, ?, ?, ?, now(), ?, now() ) ",
[ processCodeInfo.processCodeId, processCodeInfo.processCodeName, processCodeInfo.projectId ,'SYSTEM','SYSTEM'],
function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.post('/api/getCommCode/:codeNo', function(req, res, next) {
let M_CODE = req.params.codeNo;
console.log ("getCommCode/:codeNo.js >>>>>1 " + M_CODE)
conn.executeQueryTx("SELECT CM.IO_CODE_NM, CD.IO_CODE_D, CD.IO_CODE_D_NM FROM C_CODE_D CD, C_CODE_M CM WHERE CD.IO_CODE_M = CM.IO_CODE_M AND CM.IO_CODE_M = ? AND CD.USE_YN='Y' ORDER BY CD.IO_CODE_SEQ ASC ", M_CODE, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getCommCodeName/:codeNo', function(req, res, next) {
let M_CODE = req.params.codeNo;
console.log ("getCommCodeName/:codeNo.js >>>>>1 " + M_CODE)
conn.executeQueryTx("SELECT CM.IO_CODE_NM FROM C_CODE_D CD, C_CODE_M CM WHERE CD.IO_CODE_M = CM.IO_CODE_M AND CM.IO_CODE_M = ? AND CD.USE_YN='Y' ORDER BY CD.IO_CODE_SEQ ASC ", M_CODE, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
router.get('/api/getSeqId/:seqName', function(req, res, next) {
let SEQ_NAME = req.params.seqName;
console.log ("getCommCodeName/:getSeqId.js >>>>>1 " + SEQ_NAME)
conn.executeQueryTx("SELECT ID AS SEQ_ID FROM MASTER_SEQ WHERE SEQ_NAME = ? ", SEQ_NAME, function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn');
var config = require('../util/config');
var jwt = require('jsonwebtoken');
const passport = require('passport');
const passportJWT = require('passport-jwt');
let ExtractJwt = passportJWT.ExtractJwt;
let JwtStrategy = passportJWT.Strategy;
let jwtOptions = {};
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
jwtOptions.secretOrKey = config.secret;
jwtOptions.expiresIn = 60 * 30; // 30 min
console.log('333 payload received');
// lets create our strategy for web token
// let strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
// console.log('payload received', jwt_payload);
// let user = getUser({ id: jwt_payload.id });
// if (user) {
// next(null, user);
// } else {
// next(null, false);
// }
// passport.use(strategy);
// return {
// initialize: function () {
// return passport.initialize();
// },
// authenticate: function () {
// return passport.authenticate('jwt', config.jwtSession);
// }
// };
// });
/* GET Login page. */
router.post('/api/loginInfo', function(req, res, next) {
console.log ("loginInfo.js >>>>>0 ")
let user = req.body.empNo;
let pword = req.body.<PASSWORD>;
console.log ("loginInfo.js >>>>>1 " + user + ":" + pword)
conn.executeQueryTx("SELECT count(*) as cnt , name FROM IO_EMP WHERE EMP_NO = ? AND PASSWORD = ?",[user,pword],
function(result){
console.log("In Index111 : " + JSON.stringify(result));
console.log("In Index222 : " + JSON.parse(JSON.stringify(result))[0].cnt);
let resultCnt = JSON.parse(JSON.stringify(result))[0].cnt;
// console.log("In Index333 : " + JSON.parse(JSON.stringify(result))[0].cnt);
if(resultCnt > 0) { //정상 처리 되었을때
// if(result.status === 200) { //정상 처리 되었을때
// console.log("In Index222 : { cnt: result.cnt } : " + JSON.parse(JSON.stringify(result))[0].cnt );
// console.log("In Index333 : { name: result.name } : " + JSON.parse(JSON.stringify(result))[0].name);
let resultName = JSON.parse(JSON.stringify(result))[0].name;
let payload = { id: user , name: resultName };
let token = jwt.sign(payload, jwtOptions.secretOrKey , { expiresIn : 60 * 30 });
res.send({ user: payload, token: token });
} else {
throw new Error('login failed')
}
}
);
});
router.post('/api/loginInfo/22', function(request, response, next) {
var token = request.headers.accesstoken;
if(typeof token !== 'undefined'){
console.log ("loginInfo/22 >>>>> 3 " + config.secret)
console.log ("loginInfo/22 >>>>> 4 " + request.headers.accesstoken)
var decoded = jwt.verify(token, jwtOptions.secretOrKey);
console.log ("loginInfo/22 >>>>> 5 " + decoded.id)
response.send({
"data" : {
"id" : decoded.id,
"name" : decoded.name
}
});
console.log ("loginInfo/22 >>>>> 6 " + decoded.name)
}else{
response.sendStatus(403);
}
// let accessToken = JSON.parse(JSON.stringify(req.headers)).access-token;
// if(JSON.parse(JSON.stringify(req.headers)).access-token != null) {
// res.send({
// "data" : {
// "token" : accessToken
// }
// });
// } else {
// throw new Error('login failed')
// }
});
module.exports = router;<file_sep>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var admKeyRouter = require('./routes/admKey');
var customerInfoIndexRouter = require('./routes/customerInfo/index'); //./routes/customerInfo/index.js
var customerInfoUsersRouter = require('./routes/customerInfo/users'); //./routes/customerInfo/users.js
// 사원정보 관리
var rEmpInfo = require('./routes/empInfo/getEmpInfo'); //./routes/customerInfo/index.js
var cEmpInfo = require('./routes/empInfo/setEmpInfo'); //./routes/customerInfo/users.js
var uEmpInfo = require('./routes/empInfo/updEmpInfo'); //./routes/customerInfo/users.js
var dEmpInfo = require('./routes/empInfo/delEmpInfo'); //./routes/customerInfo/users.js
// 공통 쿼리
var callDirectQuery = require('./routes/common/callDirectQuery'); //./routes/common/callDirectQuery.js
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api/admKey', admKeyRouter);
app.use('/api/empInfo/getEmpInfo', rEmpInfo);
app.use('/api/empInfo/setEmpInfo', cEmpInfo);
app.use('/api/empInfo/updEmpInfo', uEmpInfo);
app.use('/api/empInfo/delEmpInfo', dEmpInfo);
app.use('/api/common/callDirectQuery', callDirectQuery);
//http:localhost:3000/api
//http:localhost:3000/api/users
app.head("/api", cors(), (req, res) => {
console.info("HEAD /api");
res.sendStatus(204);
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
<file_sep>const constants = {
'menu': '메뉴',
'test_title': '실습'
}<file_sep>let dbInfo = {
host: 'localhost',
port: '3306',
user: 'huetech',
password: <PASSWORD>',
database: 'mes'
}
function test(){
console.log('test');
}
module.exports = {
dbInfo: dbInfo,
test: test,
secret: 'HueTECHmeSERversySTEM!!',
jwtSession: { session: true }
}<file_sep>var express = require('express');
var router = express.Router();
var conn = require('../util/dbConn.js');
var conf = require('../util/config');
router.get('/api/getPartInfoSearch', function(req, res, next) {
console.log ("getPartInfoSearch.js /api/getPartInfoSearch >>>>>1 ")
conn.executeQuery("SELECT NO, PART_CD, PART_NM , SERIAL_NO, MODEL_NO,\
PART_SPEC, UNIT, MGR_EMP_NO, PURCHASE_NO, ATTRIBUTE, \
CRT_BY, CRT_DTM, MOD_BY, MOD_DTM \
FROM MES.PART_MASTER", function(result){
console.log("In Index : " + JSON.stringify(result));
res.send(JSON.stringify(result));
});
});
module.exports = router;
| 40b62669fb93c825d46a6990613677cdf0dd170a | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | maruhong/huetechMES_SERVER | d31e78afe2709d26a3f77cc9838b790246d20e09 | 7cd33e7f05feff24da58d6b5f0cc2587af1fbc11 |
refs/heads/master | <repo_name>houfio/psychopomp<file_sep>/src/createPsychopomp.ts
import { createDakpan } from 'dakpan';
import { createElement, ReactNode } from 'react';
import { Psychopomp as Component } from './Psychopomp';
export const createPsychopomp = () => {
const { Provider, withDakpan } = createDakpan({
index: 0,
steps: []
})({
nextIndex: () => ({ index, steps }) => ({
index: Math.min(index + 1, steps.length - 1)
}),
previousIndex: () => ({ index }) => ({
index: Math.max(0, index)
})
});
const Psychopomp = ({ children }: { children: ReactNode }) => createElement(
Provider,
null,
createElement(withDakpan(() => ({}))(Component)),
children
);
return {
Psychopomp,
withPsychopomp: withDakpan
};
};
<file_sep>/README.md
# Psychopomp [](https://www.npmjs.com/package/psychopomp)
Pretty walkthroughs for React applications.
## Install
```
npm install psychopomp
```
or
```
yarn add psychopomp
```
## Example
## Documentation
<file_sep>/src/index.ts
export { createPsychopomp } from './createPsychopomp';
| 901b6836d50d49dd59477c9ec8f0f743741e3d71 | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | houfio/psychopomp | 4c7ca218da0a456366f3080df5102abe503102b8 | 99975b4fe6e7533136c18a6d033c7e1a39221b97 |
refs/heads/master | <file_sep>class AddRentToProperty < ActiveRecord::Migration
def change
add_column :properties, :rent, :decimal, :precision => 6, :scale => 2
end
end
<file_sep>class PostsController < ApplicationController
before_action :authenticate_user!
respond_to :html
def show
@forum = Forum.find(params[:forum_id])
@post = Post.find(params[:id])
@comment = Comment.new
respond_with(@forum, @post, @comment)
end
def new
@forum = Forum.find(params[:forum_id])
@post = Post.new
respond_with(@forum, @post)
end
def create
@forum = Forum.find(params[:forum_id])
@post = Post.new(post_params)
@post.user_id = current_user.id
@post.forum_id = @forum.id
if @post.save
redirect_to forum_post_path(@forum, @post), notice: 'Post created successfully.'
else
flash[:alert] = @post.errors.full_messages.join(', ')
respond_with(@post)
end
end
def edit
@property = Property.find(params[:id])
respond_with(@property)
end
def update
@property = Property.find(params[:id])
@property.update_attributes(post_params)
if @property.save
redirect_to @property, notice: 'Property updated successfully.'
else
flash[:alert] = @property.errors.full_messages.join(', ')
respond_with @property
end
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
<file_sep>class LandingsController < ApplicationController
respond_to :html
def index
end
end<file_sep>class AddLandlordToProperty < ActiveRecord::Migration
def change
add_column :properties, :landlord_name, :string
add_column :properties, :landlord_phone, :string
add_column :properties, :landlord_email, :string
end
end
<file_sep>class DashboardsController < ApplicationController
before_action :authenticate_user!
respond_to :html
def index
if current_user.has_current_property?
redirect_to current_user.current_property
else
redirect_to new_property_path
end
end
end
<file_sep>every 1.minute do
runner "UtilityWorker.send_reminder"
end
<file_sep>require 'twilio-ruby'
class UtilityWorker
def self.send_reminder
@client = Twilio::REST::Client.new('<KEY>',
'fcb120473bc35632c6c98a2c786e6f0e')
@account = @client.accounts.get('<KEY>')
@account.messages.create(
from: '+12314217812',
to: '+19894827371',
body: 'Your utility bill is due in a week.'
)
end
end
<file_sep>require 'open-uri'
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
TEMP_EMAIL = '<EMAIL>'
TEMP_EMAIL_REGEX = /<EMAIL>/
has_many :properties
has_many :roommates
has_many :dues
has_many :posts
has_many :comments
has_attached_file :profile, default_url: 'profile.jpg'
validates_attachment_content_type :profile, :content_type => /\Aimage\/.*\Z/
devise :omniauthable
def self.find_for_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
if user
return user
else
registered_user = User.where(:email => auth.info.email).first
if registered_user
return registered_user
else
user = User.create(first_name:auth.extra.raw_info.first_name,
last_name:auth.extra.raw_info.last_name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email.blank? ? TEMP_EMAIL : auth.info.email,
password:<PASSWORD>[0,20],
token: auth.credentials.token,
)
end
end
user
end
def recent_payments
uri = URI("https://api.venmo.com/v1/payments?access_token=#{self.token}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
response.body
end
def pay_user(user, note, amount)
uri = URI('https://api.venmo.com/v1/payments')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path)
data = {
access_token: <PASSWORD>.token,
email: user.email,
note: note,
amount: amount
}
ap data.to_query
request.body = data.to_query
http.request(request)
end
def current_property
end_field = RentalTerm.arel_table[:end_date]
user_field = RentalTerm.arel_table[:user_id]
RentalTerm.where(end_field.gteq(Date.current).and(user_field.eq(self.id))).first.try(:property)
end
def current_dues
self.dues.where(paid: false)
end
def past_dues
self.dues.where(paid: true)
end
def has_dues?
self.current_dues.any?
end
def current_amount_due
self.current_dues.pluck(:amount).reduce(:+)
end
def has_current_property?
self.current_property.present?
end
def name
"#{first_name} #{last_name}"
end
def display_name
if first_name
first_name
else
email
end
end
end
<file_sep># Notes
Project idea is a rental and landlord review system targeted at college
students.
- When making account, also add house and link with roommates
- Ensure uniqueness of properties/landlords
- Add ability to share bills with roommates
- Integrate with Venmo and DTE?
- Forum for situations with landlords and other related things
- List legal rights by state, show to user
- Show properties by location, price, w or w/o utilities, landlord
- Allow picture upload
## MUST BE SEXY
Parts of application:
1. Reviews
2. Issues/property discussion forum
3. Bill sharing
<file_sep>Rails.application.routes.draw do
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
get '/auth/venmo/callback' => 'users/omniauth_callbacks#venmo'
root to: 'dashboards#index'
resources :landings, only: [:index]
resources :properties do
resources :issues, except: [:index] do
post :fix
end
resources :utilities do
post :pay
end
resources :rental_terms, only: [:new, :create, :edit, :update]
end
resources :users, only: [:show, :edit, :update]
resources :forums, only: [:show, :index] do
resources :posts, only: [:show, :new, :create]
end
resources :posts, only: [] do
resources :comments, only: [:create]
end
end
<file_sep>User.delete_all
Property.delete_all
RentalTerm.delete_all
Issue.delete_all
Utility.delete_all
Due.delete_all
Forum.delete_all
Post.delete_all
Comment.delete_all
jsvana = User.create!(
email: '<EMAIL>',
password: '<PASSWORD>',
first_name: 'Jay',
last_name: 'Vana'
)
rex = User.create!(
email: '<EMAIL>',
password: '<PASSWORD>',
first_name: 'Rex',
last_name: 'Baumeister'
)
phil = User.create!(
email: '<EMAIL>',
password: '<PASSWORD>',
first_name: 'Phil',
last_name: 'Middleton'
)
hubbell = Property.create!(
name: '<NAME>',
address: '216 Hubbell St, Houghton, MI 49931',
description: 'Dank place yo',
user: jsvana,
landlord_name: '<NAME>',
landlord_email: '<EMAIL>',
landlord_phone: '555.555.5555',
rent: 350.0
)
RentalTerm.create!(
user: jsvana,
property: hubbell,
start_date: Date.current - 1.year,
end_date: Date.current,
comments: 'Best haus evar',
property_rating: 4,
landlord_rating: 1
)
RentalTerm.create!(
user: phil,
property: hubbell,
start_date: Date.current - 1.year,
end_date: Date.current,
comments: "It's alright.",
property_rating: 3,
landlord_rating: 1
)
RentalTerm.create!(
user: rex,
property: hubbell,
start_date: Date.current - 2.year,
end_date: Date.current - 1.year,
comments: 'Worst haus evar',
property_rating: 3,
landlord_rating: 3
)
Issue.create!(
property: hubbell,
description: 'Stove is broken.',
fixed: true,
user: jsvana
)
Issue.create!(
property: hubbell,
description: 'Windows are cracked.',
fixed: false,
user: rex
)
Issue.create!(
property: hubbell,
description: 'Skunk lives under the deck.',
fixed: false,
user: rex
)
dte = Utility.create(
property: hubbell,
provider: 'DTE',
due_by: Date.current + 3.weeks,
cost: 117
)
Due.create(
user: jsvana,
utility: dte,
amount: dte.cost / 2
)
Due.create(
user: rex,
utility: dte,
amount: dte.cost / 2
)
#############
# Forum Stuff
#############
assistance = Forum.create(
name: 'Needing Assistance'
)
diy = Forum.create(
name: 'DIY Help'
)
bad = Post.create(
forum: assistance,
user: phil,
title: 'Roommates not working out. Help?',
body: 'Started out the year and my roommates were great. Recently, though, they started not helping out (cleaning and other chores) and are generally being negative. What can I do?',
)
sink = Post.create(
forum: diy,
user: jsvana,
title: 'Looking to fix the plumbing.',
body: "Anyone here have experience with plumbing? Our sink has something wrong with it and I'd like to fix it (landlord is not responding)."
)
Post.create(
forum: diy,
user: rex,
title: 'Just built a loft. Looking for feedback.',
body: "I just finished building a loft. Seems pretty stable, but looking for advice on making it more stable."
)
Comment.create(
post: bad,
user: rex,
content: 'Have you talked to them?'
)
Comment.create(
post: bad,
user: phil,
content: "I have, but they don't seem to care."
)
Comment.create(
post: sink,
user: phil,
content: "I would recommend having somebody trained fix it. I had an issue with my sink and nearly broke it when I tried to fix it."
)
<file_sep>class RentalTerm < ActiveRecord::Base
belongs_to :user
belongs_to :property
has_many :roommates
validates :user_id, :property_id, :start_date, :end_date, :property_rating,
:landlord_rating, presence: true
validates_numericality_of :property_rating, in: 1..5
validates_numericality_of :landlord_rating, in: 1..5
#validates_date :start_date, before: :end_date
validate :end_after_start
private
def end_after_start
return if end_date.blank? || start_date.blank?
if end_date <= start_date
errors.add(:end_date, "must be after the start date")
end
end
end
<file_sep>class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def venmo
if current_user
auth = request.env['omniauth.auth']
current_user.provider = auth.provider
current_user.uid = auth.uid
current_user.token = auth.credentials.token
current_user.save
redirect_to edit_user_path(current_user), notice: 'Venmo account linked successfully.'
else
@user = User.find_for_oauth(request.env["omniauth.auth"], current_user)
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication
set_flash_message(:notice, :success, :kind => "Venmo") if is_navigational_format?
else
session["devise.twitter_uid"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
end
<file_sep>class IssuesController < ApplicationController
before_action :authenticate_user!
respond_to :html
def new
@issue = Issue.new
@property = Property.find(params[:property_id])
respond_with(@issue, @property)
end
def create
@property = Property.find(params[:property_id])
@issue = Issue.create(issue_params)
@issue.property_id = @property.id
@issue.user_id = current_user.id
if @issue.save
redirect_to @property, notice: 'Issue added successfully.'
else
flash[:alert] = @issue.errors.full_messages.join(', ')
respond_with(@issue)
end
end
def fix
@property = Property.find(params[:property_id])
@issue = Issue.find(params[:issue_id])
@issue.fixed = true
@issue.save
redirect_to @property, notice: 'Issue marked as fixed.'
end
private
def issue_params
params.require(:issue).permit(:description)
end
end
<file_sep>class Property < ActiveRecord::Base
belongs_to :user
has_many :rental_terms
has_many :users, through: :rental_terms
has_many :issues
has_many :utilities
validates :address, :landlord_name, :rent, presence: true
has_attached_file :image, default_url: 'house_placeholder.jpg'
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
def current_occupants
end_field = RentalTerm.arel_table[:end_date]
property_field = RentalTerm.arel_table[:property_id]
RentalTerm.where(end_field.gteq(Date.current).and(property_field.eq(self.id))).map(&:user).uniq
end
def is_current_occupant?(user)
self.current_occupants.include?(user)
end
def current_term_for(user)
self.rental_terms.where(user: user).order(end_date: :desc).first
end
def has_terms?
self.rental_terms.count > 0
end
def average_property_rating
self.rental_terms.pluck(:property_rating).reduce(:+) / self.rental_terms.count
end
def average_landlord_rating
self.rental_terms.pluck(:landlord_rating).reduce(:+) / self.rental_terms.count
end
def comments
self.rental_terms.pluck(:comments)
end
def fixed_issues
self.issues.where(fixed: true)
end
def outstanding_issues
self.issues.where(fixed: false)
end
end
<file_sep>class RentalTermsController < ApplicationController
before_action :authenticate_user!
respond_to :html
def new
@property = Property.find(params[:property_id])
@rental_term = RentalTerm.new
respond_with(@property, @rental_term)
end
def create
@property = Property.find(params[:property_id])
@rental_term = RentalTerm.new(rental_term_params)
@rental_term.user_id = current_user.id
@rental_term.property_id = @property.id
if @rental_term.save
redirect_to @property, notice: 'Rental term added successfully'
else
flash[:alert] = @rental_term.errors.full_messages.join(', ')
respond_with(@rental_term)
end
end
def edit
@property = Property.find(params[:property_id])
@rental_term = RentalTerm.find(params[:id])
respond_with(@property, @rental_term)
end
def update
@property = Property.find(params[:property_id])
@rental_term = RentalTerm.find(params[:id])
@rental_term.update_attributes(rental_term_params)
if @rental_term.save
redirect_to @property, notice: 'Rental term updated successfully.'
else
flash[:alert] = @rental_term.errors.full_messages.join(', ')
respond_with(@rental_term)
end
end
private
def rental_term_params
params.require(:rental_term).permit(:start_date, :end_date, :comments,
:property_rating, :landlord_rating)
end
end
<file_sep>class UtilitiesController < ApplicationController
before_action :authenticate_user!
respond_to :html
def index
@property = Property.find(params[:property_id])
respond_with(@property)
end
def show
@utility = Utility.find(params[:id])
respond_with(@utility)
end
def new
@utility = Utility.new
@property = Property.find(params[:property_id])
respond_with(@utility, @property)
end
def create
@utility = Utility.new(utility_params)
@property = Property.find(params[:property_id])
@utility.property_id = @property.id
if @utility.save
occupants = @property.current_occupants
occupants.each do |occupant|
Due.create(
user_id: occupant.id,
utility_id: @utility.id,
amount: @utility.cost / occupants.count
)
end
redirect_to property_utilities_path(@property), notice: 'Utility added successfully.'
else
flash[:alert] = @utility.errors.full_messages.join(', ')
respond_with(@utility)
end
end
def pay
due = Due.find_by(user_id: current_user.id, utility_id: params[:utility_id])
due.paid = true
due.save
redirect_to property_utilities_path(current_user.current_property),
notice: "#{due.utility.provider} bill paid."
end
private
def utility_params
params.require(:utility).permit(:provider, :due_by, :cost)
end
end
<file_sep>class ForumsController < ApplicationController
before_action :authenticate_user!
respond_to :html
def index
@forums = Forum.all
respond_with(@forums)
end
def show
@forum = Forum.find(params[:id])
respond_with(@forum)
end
end
<file_sep>class PropertiesController < ApplicationController
before_action :authenticate_user!
respond_to :html
def index
@properties = Property.all
respond_with(@properties)
end
def show
@property = Property.find(params[:id])
respond_with(@property)
end
def new
@property = Property.new
respond_with(@property)
end
def create
@property = Property.new(property_params)
@property.user_id = current_user.id
if @property.save
redirect_to @property, notice: 'Property added successfully.'
else
flash[:alert] = @property.errors.full_messages.join(', ')
respond_with(@property)
end
end
def edit
@property = Property.find(params[:id])
respond_with(@property)
end
def update
@property = Property.find(params[:id])
@property.update_attributes(property_params)
if @property.save
redirect_to @property, notice: 'Property updated successfully.'
else
flash[:alert] = @property.errors.full_messages.join(', ')
respond_with(@property)
end
end
private
def property_params
params.require(:property).permit(:name, :address, :description,
:landlord_name, :landlord_phone,
:landlord_email, :image, :rent)
end
#def rental_term_params
#params.require(:rental_term).permit(:end_date, :start_date, :comments,
#:property_rating, :landlord_rating)
#end
end
<file_sep>class UsersController < ApplicationController
before_action :authenticate_user!
respond_to :html
def show
@user = User.find(params[:id])
respond_with(@user)
end
def edit
@user = User.find(params[:id])
respond_with(@user)
end
def update
@user = User.find(params[:id])
@user.update_attributes(user_params)
if @user.save
redirect_to @user, notice: 'Profile updated successfully.'
else
flash[:alert] = @user.errors.full_messages.join(', ')
respond_with(@user)
end
end
private
def user_params
params.require(:user).permit(:email, :first_name, :last_name, :profile)
end
end
<file_sep>class AddRatingsToRentalTerm < ActiveRecord::Migration
def change
add_column :rental_terms, :property_rating, :integer
add_column :rental_terms, :landlord_rating, :integer
end
end
<file_sep>class CommentsController < ApplicationController
before_action :authenticate_user!
respond_to :html
def create
@post = Post.find(params[:post_id])
@forum = @post.forum
@comment = Comment.new(comment_params)
@comment.post_id = @post.id
@comment.user_id = current_user.id
if @comment.save
redirect_to forum_post_path(@forum, @post), notice: 'Comment added successfully.'
else
flash[:alert] = @comment.errors.full_messages.join(', ')
respond_with(@comment)
end
end
private
def comment_params
params.require(:comment).permit(:content)
end
end
<file_sep>class Roommate < ActiveRecord::Base
belongs_to :user
belongs_to :roommate, class_name: 'User'
belongs_to :rental_term
end
<file_sep>class Utility < ActiveRecord::Base
belongs_to :property
has_many :dues
def per_occupant_cost
self.cost / self.property.current_occupants.count
end
end
<file_sep>class Due < ActiveRecord::Base
belongs_to :user
belongs_to :utility
end
| 9b001f1bb2cabca6d9c44e8dffa1546c790ce839 | [
"Markdown",
"Ruby"
] | 25 | Ruby | jsvana/rentelligently | 6a1586bf2dcfe2a5a2a5c8e08bf1cec4bf215d8b | 8d3eed098d34697b98e1e97d1805221479f1696c |
refs/heads/master | <file_sep>import argparse
import cv2
import sys
import os
import fnmatch
import re
ap = argparse.ArgumentParser()
ap.add_argument('-id', '--idir', required = True, help = 'Path to image')
args = vars(ap.parse_args())
## a function you may want to use in debugging
def display_image_pix(image, h, w):
image_pix = list(image)
for r in xrange(h):
for c in xrange(w):
print list(image_pix[r][c]), ' ',
print
## luminosity conversion
def luminosity(rgb, rcoeff=0.2126, gcoeff=0.7152, bcoeff=0.0722):
return rcoeff*rgb[0]+gcoeff*rgb[1]+bcoeff*rgb[2]
def compute_avrg_luminosity(imagepath):
im = cv2.imread(imagepath)
(x, y, z) = im.shape
imSz = x*y
total = 0
for i in xrange(x):
for j in xrange(y):
total = total+luminosity(im[i][j])
return total/imSz
def gen_avrg_lumin_for_dir(imgdir, filepat):
#for imgname in fnmatch.filter(imgdir ,filepat):
#imgpath = os.path.join(root, imgname)
for root, dirs, files in os.walk(imgdir):
for filename in fnmatch.filter(files, filepat):
imgpath = os.path.join(root,filename)
avl=compute_avrg_luminosity(str(imgpath))
yield filename, avl
## run ghe generator and output into STDOUT
for fp, lum_avrg in gen_avrg_lumin_for_dir(args['idir'], r'*.png'):
sys.stdout.write(fp + '\t' + str(lum_avrg) + '\n')
sys.stdout.flush()
<file_sep>##Yes, luminosity and temp are positively correlated r = .905. This makes sense since bright days tend to be warmer.
import argparse
import cv2
import sys
import os
import fnmatch
import re
ap = argparse.ArgumentParser()
ap.add_argument('-lf', '--lum_file', required = True, help = 'Path to lum file')
ap.add_argument('-tf', '--temp_file', required = True, help = 'Path to temp file')
args = vars(ap.parse_args())
## define regexes
lum_entry_pat = r'(?:.*_)(\d\d)(?:-\d\d-\d\d\.\w+\s*)(\d+\..*)'
temp_entry_pat = r'(?:.*_)(\d\d)(?:-\d\d-\d\d\s)(\d+\..*)'
## define two dictionaries
lum_tbl = {}
tmp_tbl = {}
with open(args['lum_file']) as infile:
for line in infile:
m = re.match(lum_entry_pat, line)
if m != None:
hr = m.group(1)
lum = m.group(2)
if hr in lum_tbl:
lum_tbl[hr].append(float(lum))
else:
lum_tbl[hr]=[float(lum)]
with open(args['temp_file']) as infile:
for line in infile:
m = re.match(temp_entry_pat, line)
if m != None:
hr = m.group(1)
tmp = m.group(2)
if hr in tmp_tbl:
tmp_tbl[hr].append(float(tmp))
else:
tmp_tbl[hr]=[float(tmp)]
## print tables and averages
print('Luminosity Table')
for h, lums in lum_tbl.items():
print h, '-->', str(lums)
print
print('Temperature Table')
for h, temps in tmp_tbl.items():
print h, '-->', str(temps)
print
print('Luminosity Averages')
for h, lums in lum_tbl.items():
print h, '-->', sum(lums)/len(lums)
print
print('Temperature Averages')
for h, temps in tmp_tbl.items():
print h, '-->', sum(temps)/len(temps)
print
<file_sep>#!/usr/bin/python3 ## print sum of integers in STDIN
import sys
print( sum([int(x) for x in sys.stdin.readlines()]))<file_sep>
from PySteppables import *
import CompuCell
import time
import sys
from PySteppablesExamples import MitosisSteppableBase
class ConstraintInitializerSteppable(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def start(self):
for cell in self.cellList:
cell.targetVolume=125
cell.lambdaVolume=2.0
class Root_Nodulation_3DSteppable(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def start(self):
# any code in the start function runs before MCS=0
pass
def step(self,mcs):
#type here the code that will run every _frequency MCS
for cell in self.cellList:
print "cell.id=",cell.id
def finish(self):
# Finish Function gets called after the last MCS
pass
class Switch(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def step(self,mcs):
for cell in self.cellList:
if cell.type == 2:
for neighbor, commonSurfaceArea in self.getCellNeighborDataList(cell):
if neighbor:
if neighbor.type==4 and mcs%25==0 and mcs>1:
cell.type = 5
class ElongationFlexSteppable(SteppableBasePy):
def __init__(self,_simulator,_frequency=10):
SteppableBasePy.__init__(self, _simulator, _frequency)
# self.lengthConstraintPlugin=CompuCell.getLengthConstraintPlugin()
def start(self):
pass
def step(self,mcs):
for cell in self.cellList:
if cell.type==4:
self.lengthConstraintPlugin.setLengthConstraintData(cell,20,20) # cell , lambdaLength, targetLength
self.connectivityGlobalPlugin.setConnectivityStrength(cell,10000000) #cell, strength
class MitosisSteppable(MitosisSteppableBase):
def __init__(self,_simulator,_frequency=1):
MitosisSteppableBase.__init__(self,_simulator, _frequency)
def step(self,mcs):
# print "INSIDE MITOSIS STEPPABLE"
cells_to_divide=[]
for cell in self.cellList:
if cell.type==5 and mcs%250==0:
cells_to_divide.append(cell)
for cell in cells_to_divide:
# to change mitosis mode leave one of the below lines uncommented
#self.divideCellRandomOrientation(cell)
# self.divideCellOrientationVectorBased(cell,1,0,0) # this is a valid option
self.divideCellAlongMajorAxis(cell) # this is a valid option
# self.divideCellAlongMinorAxis(cell) # this is a valid option
def updateAttributes(self):
#self.parentCell.targetVolume /= 2.0 # reducing parent target volume
self.cloneParent2Child()
# for more control of what gets copied from parent to child use cloneAttributes function
# self.cloneAttributes(sourceCell=self.parentCell, targetCell=self.childCell, no_clone_key_dict_list = [attrib1, attrib2] )
if self.parentCell.type==5:
self.childCell.type=5
#else:
#self.childCell.type=1 <file_sep>#!/bin/bash
import argparse
import cv2
import numpy
import math
import sys
import os
import fnmatch
def line_deg_angle(x1, y1, x2, y2):
return math.degrees(math.atan((y2-y1)/(x2-x1)))
## >>> line_deg_angle(1, 1, 5, 5)
##45.0
##>>> line_deg_angle(0, 5, 5, 0)
##-45.0
def unit_test_01(x1, y1, x2, y2):
print line_deg_angle(x1, y1, x2, y2)
def draw_lines_in_image(image, lines, color, line_thickness):
try:
for ln in lines:
x1, y1, x2, y2 = ln
cv2.line(image, (x1, y1), (x2, y2), color, line_thickness)
except Exception as e:
print str(e)
def draw_ht_lines_in_image(image, lines, color, line_thickness):
try:
for ln in lines:
x1, y1, x2, y2 = ln[0]
cv2.line(image, (x1, y1), (x2, y2), color, line_thickness)
except Exception as e:
print str(e)
def display_lines_and_angles(lines):
try:
for ln in lines:
x1, y1, x2, y2 = ln
print (x1, y1, x2, y2), line_deg_angle(x1, y1, x2, y2)
except Exception as e:
print str(e)
def display_ht_lines_and_angles(lines):
try:
for ln in lines:
x1, y1, x2, y2 = ln[0]
print (x1, y1, x2, y2), line_deg_angle(x1, y1, x2, y2)
except Exception as e:
print str(e)
def is_angle_in_range(a, ang_lower, ang_upper):
if a>=ang_lower and a<=ang_upper:
return True
else:
return False
def is_left_lane_line(x1, y1, x2, y2, ang_lower, ang_upper):
a = line_deg_angle(x1, y1, x2, y2);
return is_angle_in_range(a, ang_lower, ang_upper);
def is_right_lane_line(x1, y1, x2, y2, ang_lower, ang_upper):
a = line_deg_angle(x1, y1, x2, y2)
return is_angle_in_range(a, ang_lower, ang_upper);
def display_ht_lanes_in_image(image_path, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap):
image = cv2.imread(image_path) ## read the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ## grayscale
edges = cv2.Canny(gray, 50, 150, apertureSize=3) ## detect edges
lines = cv2.HoughLinesP(edges, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap) ## detect hough lines
print 'Detected lines and angles:'
display_ht_lines_and_angles(lines)
draw_ht_lines_in_image(image, lines, (255, 0, 0), 2)
cv2.imshow('Gray', gray)
cv2.imshow('Edges', edges)
cv2.imshow('Lines in Image', image)
cv2.waitKey(0)
def unit_test_02(image_path, num_votes, min_len, max_gap):
display_ht_lanes_in_image(image_path, 1, numpy.pi/180, num_votes, min_len, max_gap)
def filter_left_lane_lines(lines, ang_lower=-60, ang_upper=-30):
filtered_l_lanes = []
for line in lines:
if is_left_lane_line(line(1), line(2), line(3), line(4), ang_lower, ang_upper):
filtered_l_lanes.append(line)
return filtered_l_lanes
def filter_right_lane_lines(lines, ang_lower=30, ang_upper=60):
filtered_r_lanes=[]
for line in lines:
if is_right_lane_line(line(1), line(2), line(3), line(4), ang_lower, ang_upper):
filtered_r_lanes.append(line)
return filtered_r_lanes
## most common value for rho_accuracy is 1
## most common value for theta_accuracy is numpy.pi/180.
## typo with display_line_angles is fixed.
def plot_ht_lanes_in_image(image_path, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap):
image = cv2.imread(image_path) ## read the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ## grayscale
edges = cv2.Canny(gray, 50, 150, apertureSize=3) ## detect edges
lines = cv2.HoughLinesP(edges, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap) ## detect hough lines
## if you want to convert lines from 3D numpy array into 2D Py list, you
## conversion should take place here. Then you can call display_lines_and_angles.
## Take a look at numpy_opencv_test below to see how that conversion is done.
display_ht_lines_and_angles(lines)
cv2.imshow('Gray', gray)
cv2.imshow('Edges', edges)
## my implementation of filter_left_lane_lines and filter_right_lane_lines returns 2D Py lists, hence
## I call draw_lines_in_image, not draw_ht_lines_in_image.
ll_lines = filter_left_lane_lines(lines)
rl_lines = filter_right_lane_lines(lines)
draw_lines_in_image(image, ll_lines, (255, 0, 0), 2)
draw_lines_in_image(image, rl_lines, (0, 0, 255), 2)
print 'detected', len(ll_lines), 'left lanes'
print 'detected', len(rl_lines), 'right lanes'
cv2.imshow('Lanes in Image', image)
cv2.waitKey(0)
def detect_ht_lanes_in_image(image_path, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap):
image = cv2.imread(image_path) ## read the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ## grayscale
edges = cv2.Canny(gray, 50, 150, apertureSize=3) ## detect edges
lines = cv2.HoughLinesP(edges, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap) ## detect hough lines
#cv2.imshow('Gray', gray)
#cv2.imshow('Edges', edges)
ll_lines = filter_left_lane_lines(lines)
rl_lines = filter_right_lane_lines(lines)
draw_lines_in_image(image, ll_lines, (255, 0, 0), 2)
draw_lines_in_image(image, rl_lines, (0, 0, 255), 2)
cv2.imwrite(image_path[:-4] + '_lanes' + image_path[-4:], image)
#print len(ll_lines), len(rl_lines)
return (len(ll_lines), len(rl_lines))
def unit_test_03(image_path, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap):
ll, rl = detect_ht_lanes_in_image(image_path, rho_accuracy, theta_accuracy, num_votes, min_len, max_gap)
print 'number of left lanes:', ll
print 'number of right lanes:', rl
def find_ll_rl_lanes_in_images_in_dir(imgdir, filepat, rho_acc, th_acc, num_votes, min_len, max_gap):
for im in imgdir:
if re.match(filepat, im):
def unit_test_04(imgdir, filepat, rho_acc, th_acc, num_votes, min_len, max_gap):
for fp, ll_rl in find_ll_rl_lanes_in_images_in_dir(imgdir, filepat, 1, numpy.pi/180,
num_votes, min_len, max_gap):
print fp, ll_rl[0], ll_rl[1]
## these functions are only for debugging.
def numpy_opencv_ht_test(image_path):
image = cv2.imread(image_path) ## read the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ## grayscale
edges = cv2.Canny(gray, 50, 150, apertureSize=3) ## detect edges
lines = cv2.HoughLinesP(edges, 1, numpy.pi/180, 100, 10, 10) ## detect hough lines
#print lines.shape
#display_ht_lines_and_angles(lines)
print lines
def numpy_opencv_test(image_path):
image = cv2.imread(image_path) ## read the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ## grayscale
edges = cv2.Canny(gray, 50, 150, apertureSize=3) ## detect edges
lines = cv2.HoughLinesP(edges, 1, numpy.pi/180, 100, 10, 10) ## detect hough lines
# convert 3D numpy array into a 2D python list
x, y, z = lines.shape
lines.shape = (x, z) # drop the y-dimension, because it is always 1
#print lines
display_lines_and_angles(lines)
#print lines
## This is the new __main__
if __name__ == '__main__':
#unit_test_01(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
#plot_ht_lanes_in_image(sys.argv[1], 1, numpy.pi/180, int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
#unit_test_02(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
#unit_test_03(sys.argv[1], 1, numpy.pi/180, int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
#unit_test_04(sys.argv[1], sys.argv[2], 1, numpy.pi/180, int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]))
pass
<file_sep>#!/usr/bin/python
import sys
import re
toops =[]
for n in sys.stdin.readlines():
ip = n.split(None,1)[0]
tbytes = n.split(None,1)[1]
toop = (ip,tbytes)
toops.append(toop)
toops = sorted(toops, key = lambda toop: toop[1], reverse=True)
for toop in toops:
sys.stdout.write(toop[0]+' '+toop[1])
sys.stdout.flush()<file_sep>
from PySteppables import *
import CompuCell
import sys
from PySteppablesExamples import MitosisSteppableBase
class ConstraintInitializerSteppable(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def start(self):
for cell in self.cellList:
if cell.type != 3:
cell.targetVolume=25
cell.lambdaVolume=2.0
else:
cell.targetVolume=10
cell.lambdaVolume=2.0
class Switch(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def step(self,mcs):
for cell in self.cellList:
if cell.type == 3: #meristemoid 'conflict' resolves in commiting to pavement cell lineage
for neighbor, commonSurfaceArea in self.getCellNeighborDataList(cell):
if neighbor:
if neighbor.type==3 or neighbor.type==5 or neighbor.type==6:
cell.type = 4 #7
elif mcs > 250:
cell.type = 5
elif cell.type == 4: #spacing SLGC if there is no stomata lineage revert to MMC
i = 0;
for neighbor, commonSurfaceArea in self.getCellNeighborDataList(cell):
if neighbor:
if neighbor.type==3 or neighbor.type==5 or neighbor.type==6:
i=1
if neighbor.type == 5:
cell.type = 7
if i == 0 and mcs%50 == 0:
cell.type = 2
elif cell.type == 1: #spacing protoderm if there is no stomata lineage revert to MMC EPFL-ERL regulated
i = 0;
for neighbor, commonSurfaceArea in self.getCellNeighborDataList(cell):
if neighbor:
if neighbor.type==3 or neighbor.type==5 or neighbor.type==6:
i=1
if i == 0:
cell.type = 2
elif mcs > 250:
cell.type = 7
#elif cell.type == 2 and mcs > 250:
#cell.type = 4
class GrowthSteppable(SteppableBasePy):
def __init__(self,_simulator,_frequency=1):
SteppableBasePy.__init__(self,_simulator,_frequency)
def step(self,mcs):
for cell in self.cellList:
cell.targetVolume+=1
# alternatively if you want to make growth a function of chemical concentration uncomment lines below and comment lines above
# field=CompuCell.getConcentrationField(self.simulator,"PUT_NAME_OF_CHEMICAL_FIELD_HERE")
# pt=CompuCell.Point3D()
# for cell in self.cellList:
# pt.x=int(cell.xCOM)
# pt.y=int(cell.yCOM)
# pt.z=int(cell.zCOM)
# concentrationAtCOM=field.get(pt)
# cell.targetVolume+=0.01*concentrationAtCOM # you can use here any fcn of concentrationAtCOM
class MitosisSteppable(MitosisSteppableBase):
def __init__(self,_simulator,_frequency=1):
MitosisSteppableBase.__init__(self,_simulator, _frequency)
def step(self,mcs):
# print "INSIDE MITOSIS STEPPABLE"
cells_to_divide=[]
for cell in self.cellList:
if cell.type==2:
#if mcs%50==0:
cells_to_divide.append(cell)
#elif cell.type==3:#Amplifying
#for neighbor, commonSurfaceArea in self.getCellNeighborDataList(cell):
#if neighbor:
#if neighbor.type==0:
#cells_to_divide.append(cell)
elif cell.type == 5 and mcs > 275:
cells_to_divide.append(cell)
for cell in cells_to_divide:
# to change mitosis mode leave one of the below lines uncommented
# self.divideCellRandomOrientation(cell)
self.divideCellOrientationVectorBased(cell,0,1,0) # this is a valid option
# self.divideCellAlongMajorAxis(cell) # this is a valid option
# self.divideCellAlongMinorAxis(cell) # this is a valid option
def updateAttributes(self):
self.parentCell.targetVolume /= 1.3333333333 # reducing parent target volume
self.cloneParent2Child()
# for more control of what gets copied from parent to child use cloneAttributes function
# self.cloneAttributes(sourceCell=self.parentCell, targetCell=self.childCell, no_clone_key_dict_list = [attrib1, attrib2] )
if self.parentCell.type==2:
self.childCell.type=3
self.parentCell.type=4
#elif self.parentCell.type==3:
#self.childCell.type=7
elif self.parentCell.type==5:
self.parentCell.targetVolume /=2.0 # reducing parent target volume
self.cloneParent2Child()
self.childCell.type=6
self.parentCell.type=6
<file_sep>#!/usr/bin/python
import sys
import re
code = sys.argv[1]
pattern = re.compile(r'(?:\s)(\d{3})(?:\s)')
for n in sys.stdin.readlines():
fcode=re.search(pattern,n)
if code == fcode.group(1):
sys.stdout.write(n)
sys.stdout.flush()<file_sep>#!/usr/bin/python
import sys
import re
sys.stdout.write(str(len([line for line in sys.stdin.readlines() if re.match(r'\S+', line)]))+'\n');<file_sep>#!/usr/bin/python
import sys
i = int(sys.argv[1])
for x in range(0,i):
n = sys.stdin.readline()
sys.stdout.write(n)
sys.stdout.flush()<file_sep>
import sys
from os import environ
from os import getcwd
import string
sys.path.append(environ["PYTHON_MODULE_PATH"])
import CompuCellSetup
sim,simthread = CompuCellSetup.getCoreSimulationObjects()
# add extra attributes here
CompuCellSetup.initializeSimulationObjects(sim,simthread)
# Definitions of additional Python-managed fields go here
#Add Python steppables here
steppableRegistry=CompuCellSetup.getSteppableRegistry()
from Root_Nodulation_3DSteppables import Root_Nodulation_3DSteppable
steppableInstance=Root_Nodulation_3DSteppable(sim,_frequency=1)
steppableRegistry.registerSteppable(steppableInstance)
from Root_Nodulation_3DSteppables import Switch
SwitchInstance=Switch(sim,_frequency=1)
steppableRegistry.registerSteppable(SwitchInstance)
from Root_Nodulation_3DSteppables import ElongationFlexSteppable
elongationFlexSteppable=ElongationFlexSteppable(_simulator=sim,_frequency=50)
steppableRegistry.registerSteppable(elongationFlexSteppable)
from Root_Nodulation_3DSteppables import MitosisSteppable
MitosisSteppableInstance=MitosisSteppable(sim,_frequency=1)
steppableRegistry.registerSteppable(MitosisSteppableInstance)
from Root_Nodulation_3DSteppables import ConstraintInitializerSteppable
ConstraintInitializerSteppableInstance=ConstraintInitializerSteppable(sim,_frequency=1)
steppableRegistry.registerSteppable(ConstraintInitializerSteppableInstance)
CompuCellSetup.mainLoop(sim,simthread,steppableRegistry)
CompuCellSetup.mainLoop(sim,simthread,steppableRegistry)
<file_sep>#!/usr/bin/python
import sys
import re
for n in sys.stdin.readlines():
tbytes = re.search(r'(?:\d\s{1})(\d+)',n)
if tbytes !=None:
sys.stdout.write(tbytes.group(1)+' \n')
else:
sys.stdout.write('0 \n')
sys.stdout.flush() | 96ff07e316a2fd964c26344d921178ce29b208fd | [
"Python",
"Shell"
] | 12 | Python | benjaminGibbons/Portfolio | 098eaab2a4b03ef7e04988ecfa43e07ba3e93dcf | 3d228d13aaa3de6ab65d6b4667b9151bfc13064f |
refs/heads/main | <repo_name>orandorisk/API<file_sep>/1.JSON/index.php
<?php
// // mendapatkan nilai dari data
// $mahasiswa = [
// [
// "nama" => "orlando",
// "kelas" => "D3 Teknik Informatika",
// "umur" => 23
// ],
// [
// "nama" => "orlando",
// "kelas" => "D3 Teknik Informatika",
// "umur" => 23
// ]
// ];
// $display = json_encode($mahasiswa);
// echo $display;
// // mendapatkan nilai dari database
// $dbh = new PDO('mysql:host=localhost;dbname=db_sekolah','root');
// $db = $dbh->prepare('SELECT * FROM pengguna');
// $db->execute();
// $mahasiswa = $db->fetchAll(PDO::FETCH_ASSOC);
// $data = json_encode($mahasiswa);
// echo $data;
// //mendapatkan nilai json dan mengubah ke array
// $data = file_get_contents('file.json');
// $mahasiswa = json_decode($data,true);
// var_dump($mahasiswa);
// echo $mahasiswa[0]["pembimbing"]["pembimbing1"];
?><file_sep>/2.WEBJSON/FOLDER/index.php
<?php
$data = file_get_contents('data/pizza.json');
$menu = json_decode($data, true);
$menu = $menu["menu"];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<title>HUT!</title>
</head>
<body>
<!-- element -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">
<img src="img/logo.png" width="120">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#humberger" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="humberger">
<div class="navbar-nav">
<a class="nav-link active" aria-current="page" href="#">All menu</a>
</div>
</div>
</div>
</nav>
<div class="container">
<div class="row mt-3">
<div class="col">
<h1>All Menu</h1>
</div>
</div>
<div class="row">
<?php foreach ($menu as $row) : ?>
<div class="col-md-4">
<div class="card mb-3">
<img src="img/pizza/<?= $row["gambar"];?>">
<div class="card-body">
<h5 class="card-title"><?= $row["nama"];?></h5>
<p class="card-text"><?= $row["deskripsi"];?></p>
<h5 class="card-title"><?= $row["harga"];?></h5>
<a href="#" class="btn btn-primary">Pesan Sekarang</a>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<!-- bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
| d83b456189b40fd49d5b949012bab7ad844c527c | [
"PHP"
] | 2 | PHP | orandorisk/API | fbe80998c111f948f646e58b70ba685b07a6b77d | bc093ce0055f1d44f6d6531289fe4bf489907a3d |
refs/heads/master | <file_sep><?php
/* @var $options array */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
?>
<!-- separator -->
<tr>
<td colspan="2"><hr/></td>
</tr>
<!--/ separator --><file_sep><?php
/* @var $data array */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
?>
<section>
<p>Ha ocurrido un error mientras se utilizaba la pasarela de pago para WooCommerce.</p>
<p>Los datos que ha devuelto el servidor de PagoFlash son:</p>
<pre>
<?php var_dump($data); ?>
</pre>
<p>
Mensaje generado en la fecha y hora <b><?= date('d/m/Y H:i:s', current_time('timestamp')); ?></b>
</p>
</section><file_sep><?php
namespace pagoflash\woocommerce\inc\hooks;
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
/**
* Crea las acciones que utiliza el plugin
*
* @author PagoFlash International C.A. <http://www.pagoflash.com>
* @version 1.2-20160803
*/
class ActionHook
{
public function __construct()
{
add_action('parse_request', [$this, 'onActionParseRequest'], 0, 0);
}
/**
* Evalúa la URL solicitada para tomar las acciones que sean necesarias
*/
public function onActionParseRequest()
{
global $wp;
/* @var $wp \WP */
global $woocommerce;
/* @var $woocommerce \WooCommerce */
// no está definido el parámetro que identifica el punto de entrada
if (false === isset($wp->query_vars['pagename']))
{
return;
}
// no es la URL para atender la respuesta de PagoFlash
if ($wp->query_vars['pagename'] !== 'pagoflash-callback')
{
return;
}
// no se tiene el parámetro de control de PagoFlash
if (false === isset($_GET['tk']) or false === isset($_GET['callback']))
{
header('Location: ' . site_url());
exit;
}
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
// obtiene la instancia de la pasarela de pago PagoFlash para poder utilizar su configuración
$v_gateway = $pagoflash_woocommerce->retrievePagoflashGateway();
/* @var $v_gateway \WC_Gateway_Pagoflash */
// instancia la clase que permite hacer uso del API de PagoFlash
$v_pagoflash_api = $pagoflash_woocommerce->retrievePagoFlashAPI(
$v_gateway->get_option('keyToken'), //
$v_gateway->get_option('keySecret'), //
$v_gateway->retrieveCallbackUrl(), //
$v_gateway->isTestMode());
/* @var $v_pagoflash_api \apiPagoflash */
// prueba que el token recibido sea válido
$v_raw_response = $v_pagoflash_api->validarTokenDeTransaccion($_GET['tk'],
$_SERVER['HTTP_USER_AGENT']);
$v_response = json_decode($v_raw_response);
// la respuesta no fue satisfactoria
if ((null === $v_response) || (($v_response->cod != 1) && ($v_response->cod != 3)))
{
// agrega el mensaje en el log de errores
$v_gateway->log("response: {$v_raw_response}");
$pagoflash_woocommerce->template_manager->loadTemplate('gateway/callback/error',
[
'response' => $v_response,
'message' => $v_gateway->get_option('errorMessage')
]);
exit;
}
// obtiene los datos de la orden de compra
$v_order = new \WC_Order($v_response->order_number);
/* @var $v_order \WC_Order */
if (($v_response == 1))
{
// actualiza el estatus de la orden
$v_order->payment_complete($_GET['tk']);
// limpia el carro de compra
$woocommerce->cart->empty_cart();
}
$pagoflash_woocommerce->template_manager->loadTemplate('gateway/callback/success',
[
'response' => $v_response,
'message' => $v_gateway->get_option('successMessage')
]);
exit;
}
}
new ActionHook;
<file_sep><?php
namespace pagoflash\woocommerce\inc\hooks;
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
/**
* Crea los filtros que utiliza el plugin
*
* @author PagoFlash International C.A. <http://www.pagoflash.com>
* @version 1.2-20160803
*/
class FilterHook
{
public function __construct()
{
add_filter('plugin_action_links_pagoflash-woocommerce/pagoflash-woocommerce.php',
[$this, 'onFilterPluginActionLinksPagoflashWoocommerce'], 10, 4);
}
/**
* @see __construct
*/
public function onFilterPluginActionLinksPagoflashWoocommerce($p_actions, $p_plugin_file,
$p_plugin_data, $p_context)
{
// no se está desactivando el plugin
if (false === isset($p_actions['deactivate']))
{
return $p_actions;
}
// separa las partes del enlace para agregar la confirmación
$v_link_parts = explode(' ', $p_actions['deactivate'], 2);
// agrega un diálogo de confirmación para desactivar el plugin
$p_actions['deactivate'] = $v_link_parts[0]
. ' onclick="return confirm(\'' . __('This action will remove all data of this plugin, do you want to continue?',
'kemlem') . '\')" '
. $v_link_parts[1];
return $p_actions;
}
}
new FilterHook;
<file_sep># Método de pago PagoFlash para WordPress/WooCommerce
-- -------------------------------------------------------------------------------------------------
-- Aspectos técnicos
-- -------------------------------------------------------------------------------------------------
Requerimientos
--------------
- PHP 5.5 o superior
- Wordpress 4.1 o superior
- WooCommerce
Instalación
------------
1. Descargar el contenido comprimido (.zip).
2. Iniciar sesión en al área administrativa de Wordpress para tu sitio web
3. Click en "Subir nuevo plugin" y seleccionar el plugin descargado (.zip)
4. Dirígete desde tu gestor de archivos hasta wp-content/plugins/ y renombra la carpeta "pagoflash-woocommerce-master" a "pagoflash-woocommerce".
4. Ir al área de administración de plugins y activar el plugin
"PagoFlash - Método de Pago para WooCommerce"
-- -------------------------------------------------------------------------------------------------
-- Uso
-- -------------------------------------------------------------------------------------------------
01. Entra a la sección de ajustes de WooCommerce y configura el plugin de PagoFlash. Esto lo puedes
hacer a través de la URL "{mi-sitio-web}/wp-admin/admin.php?page=wc-settings&tab=checkout§ion"
02. Crea una nueva página con el siguiente URL "{mi-sitio-web}/pagoflash-callback"
03. Eso es todo, ahora tus clientes podrán realizarte los pagos utilizando PagoFlash
-- -------------------------------------------------------------------------------------------------
-- Ambiente de prueba
-- -------------------------------------------------------------------------------------------------
Para hacer pruebas ingresa en nuestro sitio de pruebas y [regístra una cuenta de negocios](http://app-test2.pagoflash.com/profile/register/business), luego de llenar y confirmar tus datos, completa los datos de tu perfil, registra un punto de venta, llena los datos necesarios y una vez registrado el punto, la plataforma generará códigos **key_token** y **key_secret** que encontrarás en la pestaña **Integración** del punto de venta, utilíza los parámetros para configurar tu plugin en woocommerce, no olvides habilitar el "Test Mode" o "Módo de Prueba" de Woocommerce para hacer las pruebas.
-- -------------------------------------------------------------------------------------------------
-- Configuración
-- -------------------------------------------------------------------------------------------------
El área de configuración del plugin se encuentra dentro de la sección de ajustes de WooCommerce, en
el apartado de "Finalizar Compra" y posee las siguientes opciones configurables:
- Activo: Activa o desactiva el uso de PagoFlash como pasarela de pago.
- Título: Requerido. Título de la opción de pago que se mostrará cuando el usuario valla a
completar su compra.
- Descripción: Requerido. Descripción o instrucciones que se mostrarán al usuario cuando valla a
seleccionar el pago.
- Mensaje al terminar exitosamente: Requerido. Mensaje que se mostrará al usuario cuando la compra
haya sido completada exitosamente.
- Mensaje en caso de error: Requerido. Mensaje que se mostrará al usuario cuando no haya sido
posible completar su pago de forma exitosa.
- Key Token: Requerido. Ficha única que genera PagoFlash al momento de registrar un punto de venta
virtual.
- Key Secret: Requerido. Ficha única complementaria que genera PagoFlash al momento de registrar
un punto de venta virtual.
- URL Callback: Solo lectura. El contenido de este campo debe ser copiado y pegado en el campo
"URL callback" del formulario de registro del punto de venta virtual en PagoFlash.
- Modo de prueba: Activa o desactiva el modo de prueba del plugin. Cuando se está en modo de
prueba las transacciones no implican un movimiento real de dinero.
- Log detallado: Activa o desactiva la escritura detallada del funcionamiento del plugin en el
registro de WooCommerce (Estado del sistema -> Registro). Si esta opción está desactivada solo
se escribirán los mensajes de error.
- Email para notificar errores: Requerido. Dirección de email hacia la cual se enviarán los
detalles técnicos de los errores que ocurran mientras los usuarios utilizan PagoFlash como
pasarela de pago. Generalmente esta dirección de email será la del personal técnico responsable
del funcionamiento del sitio web.
- Notificar errores a PagoFlash: Permítenos saber que ocurrió un error con nuestro plugin y así
podremos ayudarte proactivamente a solucionarlo.
Esta opción envía una copia de los detalles técnicos de los errores hacia nuestro equipo de
soporte para determinar que está sucediendo y darte soluciones.
El mensaje no contiene información sensible, solo nos avisa que algo no va bien y nos entrega
los datos, que ya están en nuestra plataforma, para atender la eventualidad puntualmente.
-- -------------------------------------------------------------------------------------------------
-- Agregar moneda (bs)
-- -------------------------------------------------------------------------------------------------
Para configurar woocommerce para que acepte bolívares como moneda, agrega la siguiente función al final del archivo functions.php de tu theme.
```php
add_filter( 'woocommerce_currencies', 'add_my_currency' );
function add_my_currency( $currencies ) {
$currencies['ABC'] = __( 'Bolívares', 'woocommerce' );
return $currencies;
}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);
function add_my_currency_symbol( $currency_symbol, $currency ) {
switch( $currency ) {
case 'ABC': $currency_symbol = 'Bs. '; break;
}
return $currency_symbol;
}
```
-- -------------------------------------------------------------------------------------------------
-- Personalización
-- -------------------------------------------------------------------------------------------------
Plantillas
----------
Para personalizar la organización visual de los elementos mostrados por el plugin, pueden editarse
los archivos que se encuentran dentro del directorio "templates".
<file_sep><?php
/* @var $data array */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
?>
<section>
<h2><?= __('Your store is experiencing problems', 'pagoflash'); ?></h2>
<p>
<?=
__('We have detected that your store is having dificults to complete the payments using PagoFlash',
'pagoflash');
?>
</p>
<p>
<?=
__('PagoFlash support team has been advised about the situation, but we recommend you to take some of this actions:',
'pagoflash');
?>
</p>
<ul>
<li><?=
sprintf(__('Check that the <a href="%s" target="_blank">configuration of the extension</a> match <a href="%s" target="_blank">your PagoFlash info</a>',
'pagoflash'), //
admin_url('admin.php?page=wc-settings&tab=checkout§ion=wc_gateway_pagoflash'), //
(isset($data['test-mode']) && $data['test-mode']) ? 'http://app-test.pagoflash.com/backuser.php/salepoints' : 'http://app.pagoflash.com/backuser.php/salepoints'
);
?></li>
</ul>
</section><file_sep><?php
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
wp_enqueue_style('font-awesome',
"{$pagoflash_woocommerce->base_url}/lib/font-awesome/css/font-awesome.min.css");
?>
<hr/>
<a href="https://app.pagoflash.com/backuser.php/user/new.html?tipo=empresa" class="button button-hero button-primary" style="vertical-align:top" target="_blank"><i class="fa fa-plus"></i> <?=
__('Create Account', 'pagoflash');
?></a> <img src="<?= $pagoflash_woocommerce->base_url; ?>/img/pagoflash-full.png" width="187" height="46" style="border-radius:3px; border:1px solid #D7D7D7" />
<hr/><file_sep><?php
/* @var $response stdClass */
/* @var $message string */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
// obtiene el ID de la página que muestra el resumen de la cuenta del usuario
$v_myaccount_page_id = get_option('woocommerce_myaccount_page_id');
?>
<?php get_header(); ?>
<section>
<img style="border-radius:3px; border:1px solid #D7D7D7" src="<?= $pagoflash_woocommerce->base_url; ?>/img/pagoflash-full.png" />
<br/>
<h2><?= __('Your payment has been completed', 'pagoflash'); ?></h2>
<p><?= $message; ?></p>
<p>
<?php if ($v_myaccount_page_id): ?>
<a class="button button-primary" href="<?= get_permalink($v_myaccount_page_id); ?>">
<?= __('Go To My Account', 'pagoflash'); ?>
</a>
<?php else: ?>
<a class="button button-primary" href="<?= get_permalink(woocommerce_get_page_id('shop')) ?>">
<?= __('Back To Shop', 'pagoflash'); ?>
</a>
<?php endif; ?>
</p>
</section>
<?php get_footer(); ?><file_sep><?php
namespace pagoflash\woocommerce\inc;
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
/**
* Gestor de plantillas
*
* @author PagoFlash International C.A. <http://www.pagoflash.com>
* @version 1.2-20160803
*/
class TemplateManager
{
/**
* Carga los datos de una plantilla y le aplica las variables asignadas
*
* @param string $p_template Nombre de la plantilla
* @param array $p_vars Variables que se utilizarán en la plantilla
* @param boolean $p_buffer_output Indica si la salida debe ser devuelta por
* la función
*/
public function loadTemplate($p_template, $p_vars = [],
$p_buffer_output = false)
{
// genera el nombre completo de la plantilla
$p_template = dirname(__FILE__) . "/../templates/{$p_template}.php";
// la salida debe ser devuelta por la función
if ($p_buffer_output)
{
ob_start();
}
// extrae las variabels que se utilizarán
extract($p_vars);
// agrega la plantilla
require $p_template;
// la salida debe ser devuelta por la función
if ($p_buffer_output)
{
return ob_get_clean();
}
}
}
<file_sep><?php
/* @var $options array */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
wp_enqueue_script('pagoflash-woocommerce-field-callback');
?>
<!-- callback URL -->
<tr>
<th class="titledesc" scope="row"><?= $options['title']; ?></th>
<td>
<fieldset>
<input id="callback-url" type="text" value="<?= $options['url']; ?>" readonly="readonly" class="regular-input" />
<button id="callback-url-select-button" type="button" class="button">
<?= __('Select Text', 'pagoflash'); ?>
</button>
</fieldset>
</td>
</tr>
<!--/ callback URL --><file_sep># Método de pago PagoFlash para WordPress/WooCommerce
-- -------------------------------------------------------------------------------------------------
-- Aspectos técnicos
-- -------------------------------------------------------------------------------------------------
Requerimientos
--------------
- PHP 5.5 o superior
- Wordpress 4.1 o superior
- WooCommerce
Instalación
------------
1. Colocar la carpeta "woocommerce-pagoflash" dentro del directorio "wp-content/plugins"
2. Iniciar sesión en al área administrativa de Wordpress para tu sitio web
3. Ir al área de administración de plugins y activar el plugin
"PagoFlash - Método de Pago para WooCommerce"
-- -------------------------------------------------------------------------------------------------
-- Uso
-- -------------------------------------------------------------------------------------------------
01. Entra a la sección de ajustes de WooCommerce y configura el plugin de PagoFlash. Esto lo puedes
hacer a través de la URL "{mi-sitio-web}/wp-admin/admin.php?page=wc-settings&tab=checkout§ion"
02. Crea una nueva página con el siguiente URL "{mi-sitio-web}/pagoflash-callback"
03. Eso es todo, ahora tus clientes podrán realizarte los pagos utilizando PagoFlash
-- -------------------------------------------------------------------------------------------------
-- Configuración
-- -------------------------------------------------------------------------------------------------
El área de configuración del plugin se encuentra dentro de la sección de ajustes de WooCommerce, en
el apartado de "Finalizar Compra" y posee las siguientes opciones configurables:
- Activo: Activa o desactiva el uso de PagoFlash como pasarela de pago.
- Título: Requerido. Título de la opción de pago que se mostrará cuando el usuario valla a
completar su compra.
- Descripción: Requerido. Descripción o instrucciones que se mostrarán al usuario cuando valla a
seleccionar el pago.
- Mensaje al terminar exitosamente: Requerido. Mensaje que se mostrará al usuario cuando la compra
haya sido completada exitosamente.
- Mensaje en caso de error: Requerido. Mensaje que se mostrará al usuario cuando no haya sido
posible completar su pago de forma exitosa.
- Key Token: Requerido. Ficha única que genera PagoFlash al momento de registrar un punto de venta
virtual.
- Key Secret: Requerido. Ficha única complementaria que genera PagoFlash al momento de registrar
un punto de venta virtual.
- URL Callback: Solo lectura. El contenido de este campo debe ser copiado y pegado en el campo
"URL callback" del formulario de registro del punto de venta virtual en PagoFlash.
- Modo de prueba: Activa o desactiva el modo de prueba del plugin. Cuando se está en modo de
prueba las transacciones no implican un movimiento real de dinero.
- Log detallado: Activa o desactiva la escritura detallada del funcionamiento del plugin en el
registro de WooCommerce (Estado del sistema -> Registro). Si esta opción está desactivada solo
se escribirán los mensajes de error.
- Email para notificar errores: Requerido. Dirección de email hacia la cual se enviarán los
detalles técnicos de los errores que ocurran mientras los usuarios utilizan PagoFlash como
pasarela de pago. Generalmente esta dirección de email será la del personal técnico responsable
del funcionamiento del sitio web.
- Notificar errores a PagoFlash: Permítenos saber que ocurrió un error con nuestro plugin y así
podremos ayudarte proactivamente a solucionarlo.
Esta opción envía una copia de los detalles técnicos de los errores hacia nuestro equipo de
soporte para determinar que está sucediendo y darte soluciones.
El mensaje no contiene información sensible, solo nos avisa que algo no va bien y nos entrega
los datos, que ya están en nuestra plataforma, para atender la eventualidad puntualmente.
-- -------------------------------------------------------------------------------------------------
-- Agregar moneda (bs)
-- -------------------------------------------------------------------------------------------------
Para configurar woocommerce para que acepte bolívares como moneda, agrega la siguiente función al final del archivo functions.php de tu theme.
```php
add_filter( 'woocommerce_currencies', 'add_my_currency' );
function add_my_currency( $currencies ) {
$currencies['ABC'] = __( 'Bolívares', 'woocommerce' );
return $currencies;
}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);
function add_my_currency_symbol( $currency_symbol, $currency ) {
switch( $currency ) {
case 'ABC': $currency_symbol = 'Bs. '; break;
}
return $currency_symbol;
}
```
-- -------------------------------------------------------------------------------------------------
-- Personalización
-- -------------------------------------------------------------------------------------------------
Plantillas
----------
Para personalizar la organización visual de los elementos mostrados por el plugin, pueden editarse
los archivos que se encuentran dentro del directorio "templates".
<file_sep><?php
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
/**
* Pasarela de pago de PagoFlash International
*
* @author PagoFlash International C.A. <http://www.pagoflash.com>
* @version 1.2-20160803
*/
class WC_Gateway_Pagoflash extends WC_Payment_Gateway
{
/**
* @var string URL que se utilizará para recibir la respuesta dada por PagoFlash
*/
protected $callback_url = null;
/**
* @var boolean Indica si se está utilizando la plataforma de prueba de PagoFlash
*/
protected $is_test_mode = null;
/**
* @var boolean Indica si el log está activo
*/
protected $log_enabled = false;
/**
* @var WC_Logger Objeto que es permite escribir en el log
*/
protected $log = null;
public function __construct()
{
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
// identificador único del método de pago
$this->id = 'pagoflash';
// ícono que se mostrara junto al método de pago
#$this->icon = "{$pagoflash_woocommerce->base_url}/img/pf-icon.png";
// si el metodo de pago es una integración directa deberá incluir campos en el formulario, este no lo es
$this->has_fields = false;
// título del método de pago
$this->method_title = __('PagoFlash', 'pagoflash');
// texto del botón de pago
$this->order_button_text = __('Proceed to PagoFlash', 'pagoflash');
// URL que atiende la respuesta de PagoFlash
$this->callback_url = site_url() . '/pagoflash-callback';
// descripción del método de pago
$this->method_description = __('Allow your customers to pay using PagoFlash International',
'pagoflash');
$this->method_description .= $pagoflash_woocommerce->template_manager->loadTemplate('gateway/part/signin',
[], true);
$this->init_form_fields();
$this->init_settings();
// obtiene la configuración del plugin
$this->title = $this->get_option('title')." (tarjeta de crédito Visa / Mastercard)";
$this->description = $this->get_option('description');
$this->is_test_mode = ('yes' === $this->get_option('testMode'));
$this->log_enabled = ('yes' === $this->get_option('enableLog'));
add_action("woocommerce_update_options_payment_gateways_{$this->id}",
[$this, 'process_admin_options']);
}
/**
* @inheritdoc
*
* @see WC_Payment_Gateway
*/
public function init_form_fields()
{
$this->form_fields = [
'enabled' => [
'title' => __('Enabled', 'pagoflash'),
'type' => 'checkbox',
'label' => __('Enable PagoFlash Payment', 'pagoflash'),
'default' => 'yes'
],
'title' => [
'title' => __('Title', 'pagoflash'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.',
'pagoflash'),
'default' => __('PagoFlash (tarjeta de crédito Visa / Mastercard)'),
'desc_tip' => true,
'custom_attributes' => [
'required' => 'required'
]
],
'description' => [
'title' => __('Description', 'pagoflash'),
'type' => 'textarea',
'description' => __('Payment method description that the customer will see on your checkout.',
'pagoflash'),
'default' => '',
'desc_tip' => true,
'custom_attributes' => [
'required' => 'required'
]
],
'successMessage' => [
'title' => __('Message on Successful Finish'),
'type' => 'textarea',
'default' => __('Your payment has been accepted', 'pagoflash'),
'description' => __('Message to display when the payment process has been completed successfully',
'pagoflash'),
'desc_tip' => true,
],
'errorMessage' => [
'title' => __('Message on Payment Error'),
'type' => 'textarea',
'default' => __('Your payment has been rejected', 'pagoflash'),
'description' => __('Message to display when the payment process has some error',
'pagoflash'),
'desc_tip' => true,
],
'separator1' => ['type' => 'separator'],
'keyToken' => [
'title' => __('Key Token', 'pagoflash'),
'type' => 'text',
'custom_attributes' => [
'required' => 'required'
]
],
'keySecret' => [
'title' => __('Key Secret', 'pagoflash'),
'type' => 'text',
'custom_attributes' => [
'required' => 'required'
]
],
'callback' => [
'title' => __('Site URL Callback', 'pagoflash'),
'type' => 'callback',
'url' => $this->callback_url
],
'testMode' => [
'title' => __('Test Mode', 'pagoflash'),
'type' => 'checkbox',
'label' => __('Enable Test Mode', 'pagoflash'),
'default' => 'yes'
],
'separator2' => ['type' => 'separator'],
'enableLog' => [
'title' => __('Verbose Log'),
'description' => __('Write on log the steps of the payment process. If this option is unchecked only errors are written to log',
'pagoflash'),
'desc_tip' => true,
'type' => 'checkbox',
'label' => __('Write process steps on log', 'pagoflash'),
'default' => 'yes'
],
'supportEmail' => [
'title' => __('Email to notify errors', 'pagoflash'),
'description' => __('Email address where error notifications will be sent', 'pagoflash'),
'desc_tip' => true,
'type' => 'text',
'default' => get_bloginfo('admin_email')
],
'notifyErrorsToPagoflash' => [
'title' => __('Notify errors to PagoFlash', 'pagoflash'),
'type' => 'checkbox',
'label' => __('Send a copy of the error emails to PagoFlash support team (<EMAIL>)',
'pagoflash'),
'default' => 'yes',
'description' => __('This allow to PagoFlash to be notified when an error occurs in order to help you to solve it efficiently',
'pagoflash'),
'desc_tip' => true,
]
];
}
/**
* Crea el HTML que se utiliza para el campo que muestra la URL a donde PagoFlash enviará los
* resultados
*
* @param string $p_id identificador del campo
* @param array $p_options Opciones que se configuraron para el campo
*/
public function generate_callback_html($p_id, $p_options)
{
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
return $pagoflash_woocommerce->template_manager->loadTemplate('gateway/field/callback',
['options' => $p_options], true);
}
/**
* @inheritdoc
*
* @see WC_Payment_Gateway
*/
public function process_payment($p_order_id)
{
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
$v_order = wc_get_order($p_order_id);
/* @var $v_order WC_Order */
// instancia la clase que permite hacer uso del API de PagoFlash
$v_pagoflash_api = $pagoflash_woocommerce->retrievePagoFlashAPI(
$this->get_option('keyToken'), //
$this->get_option('keySecret'), //
$this->callback_url, //
$this->is_test_mode);
/* @var $v_pagoflash_api apiPagoflash */
// crea la cabecera que contiene los datos generales de la compra
$v_header = [
'pc_order_number' => $p_order_id,
'pc_amount' => $v_order->order_total
];
// prepara los datos de los productos
$v_products = [];
$v_order_items = $v_order->get_items();
foreach ($v_order_items as $v_order_item)
{
$v_product = new WC_Product($v_order_item['product_id']);
/* @var $v_product WC_Product */
$v_description = get_post($v_order_item['product_id'])->post_content;
$v_image_id = $v_product->get_image_id();
$v_products[] = [
'pr_name' => substr($v_order_item['name'], 0, 127),
'pr_desc' => ('' === $v_description) ? '' : substr($v_description, 0, 230),
'pr_price' => $v_order_item['line_total'] / $v_order_item['qty'],
'pr_qty' => $v_order_item['qty'],
'pr_img' => (0 === $v_image_id) ? '' : wp_get_attachment_url($v_image_id)
];
}
// envía los datos hacia PagoFlash y espera la respuesta
$v_raw_response = $v_pagoflash_api->procesarPago([
'cabecera_de_compra' => $v_header,
'productos_items' => $v_products
], $_SERVER['HTTP_USER_AGENT']
);
$v_response = json_decode($v_raw_response);
// ocurrió un error al obtener la respuesta
if (null === $v_response)
{
// genera el identificador del error
$v_error_id = "pagoflash-{$v_order->order_key}" . time();
// agrega el error en el log de errores del servidor
$this->log("{$v_error_id}: {$v_raw_response}");
// notifica el error via correo electrónico
$pagoflash_woocommerce->sendErrorOnRequestEmail([
'admin' => [
'test-mode' => $this->is_test_mode
],
'support' => [
'error_log_id' => $v_error_id,
'raw_response' => $v_raw_response,
'test_mode' => $this->is_test_mode
]
]);
// notifica acerca del error
wc_add_notice(
sprintf(__('Error procesing payment, please let us check and try again in 10 minutes')),
'error');
return;
}
// ocurrió un error al ejecutar la operación
if (0 == $v_response->success)
{
// genera el identificador del error
$v_error_id = "pagoflash-{$v_order->order_key}" . time();
// agrega el error en el log de errores del servidor
$this->log("{$v_error_id}: {$v_raw_response}");
// notifica el error via correo electrónico
$pagoflash_woocommerce->sendErrorOnRequestEmail([
'admin' => [
'test-mode' => $this->is_test_mode
],
'support' => [
'error_log_id' => $v_error_id,
'raw_response' => $v_raw_response,
'test_mode' => $this->is_test_mode
]
]);
// notifica acerca del error
wc_add_notice(
sprintf(__('Error procesing payment, please let us check and try again in 10 minutes')),
'error');
return;
}
// la operación se completó exitosamente
return [
'result' => 'success',
'redirect' => $v_response->url_to_buy
];
}
/**
* Indica si se está utilizando la plataforma de prueba de PagoFlash
*
* @return boolean
*/
public function isTestMode()
{
return $this->is_test_mode;
}
/**
* Devuelve la URL que atiende las respuestas dadas por el servidor de PagoFlash
*
* @return string
*/
public function retrieveCallbackUrl()
{
return $this->callback_url;
}
/**
* Indica si se deben notificar los errores al equipo de soporte de PagoFlash
*
* @return boolean
*/
public function mustNotifyErrorsToPagoflash()
{
return 'yes' === $this->get_option('notifyErrorsToPagoflash');
}
/**
* Crea el HTML que se utiliza para el separador de las filas
*
* @param string $p_id identificador del campo
* @param array $p_options Opciones que se configuraron para el campo
*/
public function generate_separator_html($p_id, $p_options)
{
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
return $pagoflash_woocommerce->template_manager->loadTemplate('gateway/field/separator',
['options' => $p_options], true);
}
/**
* Escribe en el log de PagoFlash para WooCommerce
*
* @param string $p_message Mensaje que se escribirá en el log
*/
public function log($p_message)
{
// no está activo el log
if (false === $this->log_enabled)
{
return;
}
// no existe una instancia del log
if (null === $this->log)
{
$this->log = new WC_Logger;
}
$this->log->add('pagoflash', $p_message);
}
}
/**
* Registra el método de pago
*
* @param array $p_methods Métodos de pago ya registrados
*
* @return array
*/
function onFilterWoocommercePaymentGateways($p_methods)
{
// agrega el método de pago
$p_methods[] = 'WC_Gateway_Pagoflash';
return $p_methods;
}
add_filter('woocommerce_payment_gateways', 'onFilterWoocommercePaymentGateways');
<file_sep><?php
namespace pagoflash\woocommerce\inc;
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
require dirname(__FILE__) . '/TemplateManager.php';
/**
* Prepara el plugin para ser utilizado, centraliza las funciones de uso general del plugin y limpia
* el estatus de Wordpress una vez que el plugin es desactivado
*
* @author PagoFlash International C.A. <http://www.pagoflash.com>
* @version 1.2-20160803
*/
class Plugin
{
/**
* @var string Directorio a partir del cual se puede acceder a los archivos del plugin
*/
public $base_dir = null;
/**
* @var string URL a partir de la cual se cargarán los recursos del plugin
*/
public $base_url = null;
/**
* @var TemplateManager Gestor de las plantillas del plugin. Se utiliza para
* mostrar los archivos de plantilla dentro del directorio [[templates]]
*/
public $template_manager = null;
public function __construct()
{
// define el directorio base del plugin
$this->base_dir = plugin_dir_path(__FILE__);
// define el directorio base de recursos del plugin
$this->base_url = WP_PLUGIN_URL . '/pagoflash-woocommerce/web';
// instancia el gestor de las plantillas
$this->template_manager = new TemplateManager;
}
/**
* @see https://codex.wordpress.org/Plugin_API/Action_Reference/init
*/
public function onActionInit()
{
// carga los hooks
$this->loadHooks();
// agrega las rutas personalizadas
$this->addRewriteRules();
}
/**
* @see https://codex.wordpress.org/Plugin_API/Action_Reference/shutdown
*/
public function onActionShutdown()
{
}
/**
* @see https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
*/
public function onActionWpEnqueueScripts()
{
}
/**
* @see https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
*/
public function onActionAdminEnqueueSripts()
{
// obtiene los datos de la página actual
$v_current_page = get_current_screen();
/* @var $v_current_page WP_Screen */
// se está en el area de configuración del plugin en WooCommerce
if (strpos($v_current_page->id, 'woocommerce_page_wc-settings') !== false)
{
wp_register_script('jquery', "{$this->base_url}/lib/jquery/jquery-1.11.3.min.js", [], false,
true);
wp_register_script('pagoflash-woocommerce-field-callback',
"{$this->base_url}/js/gateway/field/callback.js", ['jquery'], false, true);
}
}
/**
* @see https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded
*/
public function onActionPluginsLoaded()
{
// registra las traducciones
load_plugin_textdomain('pagoflash', false, 'pagoflash-woocommerce/languages');
}
/**
* Lee y ejecuta la configuración de los interceptores de filtros y acciones
*/
public function loadHooks()
{
// obtiene los archivos que definen los hooks
$v_files = glob("{$this->base_dir}hooks/*.php", GLOB_NOSORT);
// recorre los archivos para ser procesados por Wordpress
foreach ($v_files as $v_file)
{
// incluye el archivo
require $v_file;
}
}
/**
* Calcula el promedio en base a una promedio anterior y un nuevo promedio
*
* @param double $p_prev_mean Promedio que se tiene hasta el momento
* @param int $p_prev_mean_items Cantidad de elementos que se utilizaron para
* calcular el promedio que se tiene hasta el momento
* @param double $p_current_mean Promedio calculado en base a un conjunto de
* nuevos elementos
* @param int $p_current_mean_items Cantidad de elementos que se utilizaron
* para calcular el nuevo promedio
*
* @return double
*/
public function calculateMean($p_prev_mean, $p_prev_mean_items, $p_current_mean,
$p_current_mean_items)
{
$v_numerator = ($p_prev_mean_items * $p_prev_mean) + ($p_current_mean_items * $p_current_mean);
$v_denominator = ($p_prev_mean_items + $p_current_mean_items) * ($p_prev_mean + $p_current_mean);
return ($v_numerator / $v_denominator) * ($p_prev_mean + $p_current_mean);
}
/**
* Devuelve una instancia de la clase que permite hacer uso del API de PagoFlash.
*
* @param string $p_key_token Ficha de control que genera PagoFlash para el punto de venta virtual
* @param string $p_key_secret Código de seguridad, privado, que genera PagoFlash para el punto de
* venta virtual
* @param string $p_url_callback URL hacia la cual se enviará al cliente luego de completar el
* proceso de pago
* @param boolean $p_test_mode Opcional. Indica si la ejecución debe realizarse en modo de prueba.
* Por defecto si el valor de este parámetro se omite se considerará como que si está en modo de
* prueba
*
* @return \apiPagoflash
*/
public function retrievePagoFlashAPI($p_key_token, $p_key_secret, $p_url_callback,
$p_test_mode = true)
{
require_once WP_PLUGIN_DIR . '/pagoflash-woocommerce/libs/pagoflash-sdk/pagoflash.api.client.php';
return new \apiPagoflash($p_key_token, $p_key_secret, urlencode($p_url_callback), $p_test_mode);
}
/**
* Agrega las rutas adicionales que pueden ser utilizadas para acceder a las funcionalidades del
* plugin
*/
protected function addRewriteRules()
{
// agrega la ruta para atender la respuesta de PagoFlash
add_rewrite_endpoint('pagoflash-callback', EP_NONE);
}
/**
* Devuelve una instancia de la pasarela de pago de PagoFlash
*
* @return \WC_Gateway_Pagoflash
*/
public function retrievePagoflashGateway()
{
require_once "{$this->base_dir}/hooks/class-wc-gateway-pagoflash.php";
return new \WC_Gateway_Pagoflash;
}
/**
* @see https://codex.wordpress.org/Function_Reference/register_activation_hook
*/
public static function onActivate()
{
// regenera las URLs para que se tomen en cuenta los puntos de entrada que agrega el plugin
flush_rewrite_rules(false);
}
/**
* @see https://codex.wordpress.org/Function_Reference/register_deactivation_hook
*/
public function onDeactivate()
{
// regenera las URLs para que ya no se tomen en cuenta los puntos de entrada que agregó el plugin
flush_rewrite_rules(false);
}
/**
* Envía un mensaje de error al responsable del sitio web y al equipo de soporte de PagoFlash para
* atender alguna eventualidad que ocurra con el plugin
*
* @param array $p_data Opcional. Datos adicionales que se enviarán en el mensaje de correo
* @param \WC_Gateway_Pagoflash $p_gateway_instance Opcional. Instancia de la pasarela de pago.
* Este parámetro facilita la obtención de la configuración de la pasarela de pago. Si no se
* indica se creará una nueva instancia de la misma
*/
public function sendErrorOnRequestEmail($p_data = [], &$p_gateway_instance = null)
{
// no se indicaron datos para el administrador
if (false === isset($p_data['admin']))
{
$p_data['admin'] = null;
}
// no se indicaron datos para el equipo de soporte de PagoFlash
if (false === $p_data['support'])
{
$p_data['support'] = null;
}
// no se indicó una instancia de la pasarela de pago
if (null === $p_gateway_instance)
{
// instancia la pasarela de pago
$p_gateway_instance = $this->retrievePagoflashGateway();
}
// agrega los filtros necesarios para enviar el mensaje de correo adecuadamente
add_filter('wp_mail_content_type', [$this, 'onFilterWpMailContentType']);
// envía el mensaje de correo electrónico al administrador
wp_mail(
get_bloginfo('admin_email'), //
sprintf(__('[PagoFlash] Your site %s is experiencing problems on payment process'), site_url()), //
$this->template_manager->loadTemplate('mail/admin/error', ['data' => $p_data['admin']], true)
);
// envía el mensaje de correo electrónico al equipo de soporte de la tienda
wp_mail(
$p_gateway_instance->get_option('supportEmail'), //
sprintf(__('[%s] Error with PagoFlash WooCommerce extension'), site_url()), //
$this->template_manager->loadTemplate('mail/support/error', ['data' => $p_data['support']],
true)
);
// se enviarán los mensajes de error a PagoFlash
if ($p_gateway_instance->mustNotifyErrorsToPagoflash())
{
// envia el mensaje de correo electrónico al equipo de sopote de PagoFlash
wp_mail(
'<EMAIL>', //
sprintf(__('[%s] Error with WooCommerce extension'), site_url()), //
$this->template_manager->loadTemplate('mail/support/error', ['data' => $p_data['support']],
true)
);
}
// elimina los filtros para no afectar otros envíos
remove_filter('wp_mail_content_type', [$this, 'onFilterWpMailContentType']);
}
/**
* Devuelve el tipo de contenido que se utilizará para enviar los mensajes de correo electrónico
*
* @return string
*/
public function onFilterWpMailContentType()
{
return 'text/html';
}
}
$v_plugin = new Plugin;
// guarda de forma global la referencia al plugin
global $pagoflash_woocommerce;
$pagoflash_woocommerce = $v_plugin;
// establece la función que se ejecutará al inicializar el CMS
add_action('plugins_loaded', [$v_plugin, 'onActionPluginsLoaded']);
add_action('init', [$v_plugin, 'onActionInit']);
add_action('shutdown', [$v_plugin, 'onActionShutdown']);
//add_action('wp_enqueue_scripts', [$v_plugin, 'onActionWpEnqueueScripts']);
add_action('admin_enqueue_scripts', [$v_plugin, 'onActionAdminEnqueueSripts']);
unset($v_plugin);
<file_sep>#Libreria Cliente PHP para el API de [PagoFlash.com](http://pagoflash.com)
Aquí encontrará la información necesaria para integrar y utilizar el API de [PagoFlash](http://pagoflash.com) en su sitio web. Para utilizar nuestro método de pago debes **[crear una cuenta](https://app.pagoflash.com/profile/account_selection)** de negocios en nuestro site y registrar un **punto de venta**, con esto obtendras la **clave pública (key public)** y la **clave privada (key secret)**, necesarios para integrar el servicio en su sitio web. Si necesitas algún tipo de ayuda puedes envíar un correo a **<EMAIL>** con el asunto **Integración de botón de pago**.
##Requisitos
- PHP 5.3 o superior
- libreria curl
##Instalación
- Descargar el [sdk](https://raw.githubusercontent.com/PagoFlash/pagoflash-sdk/master/pagoflash.api.client.php) de PagoFlash para php
- Incluir el sdk en su script principal
##Pasos para la integración
Para hacer pruebas ingresa en nuestro sitio de pruebas y [regístra una cuenta de negocios](http://app-test2.pagoflash.com/profile/register/business), luego de llenar y confirmar tus datos, completa los datos de tu perfil, registra un punto de venta, llena los datos necesarios y una vez registrado el punto, la plataforma generará códigos **key_token** y **key_secret** que encontrarás en la pestaña **Integración** del punto de venta, utilízalos en el sdk como se muestra a continuación:
```php
<?php
//Importa el archivo pagoflas.api.client.php que contiene las clases que permiten la conexión con el API
include_once('pagoflash.api.client.php');
// url de tu sitio donde deberás procesar el pago
$urlCallbacks = "http://www.misitio.com/procesar_pago.php";
// cadena de 32 caracteres generada por la aplicación, Ej. aslkasjlkjl2LKLKjkjdkjkljlk&as87
$key_public = "tu_clave_publica";
// cadena de 20 caracteres generado por la aplicación. Ej. KJHjhKJH644GGr769jjh
$key_secret = "tu_clave_secreta";
// Si deseas ejecutar en el entorno de producción pasar (false) en el 4to parametro
$api = new apiPagoflash($key_public,$key_secret, $urlCallbacks,true);
//Cabecera de la transacción
$cabeceraDeCompra = array(
// Código de la orden (Alfanumérico de máximo 45 caracteres).
"pc_order_number" => "001",
// Monto total de la orden, número decimal sin separadores de miles,
// utiliza el punto (.) como separadores de decimales. Máximo dos decimales
// Ej. 9999.99
"pc_amount" => "20000"
);
//Producto o productos que serán el motivo de la transacción
$ProductItems = array();
$product_1 = array(
// Id. de tu porducto. Ej. 1
'pr_id' => 1,
// Nombre. 127 caracteres máximo.
'pr_name' => 'Nombre del producto-servicio vendido',
// Descripción . Maximo 230 caracteres.
'pr_desc' => 'Descripción del producto-servicio vendido.',
// Precio individual del producto. sin separadores de miles,
// utiliza el punto (.) como separadores de decimales. Máximo dos decimales
// Ej. 9999.99
'pr_price' => '20000',
// Cantidad, Entero sin separadores de miles
'pr_qty' => '1',
// Dirección de imagen. debe ser una dirección (url) válida para la imagen.
'pr_img' => 'http://www.misitio.com/producto/image/imagen.jpg',
);
array_push($ProductItems, $product_1);
//La información conjunta para ser procesada
$pagoFlashRequestData = array(
'cabecera_de_compra' => $cabeceraDeCompra,
'productos_items' => $ProductItems
);
//Se realiza el proceso de pago, devuelve JSON con la respuesta del servidor
$response = $api->procesarPago($pagoFlashRequestData, $_SERVER['HTTP_USER_AGENT']);
$pfResponse = json_decode($response);
//Si es exitoso, genera y guarda un link de pago en (url_to_buy) el cual se usará para redirigir al formulario de pago
if($pfResponse->success){
?>
<a href="<?php echo $pfResponse->url_to_buy ?>" target="_blank">Pagar</a>
<?php
//header("Location: ".$pfResponse->url_to_buy);
}else{
//manejo del error.
}
?>
```
##Documentación del sdk
###Parametros
- **$key_public** *requerido*: identificador del punto de venta, se genera al crear un punto de venta en una cuenta tipo empresa de PagoFlash, formato: UOmRvAQ4FodjSfqd6trsvpJPETgT9hxZ
- **$key_secret** *requerido*: clave privada del punto de venta, se genera al crear un punto de venta en una cuenta tipo empresa de PagoFlash, formato: h0lmI11KlPpsVBCT8EZi
- **$url_process** *requerido*: url del sitio al cual se realizara la llamada de retorno desde PagoFlash cuando se complete una transaccion.
- **$test_mode**: parámetro booleano que indica si las transacciones se ralizaran en el entorno de pruebas o el real.
Utiliza estos números de tarjeta de crédito para realizar las pruebas:
###- Transacción exitosa: 2222444455556666
###- Transacción rechazada: 4444444444445555
(Puedes ingresar cualquier otra información relacionada con la tarjeta)
###Valores retornados por PagoFlash
Al finalizar la transacción retornamos un parámetro ('tk') con el cual podrán verificar si la transacción fue satisfactoria o no. Para ello existe el método en nuestro API llamado validarTokenDeTransaccion . A continuación definimos su uso.
```php
<?php
include_once('pagoflash.api.client.php');
// url de tu sitio donde deberás procesar el pago
$url_process = "http://www.misitio.com/procesar_pago.php";
// cadena de 32 caracteres generada por la aplicación, Ej. aslkasjlkjl2LKLKjkjdkjkljlk&as87
$key_public = "tu_clave_publica";
// cadena de 20 caracteres generado por la aplicación. Ej. KJHjhKJH644GGr769jjh
$key_secret = "tu_clave_secreta";
$test_mode = true
//el cuarto parámetro (true) es para activar el modo de pruebas, para desactivar colocar en **false**
$api = new apiPagoflash($key_public,$key_secret, $urlCallbacks,$test_mode);
$response = $api->validarTokenDeTransaccion($_GET["tk"], $_SERVER['HTTP_USER_AGENT']);
$responseObj = json_decode($response, true);
switch ($responseObj["cod"])
{
// Sucede cuando los parámetros para identificar el punto de venta no coinciden
// con los almacenados en la plataforma PagoFlash
case "4" :
print "Prametros recibidos no coinciden";
break;
// Sucede cuando el token enviado para ser verificado no pertenece al punto de
// venta.
case "6" :
print "Transaccion no pertenece a su punto de venta";
break;
// Sucede cuando la transacción enviada para ser verificada no fue completada
// en la plataforma.
case "5" :
print "Esta transaccion no completada";
break;
// Sucede cuando la transacción enviada para ser verificada fue completada
// de manera satisfactoria.
case "1" :
print "Transaccion valida y procesada satisfactoriamente";
break;
}
?>
```
<file_sep><?php
namespace pagoflash\woocommerce;
if (false === defined('ABSPATH'))
{
header('Location: http://www.pagoflash.com');
exit;
}
/*
* Copyright 2016 PagoFlash International C.A. - email : <EMAIL>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 2, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Plugin Name: PagoFlash - Método de Pago para WooCommerce
* Plugin URI: http://pagoflash.com/
* Description: Permite a tus clientes de la tienda virtual realizarte los pagos usando la plataforma de PagoFlash International
* Version: 1.1-2015
* Author: PagoFlash International C.A.
* Author URI: http://www.pagoflash.com
* License: GPL2
* Text Domain: pagoflash
*/
// incorpora el punto de entrada del plugin
require_once dirname(__FILE__) . '/inc/Plugin.php';
// establece la función que se ejecutará al activar el plugin
register_activation_hook(__FILE__, ['pagoflash\woocommerce\inc\Plugin', 'onActivate']);
// establece la función que se ejecutará al desactivar el plugin
register_deactivation_hook(__FILE__, ['pagoflash\woocommerce\inc\Plugin', 'onDeactivate']);
<file_sep><?php
/* @var $response stdClass */
/* @var $message string */
if (false === defined('ABSPATH'))
{
header('Location: http://www.enebruskemlem.com.ve');
exit;
}
global $pagoflash_woocommerce;
/* @var $pagoflash_woocommerce \pagoflash\woocommerce\inc\Plugin */
global $woocommerce;
/* @var $woocommerce WooCommerce */
?>
<?php get_header(); ?>
<section>
<img style="border-radius:3px; border:1px solid #D7D7D7" src="<?= $pagoflash_woocommerce->base_url; ?>/img/pagoflash-full.png" />
<br/>
<h2><?= __('Your payment could not be completed', 'pagoflash'); ?></h2>
<p><?= $message; ?></p>
<p>
<a class="button button-primary" href="<?= $woocommerce->cart->get_cart_url(); ?>">
<?= __('Back to Cart', 'pagoflash'); ?>
</a>
</p>
</section>
<?php get_footer(); ?> | 739e875b3d14c2bfa690742abe2a8ddca8cc8eff | [
"Markdown",
"Text",
"PHP"
] | 16 | PHP | PagoFlash/pagoflash-wordpress | 04825e6587a960a6cc5d4422028fc71747b85d7c | f3e47c46d2555432d06d70c00d1d47cc632ddf2a |
refs/heads/master | <file_sep>using System;
using System.Threading;
using System.Threading.Tasks;
namespace SampleAsyncAwait
{
class Program
{
static void Factorial(int n = 6, CancellationToken token)
{
if (n < 1) throw new Exception($"{n}: число не должно быть меньше 1");
int result = 1;
for(int i=1; i<=n; i++)
{
if (token.IsCancellationRequested) // На каждой итерации проверяем - не прислали-ли извне Отмену Task(-а)
{
Console.WriteLine("Операция прервана");
return;
}
result *= i;
}
Thread.Sleep(8000);
Console.WriteLine($"Факториал {result}");
}
//Определение асинхронного метода async-await
static async void FactorialAsync(int n, CancellationToken token)
{
Console.WriteLine("Начало метода FactorialAsync"); // выполняется синхронно
if (token.IsCancellationRequested) return;
try
{
Task task = Task.Run(() => Factorial(n, token));// выполняется асинхронно
await task;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
};
Console.WriteLine("Конец метода FactorialAsync");
}
static async void FactorialAsyncInSeries(CancellationToken token)
{
//Выполняется последовательно
await Task.Run(() => Factorial(4, token));
await Task.Run(() => Factorial(3, token));
await Task.Run(() => Factorial(5, token));
}
static async void FactorialAsyncInParalell(CancellationToken token)
{
Task alltasks = null;
try
{
//Выполняется паралелльно
Task t1 = Task.Run(() => Factorial(4, token));
Task t2 = Task.Run(() => Factorial(3, token));
Task t3 = Task.Run(() => Factorial(5, token));
//await Task.WhenAll(new[] { t1, t2, t3 });
alltasks = Task.WhenAll(new Task[] { t1, t2, t3 });
await alltasks;
}
catch (Exception ex)
{
Console.WriteLine("Исключение:"+ ex.Message);
Console.WriteLine("IsFaulted=" + alltasks.IsFaulted);
foreach(var inx in alltasks.Exception.InnerExceptions)
{
Console.WriteLine("Внутреннее исключение:" + inx.Message);
}
}
}
static void Main(string[] args)
{
int n;
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Console.WriteLine("Введите число:");
n = Int32.Parse(Console.ReadLine());
FactorialAsync(n, token); // Вызов асинхронного метода
tokenSource.Cancel(); // Прерываем(отменяем) Task
Console.WriteLine($"Квадрат числа равен {n*n}");
Console.Read();
}
}
}
| e26780b699b0cdeae26b7d49cf4d8b15775babd7 | [
"C#"
] | 1 | C# | SergeyArtemov/SampleAsyncAwait | 9192ec8c8f9b30f0fabb31d2d3170ec86f1e6b59 | e47aaea6a5829f13f8872eeea59aad966d89660c |
refs/heads/master | <file_sep>/**
* @license AngularJS v1.0.1
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {
'use strict';
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase =3D function(string){return isString(string) ? string.toLower=
Case() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase =3D function(string){return isString(string) ? string.toUpper=
Case() : string;};
var manualLowercase =3D function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt=
(0) | 32);})
: s;
};
var manualUppercase =3D function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt=
(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results =
in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowerca=
se/uppercase methods
// with correct but slower alternatives.
if ('i' !=3D=3D 'I'.toLowerCase()) {
lowercase =3D manualLowercase;
uppercase =3D manualUppercase;
}
function fromCharCode(code) {return String.fromCharCode(code);}
var Error =3D window.Error,
/** holds major version number for IE or NaN for real browsers */
msie =3D int((/msie (\d+)/.exec(lowercase(navigator.userAg=
ent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after u=
s.
jQuery, // delay binding
slice =3D [].slice,
push =3D [].push,
toString =3D Object.prototype.toString,
/** @name angular */
angular =3D window.angular || (window.angular =3D {}),
angularModule,
nodeName_,
uid =3D ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, =
which can be either an
* object or an array. The `iterator` function is invoked with `iterator(va=
lue, key)`, where `value`
* is the value of an object property or an array element and `key` is the =
object property key or
* array element index. Specifying a `context` for the function is optional=
.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values =3D {name: 'misko', gender: 'male'};
var log =3D [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=3D} context Object to become context (`this`) for the ite=
rator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key !=3D 'prototype' && key !=3D 'length' && ke=
y !=3D 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !=3D=3D forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key =3D 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys =3D [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys =3D sortedKeys(obj);
for ( var i =3D 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to =
have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence=
of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a nu=
mber counter is that
* the number string gets longer over time, and it can also overflow, where=
as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index =3D uid.length;
var digit;
while(index) {
index--;
digit =3D uid[index].charCodeAt(0);
if (digit =3D=3D 57 /*'9'*/) {
uid[index] =3D 'A';
return uid.join('');
}
if (digit =3D=3D 90 /*'Z'*/) {
uid[index] =3D '0';
} else {
uid[index] =3D String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties fr=
om the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !=3D=3D dst) {
forEach(obj, function(value, key){
dst[key] =3D value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when=
writing code in the
* functional style.
<pre>
function foo(callback) {
var result =3D calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject =3D [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when=
writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject =3D [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value =3D=3D 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value !=3D 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript,=
`null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value !=3D null && typeof value =3D=
=3D 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value =3D=3D 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value =3D=3D 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) =3D=3D '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) =3D=3D '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value =3D=3D 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj=
.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) =3D=3D=3D '[object File]';
}
function isBoolean(value) {
return typeof value =3D=3D 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : =
value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery e=
lement).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find metho=
d part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj =3D {}, items =3D str.split(","), i;
for ( i =3D 0; i < items.length; i++ )
obj[ items[i] ] =3D true;
return obj;
}
if (msie < 9) {
nodeName_ =3D function(element) {
element =3D element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName !=3D 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nod=
eName;
};
} else {
nodeName_ =3D function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results =3D [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties =
an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expres=
sions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=3Dfalse] Count only "own" properties in a=
n object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object=
nor an array.
*/
function size(obj, ownPropsOnly) {
var size =3D 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) !=3D -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i =3D 0; i < array.length; i++) {
if (obj =3D=3D=3D array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index =3D indexOf(array, value);
if (index >=3D0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is create=
d.
* * If a destination is provided, all of its elements (for array) or prope=
rties (for objects)
* are deleted and then all elements/properties from the source are copie=
d to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expres=
sions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `un=
defined`.
* @param {(Object|Array)=3D} destination Destination into which the source=
is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was spe=
cified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window o=
r Scope");
if (!destination) {
destination =3D source;
if (source) {
if (isArray(source)) {
destination =3D copy(source, []);
} else if (isDate(source)) {
destination =3D new Date(source.getTime());
} else if (isObject(source)) {
destination =3D copy(source, {});
}
}
} else {
if (source =3D=3D=3D destination) throw Error("Can't copy equivalent ob=
jects or arrays");
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i =3D 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] =3D copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst =3D dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !=3D=3D '$$') {
dst[key] =3D src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value t=
ypes, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the f=
ollowing is true:
*
* * Both objects or values pass `=3D=3D=3D` comparison.
* * Both objects or values are of the same type and all of their propertie=
s pass `=3D=3D=3D` comparison.
* * Both values are NaN. (In JavasScript, NaN =3D=3D NaN =3D> false. Bu=
t we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and propert=
ies with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`=3D=3D=
=3D`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 =3D=3D=3D o2) return true;
if (o1 =3D=3D=3D null || o2 =3D=3D=3D null) return false;
if (o1 !=3D=3D o1 && o2 !=3D=3D o2) return true; // NaN =3D=3D=3D=
NaN
var t1 =3D typeof o1, t2 =3D typeof o2, length, key, keySet;
if (t1 =3D=3D t2) {
if (t1 =3D=3D 'object') {
if (isArray(o1)) {
if ((length =3D o1.length) =3D=3D o2.length) {
for(key=3D0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() =3D=3D o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) ret=
urn false;
keySet =3D {};
for(key in o1) {
if (key.charAt(0) !=3D=3D '$' && !isFunction(o1[key]) &am=
p;& !equals(o1[key], o2[key])) {
return false;
}
keySet[key] =3D true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !=3D=3D '$' && =
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` bec=
omes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the funct=
ion. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` functio=
n call.
* @returns {function()} Function that wraps the `fn` with all the specifie=
d bindings.
*/
function bind(self, fn) {
var curryArgs =3D arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (not=
e: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val =3D value;
if (/^\$+/.test(key)) {
val =3D undefined;
} else if (isWindow(value)) {
val =3D '$WINDOW';
} else if (value && document =3D=3D=3D value) {
val =3D '$DOCUMENT';
} else if (isScope(value)) {
val =3D '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into=
JSON.
* @param {boolean=3D} pretty If set to true, the JSON output will contain =
newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !=3D=3D 0) {
var v =3D lowercase("" + value);
value =3D !(v =3D=3D 'f' || v =3D=3D '0' || v =3D=3D 'false' || v =3D=
=3D 'no' || v =3D=3D 'n' || v =3D=3D '[]');
} else {
value =3D false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element =3D jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
return jqLite('<div>').append(element).html().
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' +=
lowercase(nodeName); });
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj =3D {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value =3D keyValue.split('=3D');
key =3D decodeURIComponent(key_value[0]);
obj[key] =3D isDefined(key_value[1]) ? decodeURIComponent(key_value[1=
]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts =3D [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value =3D=3D=3D true ? '' : '=
=3D' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive an=
d doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (p=
char) allowed in path
* segments:
* segment =3D *pchar
* pchar =3D unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded =3D "%" HEXDIG HEXDIG
* unreserved =3D ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims =3D "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "=3D"
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=3D').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query com=
ponent. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff tha=
t doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query =3D *( pchar / "/" / "?" )
* pchar =3D unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved =3D ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded =3D "%" HEXDIG HEXDIG
* sub-delims =3D "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "=3D"
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp on optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* ot the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 =3D {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements =3D [element],
appElement,
module,
names =3D ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP =3D /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] =3D true;
append(document.getElementById(name));
name =3D name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className =3D ' ' + element.className + ' ';
var match =3D NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement =3D element;
module =3D (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement =3D element;
module =3D attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular applic=
ation.
* @param {Array<String|Function>=3D} modules an array of module decl=
arations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this ap=
p.
*/
function bootstrap(element, modules) {
element =3D jqLite(element);
modules =3D modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector =3D createInjector(modules);
injector.invoke(
['$rootScope', '$rootElement', '$compile', '$injector', function(scope,=
element, compile, injector){
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
}
var SNAKE_CASE_REGEXP =3D /[A-Z]/g;
function snake_case(name, separator){
separator =3D separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery =3D window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite =3D jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite =3D JQLite;
}
angular.element =3D jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "re=
quired"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg =3D arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg =3D=3D 'object' ? arg.constructor.name || =
'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] =3D factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules =3D {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering =
Angular modules. All
* modules (angular core or 3rd party) that should be available to an a=
pplication must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and conf=
igure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule =3D angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector =3D angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=3D} requires If specified then new modu=
le is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the mod=
ule. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] =3D null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue =3D [];
/** @type {!Array.<Function>} */
var runBlocks =3D [];
var config =3D invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance =3D {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which mus=
t be loaded before this module.
* @description
* Holds the list of modules which the injector will load before =
the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creat=
ing new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new i=
nstance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will=
be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other =
provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating =
new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.registe=
r()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider=
.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creati=
ng new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.dire=
ctive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module loa=
d. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed o=
n module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after=
injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed w=
hen the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=3D} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, argument=
s]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version.=
This object has the
* following properties:
*
* - `full` =E2=80� `{string}` =E2=80� Full version string, s=
uch as "0.9.18".
* - `major` =E2=80� `{number}` =E2=80� Major version number,=
such as "0".
* - `minor` =E2=80� `{number}` =E2=80� Minor version number,=
such as "9".
* - `dot` =E2=80� `{number}` =E2=80� Dot version number, suc=
h as "18".
* - `codeName` =E2=80� `{string}` =E2=80� Code name of the r=
elease, such as "jiggling-armfat".
*/
var version =3D {
full: '1.0.1', // all of these placeholder strings will be replaced by=
rake's
major: 1, // compile task
minor: 0,
dot: 1,
codeName: 'thorium-shielding'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule =3D setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) =
element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.=
com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in A=
ngular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded =
before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly =
needed functionality
* within a very small footprint, so only a subset of the jQuery API - meth=
ods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery o=
r jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name=
.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular privides an additional method to bot=
h jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element o=
r its parent. By default
* retrieves controller associated with the `ngController` directive. If =
`name` is provided as
* camelCase directive name, then the controller for this directive will =
be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its pa=
rent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the=
current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a val=
ue is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapp=
ed into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache =3D JQLite.cache =3D {},
jqName =3D JQLite.expando =3D 'ng-' + new Date().getTime(),
jqId =3D 1,
addEventListenerFn =3D (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, fal=
se);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}=
),
removeEventListenerFn =3D (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, =
false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); =
});
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP =3D /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP =3D /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case lette=
r.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction =
apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn =3D jQuery.fn[name];
originalJqFn =3D originalJqFn.$original || originalJqFn;
removePatch.$original =3D originalJqFn;
jQuery.fn[name] =3D removePatch;
function removePatch() {
var list =3D [this],
fireEvent =3D dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set =3D list.shift();
for(setIndex =3D 0, setLength =3D set.length; setIndex < setLength=
; setIndex++) {
element =3D jqLite(set[setIndex]);
if (fireEvent) {
events =3D element.data('events');
if ( (fns =3D events && events.$destroy) ) {
forEach(fns, function(fn){
fn.handler();
});
}
} else {
fireEvent =3D !fireEvent;
}
for(childIndex =3D 0, childLength =3D (children =3D element.childre=
n()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) !=3D '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div =3D document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML =3D '<div>&nbsp;</div>' + element; // IE =
insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i =3D 0, children =3D element.childNodes || []; i < children=
.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events =3D JQLiteExpandoStore(element, 'events'),
handle =3D JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId =3D element[jqName],
expandoStore =3D jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$des=
troy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] =3D undefined; // ie does not allow deletion of attribu=
tes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId =3D element[jqName],
expandoStore =3D jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] =3D expandoId =3D jqNextId();
expandoStore =3D jqCache[expandoId] =3D {};
}
expandoStore[key] =3D value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data =3D JQLiteExpandoStore(element, 'data'),
isSetter =3D isDefined(value),
keyDefined =3D !isSetter && isDefined(key),
isSimpleGetter =3D keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data =3D {});
}
if (isSetter) {
data[key] =3D value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className =3D trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className =3D trim(element.className + ' ' + trim(cssClass)=
);
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements =3D (!elements.nodeName && isDefined(elements.length) =
&& !isWindow(elements))
? elements
: [ elements ];
for(var i=3D0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Co=
ntroller');
}
function JQLiteInheritedData(element, name, value) {
element =3D jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType =3D=3D 9) {
element =3D element.find('html');
}
while (element.length) {
if (value =3D element.data(name)) return value;
element =3D element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype =3D JQLite.prototype =3D {
ready: function(fn) {
var fired =3D false;
function trigger() {
if (fired) return;
fired =3D true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers an=
d IE9
// we can not use jqLite since we are not done loading and jQuery could=
be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for =
others
},
toString: function() {
var value =3D [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >=3D 0) ? jqLite(this[index]) : jqLite(this[this.len=
gth + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR =3D {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), =
function(value) {
BOOLEAN_ATTR[lowercase(value)] =3D value;
});
var BOOLEAN_ELEMENTS =3D {};
forEach('input,select,option,textarea,button,form'.split(','), function(val=
ue) {
BOOLEAN_ELEMENTS[uppercase(value)] =3D true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr =3D BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] &&am=
p; booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name =3D camelCase(name);
if (isDefined(value)) {
element.style[name] =3D value;
} else {
var val;
if (msie <=3D 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not su=
re why
val =3D element.currentStyle && element.currentStyle[name];
if (val =3D=3D=3D '') val =3D 'auto';
}
val =3D val || element.style[name];
if (msie <=3D 8) {
// jquery weirdness :-/
val =3D (val =3D=3D=3D '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName =3D lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] =3D true;
element.setAttribute(name, lowercasedName);
} else {
element[name] =3D false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE,=
see jQuery code
// some elements (e.g. Document) don't have get attribute, so return =
undefined
var ret =3D element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret =3D=3D=3D null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] =3D value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType =3D=3D 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText =3D value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue =3D value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent =3D value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value =3D value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i =3D 0, childNodes =3D element.childNodes; i < childNodes.=
length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML =3D value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] =3D function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so w=
e need to special-case it
// in a way that survives minification.
if (((fn.length =3D=3D 2 && (fn !=3D=3D JQLiteHasClass &&am=
p; fn !=3D=3D JQLiteController)) ? arg1 : arg2) =3D=3D=3D undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=3D0; i < this.length; i++) {
if (fn =3D=3D=3D JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=3D0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler =3D function (event, type) {
if (!event.preventDefault) {
event.preventDefault =3D function() {
event.returnValue =3D false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation =3D function() {
event.cancelBubble =3D true; //ie
};
}
if (!event.target) {
event.target =3D event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent =3D event.preventDefault;
event.preventDefault =3D function() {
event.defaultPrevented =3D true;
prevent.call(event);
};
event.defaultPrevented =3D false;
}
event.isDefaultPrevented =3D function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <=3D 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault =3D null;
event.stopPropagation =3D null;
event.isDefaultPrevented =3D null;
} else {
// It shouldn't affect normal browsers (native methods are defined on=
prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem =3D element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events =3D JQLiteExpandoStore(element, 'events'),
handle =3D JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events =3D {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle =3D createEve=
ntHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns =3D events[type];
if (!eventFns) {
if (type =3D=3D 'mouseenter' || type =3D=3D 'mouseleave') {
var counter =3D 0;
events.mouseenter =3D [];
events.mouseleave =3D [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter =3D=3D 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter --;
if (counter =3D=3D 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] =3D [];
}
eventFns =3D events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent =3D element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index =3D node;
});
},
children: function(element) {
var children =3D [];
forEach(element.childNodes, function(element){
if (element.nodeName !=3D '#text')
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType =3D=3D=3D 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType =3D=3D=3D 1) {
var index =3D element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index =3D child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode =3D jqLite(wrapNode)[0];
var parent =3D element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent =3D element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index =3D element, parent =3D element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index =3D node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition =3D !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent =3D element.parentNode;
return parent && parent.nodeType !=3D=3D 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] =3D function(arg1, arg2) {
var value;
for(var i=3D0; i < this.length; i++) {
if (value =3D=3D undefined) {
value =3D fn(this[i], arg1, arg2);
if (value !=3D=3D undefined) {
// any function which returns a value needs to be wrapped
value =3D jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value =3D=3D undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or =
uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the sam=
e hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType =3D typeof obj,
key;
if (objType =3D=3D 'object' && obj !=3D=3D null) {
if (typeof (key =3D obj.$$hashKey) =3D=3D 'function') {
// must invoke on object to keep the right this
key =3D obj.$$hashKey();
} else if (key =3D=3D=3D undefined) {
key =3D obj.$$hashKey =3D nextUid();
}
} else {
key =3D obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype =3D {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] =3D value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value =3D this[key =3D hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they =
form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype =3D {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array =3D this[key =3D hashKey(key)];
if (!array) {
this[key] =3D [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array =3D this[key =3D hashKey(key)];
if (array) {
if (array.length =3D=3D 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as=
well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module function=
s or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $inje=
ctor}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector =3D angular.injector(['ng']);
*
* // use the injector to kick of your application
* // use the type inference to auto inject arguments, or use implicit in=
jection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$inje=
ctor $injector}.
*/
var FN_ARGS =3D /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT =3D /,/;
var FN_ARG =3D /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS =3D /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn =3D=3D 'function') {
if (!($inject =3D fn.$inject)) {
$inject =3D [];
fnText =3D fn.toString().replace(STRIP_COMMENTS, '');
argDecl =3D fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject =3D $inject;
}
} else if (isArray(fn)) {
last =3D fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject =3D fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector =3D angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dep=
endency injection. The
* following ways are all valid way of annotating function with injection a=
rguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $inject.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject =3D ['serviceA'];
* $inject.invoke(explicit);
*
* // inline
* $inject.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function de=
finition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does no=
t work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters =
can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the =
function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments com=
e form the function annotation.
* @param {Object=3D} self The `this` for the invoked method.
* @param {Object=3D} locals Optional object. If preset then any argument n=
ames are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor functio=
n invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the con=
structor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=3D} locals Optional object. If preset then any argument n=
ames are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for i=
njection. This API is used by the injector
* to determine which services need to be injected into the function when t=
he function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies=
.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of t=
he function. This is done by converting
* the function into a string using `toString()` method and extracting the =
argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this =
reason the following annotation strategies
* are supported.
*
* # The `$injector` property
*
* If a function has an `$inject` property and its value is an array of str=
ings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController =3D function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject =3D ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setti=
ng the `$inject` property is very
* inconvenient. In these situations using the array notation to specify th=
e dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn =3D function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject =3D ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supporte=
d
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRoo=
tScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScop=
e) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which de=
pendent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the func=
tion requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The provi=
ders are the factories for the instance.
* The providers share the same name as the instance they create with the `=
Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `=
$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow fo=
r configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation =3D 'Hello';
*
* this.salutation =3D function(text) {
* salutation =3D text;
* };
*
* this.$get =3D function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and ca=
n have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will b=
e available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method wil=
l be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an i=
nstance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}=
, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Interna=
lly this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will b=
e instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant=
.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be=
injected
* into configuration function (other modules) and it is not interceptable =
by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service ins=
tance creation. The
* returned instance may be the original instance, or a new instance which =
delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the ser=
vice needs to be
* instanciated. The function is called using the {@link AUTO.$injector#=
invoke
* injector.invoke} method and is therefore fully injectable. Local inje=
ction arguments:
*
* * `$delegate` - The original service instance, which can be monkey pa=
tched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING =3D {},
providerSuffix =3D 'Provider',
path =3D [],
loadedModules =3D new HashMap(),
providerCache =3D {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector =3D createInternalInjector(providerCache, function()=
{
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache =3D {},
instanceInjector =3D (instanceCache.$injector =3D
createInternalInjector(instanceCache, function(servicename) {
var provider =3D providerInjector.get(servicename + providerSuf=
fix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invok=
e(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ =3D providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.')=
;
}
return providerCache[name + providerSuffix] =3D provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factory=
Fn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] =3D value;
instanceCache[name] =3D value;
}
function decorator(serviceName, decorFn) {
var origProvider =3D providerInjector.get(serviceName + providerSuffix)=
,
orig$get =3D origProvider.$get;
origProvider.$get =3D function() {
var origInstance =3D instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstanc=
e});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks =3D [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn =3D angularModule(module);
runBlocks =3D runBlocks.concat(loadModules(moduleFn.requires)).conc=
at(moduleFn._runBlocks);
try {
for(var invokeQueue =3D moduleFn._invokeQueue, i =3D 0, ii =3D in=
vokeQueue.length; i < ii; i++) {
var invokeArgs =3D invokeQueue[i],
provider =3D invokeArgs[0] =3D=3D '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message +=3D ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message +=3D ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message +=3D ' from ' + String(module[module.len=
gth - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !=3D=3D 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] =3D=3D=3D INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] =3D INSTANTIATING;
return cache[serviceName] =3D factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args =3D [],
$inject =3D annotate(fn),
length, i,
key;
for(i =3D 0, length =3D $inject.length; i < length; i++) {
key =3D $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, path)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn =3D fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invok=
e
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], arg=
s[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], arg=
s[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], arg=
s[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], arg=
s[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], arg=
s[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor =3D function() {},
instance, returnedValue;
Constructor.prototype =3D (isArray(Type) ? Type[Type.length - 1] : Ty=
pe).prototype;
instance =3D new Constructor();
returnedValue =3D invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to=
related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-=
the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to=
match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScroll=
ing()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled =3D true;
this.disableAutoScrolling =3D function() {
autoScrollingEnabled =3D false;
};
this.$get =3D ['$window', '$location', '$rootScope', function($window, $l=
ocation, $rootScope) {
var document =3D $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result =3D null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) =3D=3D=3D 'a') r=
esult =3D element;
});
return result;
}
function scroll() {
var hash =3D $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm =3D document.getElementById(hash))) elm.scrollIntoView(=
);
// first anchor with given name :-D
else if ((elm =3D getFirstAnchor(document.getElementsByName(hash)))) =
elm.scrollIntoView();
// no element and hash =3D=3D 'top', scroll to the top of the page
else if (hash =3D=3D=3D 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $locaiton.hash() change), browser native does scr=
oll
if (autoScrollingEnabled) {
$rootScope.$watch(function() {return $location.hash();}, function() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the =
`$browser`
* service, which can be used for convenient testing of the application wit=
hout the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self =3D this,
rawDocument =3D document[0],
location =3D window.location,
history =3D window.history,
setTimeout =3D window.setTimeout,
clearTimeout =3D window.clearTimeout,
pendingDeferIds =3D {};
self.isMock =3D false;
var outstandingRequestCount =3D 0;
var outstandingRequestCallbacks =3D [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest =3D completeOutstandingRequest;
self.$$incOutstandingRequestCount =3D function() { outstandingRequestCoun=
t++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outs=
tandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallback=
s` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount =3D=3D=3D 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outs=
tanding request
*/
self.notifyWhenNoOutstandingRequests =3D function(callback) {
// force browser to execute all pollFns - this is needed so that cookie=
s and other pollers fire
// at some deterministic time in respect to the test runner's actions. =
Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount =3D=3D=3D 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns =3D [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically exec=
utes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn =3D function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions =
(ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout=
` function.
*
* @description
* Configures the poller to run in the specified intervals, using the spe=
cified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout =3D setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl =3D location.href,
baseElement =3D document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of locati=
on.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherw=
ise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Plea=
se use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=3D} replace Should new url replace current history rec=
ord ?
*/
self.url =3D function(url, replace) {
// setter
if (url) {
if (lastBrowserUrl =3D=3D url) return;
lastBrowserUrl =3D url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dm=
l?id=3D1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href =3D url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/s=
how_bug.cgi?id=3D407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners =3D [],
urlChangeInit =3D false;
function fireUrlChange() {
if (lastBrowserUrl =3D=3D self.url()) return;
lastBrowserUrl =3D self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Plea=
se use the
* {@link ng.$location $location service} to monitor url changes in angul=
ar apps.
*
* @param {function(string)} listener Listener function to be called when=
url changes.
* @return {function(string)} Returns the registered listener fn - handy =
if the fn is anonymous.
*/
self.onUrlChange =3D function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some br=
owsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fir=
e hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlCha=
nge);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit =3D true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=3D}
*/
self.baseHref =3D function() {
var href =3D baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies =3D {};
var lastCookieString =3D '';
var cookiePath =3D self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=3D} name Cookie name
* @param {string=3D} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser co=
okies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was =
called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of=
the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is =
undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) =3D=3D D=
ELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter=
)
*/
self.cookies =3D function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value =3D=3D=3D undefined) {
rawDocument.cookie =3D escape(name) + "=3D;path=3D" + cookiePath + =
";expires=3DThu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength =3D (rawDocument.cookie =3D escape(name) + '=3D' + e=
scape(value) + ';path=3D' + cookiePath).length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed b=
ecause it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed b=
ecause too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !=3D=3D lastCookieString) {
lastCookieString =3D rawDocument.cookie;
cookieArray =3D lastCookieString.split("; ");
lastCookies =3D {};
for (i =3D 0; i < cookieArray.length; i++) {
cookie =3D cookieArray[i];
index =3D cookie.indexOf('=3D');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] =3D unescape(=
cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=3D} [delay=3D0] of milliseconds to defer the function e=
xecution.
* @returns {*} DeferId that can be used to cancel the task via `$browser=
.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mo=
cked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be pr=
ogrammatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer =3D function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId =3D setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] =3D true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and =
was successfuly canceled.
*/
self.defer.cancel =3D function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get =3D ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=3D} options Options object that specifies the cache behav=
ior. Properties:
*
* - `{number=3D}` `capacity` =E2=80� turns the cache into LRU cac=
he.
*
* @returns {object} Newly created cache object with the following set of m=
ethods:
*
* - `{object}` `info()` =E2=80� Returns id, size, and options of ca=
che.
* - `{void}` `put({string} key, {*} value)` =E2=80� Puts a new key-=
value pair into the cache.
* - `{{*}} `get({string} key) =E2=80� Returns cached value for `key=
` or undefined for cache miss.
* - `{void}` `remove({string} key) =E2=80� Removes a key-value pair=
from the cache.
* - `{void}` `removeAll() =E2=80� Removes all cached values.
* - `{void}` `destroy() =E2=80� Removes references to this cache fr=
om $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get =3D function() {
var caches =3D {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size =3D 0,
stats =3D extend({}, options, {id: cacheId}),
data =3D {},
capacity =3D (options && options.capacity) || Number.MAX_=
VALUE,
lruHash =3D {},
freshEnd =3D null,
staleEnd =3D null;
return caches[cacheId] =3D {
put: function(key, value) {
var lruEntry =3D lruHash[key] || (lruHash[key] =3D {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] =3D value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry =3D lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry =3D lruHash[key];
if (lruEntry =3D=3D freshEnd) freshEnd =3D lruEntry.p;
if (lruEntry =3D=3D staleEnd) staleEnd =3D lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data =3D {};
size =3D 0;
lruHash =3D {};
freshEnd =3D staleEnd =3D null;
},
destroy: function() {
data =3D null;
stats =3D null;
lruHash =3D null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry !=3D freshEnd) {
if (!staleEnd) {
staleEnd =3D entry;
} else if (staleEnd =3D=3D entry) {
staleEnd =3D entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd =3D entry;
freshEnd.n =3D null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry !=3D prevEntry) {
if (nextEntry) nextEntry.p =3D prevEntry; //p stands for previous=
, 'prev' didn't minify
if (prevEntry) prevEntry.n =3D nextEntry; //n stands for next, 'n=
ext' didn't minify
}
}
}
cacheFactory.info =3D function() {
var info =3D {};
forEach(caches, function(cache, cacheId) {
info[cacheId] =3D cache.info();
});
return info;
};
cacheFactory.get =3D function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get =3D ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particul=
ar node
* - "childLinkFn" - function that aggregates all linking fns for child no=
des of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a com=
pilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION =3D 'Non-assignable model expression: '=
;
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a te=
mplate function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the templ=
ate together.
*
* The compilation is a process of walking the DOM tree and trying to match=
DOM elements to
* {@link ng.$compileProvider.directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returne=
d.
*
* The template function can then be used once to produce the view or as it=
is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original tem=
plate.
*
<doc:example module=3D"compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name =3D 'Angular';
$scope.html =3D 'Hello {{name}}';
}
</script>
<div ng-controller=3D"Ctrl">
<input ng-model=3D"name"> <br>
<textarea ng-model=3D"html"></textarea> <br>
<div compile=3D"html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile int=
o a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function ava=
ilable to directives.
* @param {number} maxPriority only apply directives lower then given prior=
ity (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is use=
d to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link funct=
ion will clone the
* `template` and call the `cloneAttachFn` function allowing =
the caller to attach the
* cloned elements to the DOM document at the appropriate pla=
ce. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)=
` where:
*
* * `clonedElement` - is a clone of the original `element` passed int=
o the compiler.
* * `scope` - is the current scope with which the linking function is=
working with.
*
* Calling the linking function returns the element of the template. It is =
either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provide=
d.
*
* After linking the view is not updated until after a call to $digest whic=
h typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, crea=
te the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element =3D $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view refe=
rence from the original
* example would not point to the clone, but rather to the original templ=
ate that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML =3D angular.element('<p>{{total}}</p>')=
,
* scope =3D ....;
*
* var clonedElement =3D $compile(templateHTML)(scope, function(clonedE=
lement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Gu=
ide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with compiler
*
* @param {string} name name of the directive.
* @param {function} directiveFactory An injectable directive factory funct=
ion.
* @returns {ng.$compileProvider} Self for chaining.
*/
$CompileProvider.$inject =3D ['$provide'];
function $CompileProvider($provide) {
var hasDirectives =3D {},
Suffix =3D 'Directive',
COMMENT_DIRECTIVE_REGEXP =3D /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/=
,
CLASS_DIRECTIVE_REGEXP =3D /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR =3D 'Template must have exactly one root el=
ement. was: ';
/**
* @ngdoc function
* @name ng.$compileProvider.directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code=
>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy fun=
ction. See {@link guide/directive} for more
* info.
*/
this.directive =3D function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] =3D [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives =3D [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive =3D $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive =3D { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile =3D valueFn(directive.link);
}
directive.priority =3D directive.priority || 0;
directive.name =3D directive.name || name;
directive.require =3D directive.require || (directive.contr=
oller && directive.name);
directive.restrict =3D directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
this.$get =3D [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$te=
mplateCache', '$parse',
'$controller', '$rootScope',
function($injector, $interpolate, $exceptionHandler, $http, $te=
mplateCache, $parse,
$controller, $rootScope) {
var Attributes =3D function(element, attr) {
this.$$element =3D element;
this.$attr =3D attr || {};
};
Attributes.prototype =3D {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all d=
irectives
* can share the attribute. This function properly handles boolean at=
tributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribut=
e will be deleted.
* @param {boolean=3D} writeAttr If false, does not write the value t=
o DOM element attribute.
* Defaults to true.
* @param {string=3D} attrName Optional none normalized name. Default=
s to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey =3D getBooleanAttrName(this.$$element[0], key),
$$observers =3D this.$$observers;
if (booleanKey) {
this.$$element.prop(key, value);
attrName =3D booleanKey;
}
this[key] =3D value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] =3D attrName;
} else {
attrName =3D this.$attr[key];
if (!attrName) {
this.$attr[key] =3D attrName =3D snake_case(key, '-');
}
}
if (writeAttr !=3D=3D false) {
if (value =3D=3D=3D null || value =3D=3D=3D undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not inter=
polated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the =
attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs =3D this,
$$observers =3D (attrs.$$observers || (attrs.$$observers =3D {}=
)),
listeners =3D ($$observers[key] || ($$observers[key] =3D []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets =
call it manually
fn(attrs[key]);
}
});
return fn;
}
};
return compile;
//=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D
function compile($compileNode, transcludeFn, maxPriority) {
if (!($compileNode instanceof jqLite)) {
// jquery always rewraps, where as we need to preserve the original=
selector so that we can modify it.
$compileNode =3D jqLite($compileNode);
}
// We can not compile top level text elements since text nodes can be=
merged and we will
// not be able to attach scope data to them, so we will wrap them in =
<span>
forEach($compileNode, function(node, index){
if (node.nodeType =3D=3D 3 /* text node */) {
$compileNode[index] =3D jqLite(node).wrap('<span>').parent(=
)[0];
}
});
var compositeLinkFn =3D compileNodes($compileNode, transcludeFn, $com=
pileNode, maxPriority);
return function(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery on=
e is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode =3D cloneConnectFn
? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
: $compileNode;
$linkNode.data('$scope', scope);
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directive=
s. Once all directives
* for a particular node are collected their compile functions are exec=
uted. The compile
* functions return values - the linking functions - are combined into =
a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A link=
ing function, where the
* scope argument is auto-generated to the new child of the tran=
scluded parent scope.
* @param {DOMElement=3D} $rootElement If the nodeList is the root of t=
he compilation tree then the
* rootElement must be set the jqLite collection of the compile =
root. This is
* needed so that the jqLite collection items can be replaced wi=
th widgets.
* @param {number=3D} max directive priority
* @returns {?function} A composite linking function of all of the matc=
hed directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority=
) {
var linkFns =3D [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i =3D 0; i < nodeList.length; i++) {
attrs =3D new Attributes();
// we must always refer to nodeList[i] since the nodes can be replac=
ed underneath us.
directives =3D collectDirectives(nodeList[i], [], attrs, maxPriority=
);
nodeLinkFn =3D (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transclu=
deFn, $rootElement)
: null;
childLinkFn =3D (nodeLinkFn && nodeLinkFn.terminal)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound =3D (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTransclud=
eFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
for(var i =3D 0, n =3D 0, ii =3D linkFns.length; i < ii; n++) {
node =3D nodeList[n];
nodeLinkFn =3D linkFns[i++];
childLinkFn =3D linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope =3D scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope =3D scope;
}
childTranscludeFn =3D nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transclu=
deFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope =3D scope.$new();
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeS=
cope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTran=
scludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn=
);
}
}
}
}
/**
* Looks for directives on the given node ands them to the directive co=
llection which is sorted.
*
* @param node node to search
* @param directives an array to which the directives are added to. Thi=
s array is sorted before
* the function returns.
* @param attrs the shared attrs object which is used to populate the n=
ormalized attributes.
* @param {number=3D} max directive priority
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType =3D node.nodeType,
attrsMap =3D attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPr=
iority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs =3D node.attributes,
j =3D 0, jj =3D nAttrs && nAttrs.length; j < =
jj; j++) {
attr =3D nAttrs[j];
if (attr.specified) {
name =3D attr.name;
nName =3D directiveNormalize(name.toLowerCase());
attrsMap[nName] =3D name;
attrs[nName] =3D value =3D trim((msie && name =3D=3D =
'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] =3D true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className =3D node.className;
if (isString(className)) {
while (match =3D CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName =3D directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] =3D trim(match[3]);
}
className =3D className.substr(match.index + match[0].length)=
;
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match =3D COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName =3D directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] =3D trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors wh=
en one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in tes=
t case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is e=
xecuted. This method
* is responsible for inlining directive templates as well as terminati=
ng the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute t=
heir compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile func=
tions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A link=
ing function, where the
* scope argument is auto-generated to the new child of the tran=
scluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of th=
e compile tree then this
* argument has the root jqLite array so that we can replace wid=
gets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, =
transcludeFn, $rootElement) {
var terminalPriority =3D -Number.MAX_VALUE,
preLinkFns =3D [],
postLinkFns =3D [],
newScopeDirective =3D null,
newIsolatedScopeDirective =3D null,
templateDirective =3D null,
$compileNode =3D templateAttrs.$$element =3D jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn =3D transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i =3D 0, ii =3D directives.length; i < ii; i++) {
directive =3D directives[i];
$template =3D undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue =3D directive.scope) {
assertNoDuplicate('isolated scope', newIsolatedScopeDirective, di=
rective, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolatedScopeDirective =3D directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective =3D newScopeDirective || directive;
}
directiveName =3D directive.name;
if (directiveValue =3D directive.controller) {
controllerDirectives =3D controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode)=
;
controllerDirectives[directiveName] =3D directive;
}
if (directiveValue =3D directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive,=
$compileNode);
transcludeDirective =3D directive;
terminalPriority =3D directive.priority;
if (directiveValue =3D=3D 'element') {
$template =3D jqLite(compileNode);
$compileNode =3D templateAttrs.$$element =3D
jqLite('<!-- ' + directiveName + ': ' + templateAttrs[di=
rectiveName] + ' -->');
compileNode =3D $compileNode[0];
replaceWith($rootElement, jqLite($template[0]), compileNode);
childTranscludeFn =3D compile($template, transcludeFn, terminal=
Priority);
} else {
$template =3D jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn =3D compile($template, transcludeFn);
}
}
if (directiveValue =3D directive.template) {
assertNoDuplicate('template', templateDirective, directive, $comp=
ileNode);
templateDirective =3D directive;
$template =3D jqLite('<div>' + trim(directiveValue) + '<=
/div>').contents();
compileNode =3D $template[0];
if (directive.replace) {
if ($template.length !=3D 1 || compileNode.nodeType !=3D=3D 1) =
{
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith($rootElement, $compileNode, compileNode);
var newTemplateAttrs =3D {$attr: {}};
// combine directives from the original node and from the templ=
ate:
// - take the array of directives for this element
// - split it into two parts, those that were already applied a=
nd those that weren't
// - collect directives from the template, add them to the seco=
nd group and sort them
// - append the second group with new directives to the first g=
roup
directives =3D directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii =3D directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $comp=
ileNode);
templateDirective =3D directive;
nodeLinkFn =3D compileTemplateUrl(directives.splice(i, directives=
.length - i),
nodeLinkFn, $compileNode, templateAttrs, $rootElement, direct=
ive.replace,
childTranscludeFn);
ii =3D directives.length;
} else if (directive.compile) {
try {
linkFn =3D directive.compile($compileNode, templateAttrs, child=
TranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal =3D true;
terminalPriority =3D Math.max(terminalPriority, directive.priorit=
y);
}
}
nodeLinkFn.scope =3D newScopeDirective && newScopeDirective.s=
cope;
nodeLinkFn.transclude =3D transcludeDirective && childTranscl=
udeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl =
is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require =3D directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require =3D directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod =3D 'data', optional =3D false;
if (isString(require)) {
while((value =3D require.charAt(0)) =3D=3D '^' || value =3D=3D '?=
') {
require =3D require.substr(1);
if (value =3D=3D '^') {
retrievalMethod =3D 'inheritedData';
}
optional =3D optional || value =3D=3D '?';
}
value =3D $element[retrievalMethod]('$' + require + 'Controller')=
;
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value =3D [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, bound=
TranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode =3D=3D=3D linkNode) {
attrs =3D templateAttrs;
} else {
attrs =3D shallowCopy(templateAttrs, new Attributes(jqLite(linkNo=
de), templateAttrs.$attr));
}
$element =3D attrs.$$element;
if (newScopeDirective && isObject(newScopeDirective.scope))=
{
var LOCAL_REGEXP =3D /^\s*([@=3D&])\s*(\w*)\s*$/;
var parentScope =3D scope.$parent || scope;
forEach(newScopeDirective.scope, function(definiton, scopeName) {
var match =3D definiton.match(LOCAL_REGEXP) || [],
attrName =3D match[2]|| scopeName,
mode =3D match[1], // @, =3D, or &
lastValue,
parentGet, parentSet;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] =3D value;
});
attrs.$$observers[attrName].$$scope =3D parentScope;
break;
}
case '=3D': {
parentGet =3D $parse(attrs[attrName]);
parentSet =3D parentGet.assign || function() {
// reset the change, or we will throw this exception on e=
very $digest
lastValue =3D scope[scopeName] =3D parentGet(parentScope)=
;
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrN=
ame] +
' (directive: ' + newScopeDirective.name + ')');
};
lastValue =3D scope[scopeName] =3D parentGet(parentScope);
scope.$watch(function() {
var parentValue =3D parentGet(parentScope);
if (parentValue !=3D=3D scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !=3D=3D lastValue) {
// parent changed and it has precedence
lastValue =3D scope[scopeName] =3D parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, lastValue =3D scope[scopeName]=
);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet =3D $parse(attrs[attrName]);
scope[scopeName] =3D function(locals) {
return parentGet(parentScope, locals);
}
break;
}
default: {
throw Error('Invalid isolate scope definition for directive=
' +
newScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals =3D {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller =3D directive.controller;
if (controller =3D=3D '@') {
controller =3D attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i =3D 0, ii =3D preLinkFns.length; i < ii; i++) {
try {
linkFn =3D preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $e=
lement));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, unde=
fined, boundTranscludeFn);
// POSTLINKING
for(i =3D 0, ii =3D postLinkFns.length; i < ii; i++) {
try {
linkFn =3D postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $e=
lement));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and =
proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific for=
mat.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match =3D false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives =3D $injector.get(name + Suffix),
i =3D 0, ii =3D directives.length; i<ii; i++) {
try {
directive =3D directives[i];
if ( (maxPriority =3D=3D=3D undefined || maxPriority > direc=
tive.priority) &&
directive.restrict.indexOf(location) !=3D -1) {
tDirectives.push(directive);
match =3D true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attribu=
tes
* on the template need to be merged with the existing attributes in th=
e DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr =3D src.$attr,
dstAttr =3D dst.$attr,
$element =3D dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) !=3D '$') {
if (src[key]) {
value +=3D (key =3D=3D=3D 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key =3D=3D 'class') {
safeAddClass($element, value);
dst['class'] =3D (dst['class'] ? dst['class'] + ' ' : '') + value=
;
} else if (key =3D=3D 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) !=3D '$' && !dst.hasOwnProperty(ke=
y)) {
dst[key] =3D value;
dstAttr[key] =3D srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $comp=
ileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue =3D [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode =3D $compileNode[0],
origAsyncDirective =3D directives.shift(),
// The fact that we have to copy and patch the directive seems wr=
ong!
derivedSyncDirective =3D extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
if (replace) {
$template =3D jqLite('<div>' + trim(content) + '</div&=
gt;').contents();
compileNode =3D $template[0];
if ($template.length !=3D 1 || compileNode.nodeType !=3D=3D 1) =
{
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs =3D {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode =3D beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn =3D applyDirectivesToNode(directives, $co=
mpileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn =3D compileNodes($compileNode.contents()=
, childTranscludeFn);
while(linkQueue.length) {
var controller =3D linkQueue.pop(),
linkRootElement =3D linkQueue.pop(),
beforeTemplateLinkNode =3D linkQueue.pop(),
scope =3D linkQueue.pop(),
linkNode =3D compileNode;
if (beforeTemplateLinkNode !=3D=3D beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode =3D JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), =
linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, lin=
kNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue =3D null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, roo=
tElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node,=
rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element)=
{
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', '=
+
directive.name + '] asking for ' + what + ' on: ' + startingTag(=
element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn =3D $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function(scope, node) {
var parent =3D node.parent(),
bindings =3D parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function(value) {
node[0].nodeValue =3D value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn =3D $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function(scope, element, attr) {
var $$observers =3D (attr.$$observers || (attr.$$observers =3D {}=
));
if (name =3D=3D=3D 'class') {
// we need to interpolate classes again, in the case the elemen=
t was replaced
// and therefore the two class attrs got merged - we want to in=
terpolate the result
interpolateFn =3D $interpolate(attr[name], true);
}
attr[name] =3D undefined;
($$observers[name] || ($$observers[name] =3D [])).$$inter =3D tru=
e;
(attr.$$observers && attr.$$observers[name].$$scope || sc=
ope).
$watch(interpolateFn, function(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is p=
rovided.
*
* @param {JqLite=3D} $rootElement The root of the compile tree. Used s=
o that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to re=
place. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode =3D $element[0],
parent =3D oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i =3D 0, ii =3D $rootElement.length; i < ii; i++) {
if ($rootElement[i] =3D=3D oldNode) {
$rootElement[i] =3D newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] =3D oldNode[jqLite.expando];
$element[0] =3D newNode;
}
}];
}
var PREFIX_REGEXP =3D /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case lette=
r.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which cont=
ains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The no=
rmalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind=3D"a" ng-bind=3D"a" data-ng-bind=3D"a" x-ng-bi=
nd=3D"a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized=
name. This is
* needed to do reverse lookup from normalized name back to actual=
name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property t=
o modify. The name is
* revers translated using the {@link ng.$compile.directive.Attrib=
utes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to cre=
ate new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers =3D {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optiona=
lly decorated with DI
* annotations in the array notation).
*/
this.register =3D function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] =3D constructor;
}
};
this.$get =3D ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then =
it's considered to be the
* controller constructor function. Otherwise it's considered to be =
a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$contr=
ollerProvider`
* * check if evaluating the string on the current scope returns a c=
onstructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extra=
cted into
* a service, so that one can override this service with {@link https:/=
/gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name =3D constructor;
constructor =3D controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, tr=
ue);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser=
's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get =3D ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this servi=
ce.
* The default implementation simply delegates to `$log.error` which logs i=
t into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridd=
en by
* {@link ngMock.$exceptionHandler mock $exceptionHandler}
*
* @param {Error} exception Exception associated with the error.
* @param {string=3D} cause optional information about the context in which
* the error was thrown.
*/
function $ExceptionHandlerProvider() {
this.$get =3D ['$log', function($log){
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc function
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Deafults to `{{` and `}}`=
.
*/
function $InterpolateProvider() {
var startSymbol =3D '{{';
var endSymbol =3D '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defau=
lts to `{{`.
*
* @prop {string=3D} value new value to set the starting symbol to.
*/
this.startSymbol =3D function(value){
if (value) {
startSymbol =3D value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Def=
aults to `}}`.
*
* @prop {string=3D} value new value to set the ending symbol to.
*/
this.endSymbol =3D function(value){
if (value) {
endSymbol =3D value;
return this;
} else {
return startSymbol;
}
};
this.$get =3D ['$parse', function($parse) {
var startSymbolLength =3D startSymbol.length,
endSymbolLength =3D endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This s=
ervice is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring=
the
* interpolation markup.
*
*
<pre>
var $interpolate =3D ...; // injected
var exp =3D $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=3D} mustHaveExpression if set to true then the inter=
polation string must have
* embedded expression in order to return an interpolation function.=
Strings with no
* embedded expression will return null for the interpolation functi=
on.
* @returns {function(context)} an interpolation function which is used=
to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in =
the strings are evaluated
* against.
*
*/
return function(text, mustHaveExpression) {
var startIndex,
endIndex,
index =3D 0,
parts =3D [],
length =3D text.length,
hasInterpolation =3D false,
fn,
exp,
concat =3D [];
while(index < length) {
if ( ((startIndex =3D text.indexOf(startSymbol, index)) !=3D -1) &a=
mp;&
((endIndex =3D text.indexOf(endSymbol, startIndex + startSymbo=
lLength)) !=3D -1) ) {
(index !=3D startIndex) && parts.push(text.substring(inde=
x, startIndex));
parts.push(fn =3D $parse(exp =3D text.substring(startIndex + star=
tSymbolLength, endIndex)));
fn.exp =3D exp;
index =3D endIndex + endSymbolLength;
hasInterpolation =3D true;
} else {
// we did not find anything, so we have to add the remainder to t=
he parts array
(index !=3D length) && parts.push(text.substring(index));
index =3D length;
}
}
if (!(length =3D parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length =3D 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length =3D length;
fn =3D function(context) {
for(var i =3D 0, ii =3D length, part; i<ii; i++) {
if (typeof (part =3D parts[i]) =3D=3D 'function') {
part =3D part(context);
if (part =3D=3D null || part =3D=3D undefined) {
part =3D '';
} else if (typeof part !=3D 'string') {
part =3D toJson(part);
}
}
concat[i] =3D part;
}
return concat.join('');
};
fn.exp =3D text;
fn.parts =3D parts;
return fn;
}
};
}];
}
var URL_MATCH =3D /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^=
\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH =3D /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH =3D PATH_MATCH,
DEFAULT_PORTS =3D {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments =3D path.split('/'),
i =3D segments.length;
while (i--) {
segments[i] =3D encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match =3D URL_MATCH.exec(url);
match =3D {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol =3D match.protocol;
obj.$$host =3D match.host;
obj.$$port =3D match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port =3D=3D DEFAULT_PORTS[protocol] ? '=
' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match =3D matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) !=3D basePath || isUndefined(match.has=
h) ||
match.hash.indexOf(hashPrefix) !=3D=3D 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) =
+
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.leng=
th);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match =3D matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) =3D=3D basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search =3D match.search && '?' + match.search || '',
hash =3D match.hash && '#' + match.hash || '',
pathPrefix =3D pathPrefixFromBase(basePath),
path =3D match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !=3D=3D 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + path=
Prefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) =
+ basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled a=
nd supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix =3D pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse =3D function(newAbsoluteUrl) {
var match =3D matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !=3D=3D 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefi=
x "' + pathPrefix + '" !');
}
this.$$path =3D decodeURIComponent(match.path.substr(pathPrefix.length)=
);
this.$$search =3D parseKeyValue(match.search);
this.$$hash =3D match.hash && decodeURIComponent(match.hash) ||=
'';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose =3D function() {
var search =3D toKeyValue(this.$$search),
hash =3D this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url =3D encodePath(this.$$path) + (search ? '?' + search : '') +=
hash;
this.$$absUrl =3D composeProtocolHostPort(this.$$protocol, this.$$host,=
this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl =3D function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) =3D=3D 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is di=
sabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and sea=
rch)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse =3D function(url) {
var match =3D matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !=3D=3D 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hash=
Prefix + '" !');
}
basePath =3D match.path + (match.search ? '?' + match.search : '');
match =3D HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length))=
;
if (match[1]) {
this.$$path =3D (match[1].charAt(0) =3D=3D '/' ? '' : '/') + decodeUR=
IComponent(match[1]);
} else {
this.$$path =3D '';
}
this.$$search =3D parseKeyValue(match[3]);
this.$$hash =3D match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose =3D function() {
var search =3D toKeyValue(this.$$search),
hash =3D this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url =3D encodePath(this.$$path) + (search ? '?' + search : '') +=
hash;
this.$$absUrl =3D composeProtocolHostPort(this.$$protocol, this.$$host,=
this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url =
: '');
};
this.$$rewriteAppUrl =3D function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) =3D=3D 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype =3D {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to =
rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=3Db#hash`) when called without any parameter=
.
*
* Change path, search and hash, when called with parameter and return `$=
location`.
*
* @param {string=3D} url New url without base prefix (e.g. `/path?a=3Db#=
hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match =3D PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method wil=
l add the forward slash
* if it is missing.
*
* @param {string=3D} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) =3D=3D '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any =
parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=3D} search New search param=
s - string or hash object
* @param {string=3D} paramValue If `search` is a string, then `paramValu=
e` will override only a
* single search parameter. If the value is `null`, the parameter will=
be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue =3D=3D=3D null) {
delete this.$$search[search];
} else {
this.$$search[search] =3D paramValue;
}
} else {
this.$$search =3D isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`=
.
*
* @param {string=3D} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be r=
eplacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace =3D true;
return this;
}
};
LocationHashbangUrl.prototype =3D inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra)=
{
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl =3D function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) =3D=3D 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.s=
ubstr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype =3D inherit(LocationHashbangUrl.protot=
ype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] =3D preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based o=
n the
* {@link https://developer.mozilla.org/en/window.location window.location}=
) and makes the URL
* available to your application. Changes to the URL in the address bar are=
reflected into
* $location service and changes to $location are reflected into the browse=
r address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, p=
ath, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Devel=
oper Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linkin=
g paths are stored.
*/
function $LocationProvider(){
var hashPrefix =3D '',
html5Mode =3D false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=3D} prefix Prefix for hash part (containing path and se=
arch)
* @returns {*} current value if used as getter or itself (chaining) if u=
sed as setter
*/
this.hashPrefix =3D function(prefix) {
if (isDefined(prefix)) {
hashPrefix =3D prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=3D} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if u=
sed as setter
*/
this.html5Mode =3D function(mode) {
if (isDefined(mode)) {
html5Mode =3D mode;
return this;
} else {
return html5Mode;
}
};
this.$get =3D ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl =3D $browser.url(),
initUrlParts =3D matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath =3D $browser.baseHref() || '/';
pathPrefix =3D pathPrefixFromBase(basePath);
appBaseUrl =3D
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host,=
initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location =3D new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location =3D new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =3D
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host,=
initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location =3D new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl=
);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legac=
y browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which =3D=3D 2) return;
var elm =3D jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !=3D=3D 'a') {
// ignore rewriting if no A tag (reached root element, or no parent=
- removed from document)
if (elm[0] =3D=3D=3D $rootElement[0] || !(elm =3D elm.parent())[0])=
return;
}
var absHref =3D elm.prop('href'),
rewrittenUrl =3D $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks o=
n links
window.angular['ff-684208-preventDefault'] =3D true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() !=3D initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() !=3D newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl =3D $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter =3D 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl =3D $browser.url();
if (!changeCounter || oldUrl !=3D $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUr=
l(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), $location.$$replace);
$location.$$replace =3D false;
afterLocationChange(oldUrl);
}
});
}
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), o=
ldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troublesho=
oting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log =3D $log;
this.message =3D 'Hello World!';
}
</script>
<div ng-controller=3D"LogCtrl">
<p>Reload this page with open console, enter text and hit =
the log button...</p>
Message:
<input type=3D"text" ng-model=3D"message"/>
<button ng-click=3D"$log.log(message)">log</button>
<button ng-click=3D"$log.warn(message)">warn</button>=
;
<button ng-click=3D"$log.info(message)">info</button>=
;
<button ng-click=3D"$log.error(message)">error</button&=
gt;
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $LogProvider(){
this.$get =3D ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg =3D (arg.message && arg.stack.indexOf(arg.message) =
=3D=3D=3D -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg =3D arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console =3D $window.console || {},
logFn =3D console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args =3D [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console =3D> this is=
noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at lea=
st first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS =3D {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){a=3Da(self, locals); b=3Db(self, locals=
); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, locals, a,b){a=3Da(self, locals); b=3Db(self, locals=
); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);=
},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);=
},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);=
},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);=
},
'=3D':noop,
'=3D=3D':function(self, locals, a,b){return a(self, locals)=3D=3Db(self=
, locals);},
'!=3D':function(self, locals, a,b){return a(self, locals)!=3Db(self, lo=
cals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, lo=
cals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, lo=
cals);},
'<=3D':function(self, locals, a,b){return a(self, locals)<=3Db(se=
lf, locals);},
'>=3D':function(self, locals, a,b){return a(self, locals)>=3Db(se=
lf, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&am=
p;b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals=
);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, =
locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(=
self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE =3D {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", =
'"':'"'};
function lex(text, csp){
var tokens =3D [],
token,
index =3D 0,
json =3D [],
ch,
lastCh =3D ':'; // can start regexp
while (index < text.length) {
ch =3D text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=3D=3D'{' &&
(token=3Dtokens[tokens.length-1])) {
token.json =3D token.text.indexOf('.') =3D=3D -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 =3D ch + peek(),
fn =3D OPERATORS[ch],
fn2 =3D OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index +=3D 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') &&am=
p; is('+-')});
index +=3D 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh =3D ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) !=3D -1;
}
function was(chars) {
return chars.indexOf(lastCh) !=3D -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <=3D ch && ch <=3D '9';
}
function isWhitespace(ch) {
return ch =3D=3D ' ' || ch =3D=3D '\r' || ch =3D=3D '\t' ||
ch =3D=3D '\n' || ch =3D=3D '\v' || ch =3D=3D '\u00A0'; // IE tr=
eats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <=3D ch && ch <=3D 'z' ||
'A' <=3D ch && ch <=3D 'Z' ||
'_' =3D=3D ch || ch =3D=3D '$';
}
function isExpOperator(ch) {
return ch =3D=3D '-' || ch =3D=3D '+' || isNumber(ch);
}
function throwError(error, start, end) {
end =3D end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, en=
d) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number =3D "";
var start =3D index;
while (index < text.length) {
var ch =3D lowercase(text.charAt(index));
if (ch =3D=3D '.' || isNumber(ch)) {
number +=3D ch;
} else {
var peekCh =3D peek();
if (ch =3D=3D 'e' && isExpOperator(peekCh)) {
number +=3D ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) =3D=3D 'e') {
number +=3D ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) =3D=3D 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number =3D 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident =3D "",
start =3D index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch =3D text.charAt(index);
if (ch =3D=3D '.' || isIdent(ch) || isNumber(ch)) {
if (ch =3D=3D '.') lastDot =3D index;
ident +=3D ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to las=
t dot
if (lastDot) {
peekIndex =3D index;
while(peekIndex < text.length) {
var ch =3D text.charAt(peekIndex);
if (ch =3D=3D '(') {
methodName =3D ident.substr(lastDot - start + 1);
ident =3D ident.substr(0, lastDot - start);
index =3D peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token =3D {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn =3D token.json =3D OPERATORS[ident];
} else {
var getter =3D getterFn(ident, csp);
token.fn =3D extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start =3D index;
index++;
var string =3D "";
var rawString =3D quote;
var escape =3D false;
while (index < text.length) {
var ch =3D text.charAt(index);
rawString +=3D ch;
if (escape) {
if (ch =3D=3D 'u') {
var hex =3D text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index +=3D 4;
string +=3D String.fromCharCode(parseInt(hex, 16));
} else {
var rep =3D ESCAPE[ch];
if (rep) {
string +=3D rep;
} else {
string +=3D ch;
}
}
escape =3D false;
} else if (ch =3D=3D '\\') {
escape =3D true;
} else if (ch =3D=3D quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string +=3D ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO =3D valueFn(0),
value,
tokens =3D lex(text, csp),
assignment =3D _assignment,
functionCall =3D _functionCall,
fieldAccess =3D _fieldAccess,
objectIndex =3D _objectIndex,
filterChain =3D _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses s=
omething, so that
// we prevent any accidental execution in JSON.
assignment =3D logicalOR;
functionCall =3D
fieldAccess =3D
objectIndex =3D
filterChain =3D
function() { throwError("is not valid json", {text:text, index:0});=
};
value =3D primary();
} else {
value =3D statements();
}
if (tokens.length !=3D=3D 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length =3D=3D=3D 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token =3D tokens[0];
var t =3D token.text;
if (t=3D=3De1 || t=3D=3De2 || t=3D=3De3 || t=3D=3De4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token =3D peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements =3D [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length =3D=3D 1
? statements[0]
: function(self, locals){
var value;
for ( var i =3D 0; i < statements.length; i++) {
var statement =3D statements[i];
if (statement)
value =3D statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left =3D expression();
var token;
while(true) {
if ((token =3D expect('|'))) {
left =3D binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token =3D expect();
var fn =3D $filter(token.text);
var argsFn =3D [];
while(true) {
if ((token =3D expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke =3D function(self, locals, input){
var args =3D [input];
for ( var i =3D 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left =3D logicalOR();
var right;
var token;
if ((token =3D expect('=3D'))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", toke=
n);
}
right =3D logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left =3D logicalAND();
var token;
while(true) {
if ((token =3D expect('||'))) {
left =3D binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left =3D equality();
var token;
if ((token =3D expect('&&'))) {
left =3D binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left =3D relational();
var token;
if ((token =3D expect('=3D=3D','!=3D'))) {
left =3D binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left =3D additive();
var token;
if ((token =3D expect('<', '>', '<=3D', '>=3D'))) {
left =3D binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left =3D multiplicative();
var token;
while ((token =3D expect('+','-'))) {
left =3D binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left =3D unary();
var token;
while ((token =3D expect('*','/','%'))) {
left =3D binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token =3D expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token =3D expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary =3D filterChain();
consume(')');
} else if (expect('[')) {
primary =3D arrayDeclaration();
} else if (expect('{')) {
primary =3D object();
} else {
var token =3D expect();
primary =3D token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next =3D expect('(', '[', '.'))) {
if (next.text =3D=3D=3D '(') {
primary =3D functionCall(primary, context);
context =3D null;
} else if (next.text =3D=3D=3D '[') {
context =3D primary;
primary =3D objectIndex(primary);
} else if (next.text =3D=3D=3D '.') {
context =3D primary;
primary =3D fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field =3D expect().text;
var getter =3D getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn =3D expression();
consume(']');
return extend(
function(self, locals){
var o =3D obj(self, locals),
i =3D indexFn(self, locals),
v, p;
if (!o) return undefined;
v =3D o[i];
if (v && v.then) {
p =3D v;
if (!('$$v' in v)) {
p.$$v =3D undefined;
p.then(function(val) { p.$$v =3D val; });
}
v =3D v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] =3D value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn =3D [];
if (peekToken().text !=3D ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args =3D [],
context =3D contextGetter ? contextGetter(self, locals) : self;
for ( var i =3D 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr =3D fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns =3D [];
if (peekToken().text !=3D ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array =3D [];
for ( var i =3D 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues =3D [];
if (peekToken().text !=3D '}') {
do {
var token =3D expect(),
key =3D token.string || token.text;
consume(":");
var value =3D expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object =3D {};
for ( var i =3D 0; i < keyValues.length; i++) {
var keyValue =3D keyValues[i];
var value =3D keyValue.value(self, locals);
object[keyValue.key] =3D value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element =3D path.split('.');
for (var i =3D 0; element.length > 1; i++) {
var key =3D element.shift();
var propertyObj =3D obj[key];
if (!propertyObj) {
propertyObj =3D {};
obj[key] =3D propertyObj;
}
obj =3D propertyObj;
}
obj[element.shift()] =3D setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traver=
sals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=3Dtrue} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys =3D path.split('.');
var key;
var lastInstance =3D obj;
var len =3D keys.length;
for (var i =3D 0; i < len; i++) {
key =3D keys[i];
if (obj) {
obj =3D (lastInstance =3D obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache =3D {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal =3D (locals && locals.hasOwnProperty(key0)) ? local=
s : scope,
promise;
if (pathVal =3D=3D=3D null || pathVal =3D=3D=3D undefined) return pathV=
al;
pathVal =3D pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise =3D pathVal;
promise.$$v =3D undefined;
promise.then(function(val) { promise.$$v =3D val; });
}
pathVal =3D pathVal.$$v;
}
if (!key1 || pathVal =3D=3D=3D null || pathVal =3D=3D=3D undefined) ret=
urn pathVal;
pathVal =3D pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise =3D pathVal;
promise.$$v =3D undefined;
promise.then(function(val) { promise.$$v =3D val; });
}
pathVal =3D pathVal.$$v;
}
if (!key2 || pathVal =3D=3D=3D null || pathVal =3D=3D=3D undefined) ret=
urn pathVal;
pathVal =3D pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise =3D pathVal;
promise.$$v =3D undefined;
promise.then(function(val) { promise.$$v =3D val; });
}
pathVal =3D pathVal.$$v;
}
if (!key3 || pathVal =3D=3D=3D null || pathVal =3D=3D=3D undefined) ret=
urn pathVal;
pathVal =3D pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise =3D pathVal;
promise.$$v =3D undefined;
promise.then(function(val) { promise.$$v =3D val; });
}
pathVal =3D pathVal.$$v;
}
if (!key4 || pathVal =3D=3D=3D null || pathVal =3D=3D=3D undefined) ret=
urn pathVal;
pathVal =3D pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise =3D pathVal;
promise.$$v =3D undefined;
promise.then(function(val) { promise.$$v =3D val; });
}
pathVal =3D pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys =3D path.split('.'),
pathKeysLength =3D pathKeys.length,
fn;
if (csp) {
fn =3D (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3=
], pathKeys[4])
: function(scope, locals) {
var i =3D 0, val
do {
val =3D cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i=
++], pathKeys[i++]
)(scope, locals);
locals =3D undefined; // clear after first iteration
scope =3D val;
} while (i < pathKeysLength);
return val;
}
} else {
var code =3D 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code +=3D 'if(s =3D=3D=3D null || s =3D=3D=3D undefined) return s;\n'=
+
'l=3Ds;\n' +
's=3D'+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, an=
d if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)=
') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=3Ds;\n' +
' p.$$v =3D undefined;\n' +
' p.then(function(v) {p.$$v=3Dv;});\n' +
'}\n' +
' s=3Ds.$$v\n' +
'}\n';
});
code +=3D 'return s;';
fn =3D Function('s', 'k', code); // s=3Dscope, k=3Dlocals
fn.toString =3D function() { return code; };
}
return getterFnCache[path] =3D fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter =3D $parse('user.name');
* var setter =3D getter.assign;
* var context =3D {user:{name:'angular'}};
* var locals =3D {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the com=
piled expression:
*
* * `context`: an object against which any expressions embedded in the =
strings are evaluated
* against (Topically a scope object).
* * `locals`: local variables context object, useful for overriding val=
ues in `context`.
*
* The return function also has an `assign` property, if the expression =
is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache =3D {};
this.$get =3D ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] =3D parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [<NAME>'s Q](https://g=
ithub.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) =
describes a promise as an
* interface for interacting with an object that represents the result of a=
n action that is
* performed asynchronously, and may or may not be finished at any given po=
int in time.
*
* From the perspective of dealing with error handling, deferred and promis=
e apis are to
* asynchronous programing what `try`, `catch` and `throw` keywords are to =
synchronous programing.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` an=
d `scope` are
* // available in the current lexical scope (they could have been inject=
ed or passed in).
*
* function asyncGreet(name) {
* var deferred =3D $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop=
, we need to wrap
* // our code into an $apply call so that the model changes are prop=
erly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise =3D asyncGreet('<NAME>');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* );
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the =
trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred apis make](https://github.com/kris=
kowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to=
do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-pa=
ssing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kri=
skowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise i=
nstance as well as apis
* that can be used for signaling the successful or unsuccessful completion=
of the task.
*
* **Methods**
*
* - `resolve(value)` =E2=80� resolves the derived promise with the =
`value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` =E2=80� rejects the derived promise with the `=
reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise =E2=80� `{Promise}` =E2=80� promise object assoc=
iated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created an=
d can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to =
get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` =E2=80� regardless of wh=
en the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously=
as soon as the result
* is available. The callbacks are called with a single argument the resu=
lt or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via =
the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, i=
t is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB =3D promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved an=
d it's value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be=
resolved with another
* promise (which will defer its resolution further), it is possible to pau=
se/defer resolution of
* the promises at any point in the chain. This makes it possible to implem=
ent powerful apis like
* $http's response interceptors.
*
*
* # Differences between <NAME>'s Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model obse=
rvation
* mechanism in angular, which means faster propagation of resolution or =
rejection into your
* models and avoiding unnecessary browser repaints, which would result i=
n flickering UI.
* - $q promises are recognized by the templating engine in angular, which =
means that in templates
* you can treat promises attached to a scope as if they were the resulti=
ng values.
* - Q has many more features that $q, but that comes at a cost of bytes. $=
q is tiny, but contains
* all the important functionality needed for common async tasks.
*/
function $QProvider() {
this.$get =3D ['$rootScope', '$exceptionHandler', function($rootScope, $e=
xceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in=
the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected =
exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish =
in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer =3D function() {
var pending =3D [],
value, deferred;
deferred =3D {
resolve: function(val) {
if (pending) {
var callbacks =3D pending;
pending =3D undefined;
value =3D ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i =3D 0, ii =3D callbacks.length; i < ii; i++) {
callback =3D callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result =3D defer();
var wrappedCallback =3D function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback =3D function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref =3D function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result =3D defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `rea=
son`. This api should be
* used to forward rejection in a chain of promises. If you are dealing w=
ith the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catc=
h/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if=
you "catch" an error via
* a promise error callback and you want to forward the error to the prom=
ise derived from the
* current promise, you have to "rethrow" the error by returning a reject=
ion constructed via
* `reject`.
*
* <pre>
* promiseB =3D promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representi=
ng the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as reje=
cted with the `reason`.
*/
var reject =3D function(reason) {
return {
then: function(callback, errback) {
var result =3D defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promi=
se into a $q promise.
* This is useful when you are dealing with on object that might or might=
not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with=
an array of values,
* each value coresponding to the promise at the same index in the `pro=
mises` array. If any of
* the promises is resolved with a rejection, this resulting promise wi=
ll be resolved with the
* same rejection.
*/
var when =3D function(value, callback, errback) {
var result =3D defer(),
done;
var wrappedCallback =3D function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback =3D function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done =3D true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done =3D true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when=
all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with=
an array of values,
* each value coresponding to the promise at the same index in the `pro=
mises` array. If any of
* the promises is resolved with a rejection, this resulting promise wi=
ll be resolved with the
* same rejection.
*/
function all(promises) {
var deferred =3D defer(),
counter =3D promises.length,
results =3D [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] =3D value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example=
.
*/
function $RouteProvider(){
var routes =3D {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If=
`$location.path`
* contains redundant trailing slash or is missing one, the route will=
still match and the
* `$location.path` will be updated to add or drop the trailing slash =
to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.cu=
rrent` on route
* match.
*
* Object properties:
*
* - `controller` =E2=80� `{function()=3D}` =E2=80� Cont=
roller fn that should be associated with newly
* created scope.
* - `template` =E2=80� `{string=3D}` =E2=80� html temp=
late as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` =E2=80� `{string=3D}` =E2=80� path to=
an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=3D}` - An optional =
map of dependencies which should
* be injected into the controller. If any of these dependencies are=
promises, they will be
* resolved and converted to a value before the controller is instan=
tiated and the
* `$aftreRouteChange` event is fired. The map object is:
*
* - `key` =E2=80� `{string}`: a name of a dependency to be i=
njected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alia=
s for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#inv=
oke injected}
* and the return value is treated as the dependency. If the resul=
t is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` =E2=80� {(string|function())=3D} =E2=80ᦙ=
3; value to update
* {@link ng.$location $location} path with and trigger route redire=
ction.
*
* If `redirectTo` is a function, it will be called with the followi=
ng parameters:
*
* - `{Object.<string>}` - route parameters extracted from the=
current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string w=
hich will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=3Dtrue]` - {boolean=3D} - reload route when only=
$location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, t=
hen
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when =3D function(path, route) {
routes[path] =3D extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath =3D (path[path.length-1] =3D=3D '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] =3D {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other =
route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.c=
urrent`.
* @returns {Object} self
*/
this.otherwise =3D function(params) {
this.when(null, params);
return this;
};
this.$get =3D ['$rootScope', '$location', '$routeParams', '$q', '$injecto=
r', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector,=
$http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition=
.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route defi=
nition.
* - `locals`: A map of locals which is used by {@link ng.$controller=
$controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `loca=
ls` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured rout=
es.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partial=
s).
* It watches `$location.url()` and tries to map the path to an existin=
g route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvide=
r}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng=
.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to =
match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined t=
emplates}
to get it working on jsfiddle as well.
<example module=3D"ngView">
<file name=3D"index.html">
<div ng-controller=3D"MainCntl">
Choose:
<a href=3D"Book/Moby">Moby</a> |
<a href=3D"Book/Moby/ch/1">Moby: Ch1</a> |
<a href=3D"Book/Gatsby">Gatsby</a> |
<a href=3D"Book/Gatsby/ch/4?key=3Dvalue">Gatsby: Ch4</a=
> |
<a href=3D"Book/Scarlet">Scarlet Letter</a><br/&g=
t;
<div ng-view></div>
<hr />
<pre>$location.path() =3D {{$location.path()}}</pre>
<pre>$route.current.templateUrl =3D {{$route.current.templ=
ateUrl}}</pre>
<pre>$route.current.params =3D {{$route.current.params}}&l=
t;/pre>
<pre>$route.current.scope.name =3D {{$route.current.scope.=
name}}</pre>
<pre>$routeParams =3D {{$routeParams}}</pre>
</div>
</file>
<file name=3D"book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name=3D"chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name=3D"script.js">
angular.module('ngView', [], function($routeProvider, $locationPro=
vider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay =3D $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route =3D $route;
$scope.$location =3D $location;
$scope.$routeParams =3D $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name =3D "BookCntl";
$scope.params =3D $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name =3D "ChapterCntl";
$scope.params =3D $routeParams;
}
</file>
<file name=3D"scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content =3D element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content =3D element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services=
starts
* resolving all of the dependencies needed for the route change to occ=
urs.
* Typically this involves fetching the view template as well as any de=
pendencies
* defined in `resolve` route property. Once all of the dependencies a=
re resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error=
of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reus=
ing the same
* instance of the Controller.
*/
var matcher =3D switchRouteMatcher,
forceReload =3D false,
$route =3D {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload =3D true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should constr=
uct the route matching
// regex only once and then reuse it
var regex =3D '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params =3D [],
dst =3D {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp =3D new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex =3D regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match =3D on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] =3D match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next =3D parseRoute(),
last =3D $route.current;
if (next && last && next.$route =3D=3D=3D last.$route
&& equals(next.pathParams, last.pathParams) && !n=
ext.reloadOnSearch && !forceReload) {
last.params =3D next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload =3D false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current =3D next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).sea=
rch(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path=
(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys =3D [],
values =3D [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isFunction(value) ? $injector.invoke(value) : $=
injector.get(value));
});
if (isDefined(template =3D next.template)) {
} else if (isDefined(template =3D next.templateUrl)) {
template =3D $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals =3D {};
forEach(values, function(value, index) {
locals[keys[index]] =3D value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next =3D=3D $route.current) {
if (next) {
next.locals =3D locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next =3D=3D $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error)=
;
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params =3D matcher($location.path(), path)))=
{
match =3D inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route =3D route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params=
: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result =3D [];
forEach((string||'').split(':'), function(segment, i) {
if (i =3D=3D 0) {
result.push(segment);
} else {
var segmentMatch =3D segment.match(/(\w+)(.*)/);
var key =3D segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination =
of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` para=
meters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over =
`search` params.
*
* The service guarantees that the identity of the `$routeParams` object wi=
ll remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=3Dmoby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams =3D=3D> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get =3D valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and=
memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the =
time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means tha=
t private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addi=
tion we have to add
* items to the array at the begging (shift) instead of at the end (pus=
h)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so w=
e use linked list
*
* There are few watches then a lot of observers. This is why you don't wan=
t the observer to be
* implemented in the same way as watch. Watch requires return of initializ=
ation function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute =
before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mech=
anism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on s=
copes}.
*/
function $RootScopeProvider(){
var TTL =3D 10;
this.digestTtl =3D function(value) {
if (arguments.length) {
TTL =3D value;
}
return TTL;
};
this.$get =3D ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootSc=
ope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are cre=
ated automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the=
scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope =3D $rootScope.$new();
scope.salutation =3D 'Hello';
scope.name =3D 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
this.greeting =3D this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name =3D 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent =3D $rootScope;
var child =3D parent.$new();
parent.salutation =3D "Hello";
child.name =3D "World";
expect(child.salutation).toEqual('Hello');
child.salutation =3D "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=3D} providers Map of servi=
ce factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=3D} instanceCache Provides pre-inst=
antiated services which should
* append/override services provided by `providers`. This is handy =
when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id =3D nextUid();
this.$$phase =3D this.$parent =3D this.$$watchers =3D
this.$$nextSibling =3D this.$$prevSibling =3D
this.$$childHead =3D this.$$childTail =3D null;
this['this'] =3D this.$root =3D this;
this.$$asyncQueue =3D [];
this.$$listeners =3D {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanum=
eric sequence) useful for
* debugging.
*/
Scope.prototype =3D {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$di=
gest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope ca=
n be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on =
a scope when it is desired for
* the scope and its child scopes to be permanently detached from the=
parent and thus stop
* participating in model change detection and listener notification =
by invoking.
*
* @param {boolean} isolate if true then the scoped does not prototyp=
ically inherit from the
* parent scope. The scope is isolated, as it can not se pare=
nt scope properties.
* When creating widgets it is useful for the widget to not a=
ccidently read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controlle=
rs.');
}
if (isolate) {
child =3D new Scope();
child.$root =3D this.$root;
} else {
Child =3D function() {}; // should be anonymous; This is so that =
when the minifier munges
// the name it does not become random set of chars. These will =
then show up as class
// name in the debugger.
Child.prototype =3D this;
child =3D new Child();
child.$id =3D nextUid();
}
child['this'] =3D child;
child.$$listeners =3D {};
child.$parent =3D this;
child.$$asyncQueue =3D [];
child.$$watchers =3D child.$$nextSibling =3D child.$$childHead =3D =
child.$$childTail =3D null;
child.$$prevSibling =3D this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling =3D child;
this.$$childTail =3D child;
} else {
this.$$childHead =3D this.$$childTail =3D child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watch=
Expression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$root=
Scope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.=
$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute=
multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idem=
potent.)
* - The `listener` is called only when the value from the current `w=
atchExpression` and the
* previous call to `watchExpression' are not equal (with the excep=
tion of the initial run
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object=
for later comparison
* {@link angular.copy} function is used. It also means that watchi=
ng complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger oth=
er `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detec=
ted. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$di=
gest $digest} is called,
* you can register an `watchExpression` function with no `listener`.=
(Since `watchExpression`,
* can execute multiple times per {@link ng.$rootScope.Scope#$digest =
$digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is=
called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initial=
ize the
* watcher. In rare cases, this is undesirable because the listener i=
s called when the result
* of `watchExpression` didn't change. To detect this scenario within=
the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are ide=
ntical (`=3D=3D=3D`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootS=
cope
var scope =3D $rootScope;
scope.name =3D 'misko';
scope.counter =3D 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { counter =3D =
counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name =3D 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is ev=
aluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in =
the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter=
.
* @param {(function()|string)=3D} listener Callback called whenever =
the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current an=
d previous values as parameters.
*
* @param {boolean=3D} objectEquality Compare object for equality rat=
her then for refference.
* @returns {function()} Returns a deregistration function for this l=
istener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope =3D this,
get =3D compileToFn(watchExp, 'watch'),
array =3D scope.$$watchers,
watcher =3D {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we reall=
y need this ?
if (!isFunction(listener)) {
var listenFn =3D compileToFn(listener || noop, 'listener');
watcher.fn =3D function(newVal, oldVal, scope) {listenFn(scope);}=
;
}
if (!array) {
array =3D scope.$$watchers =3D [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of =
the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener ca=
n change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch wa=
tchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loo=
p. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations =
exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider.directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typ=
ically from within a
* {@link ng.$compileProvider.directive directives}) will force a `$d=
igest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$roo=
tScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to=
simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope =3D ...;
scope.name =3D 'misko';
scope.counter =3D 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
counter =3D counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name =3D 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl =3D TTL,
next, current, target =3D this,
watchLog =3D [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty =3D false;
current =3D target;
do {
asyncQueue =3D current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers =3D current.$$watchers)) {
// process our watches
length =3D watchers.length;
while (length--) {
try {
watch =3D watchers[length];
// Most common watches are on primitives, in which case w=
e can short
// circuit it with =3D=3D=3D operator, only when =3D=3D=
=3D fails do we use .equals
if ((value =3D watch.get(current)) !=3D=3D (last =3D watc=
h.last) &&
!(watch.eq
? equals(value, last)
: (typeof value =3D=3D 'number' && typeof=
last =3D=3D 'number'
&& isNaN(value) && isNaN(last)=
))) {
dirty =3D true;
watch.last =3D watch.eq ? copy(value) : value;
watch.fn(value, ((last =3D=3D=3D initWatchVal) ? value =
: last), current);
if (ttl < 5) {
logIdx =3D 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] =3D [];
logMsg =3D (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString(=
))
: watch.exp;
logMsg +=3D '; newVal: ' + toJson(value) + '; oldVal:=
' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have test=
s to prove it!
// this piece should be kept in sync with the traversal in $bro=
adcast
if (!(next =3D (current.$$childHead || (current !=3D=3D target =
&& current.$$nextSibling)))) {
while(current !=3D=3D target && !(next =3D current.$$=
nextSibling)) {
current =3D current.$parent;
}
}
} while ((current =3D next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' =
+
'Watchers fired in the last 5 iterations: ' + toJson(watchL=
og));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent=
scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will n=
o longer
* propagate to the current scope and its children. Removal also impl=
ies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted=
on this scope.
* Application code can register a `$destroy` event handler that will=
give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
if ($rootScope =3D=3D this) return; // we can't remove the root nod=
e;
var parent =3D this.$parent;
this.$broadcast('$destroy');
if (parent.$$childHead =3D=3D this) parent.$$childHead =3D this.$$n=
extSibling;
if (parent.$$childTail =3D=3D this) parent.$$childTail =3D this.$$p=
revSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling =3D this.$=
$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling =3D this.$=
$prevSibling;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the resul=
t. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluati=
ng engular expressions.
*
* # Example
* <pre>
var scope =3D ng.$rootScope.Scope();
scope.a =3D 1;
scope.b =3D 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })=
).toEqual(3);
* </pre>
*
* @param {(string|function())=3D} expression An angular expression t=
o be executed.
*
* - `string`: execute using the rules as defined in {@link guide=
/expression expression}.
* - `function(scope)`: execute the function with the current `sco=
pe` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in t=
ime.
*
* The `$evalAsync` makes no guarantees as to when the `expression` w=
ill be executed, only that:
*
* - it will execute in the current script execution context (befor=
e any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle}=
will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded =
to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=3D} expression An angular expression t=
o be executed.
*
* - `string`: execute using the rules as defined in {@link guide=
/expression expression}.
* - `function(scope)`: execute the function with the current `sco=
pe` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outsid=
e of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third par=
ty libraries).
* Because we are calling into the angular framework we need to perfo=
rm proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages=
:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forward=
ed to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fire=
d immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $dige=
st()} method.
*
*
* @param {(string|function())=3D} exp An angular expression to be ex=
ecuted.
*
* - `string`: execute using the rules as defined in {@link guide/=
expression expression}.
* - `function(scope)`: execute the function with current `scope` =
parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listen on events of a given type. See {@link ng.$rootScope.Scope#$=
emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event =
is emitted.
* @returns {function()} Returns a deregistration function for this l=
istener.
*
* The event listener function format is: `function(event)`. The `eve=
nt` object passed into the
* listener has the following attributes
*
* - `targetScope` - {Scope}: the scope on which the event was `$em=
it`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling =
the event.
* - `name` - {string}: Name of the event.
* - `stopPropagation` - {function=3D}: calling `stopPropagation` f=
unction will cancel further event propagation
* (available only for events that were `$emit`-ed).
* - `preventDefault` - {function}: calling `preventDefault` sets `=
defaultPrevented` flag to true.
* - `defaultPrevented` - {boolean}: true if `preventDefault` was c=
alled.
*/
$on: function(name, listener) {
var namedListeners =3D this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] =3D namedListeners =3D [];
}
namedListeners.push(listener);
return function() {
arrayRemove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy not=
ifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was call=
ed. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` eve=
nt on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and =
calls all registered
* listeners along the way. The event will stop propagating if one of=
the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on list=
eners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed =
onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty =3D [],
namedListeners,
scope =3D this,
stopPropagation =3D false,
event =3D {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation =3D true;},
preventDefault: function() {
event.defaultPrevented =3D true;
},
defaultPrevented: false
},
listenerArgs =3D concat([event], arguments, 1),
i, length;
do {
namedListeners =3D scope.$$listeners[name] || empty;
event.currentScope =3D scope;
for (i=3D0, length=3DnamedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope =3D scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and thei=
r children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was=
called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` eve=
nt on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes=
of the current scope and
* calls all registered listeners along the way. The event cannot be =
canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on list=
eners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed =
onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target =3D this,
current =3D target,
next =3D target,
event =3D {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented =3D true;
},
defaultPrevented: false
},
listenerArgs =3D concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibli=
ng until back at root
do {
current =3D next;
event.currentScope =3D current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests =
to prove it!
// this piece should be kept in sync with the traversal in $diges=
t
if (!(next =3D (current.$$childHead || (current !=3D=3D target &a=
mp;& current.$$nextSibling)))) {
while(current !=3D=3D target && !(next =3D current.$$ne=
xtSibling)) {
current =3D current.$parent;
}
}
} while ((current =3D next));
return event;
}
};
var $rootScope =3D new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase =3D phase;
}
function clearPhase() {
$rootScope.$$phase =3D null;
}
function compileToFn(exp, name) {
var fn =3D $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's uniqueue we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event=
?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get =3D ['$window', function($window) {
var eventSupport =3D {},
android =3D int((/android (\d+)/.exec(lowercase($window.navigator.u=
serAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location cor=
rectly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=3D17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState &=
;& !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.docum=
entMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pret=
end that it doesn't have
// it. In particular the event is not fired when backspace or delet=
e key are pressed or
// when cut operation is performed.
if (event =3D=3D 'input' && msie =3D=3D 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm =3D $window.document.createElement('div');
eventSupport[event] =3D 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without t=
riggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, bec=
ause
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing=
.
*
* All expressions are evaluated with respect to current scope so they don'=
t
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init=3D"$window =3D $service('$window'); greeting=3D'He=
llo World!'" type=3D"text" ng-model=3D"greeting" />
<button ng-click=3D"$window.alert(greeting)">ALERT</button&=
gt;
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get =3D valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed =3D {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i =3D line.indexOf(':');
key =3D lowercase(trim(line.substr(0, i)));
val =3D trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] +=3D ', ' + val;
} else {
parsed[key] =3D val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=3D)} Returns a getter function which if called=
with:
*
* - if called with single an argument returns a single header value or n=
ull
* - if called with no arguments returns an object containing all headers=
.
*/
function headersGetter(headers) {
var headersObj =3D isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj =3D parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=3D)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of f=
unctions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data =3D fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <=3D status && status < 300;
}
function $HttpProvider() {
var JSON_START =3D /^\s*(\[|\{[^\{])/,
JSON_END =3D /[\}\]]\s*$/,
PROTECTION_PREFIX =3D /^\)\]\}',?\n/;
var $config =3D this.defaults =3D {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data =3D data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data =3D fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=3Dutf-8'},
put: {'Content-Type': 'application/json;charset=3Dutf-8'}
}
};
var providerResponseInterceptors =3D this.responseInterceptors =3D [];
this.$get =3D ['$httpBackend', '$browser', '$cacheFactory', '$rootScope',=
'$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $inje=
ctor) {
var defaultCache =3D $cacheFactory('$http'),
responseInterceptors =3D [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBacked
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates commu=
nication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/x=
mlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JS=
ONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngRes=
ource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} ex=
posed by
* the $q service. While for simple usage patters this doesn't matter m=
uch, for advanced usage,
* it is important to familiarize yourself with these apis and guarante=
es they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument =E2=
=80� a configuration object =E2=80�
* that is used to generate an http request and returns a {@link ng.$q=
promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with status
* // code outside of the <200, 400) range
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise =
object, you can also use
* the `then` method to register callbacks, and these callbacks will re=
ceive a single argument =E2=80�
* an object representing the response. See the api signature and type =
info below for more
* details.
*
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the =
http method and url and
* POST and PUT requests require response body/data to be provided as w=
ell, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all=
requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.hea=
ders` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common f=
or all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP P=
OST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT=
requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property =
from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, s=
imply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']=3D'value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defa=
ults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform funct=
ions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an ob=
ject, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations=
section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To override these transformation locally, specify transform function=
s as `transformRequest`
* and/or `transformResponse` properties of the config object. To globa=
lly override the default
* transforms, override the `$httpProvider.defaults.transformRequest` a=
nd
* `$httpProvider.defaults.transformResponse` properties of the `$httpP=
rovider`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. =
When the cache is
* enabled, `$http` stores the response from the server in local cache.=
Next time the
* response is served from the cache without sending a request to the s=
erver.
*
* Note that even if the response is served from cache, delivery of the=
data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be c=
ached using the same
* cache, but the cache is not populated yet, only one request to the s=
erver will be made and
* the remaining requests will be fulfilled using the response for the =
first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of=
synchronous or
* asynchronous preprocessing of received responses, it is desirable to=
be able to intercept
* responses for http requests before they are handed over to the appli=
cation code that
* initiated these requests. The response interceptors leverage the {@l=
ink ng.$q
* promise apis} to fulfil this need for both synchronous and asynchron=
ous preprocessing.
*
* The interceptors are service factories that are registered with the =
$httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The f=
actory is called and
* injected with dependencies (if specified) and returns the intercepto=
r =E2=80� a function that
* takes a {@link ng.$q promise} and returns the original or a new prom=
ise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, de=
pendency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, =
dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-j=
son-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSR=
F}
*
* Both server and the client must cooperate in order to eliminate thes=
e threats. Angular comes
* pre-configured with strategies that address these issues, but for th=
is to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-j=
son-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON re=
source URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under =
some conditions. To
* counter this your server can prefix all JSON requests with following=
string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as =
JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}=
is a technique by which
* an unauthorized site can gain your user's private data. Angular prov=
ides following mechanism
* to counter XSRF. When performing XHR requests, the $http service rea=
ds a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. S=
ince only JavaScript that
* runs on your domain could read the cookie, your server can be assure=
d that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a Jav=
aScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent =
non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header=
, and therefore be sure
* that only JavaScript running on your domain could have read the toke=
n. The token must be
* unique for each user and must be verifiable by the server (to preven=
t the JavaScript making
* up its own tokens). We recommend that the token is a digest of your =
site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt f=
or added security}.
*
*
* @param {object} config Object describing the request to be made and =
how it should be
* processed. The object has following properties:
*
* - **method** =E2=80� `{string}` =E2=80� HTTP method=
(e.g. 'GET', 'POST', etc)
* - **url** =E2=80� `{string}` =E2=80� Absolute or re=
lative URL of the resource that is being requested.
* - **params** =E2=80� `{Object.<string|Object>}` =E2=
=80� Map of strings or objects which will be turned to
* `?key1=3Dvalue1&key2=3Dvalue2` after the url. If the value =
is not a string, it will be JSONified.
* - **data** =E2=80� `{string|Object}` =E2=80� Data t=
o be sent as the request message data.
* - **headers** =E2=80� `{Object}` =E2=80� Map of str=
ings representing HTTP headers to send to the server.
* - **transformRequest** =E2=80� `{function(data, headersGet=
ter)|Array.<function(data, headersGetter)>}` =E2=80�
* transform function or an array of such functions. The transform=
function takes the http
* request body and headers and returns its transformed (typically=
serialized) version.
* - **transformResponse** =E2=80� `{function(data, headersGe=
tter)|Array.<function(data, headersGetter)>}` =E2=80�
* transform function or an array of such functions. The transform=
function takes the http
* response body and headers and returns its transformed (typicall=
y deserialized) version.
* - **cache** =E2=80� `{boolean|Cache}` =E2=80� If tr=
ue, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used=
for
* caching.
* - **timeout** =E2=80� `{number}` =E2=80� timeout in=
milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `with=
Credentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_ac=
cess_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with t=
he
* standard `then` method and two http specific methods: `success` an=
d `error`. The `then`
* method takes two arguments a success and an error callback which w=
ill be called with a
* response object. The `success` and `error` methods take a single a=
rgument - a function that
* will be called when the request succeeds or fails respectively. Th=
e arguments passed into
* these functions are destructured representation of the response ob=
ject passed into the
* `then` method. The response object has these properties:
*
* - **data** =E2=80� `{string|Object}` =E2=80� The res=
ponse body transformed with the transform functions.
* - **status** =E2=80� `{number}` =E2=80� HTTP status =
code of the response.
* - **headers** =E2=80� `{function([headerName])}` =E2=80A=
533; Header getter function.
* - **config** =E2=80� `{Object}` =E2=80� The configur=
ation object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config obj=
ects for currently pending
* requests. This is primarily meant to be used for debugging purpose=
s.
*
*
* @example
<example>
<file name=3D"index.html">
<div ng-controller=3D"FetchCtrl">
<select ng-model=3D"method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type=3D"text" ng-model=3D"url" size=3D"80"/>
<button ng-click=3D"fetch()">fetch</button><br&g=
t;
<button ng-click=3D"updateModel('GET', 'http-hello.html')"&g=
t;Sample GET</button>
<button ng-click=3D"updateModel('JSONP', 'http://angularjs.o=
rg/greet.php?callback=3DJSON_CALLBACK&name=3DSuper%20Hero')">Sample =
JSONP</button>
<button ng-click=3D"updateModel('JSONP', 'http://angularjs.o=
rg/doesntexist&callback=3DJSON_CALLBACK')">Invalid JSONP</button&=
gt;
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name=3D"script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method =3D 'GET';
$scope.url =3D 'http-hello.html';
$scope.fetch =3D function() {
$scope.code =3D null;
$scope.response =3D null;
$http({method: $scope.method, url: $scope.url, cache: $templa=
teCache}).
success(function(data, status) {
$scope.status =3D status;
$scope.data =3D data;
}).
error(function(data, status) {
$scope.data =3D data || "Request failed";
$scope.status =3D status;
});
};
$scope.updateModel =3D function(method, url) {
$scope.method =3D method;
$scope.url =3D url;
};
}
</file>
<file name=3D"http-hello.html">
Hello, $http!
</file>
<file name=3D"scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error=
handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method =3D uppercase(config.method);
var reqTransformFn =3D config.transformRequest || $config.transformRe=
quest,
respTransformFn =3D config.transformResponse || $config.transform=
Response,
defHeaders =3D $config.headers,
reqHeaders =3D extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-T=
OKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], conf=
ig.headers),
reqData =3D transformData(config.data, headersGetter(reqHeaders),=
reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise =3D sendReq(config, reqData, reqHeaders);
// transform future response
promise =3D promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise =3D interceptor(promise);
});
promise.success =3D function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error =3D function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp =3D extend({}, response, {
data: transformData(response.data, response.headers, respTransfor=
mFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests =3D [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request
* @param {*} data Request content
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destinat=
ion of the request
* @param {*} data Request content
* @param {Object=3D} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. All=
ows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Respon=
ses" sections above.
*/
$http.defaults =3D $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] =3D function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] =3D function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pending=
Requests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred =3D $q.defer(),
promise =3D deferred.promise,
cache,
cachedResp,
url =3D buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method =3D=3D 'GET') {
cache =3D isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp =3D cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no respon=
se yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[=
2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as=
a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the ba=
ckend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.=
timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)])=
;
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status =3D Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx =3D indexOf($http.pendingRequests, config);
if (idx !=3D=3D -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts =3D [];
forEachSorted(params, function(value, key) {
if (value =3D=3D null || value =3D=3D undefined) return;
if (isObject(value)) {
value =3D toJson(value);
}
parts.push(encodeURIComponent(key) + '=3D' + encodeURIComponent=
(value));
});
return url + ((url.indexOf('?') =3D=3D -1) ? '?' : '&') + par=
ts.join('&');
}
}];
}
var XHR =3D window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the high=
er-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBa=
ckend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get =3D ['$browser', '$window', '$document', function($browser, $wi=
ndow, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular=
.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocu=
ment, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCreden=
tials) {
$browser.$$incOutstandingRequestCount();
url =3D url || $browser.url();
if (lowercase(method) =3D=3D 'jsonp') {
var callbackId =3D '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] =3D function(data) {
callbacks[callbackId].data =3D data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callback=
Id),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr =3D new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send bel=
ow is called and the
// response is in the cache. the promise api will ensure that to the =
app code the api is
// always async
xhr.onreadystatechange =3D function() {
if (xhr.readyState =3D=3D 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllR=
esponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials =3D true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status =3D -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol =3D (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status =3D (protocol =3D=3D 'file') ? (response ? 200 : 404) : status=
;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status =3D status =3D=3D 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with =
script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script =3D rawDocument.createElement('script'),
doneWrapper =3D function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type =3D 'text/javascript';
script.src =3D url;
if (msie) {
script.onreadystatechange =3D function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload =3D script.onerror =3D doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular componen=
ts. As of right now the
* only public api is:
*
* * `id` =E2=80� `{string}` =E2=80� locale id formatted as `=
languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get =3D function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September=
,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.spli=
t(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.spl=
it(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num =3D=3D=3D 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get =3D ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds =3D {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wra=
pped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise whi=
ch will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delaye=
d.
* @param {number=3D} [delay=3D0] Delay in milliseconds.
* @param {boolean=3D} [invokeApply=3Dtrue] If set to false skips mode=
l dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $ap=
ply} block.
* @returns {*} Promise that will be resolved when the timeout is reac=
hed. The value this
* promise will be resolved with is the return value of the `fn` fun=
ction.
*/
function timeout(fn, delay, invokeApply) {
var deferred =3D $q.defer(),
promise =3D deferred.promise,
skipApply =3D (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId =3D $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup =3D function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId =3D timeoutId;
deferreds[timeoutId] =3D deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this t=
he promise will be
* resolved with a rejection.
*
* @param {Promise=3D} promise Promise returned by the `$timeout` func=
tion.
* @returns {boolean} Returns `true` if the task hasn't executed yet a=
nd was successfully
* canceled.
*/
timeout.cancel =3D function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However f=
ilters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is=
annotated with dependencies and is
* responsible for creating a the filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter =
name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create y=
our own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} =
in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject =3D ['$provide'];
function $FilterProvider($provide) {
var suffix =3D 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register =3D register;
this.$get =3D ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expre=
ssions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used fo=
r selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the valu=
e of `expression`
* string. All strings or objects with string properties in `array` tha=
t contain this string
* will be returned. The predicate can be negated by prefixing the stri=
ng with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties=
on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will retur=
n an array of items
* which have property `name` containing "M" and property `phone` conta=
ining "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match=
against any
* property of the object. That's equivalent to the simple substring ma=
tch with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filt=
ers. The function is
* called for each element of `array`. The final result is an array of =
those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init=3D"friends =3D [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></=
div>
Search: <input ng-model=3D"searchText">
<table id=3D"searchTextResults">
<tr><th>Name</th><th>Phone</th><t=
r>
<tr ng-repeat=3D"friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input ng-model=3D"search.$"> <br>
Name only <input ng-model=3D"search.name"><br>
Phone only <input ng-model=3D"search.phone"=C3=A5><br>
<table id=3D"searchObjResults">
<tr><th>Name</th><th>Phone</th><t=
r>
<tr ng-repeat=3D"friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', f=
unction() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').colu=
mn('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').colu=
mn('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate=
object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').colum=
n('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!(array instanceof Array)) return array;
var predicates =3D [];
predicates.check =3D function(value) {
for (var j =3D 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search =3D function(obj, text){
if (text.charAt(0) =3D=3D=3D '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !=3D=3D '$' && search(obj[objKey],=
text)) {
return true;
}
}
return false;
case "array":
for ( var i =3D 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression =3D {$:expression};
case "object":
for (var key in expression) {
if (key =3D=3D '$') {
(function() {
var text =3D (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path =3D key;
var text =3D (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered =3D [];
for ( var j =3D 0; j < array.length; j++) {
var value =3D array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol i=
s provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=3D} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount =3D 1234.56;
}
</script>
<div ng-controller=3D"Ctrl">
<input type=3D"number" ng-model=3D"amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)')=
;
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject =3D ['$locale'];
function currencyFilter($locale) {
var formats =3D $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol =3D formats.CURRENCY_SY=
M;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, for=
mats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=3D} [fractionSize=3D2] Number of decimal places =
to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a =E2=80=
5533;,=E2=80� after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val =3D 1234.56789;
}
</script>
<div ng-controller=3D"Ctrl">
Enter number: <input ng-model=3D'val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject =3D ['$locale'];
function numberFilter($locale) {
var formats =3D $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, for=
mats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP =3D '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) =
{
if (isNaN(number) || !isFinite(number)) return '';
var isNegative =3D number < 0;
number =3D Math.abs(number);
var numStr =3D number + '',
formatedText =3D '',
parts =3D [];
if (numStr.indexOf('e') !=3D=3D -1) {
formatedText =3D numStr;
} else {
var fractionLen =3D (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize =3D Math.min(Math.max(pattern.minFrac, fractionLen), pat=
tern.maxFrac);
}
var pow =3D Math.pow(10, fractionSize);
number =3D Math.round(number * pow) / pow;
var fraction =3D ('' + number).split(DECIMAL_SEP);
var whole =3D fraction[0];
fraction =3D fraction[1] || '';
var pos =3D 0,
lgroup =3D pattern.lgSize,
group =3D pattern.gSize;
if (whole.length >=3D (lgroup + group)) {
pos =3D whole.length - lgroup;
for (var i =3D 0; i < pos; i++) {
if ((pos - i)%group =3D=3D=3D 0 && i !=3D=3D 0) {
formatedText +=3D groupSep;
}
formatedText +=3D whole.charAt(i);
}
}
for (i =3D pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup =3D=3D=3D 0 && i !=3D=3D 0) {
formatedText +=3D groupSep;
}
formatedText +=3D whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction +=3D '0';
}
if (fractionSize) formatedText +=3D decimalSep + fraction.substr(0, fra=
ctionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg =3D '';
if (num < 0) {
neg =3D '-';
num =3D -num;
}
num =3D '' + num;
while(num.length < digits) num =3D '0' + num;
if (trim)
num =3D num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value =3D date['get' + name]();
if (offset > 0 || value > -offset)
value +=3D offset;
if (value =3D=3D=3D 0 && offset =3D=3D -12 ) value =3D 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value =3D date['get' + name]();
var get =3D uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset =3D date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS =3D {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT =3D /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y=
+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING =3D /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 =3D> 0001, AD=
2010 =3D> 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 200=
1 =3D> 01, AD 2010 =3D> 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 =3D> 1, AD 199 =
=3D> 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-=
1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9=
/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. Se=
ptember 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. S=
ep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/1=
0)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 1=
2:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05=
pm)
*
* `format` string can contain literal values. These need to be quoted wi=
th single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two sing=
le quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object,=
milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddT=
HH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmms=
sZ).
* @param {string=3D} format Formatting rules (see Description). If not spe=
cified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recogniz=
ed as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</sp=
an>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm=
:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:m=
ma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject =3D ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR =3D /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?=
(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match =3D string.match(R_ISO8601_STR)) {
var date =3D new Date(0),
tzHour =3D 0,
tzMin =3D 0;
if (match[9]) {
tzHour =3D int(match[9] + match[10]);
tzMin =3D int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin,=
int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text =3D '',
parts =3D [],
fn, match;
format =3D format || 'mediumDate';
format =3D $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date =3D int(date);
} else {
date =3D jsonStringToDate(date);
}
}
if (isNumber(date)) {
date =3D new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match =3D DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts =3D concat(parts, match, 1);
format =3D parts.pop();
} else {
parts.push(format);
format =3D null;
}
}
forEach(parts, function(value){
fn =3D DATE_FORMATS[value];
text +=3D fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curl=
y {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive =
types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value=
"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter =3D valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter =3D valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an=
array. The elements
* are taken from either the beginning or the end of the source array, as s=
pecified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expre=
ssions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `l=
imit` number is
* positive, `limit` number of items from the beginning of the source a=
rray are copied.
* If the number is negative, `limit` number of items from the end of =
the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input arra=
y had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers =3D [1,2,3,4,5,6,7,8,9];
$scope.limit =3D 3;
}
</script>
<div ng-controller=3D"Ctrl">
Limit {{numbers}} to: <input type=3D"integer" ng-model=3D"limit=
">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=3Dlimit]').val())=
.toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7=
,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit =3D int(limit);
var out =3D [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit =3D array.length;
else if (limit < -array.length)
limit =3D -array.length;
if (limit > 0) {
i =3D 0;
n =3D limit;
} else {
i =3D array.length + limit;
n =3D array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expre=
ssions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expressio=
n A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be so=
rted using the
* `<`, `=3D`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to ord=
er by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` o=
r `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predi=
cate in the array
* is used for sorting, but when two items are equivalent, the next pr=
edicate is used.
*
* @param {boolean=3D} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =3D
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate =3D '-age';
}
</script>
<div ng-controller=3D"Ctrl">
<pre>Sorting predicate =3D {{predicate}}; reverse =3D {{reve=
rse}}</pre>
<hr/>
[ <a href=3D"" ng-click=3D"predicate=3D''">unsorted</a>=
; ]
<table class=3D"friend">
<tr>
<th><a href=3D"" ng-click=3D"predicate =3D 'name'; re=
verse=3Dfalse">Name</a>
(<a href ng-click=3D"predicate =3D '-name'; reverse=3Df=
alse">^</a>)</th>
<th><a href=3D"" ng-click=3D"predicate =3D 'phone'; r=
everse=3D!reverse">Phone Number</a></th>
<th><a href=3D"" ng-click=3D"predicate =3D 'age'; rev=
erse=3D!reverse">Age</a></th>
<tr>
<tr ng-repeat=3D"friend in friends | orderBy:predicate:revers=
e">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('frien=
d.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('frien=
d.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate',=
function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('frien=
d.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('frien=
d.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('frien=
d.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-12=
12']);
expect(repeater('table.friend', 'friend in friends').column('frien=
d.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject =3D ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!(array instanceof Array)) return array;
if (!sortPredicate) return array;
sortPredicate =3D isArray(sortPredicate) ? sortPredicate: [sortPredicat=
e];
sortPredicate =3D map(sortPredicate, function(predicate){
var descending =3D false, get =3D predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) =3D=3D '+' || predicate.charAt(0) =3D=3D '=
-')) {
descending =3D predicate.charAt(0) =3D=3D '-';
predicate =3D predicate.substring(1);
}
get =3D $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy =3D [];
for ( var i =3D 0; i < array.length; i++) { arrayCopy.push(array[i])=
; }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i =3D 0; i < sortPredicate.length; i++) {
var comp =3D sortPredicate[i](o1, o2);
if (comp !=3D=3D 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 =3D typeof v1;
var t2 =3D typeof v2;
if (t1 =3D=3D t2) {
if (t1 =3D=3D "string") v1 =3D v1.toLowerCase();
if (t1 =3D=3D "string") v2 =3D v2.toLowerCase();
if (v1 =3D=3D=3D v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive =3D {
link: directive
}
}
directive.restrict =3D directive.restrict || 'AC';
return valueFn(directive);
}
/*
* Modifies the default behavior of html A tag, so that the default action =
is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links =
with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* <a href=3D"" ng-click=3D"model.$save()">Save</a>
*/
var htmlAnchorDirective =3D valueFn({
restrict: 'E',
compile: function(element, attr) {
// turn <a href ng-click=3D"..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an an=
chor
if (!attr.href) {
attr.$set('href', '');
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href=3D"http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href=3D"http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model=3D"value" /><br />
<a id=3D"link-1" href ng-click=3D"value =3D 1">link 1</a&g=
t; (link, don't reload)<br />
<a id=3D"link-2" href=3D"" ng-click=3D"value =3D 2">link 2<=
;/a> (link, don't reload)<br />
<a id=3D"link-3" ng-href=3D"/{{'123'}}">link 3</a> (lin=
k, reload!)<br />
<a id=3D"link-4" href=3D"" name=3D"xx" ng-click=3D"value =3D 4"&=
gt;anchor</a> (link, don't reload)<br />
<a id=3D"link-5" name=3D"xxx" ng-click=3D"value =3D 5">anchor=
</a> (no link)<br />
<a id=3D"link-6" ng-href=3D"{{value}}">link</a> (link, =
change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value'=
, function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string',=
function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified',=
function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string a=
nd name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name sp=
ecified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe('');
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src=3D"http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src=3D"http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but =
not on IE8 and older IEs:
* <pre>
* <div ng-init=3D"scope =3D { isDisabled: false }">
* <button disabled=3D"{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attribute=
s such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding=
expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type=3D"checkbox" ng-model=3D"checked=
"><br/>
<button ng-model=3D"button" ng-disabled=3D"checked">Button<=
;/button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toB=
eFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toB=
eTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated=
.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attribute=
s such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding=
expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type=3D"checkbox" ng-model=3D"mas=
ter"><br/>
<input id=3D"checkSlave" type=3D"checkbox" ng-checked=3D"master"=
>
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).=
toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).=
toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attribute=
s such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding=
expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type=3D"checkbox" ng-model=3D"c=
hecked"><br/>
<select id=3D"select" ng-multiple=3D"checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).to=
BeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).to=
BeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated=
.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attribute=
s such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding=
expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type=3D"checkbox" ng-mode=
l=3D"checked"><br/>
<input type=3D"text" ng-readonly=3D"checked" value=3D"I'm Angula=
r"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeF=
alsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeT=
ruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attribute=
s such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding=
expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type=3D"checkbox" ng-model=3D"selecte=
d"><br/>
<select>
<option>Hello!</option>
<option id=3D"greet" ng-selected=3D"selected">Greetings!<=
;/option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBe=
Falsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBe=
Truthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives =3D {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized =3D directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] =3D function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized =3D directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] =3D function() {
return {
priority: 99, // it needs to run after the attributes are interpolate=
d
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" att=
ribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do any=
thing, so we need
// to set the property as well to achieve the desired effect
if (msie) element.prop(attrName, value);
});
}
};
};
});
var nullFormCtrl =3D {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the f=
orm yet.
* @property {boolean} $dirty True if user has already interacted with the =
form.
* @property {boolean} $valid True if all of the containg forms and control=
s are valid.
* @property {boolean} $invalid True if at least one containing control or =
form is invalid.
*
* @property {Object} $error Is an object hash, containing references to al=
l invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) =E2=80� such as `REQU=
IRED`, `URL` or `EMAIL`),
* - values are arrays of controls or forms that are invalid with given er=
ror.
*
* @description
* `FormController` keeps track of all its controls and nested forms as wel=
l as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject =3D ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form =3D this,
parentForm =3D element.parent().controller('form') || nullFormCtrl,
invalidCount =3D 0, // used to easily determine if we are valid
errors =3D form.$error =3D {};
// init state
form.$name =3D attrs.name;
form.$dirty =3D false;
form.$pristine =3D true;
form.$valid =3D true;
form.$invalid =3D false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey =3D validationErrorKey ? '-' + snake_case(validation=
ErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationError=
Key).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey=
);
}
form.$addControl =3D function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] =3D control;
}
};
form.$removeControl =3D function(control) {
if (control.$name && form[control.$name] =3D=3D=3D control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity =3D function(validationToken, isValid, control) {
var queue =3D errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid =3D true;
form.$invalid =3D false;
}
errors[validationToken] =3D false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] =3D queue =3D [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid =3D false;
form.$invalid =3D true;
}
};
form.$setDirty =3D function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty =3D true;
form.$pristine =3D false;
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for=
example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=3D} ngForm|name Name of the form. If specified, the form =
controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto =
the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid =
when all of the child
* forms are valid as well. However browsers do not allow nesting of `<f=
orm>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different=
than in classical
* roundtrip apps, it is desirable for the browser not to translate the for=
m submission into a full
* page reload that sends the data to the server. Instead some javascript l=
ogic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to=
the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript met=
hod should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=3Dsubmit])
*
* To prevent double execution of the handler, use only one of ngSubmit or =
ngClick directives. This
* is because of the following form submission rules coming from the html s=
pec:
*
* - If a form has only one input field then hitting enter in this field tr=
iggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=3Dsubmi=
t] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or inpu=
t[type=3Dsubmit] then
* hitting enter in any of the input fields will trigger the click handler =
on the *first* button or
* input[type=3Dsubmit] (`ngClick`) *and* a submit handler on the enclosing=
form (`ngSubmit`)
*
* @param {string=3D} name Name of the form. If specified, the form control=
ler will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType =3D 'guest';
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
userType: <input name=3D"input" ng-model=3D"userType" required&=
gt;
<span class=3D"error" ng-show=3D"myForm.input.$error.REQUIRED"&=
gt;Required!</span><br>
<tt>userType =3D {{userType}}</tt><br>
<tt>myForm.input.$valid =3D {{myForm.input.$valid}}</tt&g=
t;<br>
<tt>myForm.input.$error =3D {{myForm.input.$error}}</tt&g=
t;<br>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br>
<tt>myForm.$error.REQUIRED =3D {{!!myForm.$error.REQUIRED}}&=
lt;/tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveDir =3D {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
formElement.bind('submit', function(event) {
event.preventDefault();
});
}
var parentFormCtrl =3D formElement.parent().controller('form'),
alias =3D attr.name || attr.ngForm;
if (alias) {
scope[alias] =3D controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] =3D undefined;
}
extend(controller, nullFormCtrl); //stop propagating child dest=
ruction handlers upwards
});
}
}
};
}
};
var formDirective =3D valueFn(formDirectiveDir);
var ngFormDirective =3D valueFn(extend(copy(formDirectiveDir), {restrict: '=
EAC'}));
var URL_REGEXP =3D /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\=
/|\/([\w#!:.?+=3D&%@!\-\/]))?$/;
var EMAIL_REGEXP =3D /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP =3D /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType =3D {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} required Sets `required` validation error key if th=
e value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key i=
f the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key i=
f the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if th=
e value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline =
patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=3D} ngChange Angular expression to be executed when inp=
ut changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text =3D 'guest';
$scope.word =3D /^\w*$/;
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
Single word: <input type=3D"text" name=3D"input" ng-model=3D"=
text"
ng-pattern=3D"word" required>
<span class=3D"error" ng-show=3D"myForm.input.$error.required=
">
Required!</span>
<span class=3D"error" ng-show=3D"myForm.input.$error.pattern"=
>
Single word only!</span>
<tt>text =3D {{text}}</tt><br/>
<tt>myForm.input.$valid =3D {{myForm.input.$valid}}</tt=
><br/>
<tt>myForm.input.$error =3D {{myForm.input.$error}}</tt=
><br/>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br/&=
gt;
<tt>myForm.$error.required =3D {{!!myForm.$error.required}=
}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number=
` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} min Sets the `min` validation error key if the valu=
e entered is less then `min`.
* @param {string=3D} max Sets the `max` validation error key if the valu=
e entered is greater then `min`.
* @param {string=3D} required Sets `required` validation error key if th=
e value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key i=
f the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key i=
f the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if th=
e value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline =
patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=3D} ngChange Angular expression to be executed when inp=
ut changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value =3D 12;
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
Number: <input type=3D"number" name=3D"input" ng-model=3D"val=
ue"
min=3D"0" max=3D"99" required>
<span class=3D"error" ng-show=3D"myForm.list.$error.required"=
>
Required!</span>
<span class=3D"error" ng-show=3D"myForm.list.$error.number"&g=
t;
Not valid number!</span>
<tt>value =3D {{value}}</tt><br/>
<tt>myForm.input.$valid =3D {{myForm.input.$valid}}</tt=
><br/>
<tt>myForm.input.$error =3D {{myForm.input.$error}}</tt=
><br/>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br/&=
gt;
<tt>myForm.$error.required =3D {{!!myForm.$error.required}=
}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if=
the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} required Sets `required` validation error key if th=
e value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key i=
f the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key i=
f the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if th=
e value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline =
patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=3D} ngChange Angular expression to be executed when inp=
ut changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text =3D 'http://google.com';
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
URL: <input type=3D"url" name=3D"input" ng-model=3D"text" req=
uired>
<span class=3D"error" ng-show=3D"myForm.input.$error.required=
">
Required!</span>
<span class=3D"error" ng-show=3D"myForm.input.$error.url">
Not valid url!</span>
<tt>text =3D {{text}}</tt><br/>
<tt>myForm.input.$valid =3D {{myForm.input.$valid}}</tt=
><br/>
<tt>myForm.input.$error =3D {{myForm.input.$error}}</tt=
><br/>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br/&=
gt;
<tt>myForm.$error.required =3D {{!!myForm.$error.required}=
}</tt><br/>
<tt>myForm.$error.url =3D {{!!myForm.$error.url}}</tt&g=
t;<br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error ke=
y if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} required Sets `required` validation error key if th=
e value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key i=
f the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key i=
f the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if th=
e value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline =
patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text =3D '<EMAIL>';
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
Email: <input type=3D"email" name=3D"input" ng-model=3D"tex=
t" required>
<span class=3D"error" ng-show=3D"myForm.input.$error.requir=
ed">
Required!</span>
<span class=3D"error" ng-show=3D"myForm.input.$error.email"=
>
Not valid email!</span>
<tt>text =3D {{text}}</tt><br/>
<tt>myForm.input.$valid =3D {{myForm.input.$valid}}</=
tt><br/>
<tt>myForm.input.$error =3D {{myForm.input.$error}}</=
tt><br/>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br=
/>
<tt>myForm.$error.required =3D {{!!myForm.$error.require=
d}}</tt><br/>
<tt>myForm.$error.email =3D {{!!myForm.$error.email}}<=
;/tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('<EMAIL>');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set =
when selected.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} ngChange Angular expression to be executed when inp=
ut changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color =3D 'blue';
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
<input type=3D"radio" ng-model=3D"color" value=3D"red"> R=
ed <br/>
<input type=3D"radio" ng-model=3D"color" value=3D"green"> =
Green <br/>
<input type=3D"radio" ng-model=3D"color" value=3D"blue"> B=
lue <br/>
<tt>color =3D {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the cont=
rol is published.
* @param {string=3D} ngTrueValue The value to which the expression shoul=
d be set when selected.
* @param {string=3D} ngFalseValue The value to which the expression shou=
ld be set when not selected.
* @param {string=3D} ngChange Angular expression to be executed when inp=
ut changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 =3D true;
$scope.value2 =3D 'YES'
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
Value1: <input type=3D"checkbox" ng-model=3D"value1"> <=
br/>
Value2: <input type=3D"checkbox" ng-model=3D"value2"
ng-true-value=3D"YES" ng-false-value=3D"NO"> &=
lt;br/>
<tt>value1 =3D {{value1}}</tt><br/>
<tt>value2 =3D {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value =3D=3D=3D '' || value =3D=3D=3D null |=
| value !=3D=3D value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener =3D function() {
var value =3D trim(element.val());
if (ctrl.$viewValue !=3D=3D value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9=
which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key =3D event.keyCode;
// ignore
// command modifiers arrows
if (key =3D=3D=3D 91 || (15 < key && key < 19) || (37 &=
lt;=3D key && key <=3D 40)) return;
if (!timeout) {
timeout =3D $browser.defer(function() {
listener();
timeout =3D null;
});
}
});
// if user paste into input using mouse, we need "change" event to catc=
h it
element.bind('change', listener);
}
ctrl.$render =3D function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern =3D attr.ngPattern,
patternValidator;
var validate =3D function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern =3D new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator =3D function(value) {
return validate(pattern, value)
};
} else {
patternValidator =3D function(value) {
var patternObj =3D scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was =
' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength =3D int(attr.ngMinlength);
var minLengthValidator =3D function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength =3D int(attr.ngMaxlength);
var maxLengthValidator =3D function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty =3D isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value =3D=3D=3D '' ? null : (empty ? value : parseFloat(value)=
);
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min =3D parseFloat(attr.min);
var minValidator =3D function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max =3D parseFloat(attr.max);
var maxValidator =3D function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator =3D function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator =3D function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render =3D function() {
var value =3D attr.value;
element[0].checked =3D (value =3D=3D ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue =3D attr.ngTrueValue,
falseValue =3D attr.ngFalseValue;
if (!isString(trueValue)) trueValue =3D true;
if (!isString(falseValue)) falseValue =3D false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render =3D function() {
element[0].checked =3D ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value =3D=3D=3D trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-bindin=
g and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the contro=
l is published.
* @param {string=3D} required Sets `required` validation error key if the =
value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key if =
the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key if =
the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if the =
value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline pa=
tterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=3D} ngChange Angular expression to be executed when input=
changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control foll=
ows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=3D} name Property name of the form under which the contro=
l is published.
* @param {string=3D} required Sets `required` validation error key if the =
value is not entered.
* @param {number=3D} ngMinlength Sets `minlength` validation error key if =
the value is shorter than
* minlength.
* @param {number=3D} ngMaxlength Sets `maxlength` validation error key if =
the value is longer than
* maxlength.
* @param {string=3D} ngPattern Sets `pattern` validation error key if the =
value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline pa=
tterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=3D} ngChange Angular expression to be executed when input=
changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user =3D {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller=3D"Ctrl">
<form name=3D"myForm">
User name: <input type=3D"text" name=3D"userName" ng-model=3D=
"user.name" required>
<span class=3D"error" ng-show=3D"myForm.userName.$error.requi=
red">
Required!</span><br>
Last name: <input type=3D"text" name=3D"lastName" ng-model=3D=
"user.last"
ng-minlength=3D"3" ng-maxlength=3D"10">
<span class=3D"error" ng-show=3D"myForm.lastName.$error.minle=
ngth">
Too short!</span>
<span class=3D"error" ng-show=3D"myForm.lastName.$error.maxle=
ngth">
Too long!</span><br>
</form>
<hr>
<tt>user =3D {{user}}</tt><br/>
<tt>myForm.userName.$valid =3D {{myForm.userName.$valid}}<=
;/tt><br>
<tt>myForm.userName.$error =3D {{myForm.userName.$error}}<=
;/tt><br>
<tt>myForm.lastName.$valid =3D {{myForm.lastName.$valid}}<=
;/tt><br>
<tt>myForm.userName.$error =3D {{myForm.lastName.$error}}<=
;/tt><br>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required =3D {{!!myForm.$error.required}}&=
lt;/tt><br>
<tt>myForm.$error.minlength =3D {{!!myForm.$error.minlength}=
}</tt><br>
<tt>myForm.$error.maxlength =3D {{!!myForm.$error.maxlength}=
}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"=
}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function()=
{
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective =3D ['$browser', '$sniffer', function($browser, $sniffer=
) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element,=
attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS =3D 'ng-valid',
INVALID_CLASS =3D 'ng-invalid',
PRISTINE_CLASS =3D 'ng-pristine',
DIRTY_CLASS =3D 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bo=
und to.
* @property {Array.<Function>} $parsers Whenever the control reads v=
alue from the DOM, it executes
* all of these functions to sanitize / convert the value as well as va=
lidate.
*
* @property {Array.<Function>} $formatters Whenever the model value =
changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the c=
ontrol yet.
* @property {boolean} $dirty True if user has already interacted with the =
control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The contr=
oller contains
* services for data-binding, validation, CSS update, value formatting and =
parsing. It
* specifically does not contain any logic which deals with DOM rendering o=
r listening to
* DOM events. The `NgModelController` is meant to be extended by other dir=
ectives where, the
* directive provides DOM manipulation and the `NgModelController` provides=
the data-binding.
*
* This example shows how to use `NgModelController` with a custom control =
to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-mo=
del`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module=3D"customControl">
<file name=3D"style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name=3D"script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render =3D function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name=3D"index.html">
<form name=3D"myForm">
<div contenteditable
name=3D"myWidget" ng-model=3D"userContent"
required>Change me!</div>
<span ng-show=3D"myForm.myWidget.$error.required">Required!&l=
t;/span>
<hr>
<textarea ng-model=3D"userContent"></textarea>
</form>
</file>
<file name=3D"scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable =3D element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-requi=
red/);
});
</file>
* </example>
*
*/
var NgModelController =3D ['$scope', '$exceptionHandler', '$attrs', '$eleme=
nt', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue =3D Number.NaN;
this.$modelValue =3D Number.NaN;
this.$parsers =3D [];
this.$formatters =3D [];
this.$viewChangeListeners =3D [];
this.$pristine =3D true;
this.$dirty =3D false;
this.$valid =3D true;
this.$invalid =3D false;
this.$name =3D $attr.name;
var ngModelGet =3D $parse($attr.ngModel),
ngModelSet =3D ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user=
of the ng-model
* directive will implement this method.
*/
this.$render =3D noop;
var parentForm =3D $element.inheritedData('$formController') || nullFormC=
trl,
invalidCount =3D 0, // used to easily determine if we are valid
$error =3D this.$error =3D {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey =3D validationErrorKey ? '-' + snake_case(validation=
ErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationError=
Key).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey=
);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control chan=
ges validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or format=
ter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validat=
ionErrorKey` will assign
* to `$error[validationErrorKey]=3DisValid` so that it is availab=
le for data-binding.
* The `validationErrorKey` should be in camelCase and will get co=
nverted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-=
error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.my=
Error}}` .
* @param {boolean} isValid Whether the current state is valid (true) or =
invalid (false).
*/
this.$setValidity =3D function(validationErrorKey, isValid) {
if ($error[validationErrorKey] =3D=3D=3D !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid =3D true;
this.$invalid =3D false;
}
} else {
toggleValidCss(false);
this.$invalid =3D true;
this.$valid =3D false;
invalidCount++;
}
$error[validationErrorKey] =3D !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, u=
pdates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue =3D function(value) {
this.$viewValue =3D value;
// change to dirty
if (this.$pristine) {
this.$dirty =3D true;
this.$pristine =3D false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value =3D fn(value);
});
if (this.$modelValue !=3D=3D value) {
this.$modelValue =3D value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl =3D this;
$scope.$watch(ngModelGet, function(value) {
// ignore change from view
if (ctrl.$modelValue =3D=3D=3D value) return;
var formatters =3D ctrl.$formatters,
idx =3D formatters.length;
ctrl.$modelValue =3D value;
while(idx--) {
value =3D formatters[idx](value);
}
if (ctrl.$viewValue !=3D=3D value) {
ctrl.$viewValue =3D value;
ctrl.$render();
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works tog=
ether with `input`,
* `select`, `textarea`. You can easily write your own directives to use `n=
gModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input=
`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validatio=
n errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, =
`ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective =3D function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl =3D ctrls[0],
formCtrl =3D ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the=
model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter =3D 0;
* $scope.change =3D function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller=3D"Controller">
* <input type=3D"checkbox" ng-model=3D"confirmed" ng-change=3D"ch=
ange()" id=3D"ng-change-example1" />
* <input type=3D"checkbox" ng-model=3D"confirmed" id=3D"ng-change=
-example2" />
* <label for=3D"ng-change-example2">Confirmed</label><=
;br />
* debug =3D {{confirmed}}<br />
* counter =3D {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function(=
) {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', func=
tion() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective =3D valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective =3D function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required =3D true; // force truthy in case we are on non input e=
lement
var validator =3D function(value) {
if (attr.required && (isEmpty(value) || value =3D=3D=3D fal=
se)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-seperated string into an array of=
strings.
*
* @element input
* @param {string=3D} ngList optional delimiter that should be used to spli=
t the value. If
* specified in form `/something/` then the value will be converted into =
a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names =3D ['igor', 'misko', 'vojta'];
}
</script>
<form name=3D"myForm" ng-controller=3D"Ctrl">
List: <input name=3D"namesInput" ng-model=3D"names" ng-list req=
uired>
<span class=3D"error" ng-show=3D"myForm.list.$error.required"&g=
t;
Required!</span>
<tt>names =3D {{names}}</tt><br/>
<tt>myForm.namesInput.$valid =3D {{myForm.namesInput.$valid}=
}</tt><br/>
<tt>myForm.namesInput.$error =3D {{myForm.namesInput.$error}=
}</tt><br/>
<tt>myForm.$valid =3D {{myForm.$valid}}</tt><br/>=
;
<tt>myForm.$error.required =3D {{!!myForm.$error.required}}&=
lt;/tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective =3D function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match =3D /\/(.*)\//.exec(attr.ngList),
separator =3D match && new RegExp(match[1]) || attr.ngLis=
t || ',';
var parse =3D function(viewValue) {
var list =3D [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value) && !equals(parse(ctrl.$viewValue), value=
)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP =3D /^(true|false|\d+)$/;
var ngValueDirective =3D function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the =
specified HTML element
* with the value of a given expression, and to update the text content whe=
n the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the doub=
le curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expressi=
on }}` binding is when
* it's desirable to put bindings into template that is momentarily display=
ed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attri=
bute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evalua=
te.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text b=
ox changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name =3D 'Whirled';
}
</script>
<div ng-controller=3D"Ctrl">
Enter name: <input type=3D"text" ng-model=3D"name"><br>=
;
Hello <span ng-bind=3D"name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled')=
;
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective =3D ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function(value) {
element.text(value =3D=3D undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}&l=
t;/tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation =3D 'Hello';
$scope.name =3D 'World';
}
</script>
<div ng-controller=3D"Ctrl">
Salutation: <input type=3D"text" ng-model=3D"salutation"><=
br>
Name: <input type=3D"text" ng-model=3D"name"><br>
<pre ng-bind-template=3D"{{salutation}} {{name}}!"></pre&g=
t;
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective =3D ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn =3D $interpolate(element.attr(attr.$attr.ngBindTempla=
te));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expr=
ession` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should us=
e this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you =
are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression}=
to evaluate.
*/
var ngBindHtmlUnsafeDirective =3D [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name =3D 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
scope.$watch(attr[name], function(newVal, oldVal) {
if (selector =3D=3D=3D true || scope.$index % 2 =3D=3D=3D selector) {
if (oldVal && (newVal !=3D=3D oldVal)) {
if (isObject(oldVal) && !isArray(oldVal))
oldVal =3D map(oldVal, function(v, k) { if (v) return k });
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal)=
;
}
if (isObject(newVal) && !isArray(newVal))
newVal =3D map(newVal, function(v, k) { if (v) return k });
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : =
newVal); }
}, true);
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by=
databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was alre=
ady set.
*
* When the expression changes, the previously added classes are removed an=
d only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval.=
The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name=3D"index.html">
<input type=3D"button" value=3D"set" ng-click=3D"myVar=3D'my-class=
'">
<input type=3D"button" value=3D"clear" ng-click=3D"myVar=3D''">
<br>
<span ng-class=3D"myVar">Sample Text</span>
</file>
<file name=3D"style.css">
.my-class {
color: red;
}
</file>
<file name=3D"scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective =3D classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to ev=
al. The result
* of the evaluation can be a string representing space delimited class n=
ames or an array.
*
* @example
<example>
<file name=3D"index.html">
<ol ng-init=3D"names=3D['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat=3D"name in names">
<span ng-class-odd=3D"'odd'" ng-class-even=3D"'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name=3D"style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name=3D"scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className'=
)).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')=
).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective =3D classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to e=
val. The
* result of the evaluation can be a string representing space delimited =
class names or an array.
*
* @example
<example>
<file name=3D"index.html">
<ol ng-init=3D"names=3D['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat=3D"name in names">
<span ng-class-odd=3D"'odd'" ng-class-even=3D"'even'">
{{name}} &nbsp; &nbsp; &nbsp;
</span>
</li>
</ol>
</file>
<file name=3D"style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name=3D"scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className'=
)).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')=
).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective =3D classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template fro=
m being briefly
* displayed by the browser in its raw (uncompiled) form while your applica=
tion is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html tem=
plate display.
*
* The directive can be applied to the `<body>` element, but typicall=
y a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser v=
iew.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `=
angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (includin=
g their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes =
across this directive
* during the compilation of the template it deletes the `ngCloak` element =
attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head sect=
ion of the html file;
* alternatively, the css rule (above) must be included in the external sty=
lesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (ad=
ded in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation,=
you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the examp=
le below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id=3D"template1" ng-cloak>{{ 'hello' }}</div>
<div id=3D"template2" ng-cloak class=3D"ng-cloak">{{ 'hello I=
E7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() =
{
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective =3D ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key =
aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model =E2=80� The Model is data in scope properties; scopes are=
attached to the DOM.
* * View =E2=80� The template (HTML with data bindings) is rendered=
into the View.
* * Controller =E2=80� The `ngController` directive specifies a Con=
troller class; the class has
* methods that typically express the business logic behind the applicati=
on.
*
* Note that an alternative way to define controllers is via the `{@link ng=
.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible construct=
or function or an
* {@link guide/expression expression} that on the current scope evalua=
tes to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, remo=
ving, clearing, and
* greeting are methods declared on the controller (see source tab). These =
methods can
* easily be called from the angular markup. Notice that the scope becomes =
the `this` for the
* controller's instance. This allows for easy access to the view data from=
the controller. Also
* notice that any changes to the data are automatically reflected in the V=
iew without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name =3D "<NAME>";
$scope.contacts =3D [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'<EMAIL>'} ];
$scope.greet =3D function() {
alert(this.name);
};
$scope.addContact =3D function() {
this.contacts.push({type:'email', value:'<EMAIL>'})=
;
};
$scope.removeContact =3D function(contactToRemove) {
var index =3D this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact =3D function(contact) {
contact.type =3D 'phone';
contact.value =3D '';
};
}
</script>
<div ng-controller=3D"SettingsController">
Name: <input type=3D"text" ng-model=3D"name"/>
[ <a href=3D"" ng-click=3D"greet()">greet</a> ]<br/&=
gt;
Contact:
<ul>
<li ng-repeat=3D"contact in contacts">
<select ng-model=3D"contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type=3D"text" ng-model=3D"contact.value"/>
[ <a href=3D"" ng-click=3D"clearContact(contact)">clear&l=
t;/a>
| <a href=3D"" ng-click=3D"removeContact(contact)">X</=
a> ]
</li>
<li>[ <a href=3D"" ng-click=3D"addContact()">add</=
a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('Joh=
n Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('<EMAIL>');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('')=
;
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('<EMAIL>');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective =3D [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en=
/Security/CSP) support.
* This directive should be used on the root element of the application (ty=
pically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer =
slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective =3D ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp =3D true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evalu=
ate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click=3D"count =3D count + 1" ng-init=3D"count=3D0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are def=
ined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to p=
ropagate further.
*/
var ngEventDirectives =3D {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter=
mouseleave'.split(' '),
function(name) {
var directiveName =3D directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] =3D ['$parse', function($parse) {
return function(scope, element, attr) {
var fn =3D $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblc=
lick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to ev=
aluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mouse=
down event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to e=
valuate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to eva=
luate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to e=
valuate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to =
evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to =
evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to e=
valuate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sendin=
g the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval=
.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list =3D [];
$scope.text =3D 'hello';
$scope.submit =3D function() {
if (this.text) {
this.list.push(this.text);
this.text =3D '';
}
};
}
</script>
<form ng-submit=3D"submit()" ng-controller=3D"Ctrl">
Enter text and hit enter:
<input type=3D"text" ng-model=3D"text" name=3D"text" />
<input type=3D"submit" id=3D"submit" value=3D"Submit" />
<pre>list=3D{{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective =3D ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and=
for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If t=
he source is a string constant,
* make sure you wrap it in quotes, e.g. `src=3D"'myPartial=
Template.html'"`.
* @param {string=3D} onload Expression to evaluate when a new partial is l=
oaded.
*
* @param {string=3D} autoscroll Whether `ngInclude` should call {@link ng.=
$anchorScroll
* $anchorScroll} to scroll the viewport after the content=
is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolli=
ng.
* - Otherwise enable scrolling only if the expression eva=
luates to truthy value.
*
* @example
<example>
<file name=3D"index.html">
<div ng-controller=3D"Ctrl">
<select ng-model=3D"template" ng-options=3D"t.name for t in templ=
ates">
<option value=3D"">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src=3D"template.url"></div>
</div>
</file>
<file name=3D"script.js">
function Ctrl($scope) {
$scope.templates =3D
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template =3D $scope.templates[0];
}
</file>
<file name=3D"template1.html">
Content of template1.html
</file>
<file name=3D"template2.html">
Content of template2.html
</file>
<file name=3D"scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('')=
;
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective =3D ['$http', '$templateCache', '$anchorScroll', '$c=
ompile',
function($http, $templateCache, $anchorScroll, $com=
pile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp =3D attr.ngInclude || attr.src,
onloadExp =3D attr.onload || '',
autoScrollExp =3D attr.autoscroll;
return function(scope, element) {
var changeCounter =3D 0,
childScope;
var clearContent =3D function() {
if (childScope) {
childScope.$destroy();
childScope =3D null;
}
element.html('');
};
scope.$watch(srcExp, function(src) {
var thisChangeId =3D ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(respon=
se) {
if (thisChangeId !=3D=3D changeCounter) return;
if (childScope) childScope.$destroy();
childScope =3D scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || sc=
ope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId =3D=3D=3D changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init=3D"greeting=3D'Hello'; person=3D'World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective =3D ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but wh=
ich should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) i=
s present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective =3D ngDirective({ terminal: true, priority: 1000=
});
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US l=
ocalization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPlurali=
ze directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/languag=
e_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/languag=
e_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US loc=
ale, "other" can match
* any number that is not 1), an explicit number rule can only match one nu=
mber. For example, the
* explicit number rule for "3" matches the number 3. You will see the use =
of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link g=
uide/expression
* Angular expression}; these are evaluated on the current scope for its bo=
und value.
*
* The `when` attribute specifies the mappings between plural categories an=
d the actual
* string to be displayed. The value of the attribute should be a JSON obje=
ct so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count=3D"personCount"
when=3D"{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If=
you did not
* specify this rule, 0 would be matched to the "other" category and "0 peo=
ple are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explic=
it number rule for
* other numbers, for example 12, so that instead of showing "12 people are=
viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number=
that you want substituted
* into pluralized strings. In the previous example, Angular will replace `=
{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed b=
races `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, =
which can result in
* a better user experience. For example, instead of the message "4 people =
are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count=3D"personCount" offset=3D2
* when=3D"{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other pers=
on are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other peo=
ple are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we=
added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" wil=
l be shown.
* When three people view the document, no explicit number rule is found, s=
o
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural c=
ategory.
* In this case, plural category 'one' is matched and "John, Marry and one =
other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rul=
es for
* numbers from 0 up to and including the offset. If you use an offset of 3=
, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also =
provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspo=
ding strings.
* @param {number=3D} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 =3D 'Igor';
$scope.person2 =3D 'Misko';
$scope.personCount =3D 1;
}
</script>
<div ng-controller=3D"Ctrl">
Person 1:<input type=3D"text" ng-model=3D"person1" value=3D"Ig=
or" /><br/>
Person 2:<input type=3D"text" ng-model=3D"person2" value=3D"Mi=
sko" /><br/>
Number of People:<input type=3D"text" ng-model=3D"personCount"=
value=3D"1" /><br/>
<!--- Example with simple pluralization rules for en locale --=
->
Without Offset:
<ng-pluralize count=3D"personCount"
when=3D"{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count=3D"personCount" offset=3D2
when=3D"{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewin=
g.',
'one': '{{person1}}, {{person2}} and one oth=
er person are viewing.',
'other': '{{person1}}, {{person2}} and {} ot=
her people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are vi=
ewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are view=
ing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective =3D ['$locale', '$interpolate', function($locale, =
$interpolate) {
var BRACE =3D /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp =3D attr.count,
whenExp =3D element.attr(attr.$attr.when), // this is because we =
have {{}} in attrs
offset =3D attr.offset || 0,
whens =3D scope.$eval(whenExp),
whensExpFns =3D {};
forEach(whens, function(expression, key) {
whensExpFns[key] =3D
$interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + o=
ffset + '}}'));
});
scope.$watch(function() {
var value =3D parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use=
it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value =3D $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a co=
llection. Each template
* instance gets its own scope, where the given loop variable is set to the=
current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template insta=
nce, including:
*
* * `$index` =E2=80� `{number}` =E2=80� iterator offset of=
the repeated element (0..length-1)
* * `$first` =E2=80� `{boolean}` =E2=80� true if the repea=
ted element is first in the iterator.
* * `$middle` =E2=80� `{boolean}` =E2=80� true if the repe=
ated element is between the first and last in the iterator.
* * `$last` =E2=80� `{boolean}` =E2=80� true if the repeat=
ed element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enu=
merate a collection. Two
* formats are currently supported:
*
* * `variable in expression` =E2=80� where variable is the user d=
efined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` =E2=80� where `key` and `value` =
can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to en=
umerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init=3D"friends =3D [{name:'John', age:25}, {name:'Mary'=
, age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat=3D"friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years =
old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r =3D using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective =3D ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression =3D attr.ngRepeat;
var match =3D expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' =
but got '" +
expression + "'.");
}
lhs =3D match[1];
rhs =3D match[2];
match =3D lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or=
(key, value) but got '" +
lhs + "'.");
}
valueIdent =3D match[3] || match[1];
keyIdent =3D match[2];
// Store a list of elements from previous run. This is a hash where k=
ey is the item from the
// iterator, and the value is an array of objects with following prop=
erties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be ret=
urned from the iterator.
// We expect this to be a rare case.
var lastOrder =3D new HashQueueMap();
scope.$watch(function(scope){
var index, length,
collection =3D scope.$eval(rhs),
collectionLength =3D size(collection, true),
childScope,
// Same as lastOrder but it has the current state. It will beco=
me the
// lastOrder on the next iteration.
nextOrder =3D new HashQueueMap(),
key, value, // key/value of iteration
array, last, // last object information {scope, element, =
index}
cursor =3D iterStartElement; // current position of the nod=
e
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order =
of iteration over obj props
array =3D [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) !=
=3D '$') {
array.push(key);
}
}
array.sort();
} else {
array =3D collection || [];
}
// we are not using forEach for perf reasons (trying to avoid #call=
)
for (index =3D 0, length =3D array.length; index < length; index=
++) {
key =3D (collection =3D=3D=3D array) ? index : array[index];
value =3D collection[key];
last =3D lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse t=
he
// associated scope/element
childScope =3D last.scope;
nextOrder.push(value, last);
if (index =3D=3D=3D last.index) {
// do nothing
cursor =3D last.element;
} else {
// existing item which got moved
last.index =3D index;
// This may be a noop, if the element is next, but I don't kn=
ow of a good way to
// figure this out, since it would require extra DOM access,=
so let's just hope that
// the browsers realizes that it is noop, and treats it as su=
ch.
cursor.after(last.element);
cursor =3D last.element;
}
} else {
// new item which we don't know about
childScope =3D scope.$new();
}
childScope[valueIdent] =3D value;
if (keyIdent) childScope[keyIdent] =3D key;
childScope.$index =3D index;
childScope.$first =3D (index =3D=3D=3D 0);
childScope.$last =3D (index =3D=3D=3D (collectionLength - 1));
childScope.$middle =3D !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last =3D {
scope: childScope,
element: (cursor =3D clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array =3D lastOrder[key];
while(array.length) {
value =3D array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder =3D nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM t=
ree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is=
truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type=3D"checkbox" ng-model=3D"checked"><b=
r/>
Show: <span ng-show=3D"checked">I show up when your checkbox =
is checked.</span> <br/>
Hide: <span ng-hide=3D"checked">I hide when your checkbox is =
checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toE=
qual(1);
expect(element('.doc-example-live span:last:visible').count()).toE=
qual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).to=
Equal(1);
expect(element('.doc-example-live span:last:hidden').count()).toEq=
ual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective =3D ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} tr=
uthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type=3D"checkbox" ng-model=3D"checked"><b=
r/>
Show: <span ng-show=3D"checked">I show up when you checkbox i=
s checked?</span> <br/>
Hide: <span ng-hide=3D"checked">I hide when you checkbox is c=
hecked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toE=
qual(1);
expect(element('.doc-example-live span:last:visible').count()).toE=
qual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).to=
Equal(1);
expect(element('.doc-example-live span:last:hidden').count()).toEq=
ual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective =3D ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element c=
onditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which ev=
als to an
* object whose keys are CSS style names and values are corresponding =
values for those CSS
* keys.
*
* @example
<example>
<file name=3D"index.html">
<input type=3D"button" value=3D"set" ng-click=3D"myStyle=3D{colo=
r:'red'}">
<input type=3D"button" value=3D"clear" ng-click=3D"myStyle=3D{}"=
>
<br/>
<span ng-style=3D"myStyle">Sample Text</span>
<pre>myStyle=3D{{myStyle}}</pre>
</file>
<file name=3D"style.css">
span {
color: black;
}
</file>
<file name=3D"scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0=
, 0, 0)');
element('.doc-example-live :button[value=3Dset]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(2=
55, 0, 0)');
element('.doc-example-live :button[value=3Dclear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0=
, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective =3D ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
if (oldStyles && (newStyles !=3D=3D oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <ANY ng-switch-when=3D"matchValue1">...</ANY>
* <ANY ng-switch-when=3D"matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-w=
hen</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then thi=
s
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items =3D ['settings', 'home', 'other'];
$scope.selection =3D $scope.items[0];
}
</script>
<div ng-controller=3D"Ctrl">
<select ng-model=3D"selection" ng-options=3D"item for item in =
items">
</select>
<tt>selection=3D{{selection}}</tt>
<hr/>
<div ng-switch on=3D"selection" >
<div ng-switch-when=3D"settings">Settings Div</div>
<span ng-switch-when=3D"home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/S=
ettings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/H=
ome Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/d=
efault/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH =3D 'ng-switch';
var ngSwitchDirective =3D valueFn({
restrict: 'EA',
compile: function(element, attr) {
var watchExpr =3D attr.ngSwitch || attr.on,
cases =3D {};
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement =3D selectedScope =3D null;
}
if ((selectedTransclude =3D cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedScope =3D scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement =3D caseElement;
element.append(caseElement);
});
}
});
};
}
});
var ngSwitchWhenDirective =3D ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases =3D element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['!' + attrs.ngSwitchWhen] =3D transclude;
}
});
var ngSwitchDefaultDirective =3D ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases =3D element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['?'] =3D transclude;
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module=3D"transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title =3D 'Lorem Ipsum';
$scope.text =3D 'Neque porro quisquam est qui dolorem ipsum quia=
dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style=3D"border: 1px solid black;">' +
'<div style=3D"background-color: gray">{{t=
itle}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller=3D"Ctrl">
<input ng-model=3D"title"><br>
<textarea ng-model=3D"text"></textarea> <br/>
<pane title=3D"{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective =3D ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} se=
rvice by
* including the rendered template of the current route into the main layou=
t (`index.html`) file.
* Every time the current route changes, the included view changes with it =
according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module=3D"ngView">
<file name=3D"index.html">
<div ng-controller=3D"MainCntl">
Choose:
<a href=3D"Book/Moby">Moby</a> |
<a href=3D"Book/Moby/ch/1">Moby: Ch1</a> |
<a href=3D"Book/Gatsby">Gatsby</a> |
<a href=3D"Book/Gatsby/ch/4?key=3Dvalue">Gatsby: Ch4</a&=
gt; |
<a href=3D"Book/Scarlet">Scarlet Letter</a><br/>=
;
<div ng-view></div>
<hr />
<pre>$location.path() =3D {{$location.path()}}</pre>
<pre>$route.current.template =3D {{$route.current.template}=
}</pre>
<pre>$route.current.params =3D {{$route.current.params}}<=
;/pre>
<pre>$route.current.scope.name =3D {{$route.current.scope.n=
ame}}</pre>
<pre>$routeParams =3D {{$routeParams}}</pre>
</div>
</file>
<file name=3D"book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name=3D"chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name=3D"script.js">
angular.module('ngView', [], function($routeProvider, $locationProv=
ider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route =3D $route;
$scope.$location =3D $location;
$scope.$routeParams =3D $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name =3D "BookCntl";
$scope.params =3D $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name =3D "ChapterCntl";
$scope.params =3D $routeParams;
}
</file>
<file name=3D"scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content =3D element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content =3D element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective =3D ['$http', '$templateCache', '$route', '$anchorScrol=
l', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll,=
$compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp =3D attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope =3D null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals =3D $route.current && $route.current.locals,
template =3D locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link =3D $compile(element.contents()),
current =3D $route.current,
controller;
lastScope =3D current.scope =3D scope.$new();
if (current.controller) {
locals.$scope =3D lastScope;
controller =3D $controller(current.controller, locals);
element.contents().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templ=
ateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type=3D"text/ng-template" id=3D"/tpl.html">
Content of the template.
</script>
<a ng-click=3D"currentTpl=3D'/tpl.html'" id=3D"tpl-link">Load i=
nlined template</a>
<div id=3D"tpl-content" ng-include src=3D"currentTpl"></div&=
gt;
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the temp=
late/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective =3D ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type =3D=3D 'text/ng-template') {
var templateUrl =3D attr.id,
// IE is not consistent, in scripts we have to read .text but i=
n other nodes we have to read .textContent
text =3D element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a l=
ist of `<option>`
* elements for a `<select>` element using an array or an object obta=
ined by evaluating the
* `ngOptions` expression.
*=CB=9D=CB=9D
* When an item in the select menu is select, the value of array element or=
object property
* represented by the selected option will be bound to the model identified=
by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value=
set to an empty string, can
* be nested into the `<select>` element. This element will then repr=
esent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` elemen=
t which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an opt=
ion element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=3D} required The control is considered valid only if valu=
e is entered.
* @param {comprehension_expression=3D} ngOptions in one of the following f=
orms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value`=
**`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`=
** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`)=
in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / obje=
ct to iterate over.
* * `value`: local variable which will refer to each item in the `array`=
or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object=
` during iteration.
* * `label`: The result of this expression will be the label for `<op=
tion>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `v=
alue.propertyName`).
* * `select`: The result of this expression will be bound to the model o=
f the parent `<select>`
* element. If not specified, `select` expression will default to `val=
ue`.
* * `group`: The result of this expression will be used to group options=
using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors =3D [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color =3D $scope.colors[2]; // red
}
</script>
<div ng-controller=3D"MyCntrl">
<ul>
<li ng-repeat=3D"color in colors">
Name: <input ng-model=3D"color.name">
[<a href ng-click=3D"colors.splice($index, 1)">X</a&=
gt;]
</li>
<li>
[<a href ng-click=3D"colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model=3D"color" ng-options=3D"c.name for c in color=
s"></select><br>
Color (null allowed):
<span class=3D"nullable">
<select ng-model=3D"color" ng-options=3D"c.name for c in col=
ors">
<option value=3D"">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model=3D"color" ng-options=3D"c.name group by c.sha=
de for c in colors">
</select><br/>
Select <a href ng-click=3D"color=3D{name:'not in list'}">bo=
gus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style=3D"border:solid 1px black; height:20px"
ng-style=3D"{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective =3D valueFn({ terminal: true });
var selectDirective =3D ['$compile', '$parse', function($compile, $parse)=
{
//000011111000000000002222000000000000000000000033=
330000000000000444444444444444440000000005555555555555555500000006666666666=
66666660000000000000007777
var NG_OPTIONS_REGEXP =3D /^\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+(.*)$/,
nullModelCtrl =3D {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope,=
$attrs) {
var self =3D this,
optionsMap =3D {},
ngModelCtrl =3D nullModelCtrl,
nullOption,
unknownOption;
self.databound =3D $attrs.ngModel;
self.init =3D function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl =3D ngModelCtrl_;
nullOption =3D nullOption_;
unknownOption =3D unknownOption_;
}
self.addOption =3D function(value) {
optionsMap[value] =3D true;
if (ngModelCtrl.$viewValue =3D=3D value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption =3D function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue =3D=3D value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption =3D function(val) {
var unknownVal =3D '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption =3D function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole s=
elect is being destroyed
self.renderUnknownOption =3D noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl =3D ctrls[0],
ngModelCtrl =3D ctrls[1],
multiple =3D attr.multiple,
optionsExp =3D attr.ngOptions,
nullOption =3D false, // if false, user will not be able to selec=
t it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not sma=
rt enough
// to create it in <select> and IE barfs otherwise.
optionTemplate =3D jqLite(document.createElement('option')),
optGroupTemplate =3DjqLite(document.createElement('optgroup')),
unknownOption =3D optionTemplate.clone();
// find "null" option
for(var i =3D 0, children =3D element.children(), ii =3D children.len=
gth; i < ii; i++) {
if (children[i].value =3D=3D '') {
emptyOption =3D nullOption =3D children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator =3D function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value &am=
p;& value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render =3D function() {
var viewValue =3D ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue =3D=3D=3D '') emptyOption.prop('selected', true);=
// to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render =3D function() {
var items =3D new HashMap(ctrl.$viewValue);
forEach(selectElement.children(), function(option) {
option.selected =3D isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, =
but
// we need to work of an array, so we need to see if anything was i=
nserted/removed
scope.$watch(function() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView =3D copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array =3D [];
forEach(selectElement.children(), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match =3D optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_ke=
y_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn =3D $parse(match[2] || match[1]),
valueName =3D match[4] || match[6],
keyName =3D match[5],
groupByFn =3D $parse(match[3] || ''),
valueFn =3D $parse(match[2] ? match[1] : valueName),
valuesFn =3D $parse(match[7]),
// This is an array of array of existing option groups in DOM. =
We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or =
OPTGROUP element
optionGroupsCache =3D [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we reco=
mpile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') bec=
ause otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection =3D valuesFn(scope) || [],
locals =3D {},
key, value, optionElement, index, groupIndex, length, group=
Length;
if (multiple) {
value =3D [];
for (groupIndex =3D 0, groupLength =3D optionGroupsCache.leng=
th;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the pare=
nt)
optionGroup =3D optionGroupsCache[groupIndex];
for(index =3D 1, length =3D optionGroup.length; index < =
length; index++) {
if ((optionElement =3D optionGroup[index].element)[0].sel=
ected) {
key =3D optionElement.val();
if (keyName) locals[keyName] =3D key;
locals[valueName] =3D collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key =3D selectElement.val();
if (key =3D=3D '?') {
value =3D undefined;
} else if (key =3D=3D ''){
value =3D null;
} else {
locals[valueName] =3D collection[key];
if (keyName) locals[keyName] =3D key;
value =3D valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render =3D render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups =3D {'':[]}, // Temporary location for the optio=
n groups before we render them
optionGroupNames =3D [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue =3D ctrl.$modelValue,
values =3D valuesFn(scope) || [],
keys =3D keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals =3D {},
selected,
selectedSet =3D false, // nothing is selected yet
lastElement,
element;
if (multiple) {
selectedSet =3D new HashMap(modelValue);
} else if (modelValue =3D=3D=3D null || nullOption) {
// if we are not multiselect, and we are null then we have to a=
dd the nullOption
optionGroups[''].push({selected:modelValue =3D=3D=3D null, id:'=
', label:''});
selectedSet =3D true;
}
// We now build up the list of options we need (we merge later)
for (index =3D 0; length =3D keys.length, index < length; inde=
x++) {
locals[valueName] =3D values[keyName ? locals[keyName]=3Dkey=
s[index]:index];
optionGroupName =3D groupByFn(scope, locals) || '';
if (!(optionGroup =3D optionGroups[optionGroupName])) {
optionGroup =3D optionGroups[optionGroupName] =3D [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected =3D selectedSet.remove(valueFn(scope, locals)) !=3D =
undefined;
} else {
selected =3D modelValue =3D=3D=3D valueFn(scope, locals);
selectedSet =3D selectedSet || selected; // see if at least o=
ne item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into=
array or key from object
label: displayFn(scope, locals) || '', // what will be seen b=
y the user
selected: selected // determine if we shoul=
d be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optio=
nGroups we computed above
for (groupIndex =3D 0, groupLength =3D optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName =3D optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup =3D optionGroups[optionGroupName];
if (optionGroupsCache.length <=3D groupIndex) {
// we need to grow the optionGroups
existingParent =3D {
element: optGroupTemplate.clone().attr('label', optionGroup=
Name),
label: optionGroup.label
};
existingOptions =3D [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions =3D optionGroupsCache[groupIndex];
existingParent =3D existingOptions[0]; // either SELECT (no =
group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label !=3D optionGroupName) {
existingParent.element.attr('label', existingParent.label =
=3D optionGroupName);
}
}
lastElement =3D null; // start at the beginning
for(index =3D 0, length =3D optionGroup.length; index < leng=
th; index++) {
option =3D optionGroup[index];
if ((existingOption =3D existingOptions[index+1])) {
// reuse elements
lastElement =3D existingOption.element;
if (existingOption.label !=3D=3D option.label) {
lastElement.text(existingOption.label =3D option.label);
}
if (existingOption.id !=3D=3D option.id) {
lastElement.val(existingOption.id =3D option.id);
}
if (existingOption.element.selected !=3D=3D option.selected=
) {
lastElement.prop('selected', (existingOption.selected =3D=
option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id =3D=3D=3D '' && nullOption) {
// put back the pre-compiled element
element =3D nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the met=
hod calls, but
// in this version of jQuery on some browser the .text() =
returns a string
// rather then the element.
(element =3D optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption =3D {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement =3D element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent el=
ement not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective =3D ['$interpolate', function($interpolate) {
var nullSelectCtrl =3D {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
require: '^select',
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn =3D $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr, selectCtrl) {
if (selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden t=
his messes up the repeater.
// We don't want the view to drive the initialization of the mode=
l anyway.
element.prop('selected', false);
} else {
selectCtrl =3D nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !=3D=3D oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective =3D valueFn({
restrict: 'E',
terminal: true
});
//try to bind to jquery now so that one can write angular.element().read(=
)
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
angular.element(document).find('head').append('<style type=3D"text/css"&=gt;@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ngcloak],[x-ng-cloak],.n=g-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>')=;
<file_sep># lekkerus
## Plan
Learn `flask`, and use it to build some suitable entrance property.
Try some valuable CSS/JS framework<file_sep>from flask import Flask, render_template, session, redirect, url_for
__author__ = 'ykliu'
__name__ = 'main'
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def index():
form = NameForm()
if form.validate_on_submit():
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get(name))
<file_sep>from flask import Flask
from flask import request
from flask import render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from datetime import datetime
from wtf import WTF
__author__ = 'ykliu'
__name__ = '__main__'
app = Flask(__name__) # create an application instance
# Init flask-bootstrap
bootstrap = Bootstrap(app)
# Init flask-moment
moment = Moment(app)
current_time = datetime.utcnow()
@app.route('/')
def index():
user_agent = request.headers.get('User-agent')
return 'hello world! lyk in your %s' % user_agent
@app.route('/cv/<content>')
def cv(content):
return 'my %s is X' % content
@app.route('/try/<content>')
def try_template(content):
return render_template('try.html')
@app.route('/bootstrap/<content>')
def bootstrap(content):
return render_template('bootstrap.html', name=content) # Notice: your form!!!!
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
u
if __name__ == '__main__':
app.run(debug=True)
| 00a92cb246a9034a84618fddaf55767dc66da407 | [
"JavaScript",
"Python",
"Markdown"
] | 4 | JavaScript | lekkerus/lekkerus | 49d41ba237b9b6a065654e25002ef1c32e6084f0 | 9424f53fdfe8f662eb766f654c6cd1a126432ad2 |
refs/heads/master | <file_sep>console.log('this is loaded');
exports.twitterKeys = {
consumer_key: 'vwjx7AsMIKlNZXFiwudVbqc87',
consumer_secret: '<KEY>',
access_token_key: '<KEY>',
access_token_secret: '<KEY>',
} | 3feda25c4012a4e884fb20c67eda36457caed6e0 | [
"JavaScript"
] | 1 | JavaScript | bhart2017/liri-node-app | 7901e209dd7111f66f8bf71b66844f28eac5e807 | 0e3498f0562d8d74fe4da7bca227e82e96f8e76d |
refs/heads/master | <file_sep>import numpy as np
class legendre_decomposition:
"""
A 2D implementation of lengendre decomposition.
<NAME>., <NAME>., <NAME>.:
Legendre Decomposition for Tensors,
NeurIPS 2018
"""
def __init__(self, P):
"""
Parameters:
-----------
P: numpy.ndarray
Input Matrix
Returns:
--------
None
"""
self.P = P
self.theta_mat = np.zeros(P.shape)
self.eta_emp_mat = self._compute_eta(P)
def reconstruct(self):
"""
Use theta to reconstruct input
Paramaters:
-----------
None
Returns:
--------
None
"""
exp_theta_mat = np.exp(self.theta_mat)
k, l = exp_theta_mat.shape
Q = np.empty((k, l))
for i in range(k):
for j in range(l):
Q[i, j] = np.prod(exp_theta_mat[np.arange(0, i+1)][:, np.arange(0, j+1)])
psi = np.sum(Q)
Q /= psi
return Q
def _compute_eta(self, P_mat):
"""
Compute eta for parameter P_mat
Parameters:
-----------
P_mat: numpy.ndarray
Normalised matrix.
Returns:
--------
eta_mat: numpy.ndarray
eta matrix for P_mat.
"""
k, l = P_mat.shape
eta_mat = np.empty((k, l))
for i in range(k):
for j in range(l):
eta_mat[i,j] = np.sum(P_mat[np.arange(i, k)][:, np.arange(j, l)])
return eta_mat
def _gradient_descent_step(self, lr=0.01, verbose=False):
"""
Single step to train the algorithm. Minimises the KL Divergence
between the input and the model.
Paramaters:
-----------
lr: int
Learning rate
verbose: bool
print progress of training
Returns:
--------
None
"""
gradient = self._compute_eta(self.reconstruct()) - self.eta_emp_mat
if verbose:
print('============================================')
print('eta:\n', np.around(self._compute_eta(self.reconstruct()), 3))
print('eta_emp:\n', np.around(self.eta_emp_mat, 3))
print('gradient:\n', np.around(gradient, 3))
print('theta:\n', np.around(self.theta_mat, 3))
print('np.exp(theta):\n', np.around(np.exp(self.theta_mat), 3))
print('P:\n', np.around(self.P, 3))
print('Q:\n', np.around(self.reconstruct(), 3))
print('total error:', np.around(np.sum(gradient**2)**0.5, 3))
print('============================================')
self.theta_mat -= lr*gradient
def train(self, N_iter, lr=0.01, verbose=False, verbose_step=100):
"""
Trains the model.
Paramaters:
-----------
lr: int
Learning rate
verbose: bool
print progress of training
verbose_step: int
Number of iterations before printing progress of training.
verbose must be set to True to print progress.
Returns:
--------
None
"""
for i in range(N_iter):
if i % verbose_step == 0:
verbose_flag = verbose
else:
verbose_flag = False
self._gradient_descent_step(lr=lr, verbose=verbose_flag)
def get_theta(self):
"""
Returns theta, the natural parameter.
Parameters:
-----------
None
Returns:
--------
self.theta_mat: numpy.ndarray
Returns a matrix of theta, the natural parameter.
"""
return self.theta_mat
def get_eta(self):
"""
Returns eta, the expectation parameter.
Parameters:
-----------
None
Returns:
--------
eta_mat: numpy.ndarray
Returns a matrix of eta, the expectation parameter.
"""
eta_mat = self._compute_eta(self.reconstruct())
return eta_mat
def change_P(self, P):
"""
Parameters:
-----------
P: numpy.ndarray
The input matrix
Returns:
--------
None
"""
self.P = P
self.eta_est_mat = self._compute_eta(P)
def main():
np.random.seed(1)
P = np.random.rand(5,5)
P /= np.sum(P)
ld = legendre_decomposition(P)
ld.train(10000, lr=1, verbose=True, verbose_step=1000)
if __name__ == '__main__':
main() | 535d36cba7d487decefe975ad17c908ea944c617 | [
"Python"
] | 1 | Python | sjmluo/legendre_decomposition | f1ce0625a3a45ebaac8d578d1078f5688d4d597c | 1e94358b349603be202db3dfb0c4a45f975ae75e |
refs/heads/master | <file_sep><?php
namespace App\Helpers;
class Helper
{
public static function first_and_last_name( $first_or_last = '', $name = '' ) // Added: 08/15/2021.
{
$parts = explode( ' ', $name );
if( count( $parts ) > 1 ) {
$last_name = array_pop( $parts );
$first_name = implode( ' ', $parts );
}
else {
$first_name = $name;
$last_name = '';
}
if( $first_or_last === 'first' ) {
return $first_name;
}
elseif( $first_or_last === 'last' ) {
return $last_name;
}
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\JGDevController;
use App\Http\Controllers\FormSubmissionController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*
Route::get( '/', function() {
return view('welcome');
} );
*/
Route::get( '/', [ JGDevController::class, 'home' ] )->name( 'home.get' );
Route::post( '/', [ FormSubmissionController::class, 'form_submission' ] )->name( 'home.post' ); // Added: 07/18/2021.
Route::get( 'ce', [ JGDevController::class, 'condor_elite' ] )->name( 'condorElite' );
Route::get( 'dd', [ JGDevController::class, 'discount_dance' ] )->name( 'discountDance' );
Route::get( 'up', [ JGDevController::class, 'uat_parts' ] )->name( 'uatParts' );
Route::get( 'nch', [ JGDevController::class, 'nevada_corporate_headquarters' ] )->name( 'nevadaCorporateHeadquarters' ); // Added: 05/24/2021.
Route::get( 'portal', [ JGDevController::class, 'nch_portal' ] )->name( 'nchPortal' ); // Added: 05/24/2021.
Route::get( 'csc', [ JGDevController::class, 'csc' ] )->name( 'csc' ); // Added: 05/29/2021.
Route::get( 'vault', [ JGDevController::class, 'vault' ] )->name( 'vault' ); // Added: 05/30/2021.
Route::get( 'paul', [ JGDevController::class, 'paul' ] )->name( 'paul' ); // Added: 05/31/2021.
Route::get( 'vcl', [ JGDevController::class, 'vital_care_lab' ] )->name( 'vital' ); // Added: 05/31/2021.
<file_sep>/* globals lozad */
( function() {
'use strict';
/* Since I started lazy-loading images with Lozad.js, the isotope-layout package used in the portfolio section stopped working. The portfolio thumbnail images were the right width, but they were very short in height.
Isotope-layout couldn't calculate the height of the images because they were lazy-loaded. To fix that, I had to use the window.portfolioIsotope.arrange() method to refresh the isotope-layout portfolio.
My first idea was to call window.portfolioIsotope.arrange() when the portfolio was visible (in view), but I would've needed a JavaScript plugin to detect when "div.portfolio-container" was visible.
Instead, I used the MutationObserver() class to detect the "div.portfolio-container" node for changes. When Lozad.js loads an image, it adds the data-loaded="true" attribute to the <img> element.
Each time the "div.portfolio-container" was mutated with a new "data-loaded" attribute, my custom arrangePortfolioIsotope() function calls window.portfolioIsotope.arrange() to refresh the isotope-layout and
show the lazy-loaded images right.
Source: Myself, mutation-observer.html on my sample-code.
Added: 05/01/2021.
*/
function arrangePortfolioIsotope() {
if( document.querySelector( 'div.portfolio-container' ) ) { // Prevent the "Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'" when observer.observe( target, config ); is called from a "Project Information" page, since those pages don't have a <div class="portfolio-container"> element. Source: Myself. 05/24/2021.
const lozadObserver = lozad(); // Initialize Lozad.js to lazy load images with the "lozad" class. Source: https://www.npmjs.com/package/lozad Added: 05/01/2021.
lozadObserver.observe();
var numberOfPortfolioImagesLoaded = 0,
target = document.querySelector( 'div.portfolio-container' ),
observer = new MutationObserver( mutate ), // Pass the mutate() function by reference.
config = { attributes: true, characterData: true, childList: true, subtree: true };
observer.observe( target, config );
function mutate( mutations ) { // This is MutationObserver()'s callback function.
mutations.forEach( function( mutation ) {
if( mutation.type === 'attributes' && mutation.attributeName === 'data-loaded' && typeof window.portfolioIsotope !== 'undefined' && window.portfolioIsotope !== null ) { // The typeof operator is used to prevent the "Uncaught TypeError: Cannot read property 'arrange' of undefined" in a browser's JavaScript console when reloading the home page with the portfolio section's title in view. Source: Myself. Added: 05/24/2021.
window.portfolioIsotope.arrange();
numberOfPortfolioImagesLoaded++;
if( numberOfPortfolioImagesLoaded === 9 ) {
setTimeout( function() {
window.portfolioIsotope.arrange(); // I added this final call on a slight delay since the last portfolio image wasn't appearing right on mobile (its height was very short).
observer.disconnect(); // After the ninth and final portfolio image has been loaded, disconnect the observer to prevent wasting system resources.
}, 500 );
}
}
} ); // End mutations.forEach().
}
}
} // End arrangePortfolioIsotope().
document.addEventListener( 'DOMContentLoaded', function() {
arrangePortfolioIsotope();
} ); // End document.addEventListener( 'DOMContentLoaded' ).
} ) (); // End self-executing anonymous function.
<file_sep><?php
// Created: 07/18/2021.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FormValidationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'home_page_contact_form_name' => 'required|min:3|max:30',
'home_page_contact_form_email' => 'required|string|email:rfc,dns,filter|max:50',
'home_page_contact_form_phone' => 'required|string|min:14|max:20', // Added: 08/14/2021.
'home_page_contact_form_subject' => 'required|min:3|max:80',
'home_page_contact_form_message' => 'required|min:5|max:500'
];
}
/**
* Custom <input name=""> attributes for validation.
*
* @return array
*/
public function attributes() // Added: 07/24/2021.
{
return [
'home_page_contact_form_name' => 'name',
'home_page_contact_form_email' => 'email',
'home_page_contact_form_phone' => 'phone', // Added: 08/14/2021.
'home_page_contact_form_subject' => 'subject',
'home_page_contact_form_message' => 'message'
];
}
/**
* Custom messages for validation.
*
* @return array
*/
public function messages()
{
return [
'home_page_contact_form_email.email' => 'A valid email address is required.', // The default message is horrible: "The email must be a valid email address." Source: Myself. Added: 07/18/2021.
];
}
}
<file_sep><?php
// Created: 07/18/2021.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\FormValidationRequest;
use Helper;
use App\Models\ContactFormSubmission;
use Illuminate\Support\Facades\Mail;
class FormSubmissionController extends Controller
{
public function form_submission( FormValidationRequest $request ) {
$name = strip_tags( request( 'home_page_contact_form_name' ) );
$first_name = Helper::first_and_last_name( 'first', $name );
$last_name = Helper::first_and_last_name( 'last', $name );
$email = strip_tags( request( 'home_page_contact_form_email' ) );
$phone = strip_tags( request( 'home_page_contact_form_phone' ) );
$subject = strip_tags( request( 'home_page_contact_form_subject' ) );
$body = strip_tags( request( 'home_page_contact_form_message' ) );
ContactFormSubmission::create( // Insert the contact form submission into the database. Added: 08/14/2021.
[
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'phone' => $phone,
'subject' => $subject,
'message' => $body
]
);
if( request( 'form_id' ) === 'homePageContactForm' ) {
echo <<< html
<script type="application/javascript">
document.addEventListener( 'DOMContentLoaded', function( eventObj ) {
scrollToContactSection(); // Defined in /js/script.js.
} );
</script>
html;
}
$admin_to = [ '<EMAIL>' => '<NAME>' ];
$admin_subject = 'JoeGutierrez.dev Form Submission, Subject: ' . $subject;
$data = [
'name' => $name,
'email' => $email,
'phone' => $phone,
'subject' => $subject,
'body' => $body
];
Mail::send( 'emails.home-page-form-submission', $data, function ( $admin_email ) use ( $admin_to, $admin_subject ) { // Added: 08/28/2021.
$admin_email->to( $admin_to )->subject( $admin_subject );
} );
return view( 'home' );
}
}
<file_sep><?php
// Created: 08/29/2021.
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Log;
use Throwable;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Illuminate\Support\Facades\Mail;
use DOMDocument;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
*/
public function report( Throwable $exception )
{
// emails.exception is the template of your email
// it will have access to the $error that we are passing below
if( $this->shouldReport( $exception ) ) {
$this->sendEmail( $exception ); // sends an email
}
return parent::report( $exception );
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render( $request, Throwable $exception )
{
return parent::render( $request, $exception );
}
public function sendEmail( Throwable $exception )
{
try {
if( get_class( $exception ) === 'Facade\Ignition\Exceptions\ViewException' ) { // Prevent the "FlattenException::create() must be an instance of Exception, instance of TypeError given" error in the logs. Source: https://stackoverflow.com/questions/30331322/how-can-i-check-if-a-object-is-an-instance-of-a-specific-class#65158321 Added: 09/05/2021.
$e = FlattenException::create( $exception );
$handler = new HtmlErrorRenderer( true ); // The true Boolean raises the debug flag.
$content = $handler->getBody( $e );
$content = strlen( $content ) > 20000 ? substr( $content, 0, 20000 ) : $content; // If the email content is greater than 20,000 characters, trim it to 20,000 characters.
$dom = new DOMDocument;
$dom->loadHTML( $content, LIBXML_NOERROR ); // The LIBXML_NOERROR argument is to suppress (in the logs) the ErrorException: DOMDocument::loadHTML(): Tag svg invalid in Entity, line: 6 in app/Exceptions/Handler.php:82. That error happens because loadHTML() doesn't support HTML5 elements. Sources: https://stackoverflow.com/questions/9149180/domdocumentloadhtml-error#64471875 https://www.php.net/manual/en/domdocument.loadhtml.php#118107 Added: 09/05/2021.
$h1 = $dom->getElementsByTagName( 'h1' )[ 0 ]->textContent;
$data = [
'content' => $content,
'full_url' => url()->full(),
];
Mail::send( 'emails.exception', $data, function( $message ) use ( $h1 ) {
$message->to( [ '<EMAIL>' => '<NAME>' ] )->subject( 'JoeGutierrez.dev Exception: ' . $h1 );
} );
}
}
catch( Throwable $exception ) {
Log::error( $exception );
}
}
}
<file_sep><?php
// Created: 08/13/2021.
// The command I used to create this file was: php artisan make:command sql
// The command I ran to create the database was: php artisan sql:createdb joegutierrez_dev
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class sql extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sql:createdb {name?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new SQL database schema based on the database config file.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$schemaName = $this->argument( 'name' ) ?: config( 'database.connections.mysql.database' );
$charset = config( 'database.connections.mysql.charset', 'utf8mb4' );
$collation = config( 'database.connections.mysql.collation', 'utf8mb4_unicode_520_ci' );
config( [ 'database.connections.mysql.database' => null ] );
$query = 'CREATE DATABASE IF NOT EXISTS ' . $schemaName . ' CHARACTER SET ' . $charset . ' COLLATE ' . $collation . ';';
DB::statement( $query );
config( [ 'database.connections.mysql.database' => $schemaName ] );
}
}
<file_sep><?php
// Created: 08/14/2021.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContactFormSubmissionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create( 'contact_form_submissions', function( Blueprint $table ) {
$table->id();
$table->string( 'first_name', 30 )->nullable( false );
$table->string( 'last_name', 30 )->nullable( false ); // Both the first and last names must be allowed to be the maximum's 30 characters in case someone enters just one very long first name or one very long last name.
$table->string( 'phone', 20 )->nullable( false );
$table->string( 'email', 50 )->nullable( false );
$table->string( 'subject', 80 )->nullable( false );
$table->string( 'message', 500 )->nullable( false );
$table->timestamps();
} );
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists( 'contact_form_submissions' );
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\ViewErrorBag;
class JGDevController extends Controller
{
public function home() {
$errors = session()->get( 'errors', app( ViewErrorBag::class ) );
if( $errors->hasAny( [ 'home_page_contact_form_name', 'home_page_contact_form_email', 'home_page_contact_form_phone', 'home_page_contact_form_subject', 'home_page_contact_form_message' ] ) ) {
echo <<< html
<script type="application/javascript">
document.addEventListener( 'DOMContentLoaded', function( eventObj ) {
scrollToContactSection();
} );
</script>
html;
}
return view( 'home' );
}
public function condor_elite() {
return view( 'project-template', [
'title' => 'Condor Elite',
'category' => 'Ecommerce',
'tech_stack' => 'Magento, PHP, Bootstrap, CSS, JavaScript, jQuery',
'url' => 'https://www.condor-elite.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'ce-1.jpg', 'ce-2.jpg', 'ce-3.jpg' ],
] );
}
public function discount_dance() {
return view( 'project-template', [
'title' => 'Discount Dance',
'category' => 'Ecommerce',
'tech_stack' => 'SQL, PHP, jQuery Mobile, CSS, JavaScript, jQuery, New Relic, Mouseflow API, InkSoft API',
'url' => 'https://www.discountdance.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'dd-1.jpg', 'dd-2.jpg', 'dd-3.jpg' ],
] );
}
public function uat_parts() {
return view( 'project-template', [
'title' => 'UAT Parts',
'category' => 'Ecommerce',
'tech_stack' => 'Miva Merchant, PHP, HTML, CSS, JavaScript, jQuery',
'url' => 'https://www.uatparts.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'up-1.jpg', 'up-2.jpg', 'up-3.jpg' ],
] );
}
public function nevada_corporate_headquarters() {
return view( 'project-template', [
'title' => 'Nevada Corporate Headquarters',
'category' => 'Web, Lead Collection, Forms, Landing Pages',
'tech_stack' => 'Laravel, Bootstrap, PHP, SQL, jQuery, AJAX',
'url' => 'https://www.nchinc.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'nch-1.jpg', 'nch-2.jpg', 'nch-3.jpg' ],
] );
}
public function nch_portal() {
return view( 'project-template', [
'title' => 'Client Portal',
'category' => 'Laravel',
'tech_stack' => 'Laravel, Bootstrap',
'url' => 'https://portal.nchinc.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'portal-1.jpg', 'portal-2.jpg', 'portal-3.jpg' ],
] );
}
public function csc() {
return view( 'project-template', [
'title' => 'Corporate Service Center',
'category' => 'Web, Landing Page, Lead Collection',
'tech_stack' => 'Laravel, Bootstrap',
'url' => 'https://www.corporateservicecenter.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'csc-1.jpg', 'csc-2.jpg', 'csc-3.jpg' ],
] );
}
public function vault() {
return view( 'project-template', [
'title' => 'Company Vault',
'category' => 'Web',
'tech_stack' => 'WordPress, Avada theme',
'url' => '',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'vault-1.jpg', 'vault-2.jpg', 'vault-3.jpg' ],
] );
}
public function paul() {
return view( 'project-template', [
'title' => '<NAME>',
'category' => 'Art, Personal, Biography, Portfolio, Blog',
'tech_stack' => 'WordPress, Avada theme, Custom Post Type plugin, CSS',
'url' => 'https://www.paultzanetopoulos.com/',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'paul-1.jpg', 'paul-2.jpg', 'paul-3.jpg' ],
] );
}
public function vital_care_lab() {
return view( 'project-template', [
'title' => 'Vital Care Lab',
'category' => 'Web, Medical, Blog',
'tech_stack' => 'WordPress, Avada theme',
'url' => '',
'description' => 'Autem ipsum nam porro corporis rerum. Quis eos dolorem eos itaque inventore commodi labore quia quia. Exercitationem repudiandae officiis neque suscipit non officia eaque itaque enim. Voluptatem officia accusantium nesciunt est omnis tempora consectetur dignissimos. Sequi nulla at esse enim cum deserunt eius.',
'imgs' => [ 'vital-1.jpg' ],
] );
}
}
<file_sep>// Created: 07/18/2021.
( function () {
'use strict';
$( document ).ready( function () {
$( 'form#homePageContactForm' ).on( 'submit', function ( eventObj ) { // To test posting with Laravel instead of jQuery AJAX, just change the on() method's selector.
eventObj.preventDefault();
$( this ).find( 'button[ type="submit" ]' ).prop( 'disabled', true ).html( '<div class="loader"></div>' ); // Disable the submit button after the form has been submitted to prevent multiple submits. Without this, the user will be able to click the submit button several times, allowing the form to be submitted multiple times. To be able to test that, I added a three-second delay in app/Http/Controllers/TestController.php to simulate data being sent via an API or posting to a database. That will delay the success() and error() methods, allowing you to confirm the submit button has been disabled. Source: https://stackoverflow.com/questions/13606573/disable-button-after-submit-with-jquery#13606633 Added: 01/18/2021.
// html( '<div class="loader"></div>' ) is used to insert a CSS loading spinner to indicate that the form is sending. It provides a better UX. Source: https://www.w3schools.com/howto/howto_css_loader.asp Added: 01/30/2021.
$.ajax( {
type: 'post',
url: '/',
data: $( 'form#homePageContactForm' ).serialize(), // The form fields you're first sending to the controller, then second to the request class for validation, including the Laravel CSRF token, $( 'form#homePageContactForm input[name="_token"]' ).val(), to prevent the "419 | Page Expired" Laravel error when submitting a form.
/*
IMPORTANT! Don't set the dataType! The reason for that is that it's dynamic! On an ajax() error, it returns JSON; but on ajax() success, it returns HTML. So, let the ajax() method detect it for you. At first, I was setting it to "json" but then I noticed the success function was never triggering, even when the form was submitted successfully, and that was the reason. Sources: Myself https://stackoverflow.com/questions/46895031/ajax-request-keeps-returning-error-function-in-laravel#46895091 Added: 01/09/2021.
dataType: 'json', // The response format.
*/
success: function( responseHTML ) {
$( 'div#homePageContactFormContainer div.alert-success' ).removeClass( 'd-none' ); // Instead of inserting a new "success" element with jQuery, I decided to show/hide them with both the jQuery and Laravel versions. That way, you're not inserting two separate elements, a success element for jQuery AJAX validation and one for Laravel validation. There's just ONE element that'll get shown/hidden with both versions. That makes it easier to maintain.
$( 'form#homePageContactForm' ).addClass( 'd-none' );
},
error: function( err ) { // Don't try changing "err" to "error" since there's already another argument named "error."
$( 'form#homePageContactForm button[ type="submit" ]' ).prop( 'disabled', false ).text( 'Send Message' );
// console.log( 'The submit button has been re-enabled since there are validation errors.' );
if( err.status === 422 ) { // When the status code is 422, it's a validation issue.
/*
console.log( 'Error 422' );
console.log( err.responseJSON.message );
console.log( err.responseJSON );
console.log( err.responseJSON.errors );
*/
// Clear any errors from the previous submit.
$( 'form#homePageContactForm span.invalid-feedback' ).text( '' ).removeClass( 'd-inline' ); // Hide all of the error messages.
$( 'form#homePageContactForm .is-invalid' ).removeClass( 'is-invalid' ); // Hide the exclamation point in a circle Bootstrap icon and return the form field's border color from red to its regular color.
// Display any Laravel validation errors via the DOM.
$.each( err.responseJSON.errors, function( index, error ) {
var element = $( document ).find( 'form#homePageContactForm [name = "' + index + '"]' );
if( element.attr( 'type' ) === 'text' || element[ 0 ].nodeName === 'TEXTAREA' || element[ 0 ].nodeName === 'SELECT' ) {
element.addClass( 'is-invalid' ); // Show the exclamation point in a circle Bootstrap icon inside the form field and make the form field's border red.
element.next().text( error[ 0 ] ).removeClass( 'd-none' ); // Insert the error message to the span.invalid-feedback element.
}
else if( element.attr( 'type' ) === 'radio' ) {
$( element[ 1 ] ).parent().next().text( error[ 0 ] ).addClass( 'd-inline' ); // $( element[ 1 ] ) is used to select only the second radio button. Otherwise, the error message is printed twice.
}
} );
}
else if( err.status === 405 ) { // This error usually happens when ajax() is sending to the wrong URL.
// Example 405 HTTP response code error message: The POST method is not supported for this route. Supported methods: GET, HEAD.
console.log( err.responseJSON.message );
}
else {
console.log( err.responseText );
console.log( err );
console.log( err.responseJSON.message );
}
}
} );
} );
} ); // End $( document ).ready().
} ) (); // End self-executing anonymous function.
| 4f72800d2d786e5164ae6ca9e43aa5939e0d0cb6 | [
"JavaScript",
"PHP"
] | 10 | PHP | JoeGutierrez/JoeGutierrez.dev | 1e500c2abf471281bd9a0a71e6e5412ca383a933 | b7aeb4eaba85b8d0bc27d02d2726ddac40c639b0 |
refs/heads/master | <file_sep>module Players
class Computer < Player
end
end | 29552e14894f7e8784b7b642df5782185b94e4ce | [
"Ruby"
] | 1 | Ruby | abrolon87/ttt-with-ai-project-onl01-seng-pt-120819 | 5baa38ae0bd7009f45c0f5500a4ca8dec7171f27 | 362fa6ab207fc9fa7637b23e29978a85a1dd5ff3 |
refs/heads/main | <repo_name>joeray100/snowy-pine-8251<file_sep>/spec/models/flight_spec.rb
require 'rails_helper'
RSpec.describe Flight, type: :model do
describe "relationships" do
it {should belong_to :airline}
end
end
<file_sep>/db/seeds.rb
Airline.destroy_all
Flight.destroy_all
Passenger.destroy_all
@airline_1 = Airline.create!(name: "Frontier")
@flight_1 = @airline_1.flights.create!(number: "1727", date: "08/03/20", departure_city: "Denver", arrival_city: "Reno")
@flight_2 = @airline_1.flights.create!(number: "1628", date: "08/20/21", departure_city: "Atlanta", arrival_city: "Detriot")
@flight_3 = @airline_1.flights.create!(number: "1212", date: "09/10/22", departure_city: "Columbus", arrival_city: "Austin")
@passenger_1 = @flight_3.passengers.create!(name: "Tim", age: 22)
@passenger_2 = @flight_3.passengers.create!(name: "Tyna", age: 30)
@passenger_3 = @flight_3.passengers.create!(name: "Craig", age: 15)
| 57c287f48a0eba3f280f7ccdac487b5c955ec9aa | [
"Ruby"
] | 2 | Ruby | joeray100/snowy-pine-8251 | 3bd023a4746a304f0a43c765dc602351ba5c3596 | 702072ec34a02c62dd7f8e1f7b7d269c455ffb34 |
refs/heads/master | <file_sep>package com.cts;
import com.cts.data.Class;
import com.cts.data.Teacher;
import com.cts.client.TeacherService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class TeacherServiceIntegrationTest
{
private static TeacherService teacherService;
@BeforeClass
public static void setup()
{
teacherService = new TeacherService();
}
@Test
public void test01Save()
{
Teacher teacher = new Teacher();
teacher.setId("teacher1");
Class class1 = new Class();
class1.setStart(new Date());
class1.setEnd(new Date());
List<String> students = new ArrayList<>();
students.add("<NAME>");
students.add("<NAME>");
class1.setStudents(students);
teacher.setClassList(Collections.singletonList(class1));
teacherService.update(teacher);
}
@Test
public void test02Read()
{
Teacher teacher = new Teacher();
teacher.setId("teacher1");
Teacher fromDb = teacherService.findTeacher(teacher.getId());
Assert.assertNotNull(fromDb);
Assert.assertEquals(fromDb.getClassList().size(), 1);
Assert.assertEquals(fromDb.getClassList().get(0).getStudents().size(), 2);
}
@Test
public void test03Delete() throws Exception
{
teacherService.delete("teacher1");
Teacher fromDb = teacherService.findTeacher("teacher1");
Assert.assertNull(fromDb);
}
}
<file_sep># aws-lambda-score-service
<file_sep>package com.cts.data;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBDocument;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@DynamoDBDocument
public class Class
{
private String title;
private Date start;
private Date end;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
private List<String> students = new ArrayList<>();
public Date getStart()
{
return start;
}
public void setStart(Date start)
{
this.start = start;
}
public Date getEnd()
{
return end;
}
public void setEnd(Date end)
{
this.end = end;
}
public List<String> getStudents()
{
return students;
}
public void setStudents(List<String> students)
{
this.students = students;
}
}
<file_sep>package com.cts.sheets.data;
import com.cts.sheets.data.Table;
public class Response
{
private String status;
private Table table;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public Table getTable()
{
return table;
}
public void setTable(Table table)
{
this.table = table;
}
}
<file_sep>package com.cts;
import com.cts.data.Teacher;
import org.junit.Assert;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class DrawSticksHandlerTest
{
@Test
public void testFindTeacher()
{
DrawSticksHandler drawSticksHandler = new DrawSticksHandler();
Teacher teacher = drawSticksHandler.findTeacher("<EMAIL>");
Assert.assertNotNull(teacher);
}
@Test
public void testFindCurrentStudents()
{
DrawSticksHandler drawSticksHandler = new DrawSticksHandler();
FindCurrentStudentsRequest request = new FindCurrentStudentsRequest();
request.setCurrentTime(new Date());
request.setTeacherId("<EMAIL>");
List<String> students = drawSticksHandler.findCurrentStudents(request).getStudents();
Assert.assertNotNull(students);
Assert.assertTrue(students.size()>0);
}
@Test
public void testFindCurrentStudentsWhenNoStudents()
{
DrawSticksHandler drawSticksHandler = new DrawSticksHandler();
FindCurrentStudentsRequest request = new FindCurrentStudentsRequest();
request.setCurrentTime(new Date());
request.setTeacherId("BAD_ID");
List<String> students = drawSticksHandler.findCurrentStudents(request).getStudents();
Assert.assertTrue(students.isEmpty());
}
}
<file_sep>package com.cts;
import java.util.ArrayList;
import java.util.List;
public class FindStudentsResponse
{
private List<String> students = new ArrayList<>();
public FindStudentsResponse()
{
}
public FindStudentsResponse(List<String> students)
{
this.students = students;
}
public List<String> getStudents()
{
return students;
}
public void setStudents(List<String> students)
{
this.students = students;
}
}
<file_sep>package com.cts.sheets.data;
import java.util.List;
public class Column
{
private List<Data> c;
public List<Data> getC()
{
return c;
}
public void setC(List<Data> c)
{
this.c = c;
}
}
<file_sep>package com.cts;
import java.util.Date;
public class FindCurrentStudentsRequest
{
private String teacherId;
private Date currentTime;
public String getTeacherId()
{
return teacherId;
}
public void setTeacherId(String teacherId)
{
this.teacherId = teacherId;
}
public Date getCurrentTime()
{
return currentTime;
}
public void setCurrentTime(Date currentTime)
{
this.currentTime = currentTime;
}
}
| 28b8ce3fee29c7c9c7b8b8cd8f76ca2d48a983bd | [
"Markdown",
"Java"
] | 8 | Java | wedgwoodtom/aws-lambda-draw-straws | 91e767aa6df777b925d5fe3dfc640c3f5fb8aec6 | c12fc1ca917c56322fa48c1b8bbdac10fa3bb89c |
refs/heads/main | <repo_name>mohan-sathiyamoorthi-appasamy/OCT-Segmentation-Tomograph<file_sep>/TomoGraph_Radial_Image.py
import cv2
import matplotlib.pyplot as plt
import math
import numpy as np
import scipy.io
from scipy import sparse
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix, vstack
from scipy import interpolate
from scipy.signal import savgol_filter
import pandas as pd
import itertools
from scipy import signal
import statistics
import glob
import csv
import sys
axialRes = 6.7
lateralRes = 13.4
MATRIX_INDICES = [0,1,2,4,4,4,3,3,4,5]
matrixIndices = np.array(MATRIX_INDICES)
MIN_WEIGHTS = 0.00001
X_FILTER_SIZE = 40.2
Y_FILTER_SIZE = 20.1
SIGMA = 6
EDGE_FILTER = np.array([[0.2,0.6,0.2],[-0.2,-0.6,-0.2]])
NUM_LAYERS = 8
MAX_NUM_LAYERS = 8
numLayers = NUM_LAYERS
LAYER_INDICES = [0,7,7,6,5,3,2,4,3,1]
layerIndices = np.array(LAYER_INDICES)
maxIndex = 0
uniqueLayerIndices = []
LATERAL_RESOLUTION = 2
AXIAL_RESOLUTION = 3
X_RESOLUTION = 13.4
Y_RESOLUTION = 6.7
X_STREL_SIZE = 40.2
Y_STREL_SIZE = 20.1
def normal_getBWImage(resizedImage):
#normalization
norm_img = np.zeros((resizedImageHeight,resizedImageWidth))
normalizedImage = cv2.normalize(resizedImage,norm_img, 0, 255, cv2.NORM_MINMAX)
#Filtering image
size = 11
std = 7
kernel = fspecial_gauss(size,std)
blurImage= cv2.filter2D(normalizedImage,-1, kernel,borderType=cv2.BORDER_CONSTANT)
#difference image
diffImage = np.diff(blurImage,axis=0)
#padding
diffImage1 = cv2.copyMakeBorder(diffImage,1,0,0,0,cv2.BORDER_CONSTANT,0)
#threshold image
ret,thresh = cv2.threshold(diffImage1,190,255,cv2.THRESH_TOZERO_INV)
#get structuring element
XStrelSize = round(X_STREL_SIZE/X_RESOLUTION)
YStrelSize = round(Y_STREL_SIZE/Y_RESOLUTION)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(XStrelSize,YStrelSize))
#morphological operation
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel)
#get connected components
num_labels,lables,stats,centroids = cv2.connectedComponentsWithStats(opening, connectivity=8)
minClustersize = 130;
sizes = stats[1:, -1]; num_labels = num_labels - 1
filterImage = np.zeros((lables.shape))
#remove unwanted clusters
for i in range(0, num_labels):
if sizes[i] >= minClustersize:
filterImage[lables == i+1] = 255
#closing image
closing = cv2.morphologyEx( filterImage,cv2.MORPH_CLOSE,kernel)
closing = np.delete(closing,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],0)
closing = cv2.copyMakeBorder(closing,16,0,0,0,cv2.BORDER_CONSTANT,0)
return closing
def fspecial_gauss(size, sigma):
x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
g = np.exp(-((x**2 + y**2)/(2.0*sigma**2)))
return g/g.sum()
def normalgetBorders(bwImage):
#Add column both side Image
borderAddBWImage = addColumns(bwImage,1)
newImageheight = borderAddBWImage.shape[0]
newImagewidth = borderAddBWImage.shape[1]
newImageSize = (newImageheight,newImagewidth)
Edges,weightingMatrix = bwWeightingMatrix(borderAddBWImage,newImagewidth,newImageheight)
#Cut Each border
numBorder = 4
lines = np.zeros([numBorder,newImagewidth])
invalidIndices1 = []
invalidIndex = []
for iBorder in range(0,numBorder):
if iBorder >0:
x = np.arange(1,resizedImageWidth+1)
y = lines[iBorder-1,x]
removedInd = np.array(np.where((y == 0) | (y == resizedImageHeight-1)))
x = np.delete(x,removedInd)
y = np.delete(y,removedInd)
y = y.astype('int')
arr = (y,x)
invalidIndices = np.ravel_multi_index(arr,(newImageheight,newImagewidth),order ='F')
invalidIndices1.append(invalidIndices)
if iBorder < numBorder-1:
yBottom = newImageheight-1 * np.ones(newImagewidth)
else:
yBottom = np.amax(lines,axis =0)
#Get the Region to Cut
invalidIndex = np.array((invalidIndices1),dtype=object)
invalidIndex = invalidIndex.flatten()
regionIndices = getRegion(newImageSize,[0] * newImagewidth,yBottom,0,0,invalidIndex,[])
# Cut the Region to get the border
lines[iBorder,:] = cutRegion(newImageSize,regionIndices,Edges,weightingMatrix[((iBorder+1) % 2)])
#Remove the added Column
bwImageColremoved = borderAddBWImage[:,1:-1]
bwImageColremoved1 = np.where((bwImageColremoved == 255),1, bwImageColremoved)
imageHeight, imageWidth = bwImageColremoved1.shape
lines = lines[:,1:-1]
oddIndices = np.array((range(0,4,2)))
evenIndices = np.array((range(1,4,2)))
oddSortOrder = np.sort((np.nanmean((lines[oddIndices,:]),1),(range(0,len(oddIndices)))))
evenSortOrder = np.sort((np.nanmean((lines[evenIndices,:]),1),(range(0,len(evenIndices)))))
vector = np.vectorize(np.int)
bottomBorders = lines[oddIndices[vector(oddSortOrder[1,:])]]
topBorders = lines[evenIndices[vector(evenSortOrder[1,:])]]
borders = np.flip(lines, axis=0)
bordersFinal = np.zeros([4,imageWidth])
#Replace extrapolated points (those that do not lie along ahyper-reflective band) with NaN
for iBorder in range(0,4):
border = borders[iBorder,:]
if np.mod(iBorder,2):
border = border - 1
border[border < 1] = 1
imageWidthArr =np.array(range(0,imageWidth))
imageWidthArr = imageWidthArr.astype('int')
border = border.astype('int')
arr = (border,imageWidthArr)
ind = np.ravel_multi_index(arr,(imageHeight,imageWidth),order = 'F')
ind = vector(ind)
bwImageVec = bwImageColremoved1.flatten()
bwImagetype = bwImageVec.astype('int')
val = bwImagetype[ind]
indexValues = np.array(np.where(val == 0))
indexValues = indexValues.flatten()
first = indexValues[0]
last = indexValues[-1]
yStart,xStart = np.unravel_index(ind[first],(imageHeight,imageWidth),order = 'F')
yEnd,xEnd = np.unravel_index(ind[last],(imageHeight,imageWidth),order = 'F')
xStart = xStart.astype('int')
yStart = yStart.astype('int')
bordersFinal[iBorder,xStart:xEnd+1] = border[xStart:xEnd+1]
return bordersFinal
def addColumns(bwImage,numColumns):
height,width = bwImage.shape
leftColumns = bwImage[:,0]
rightColumns = bwImage[:,-1]
mx = np.zeros([height,width+2])
mx[0:height,1:width+1] = bwImage
mx[0:height,0] = leftColumns
mx[0:height,-1] = rightColumns
return mx
def bwWeightingMatrix(borderAddBWImage,width,height):
#----------------------------------------------------------------------
# Calculate the weights based on the image gradient. Lower weights
# are assigned to areas with a higher gradient
#---------------------------------------------------------------------
# Create two edge maps (one for edges that transition from dark->light
# in the vertical direction, and one for edges transitioning from
# light->dark)
borderAddBWImage = np.where((borderAddBWImage > 0),1,0)
diffimage = np.diff(borderAddBWImage,axis=0)
diffImage = cv2.copyMakeBorder(diffimage,1,0,0,0,cv2.BORDER_CONSTANT,0)
lightDarkEdgeImage = np.where((diffImage > 0),1,0)
darklightEdgeImage = np.where((diffImage < 0),1,0)
ind = np.where(((lightDarkEdgeImage == 0) & (borderAddBWImage == 1)))
lightDarkEdgeImage[ind] =-1
ind = np.where(((darklightEdgeImage == 0) & (borderAddBWImage == 1)))
darklightEdgeImage[ind] =-1
#Calculate the gradient weights for each of the edge maps
edges = createLattice(borderAddBWImage.shape)
imageHeight,imageWidth = borderAddBWImage.shape
maxIndex = imageHeight*imageWidth
leftColIndices = np.arange(0,imageHeight-1)
rightColIndices = np.arange(((imageHeight-1)*(imageWidth-2)) , maxIndex)
columnIndices = np.concatenate((leftColIndices,rightColIndices),axis=0)
imageIndices = np.setdiff1d((np.arange(0,edges.shape[0])), columnIndices)
columnEdges = edges[columnIndices,:]
imageEdges = edges[imageIndices,:]
imageEdgesrow1 = imageEdges[:,0]
imageEdgesrow2 = imageEdges[:,1]
lightDarkEdgeImageVec = lightDarkEdgeImage.flatten(order='F')
lightDarkGrandientWeights = 2 - lightDarkEdgeImageVec[imageEdgesrow1] - lightDarkEdgeImageVec[imageEdgesrow2]
darklightEdgeImageVec = darklightEdgeImage.flatten(order='F')
darkLightGrandientWeights = 2 - darklightEdgeImageVec[imageEdgesrow1] - darklightEdgeImageVec[imageEdgesrow2]
#Combining weights of lightDark and DarkLight images
weights_2 = ([(lightDarkGrandientWeights)],[(darkLightGrandientWeights)])
#set the min_weights
min_weights = 0.00001
columnWeight = min_weights
min_value = 0
max_value = 1
columnEdges = columnEdges.astype('int')
imageSize = borderAddBWImage.shape
totWeightsLightDark,totalEdges = generateWeightingMatrix(imageSize,imageEdges,weights_2[0],columnEdges,columnWeight)
totWeightsdarkLight,totalEdges = generateWeightingMatrix(imageSize,imageEdges,weights_2[1],columnEdges,columnWeight)
return_weight=(totWeightsLightDark,totWeightsdarkLight)
return totalEdges,return_weight
def createLattice(imagesize):
imageHeight = imagesize[0]
imageWidth = imagesize[1]
image = np.arange(0,imageHeight*imageWidth)
indexMatrix = np.reshape(image,(imageHeight,imageWidth),order='F')
height,width = indexMatrix.shape
startNodes = indexMatrix[0:height-1,:]
startNodes =startNodes.flatten(order='F')
endNodes = indexMatrix[1:height,:]
endNodes =endNodes.flatten(order='F')
edges = np.stack([startNodes,endNodes],axis=1)
startNodes = indexMatrix[:,0:width-1]
startNodes =startNodes.flatten(order='F')
endNodes = indexMatrix[:,1:width]
endNodes =endNodes.flatten(order='F')
edge1 = np.stack([startNodes[:], endNodes[:]],axis=1)
edges =np.vstack([edges, edge1])
startNodes = indexMatrix[0:height-1,0:width-1]
startNodes =startNodes.flatten(order='F')
endNodes = indexMatrix[1:height,1:width]
endNodes =endNodes.flatten(order='F')
edge2 = np.stack([startNodes[:], endNodes[:]],axis=1)
edges =np.vstack ([edges, edge2 ])
startNodes = indexMatrix[1:height,0:width-1]
startNodes =startNodes.flatten(order='F')
endNodes = indexMatrix[0:height-1,1:width]
endNodes =endNodes.flatten(order='F')
edge3 = np.stack([startNodes[:], endNodes[:]],axis=1)
edges =np.vstack ([edges, edge3])
return edges
def generateWeightingMatrix(imageSize,imageEdges,GrandientWeights,columnEdges,columnWeight):
columnEdgesShape = columnEdges.shape[0]
column = np.ones(columnEdgesShape)
#set the column weights
columnWeights = columnWeight * column
min_value = 0
max_value = 1
imageWeights = columnWeight
weightLength = len(GrandientWeights)
if weightLength > 0:
for index in range(0,weightLength):
normalizeValue = normalizeValues(GrandientWeights[index],min_value,max_value)
imageWeights = imageWeights + normalizeValue
else:
normalizeValue = normalizeValues(GrandientWeights,min_value,max_value)
imageWeights = imageWeights + normalizeValue
totalEdges = np.concatenate((imageEdges,columnEdges),axis=0)
#finding the totalWeights
totalWeights = np.concatenate((imageWeights,columnWeights),axis=None)
return totalWeights,totalEdges
def normalizeValues(weights,min_value,max_value):
#find oldMaxvalue and oldMinvalue
oldMinValue = np.min(weights)
oldMaxValue = np.max(weights)
#finding the normalize value
normalizeValue = ((weights-oldMinValue) / (oldMaxValue-oldMinValue) * (max_value-min_value)) + min_value
#print(normalizeValue)
return normalizeValue
def getRegion(imageSize,topLayer,bottomLayer,topAddition,bottomAddition,InvalideIndices,correctBottomLine):
InvalideIndices = np.int_(InvalideIndices)
topLayer = np.array(topLayer)
bottomLayer = np.array(bottomLayer)
imageHeight = imageSize[0]
imageWidth = imageSize[1]
np.where(topLayer<0,0,topLayer)
np.where(topLayer> imageHeight,imageHeight,topLayer)
np.where(bottomLayer<0,0,bottomLayer)
np.where(bottomLayer>imageHeight,imageHeight,bottomLayer)
#---------------------------------------------------------------------
#Expand the each layer boundary by the number of pixels to add,
#making sure to take care of any pixels that are out of bounds
#---------------------------------------------------------------------
bottomLayer = bottomLayer + bottomAddition;
topLayer = topLayer + topAddition;
#----------------------------------------------------------------------
# Limit the layers by the invalid region
#-----------------------------------------------------------------------
invalidImage = np.zeros(imageHeight*imageWidth)
invalidImage[InvalideIndices] = 1
invalidImage = np.reshape(invalidImage,(imageHeight,imageWidth))
for iCol in range(0,imageWidth):
t1 = np.array(np.where(invalidImage[:,iCol] == 0))
topIndex = t1[0,0]
bottomIndex = t1[0,np.size(t1)-1]
#print('topLayer.shape',topLayer.shape)
#print('bottomLayer.shape',bottomLayer.shape)
topLayer[iCol] = max(topLayer[iCol],topIndex)
bottomLayer[iCol] = min(bottomLayer[iCol],bottomIndex)
# print(bottomLayer)
#----------------------------------------------------------------------
#Correct the appropriate line if it crosses the other line
#----------------------------------------------------------------------
difference = np.subtract(bottomLayer,topLayer)
invalidInd = np.where(difference < 0)
if not invalidInd:
print('invalidInd is empty')
else:
bottomLayer[invalidInd] = topLayer[invalidInd]
#----------------------------------------------------------------------
# Get the indices of all pixels in between the two regions
#----------------------------------------------------------------------
regionImage = np.zeros([imageHeight*imageWidth])
for iCol in range(0,imageWidth):
if iCol < imageWidth-1:
if topLayer[iCol] > bottomLayer[iCol+1]:
topLayer[iCol] = topLayer[iCol+1]
bottomLayer[iCol+1] = bottomLayer[iCol]
elif (bottomLayer[iCol] < topLayer[iCol+1]):
bottomLayer[iCol] = bottomLayer[iCol+1]
topLayer[iCol+1] = topLayer[iCol]
yRegion = np.arange(topLayer[iCol],bottomLayer[iCol]+1)
yRegion = yRegion.astype('int')
cols = iCol * np.ones(len(yRegion))
cols = cols.astype('int')
arr = (yRegion,cols)
indices = np.ravel_multi_index(arr,(imageHeight,imageWidth), order='F')
regionImage[indices] = 1
#----------------------------------------------------------------------
#Take out any region indices that were specified as invalid
#----------------------------------------------------------------------
invalidImage1 = np.zeros(imageHeight*imageWidth)
invalidImage1[InvalideIndices] = 1
invalidImage = ((invalidImage1.astype('int')) & (regionImage.astype('int')))
# Remove invalid indices from the region
regionImage[InvalideIndices] = 0
# Get the Indices
regionIndices = np.where(regionImage == 1)
return regionIndices
def cutRegion(imageSize,regionIndices,Edges,weightingMatrix):
regionIndices = np.asarray(regionIndices).ravel()
regionIndices = regionIndices.astype('int')
imageWidth = imageSize[1]
regionIndArr = np.zeros(imageSize[0]*imageSize[1])
region = np.zeros(imageSize[0]*imageSize[1])
#Mask Creation
regionIndArr[regionIndices] = 1
regionIndArr = np.array(regionIndArr,dtype = bool)
# Make sure the region spans the entire width of the image
y,x = np.unravel_index([regionIndices],(imageSize[0],imageSize[1]),'F')
startIndex = regionIndices[0]
t1 = np.array(np.where(x == (imageWidth-1)))
endIndex = t1[1,0]
# Make sure the coordinate indices span the entire width of the image
coordinateIndices = []
if (len(coordinateIndices) == 0) or (coordinateIndices[0] > imageWidth):
coordinateIndices = [startIndex]
y,x = np.unravel_index(coordinateIndices,(imageSize[0],imageSize[1]))
if (len(coordinateIndices) == 0) or (x < imageWidth):
endIndex = regionIndices[endIndex]
coordinateIndices = [coordinateIndices,endIndex]
A = sparse.coo_matrix((weightingMatrix,(Edges[:,0],Edges[:,1])),shape=(imageSize[0]*imageSize[1],imageSize[0]*imageSize[1]))
sparseMatrixT = csr_matrix(A)
sparseMatrix = sparseMatrixT[regionIndArr][:,regionIndArr]
#Dijkstra Shortest Path
region = np.zeros(imageSize[0]*imageSize[1])
region[regionIndices]=np.arange(0,len(regionIndices))
firstIndex = coordinateIndices[0]
secondIndex = coordinateIndices[-1]
startIndex = int(region[firstIndex])
endIndex = int(region[secondIndex])
D, Pr = dijkstra(sparseMatrix, directed=False, indices=0, return_predecessors=True)
path = get_path(Pr,endIndex)
y,x = np.unravel_index(regionIndices[path],(imageSize[0],imageSize[1]),order = 'F')
cut = np.zeros(imageWidth)
for column in range(0,imageWidth):
if column == 0:
t1 = np.array(np.where(x == column))
index = t1[0,np.size(t1)-1]
else:
t1 = np.array(np.where(x == column))
index = t1[0,0]
cut[column] = y[index]
return cut
#step 2.4.1
def get_path(Pr, j):
path = [j]
k = j
while Pr[ k] != -9999:
path.append(Pr[ k])
k = Pr[ k]
return path[::-1]
#Step 4: Resampling
def resampleLayers(layers):
nLayers,layersLength =layers.shape
layers = np.array(layers)
newSize = (inputImageHeight,inputImageWidth)
originalSize = (resizedImageHeight,resizedImageWidth)
#Scaling to upsampling
scale = np.divide(newSize,originalSize)
#Upsample in the Y direction
layers = np.round(layers * scale[0])
#----------------------------------------------------------------------
#Upsample each layer in the x direction using interpolation
#----------------------------------------------------------------------
#nLayers = 4
newWidth = newSize[1]
x = np.array(range(0,newWidth))
y = np.array(layers)
layers = np.empty((nLayers,newWidth))
layers[:] = np.NaN
ind = np.round(np.arange(0,newWidth,scale[1]))
ind = ind.astype('int')
ind[-1] = newWidth-1
layers[:,ind] = y
#print(layers.shape)
for iLayer in range(0,nLayers):
layer = layers[iLayer,:]
validInd = np.argwhere(~np.isnan(layer))
invalidInd = np.argwhere(np.isnan(layer))
temp = np.copy(layer)
temp[validInd] = 1
validIndArr = np.where(temp == 1,1,0)
temp1 = np.copy(layer)
temp1[invalidInd] = 1
invalidIndArr = np.where(temp1 == 1,1,0)
t1 = np.array(np.where(invalidIndArr == 0))
val = t1[0,0]
invalidIndArr[0:val] =0
val1 = t1[0,-1]
invalidIndArr[val1:-1] =0
#Interpolation
tck = interpolate.splrep(validInd,layer[validInd])
layer[invalidInd] = interpolate.splev(invalidInd, tck)
#print(layer.shape)
#Make sure the layers do not cross
if iLayer > 0:
diffVal = layer - layers[iLayer-1,:]
invInd = np.where(diffVal < 0)
layer[invInd] = layers[iLayer-1,invInd]
layers[iLayer,:] = np.round(layer)
return layers
def normal_graphCut(image,axialRes,laterRes,rpeTop,rpeBottom,invalidIndices,recalculateWeights):
image = normalizeValues(image,0,1)
imageHeight = image.shape[0]
image = addColumns(image, 1)
rpeTop = addColumns(rpeTop, 1)
rpeBottom = addColumns(rpeBottom, 1)
invalidIndices = invalidIndices[0] + imageHeight
#rpeTop = rpeTop.ravel()
#rpeBottom = rpeBottom.ravel()
maxIndex = 0
#LAYER_INDICES = [0,7,7,6]
LAYER_INDICES = [0,7,7,6,5,3,2,4,3,1]
layerIndices = np.array(LAYER_INDICES)
#MATRIX_INDICES = [0,1,2,4]
MATRIX_INDICES = [0,1,2,4,4,4,3,3,4,5]
matrixIndices = np.array(MATRIX_INDICES)
uniqueLayerIndices, index = np.unique(layerIndices, return_index=True)
uniqueLayerIndices = uniqueLayerIndices[index.argsort()]
for index in range(0,numLayers):
lastIndex = np.array(np.where(layerIndices == uniqueLayerIndices[index]))
lastIndex = lastIndex[-1,0]
if bool(lastIndex) & (lastIndex > maxIndex):
maxIndex = lastIndex
if maxIndex > 0:
layerIndices = layerIndices[0:maxIndex+1]
if bool(matrixIndices.all):
matrixIndices = matrixIndices[0:maxIndex+1]
#------------------------------------------------------------------
# Generate a weighting matrix for the image
#------------------------------------------------------------------
if recalculateWeights:
weightingMatrices,edges = normal_weightingMatrix(image,axialRes,lateralRes,matrixIndices,invalidIndices)
imageSize = image.shape
nLayers = max(layerIndices)
layers = np.zeros([8, imageSize[1]])
layers[:,:] = np.nan
#foveaParams = {'Index':0, 'Range':0, 'Percentage':0}
Index = 0
Range = 0
Percentage = 0
#Loop through Each layer to segment
for iLayer in range(0,len(layerIndices)):
#for iLayer in range(0,1):
layerIndex = layerIndices[iLayer]
#Get parameters for the current layer to segment-Normal GraphCut Region
eye =1
regionIndices = normal_getGraphCutRegion(image, layerIndex, axialRes, eye,Index,Range, rpeTop, rpeBottom,layers)
matrixIndex = matrixIndices[iLayer]
weightMatrix = weightingMatrices[matrixIndex]
#Cut Region
cut = cutRegion(imageSize, regionIndices,edges, weightMatrix)
if iLayer == 0:
cut_1 = cut
#Fovea Region
if layerIndex == 2:
ilm = layers[0,:].astype('int')
innerLayer = np.round(savgol_filter(cut,151,2))
rpe = layers[5,:].astype('int')
Index,Range,Percentage = locateFovea(imageSize, axialRes, lateralRes, ilm, innerLayer, rpe, invalidIndices)
layers[layerIndex,:] = cut
layers[0,:] = cut_1
for iLayer in range(0,nLayers+1):
if iLayer < nLayers:
topLayer = layers[iLayer,:]
bottomLayer = layers[iLayer+1,:]
crossIndices = np.array(np.where((bottomLayer - topLayer) < 0))
bottomLayer[crossIndices] = topLayer[crossIndices]
layers[iLayer+1,:] = bottomLayer
# Remove the extra columns and layers
layers = layers[:,1:-1]
# Remove extra layers that were not segmented or supposed to be
# segmented
layersToRemove = np.setdiff1d(np.arange(0,nLayers+1),uniqueLayerIndices)
layers = np.delete(layers,(layersToRemove),axis=0)
#layers = cut[1:-1]
return layers
def normal_weightingMatrix(image,axialRes,lateralRes,matrixIndices,invalidIndices):
imageSize = image.shape
imageHeight = imageSize[0]
imageWidth = imageSize[1]
edges = createLattice(imageSize)
#np.savetxt('edges.txt',edges,delimiter=' ',fmt='%d')
maxIndex = imageHeight*imageWidth
leftColIndices = np.arange(0,imageHeight-1)
rightColIndices = np.arange(((imageHeight-1)*(imageWidth-1)), maxIndex)
columnIndices = np.concatenate((leftColIndices,rightColIndices),axis=0)
imageIndices = np.setdiff1d((np.arange(0,edges.shape[0])), columnIndices)
columnEdges = edges[columnIndices,:]
imageEdges = edges[imageIndices,:]
xFilterSize = round(X_FILTER_SIZE / lateralRes)
yFilterSize = round(Y_FILTER_SIZE / axialRes)
kernel = fspecial_gauss2d((xFilterSize,yFilterSize),SIGMA)
smoothImage = blurImage(image,kernel)
kernel = fspecial_gauss2d((1,xFilterSize),SIGMA)
smoothImage2 = blurImage(image,kernel)
lightDarkEdgeImage = (blurImage(smoothImage, -EDGE_FILTER) > 0) * blurImage(smoothImage, -EDGE_FILTER)
lightDarkEdgeImage = np.abs(lightDarkEdgeImage)
darkLightEdgeImage = (blurImage(smoothImage, EDGE_FILTER) > 0) * blurImage(smoothImage, EDGE_FILTER)
darkLightEdgeImage = np.abs(darkLightEdgeImage)
lightDarkEdgeImage2 = (blurImage(smoothImage2, -EDGE_FILTER) > 0) * blurImage(smoothImage2, -EDGE_FILTER)
lightDarkEdgeImage2 = np.abs(lightDarkEdgeImage2)
darkLightEdgeImage2 = (blurImage(smoothImage2, EDGE_FILTER) > 0) * blurImage(smoothImage2, EDGE_FILTER)
darkLightEdgeImage2 = np.abs(darkLightEdgeImage2)
darkLightInd = (darkLightEdgeImage > 0)
lightDarkInd = (lightDarkEdgeImage > 0)
darkLightInd2 = (darkLightEdgeImage2 > 0)
darkLightEdgeImage[lightDarkInd] = 0
lightDarkEdgeImage[darkLightInd] = 0
lightDarkEdgeImage2[darkLightInd2] = 0
lightDarkEdgeImage = normalizeValues(lightDarkEdgeImage,0,1)
darkLightEdgeImage = normalizeValues(darkLightEdgeImage,0,1)
lightDarkEdgeImage2 = normalizeValues(lightDarkEdgeImage2,0,1)
lightDarkEdgeImage3 = lightDarkEdgeImage
for iCol in range(0,imageWidth):
column = darkLightEdgeImage[:,iCol]
column = np.array(column)
maxima = np.where(np.diff(np.sign(np.diff(column,n=1,axis=-1,append=0))) < 0)
maxima = maxima[0]
darkLightEdgeImage[:,iCol] = 0
darkLightEdgeImage[maxima,iCol] = column[maxima]
column = lightDarkEdgeImage[:,iCol]
column = np.array(column)
maxima = np.where(np.diff(np.sign(np.diff(column,n=1,axis=-1,append=0))) < 0)
maxima = maxima[0]
lightDarkEdgeImage[:,iCol] = 0
lightDarkEdgeImage[maxima,iCol] = column[maxima]
darkLightEdgeImage[lightDarkInd] = -1
lightDarkEdgeImage[darkLightInd] = -1
darkLightEdgeImage = darkLightEdgeImage.ravel(order='F')
darkLightEdgeImage[invalidIndices] = 0
lightDarkEdgeImage = lightDarkEdgeImage.ravel(order='F')
lightDarkEdgeImage[invalidIndices] = 0
lightDarkEdgeImage2 = lightDarkEdgeImage2.ravel(order='F')
lightDarkEdgeImage2[invalidIndices] = 0
lightDarkEdgeImage3 = lightDarkEdgeImage3.ravel(order='F')
lightDarkEdgeImage3[invalidIndices] = 0
darkLightGradientWeights = 2 - darkLightEdgeImage[imageEdges[:,0]] - darkLightEdgeImage[imageEdges[:,1]]
lightDarkGradientWeights = 2 - lightDarkEdgeImage[imageEdges[:,0]] - lightDarkEdgeImage[imageEdges[:,1]]
lightDarkGradientWeights2 = 2 - lightDarkEdgeImage2[imageEdges[:,0]] - lightDarkEdgeImage2[imageEdges[:,1]]
lightDarkGradientWeights3 = 2 - lightDarkEdgeImage3[imageEdges[:,0]] - lightDarkEdgeImage3[imageEdges[:,1]]
smoothImage = smoothImage.ravel(order='F')
smoothImage[invalidIndices] = 0
brightIntensityWeights = - smoothImage[imageEdges[:,0]] - smoothImage[imageEdges[:,1]]
darkIntensityWeights = smoothImage[imageEdges[:,0]] + smoothImage[imageEdges[:,1]]
[yFirstPoint, xFirstPoint] = np.unravel_index(imageEdges[:,0],imageSize,order='F')
[ySecondPoint, xSecondPoint] = np.unravel_index(imageEdges[:,1],imageSize,order='F')
distanceWeights = np.sqrt((xFirstPoint - xSecondPoint) ** 2 + (yFirstPoint - ySecondPoint) ** 2)
weights = ([(darkLightGradientWeights)],(brightIntensityWeights,distanceWeights),
(lightDarkGradientWeights2,distanceWeights),
(lightDarkGradientWeights3,distanceWeights),
(darkLightGradientWeights,distanceWeights),
(lightDarkGradientWeights,darkIntensityWeights,distanceWeights))
nMatrices = len(weights)
matrixIndices1 = (matrixIndices > 0)
matrixIndices = matrixIndices[matrixIndices1]
matrixIndices1 = (matrixIndices < nMatrices+1)
matrixIndices = matrixIndices[matrixIndices1]
weightingMatrices = []
matrixSize = maxIndex
matrixIndices1 = np.array([0,1,2,3,4,5])
for iMatrix in range(0,len(weights)):
matrixIndex = matrixIndices1[iMatrix]
weightingMatrices1,edges = generateWeightingMatrix(matrixSize,imageEdges,weights[iMatrix],columnEdges,MIN_WEIGHTS)
weightingMatrices.append(weightingMatrices1)
return weightingMatrices,edges
def fspecial_gauss2d(shape,sigma):
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
def blurImage(image,filter1):
[imageHeight, imageWidth] = image.shape
filterSize = filter1.shape
yHW = round(filterSize[0]/2)
xHW = round(filterSize[1]/2)
image1 = cv2.copyMakeBorder(image, 0, yHW, 0, xHW, cv2.BORDER_CONSTANT)
image1[yHW:imageHeight+yHW+1,xHW:imageWidth+xHW+1] = image
rows_to_added = image1[imageHeight-1:imageHeight+yHW-1,:]
rows_to_added = np.flip(rows_to_added,axis=0)
image1 = np.vstack ((image1, rows_to_added))
rows_to_changed = image1[yHW+1:2*yHW+1,:]
rows_to_changed = np.flip(rows_to_changed,axis=0)
image1[0:yHW,:] = rows_to_changed
columns_to_added = image1[:,imageWidth-1:imageWidth+xHW-1]
columns_to_added = np.flip(columns_to_added,axis=1)
image1 = np.hstack ((image1, columns_to_added))
columns_to_changed = image1[:,xHW+1:2*xHW+1]
columns_to_changed = np.flip(columns_to_changed,axis=1)
image1[:,0:xHW] = columns_to_changed
image1 = signal.convolve2d(image1, filter1, boundary='symm', mode='same')
image1 = image1[yHW:imageHeight+yHW,xHW:imageWidth+xHW]
return image1
def normal_getGraphCutRegion(image, layersNumber, axialRes, eye,Index,Range, rpeTop, rpeBottom, layers):
imageSize = image.shape
imageHeight = imageSize[0]
imageWidth = imageSize[1]
topLayerAddition = 0
bottomLayerAddition = 0
correctBottomLine = 0
#vitreous-NFL
if layersNumber == 0:
yTop = np.zeros([imageWidth])
yBottom = rpeTop
correctBottomLine = 1
#cut RPE-Choroid
elif layersNumber ==7:
if np.all(np.isnan(layers[7,:])):
if np.all(np.isnan(rpeTop)):
yTop = layers[0,:] + np.round(100.5/axialRes)
else:
yTop = rpeTop
yBottom = rpeBottom
else:
yTop = layers[7,:] + np.round(13.4/axialRes)
yBottom = layers[7,:] + np.round(67/axialRes)
#cut OS-RPE
elif layersNumber == 6:
yTop = layers[7,:] - np.round(33.5/axialRes)
yBottom = layers[7,:] - np.round(13.4/axialRes)
elif layersNumber == 5:
yTop = layers[6,:] - np.round(67/axialRes);
yBottom = layers[6,:] - np.round(20.1/axialRes);
elif layersNumber == 3:
if np.all(np.isnan(layers[4,:])):
difference = layers[5,:] - layers[0,:]
yTop1 = layers[0,:] + np.round(difference/3)
yTop2 = layers[5,:] - np.round(134/axialRes)
yTop3 = layers[0,:] + np.round(13.4/axialRes)
yTop = np.maximum(np.minimum(yTop1,yTop2),yTop3)
yBottom = layers[5,:] - np.round(40.2/axialRes)
else:
yTop = layers[2,:]
yBottom = layers[4,:]
correctBottomLine = 1
elif layersNumber == 2:
yTop = layers[3,:] - np.round(46.9/axialRes)
yBottom = layers[3,:]
elif layersNumber == 4:
a = savgol_filter(layers[3,:],151, 2)
yTop =np.round(np.transpose(a))
yBottom1 = yTop + np.round(100.5/axialRes)
yBottom2 = layers[5,:] - np.round(13.4/axialRes)
yBottom = np.minimum(yBottom1,yBottom2)
if bool(Index):
Index = int(Index)
range1 = np.arange(Range[0],Index)
yFovea = layers[2,Index] - np.round(13.4/axialRes)
thickness = np.arange(0,len(range1))
thickness = np.round((yFovea-yTop[range1[0]])/len(range1) * thickness)
yTop[range1] = yTop[range1[1]] + thickness
range1 = np.arange(Index,Range[1])
yFovea = layers[2,Index] - np.round(13.4/axialRes)
thickness = np.arange(0,len(range1))
thickness = np.round((yTop[range1[-1]]-yFovea)/len(range1) * thickness)
yTop[range1] = yFovea + thickness
elif layersNumber == 1:
yTop =layers[0,:]
yBottom = layers[2,:] -np.round(26.8/axialRes)
if bool(Index):
range1 = np.arange(Range[0],Range[1])
yBottom[range1] = layers[0,range1] + np.round(20.1/axialRes)
if eye == 1:
thinRange = np.arange(range1[-1],imageWidth)
thickRange =np.arange(0,range1[0])
elif eye == 2:
thinRange = np.arange(0,range1[1])
thickRange =np.arange(range1[-1],imageWidth)
thickness =np.arange(0,len(thickRange))
thickness = np.round(np.round(33.5/axialRes) / len(thickRange) * thickness)
yTop[thickRange] = yTop[thickRange] + thickness
yBottom[thickRange] = layers[2,thickRange] - (thickness)
yBottom[thinRange] = yTop[thinRange] + np.round(26.8/axialRes)
correctBottomLine = 1
else:
range1 = np.arange(0,imageWidth)
if eye == 1:
range1 = range1[::-1]
thickness = np.arange(0,len(range1))
thickness = np.round(np.round(13.4/axialRes) / len(range1) * thickness)
yTop[range1] = yTop[range1] + thickness
else:
print('Segmentation of layer %d is not supported', layerNumber)
#Handle cases where the input layer is NaN or empty.
nanIndices = np.isnan(yTop)
if np.sum(nanIndices) > 0:
yTop[nanIndices] = np.ones([np.sum(nanIndices)])
nanIndices = np.isnan(yBottom)
if np.sum(nanIndices) > 0:
yBottom[nanIndices] = imageHeight*np.ones([np.sum(nanIndices)]);
#Make the region smaller with respect to the selected minimum distance between lines
yTop = yTop.ravel()
yBottom = yBottom.ravel()
regionIndices = getRegion(imageSize,yTop,yBottom,topLayerAddition,bottomLayerAddition,[],correctBottomLine)
regionIndices = np.array(regionIndices)
return regionIndices
def locateFovea(imageSize,axialRes,lateralRes,ilm, innerLayer, rpe,invalidIndices):
imageWidth = imageSize[1]
margin = round(imageWidth/8)
# create the zeros array
middleInd = np.zeros((imageWidth), dtype=np.int)
middleInd[margin-1:imageWidth-margin] = 1
# find intersect value
x = np.arange(imageWidth)
invalidInd = np.intersect1d(np.ravel_multi_index((np.hstack((ilm,rpe)),np.hstack((x,x))),imageSize,order='F'),invalidIndices,assume_unique=False,return_indices=False)
yInvalid,xInvalid = np.unravel_index(invalidInd,imageSize,order='F')
xInvalid = np.unique([xInvalid])
middleInd[xInvalid] = 0
# using the filter
thicknessOrig = innerLayer - ilm
thicknessOrig = thicknessOrig.reshape(1,thicknessOrig.shape[0])
# thicknessOrig = np.array(thicknessOrig)
thickness = savgol_filter(thicknessOrig,21,2)
# find the difference and sign value
midIndValue = middleInd[1:].T
thickness = thickness.T
out = np.diff(np.sign(np.diff(np.vstack([thickness[0],thickness]).ravel(order='F'))),axis=0)
# calculate the maxima & minima value using np.where
midIndValue = midIndValue.ravel(order = 'F')
maxima = np.where((midIndValue) & (out < 0))
maxima = maxima[0]
# maxima_temp = maxima[np.where((np.diff(maxima))==1)]
maxima_New = np.delete(maxima,np.where((np.diff(maxima))==1))
minima = np.where((midIndValue) & (out > 0))
minima = minima[0]
# minima_temp = minima[np.where((np.diff(minima))==1)]
minima_New = np.delete(minima,np.where((np.diff(minima))==1))
# create the zeros and ones
combined1 = np.hstack((np.vstack((maxima_New,np.zeros((len(maxima_New))))),np.vstack((minima_New,np.ones((len(minima_New)))))))
# sorting the array
values = pd.DataFrame(combined1).sort_values(by=0, axis=1)
combined = (values.values).astype("int")
# find the fovea location
difference = np.abs(np.diff(np.hstack(thickness[combined[0,:].astype(int)])))
locations = np.where(difference>round(33.5/axialRes))
locations = locations[0]
# Look for the largest change in thickness (corresponding to the fovea location)
Index = []
Range = []
Percentage = []
for index in range(len(locations)-1):
if ((((combined[1,locations[index]] == 0) and (combined[1,locations[index]+1] == 1))) and (((combined[1,locations[index+1]] == 1) and (combined[1,locations[index+1]+1] == 0)))):
foveaRange = [combined[0,locations[index]], combined[0,locations[index+1]+1]]
thicknessOrig = thicknessOrig.flatten(order='F')
foveaThick = thicknessOrig[int(foveaRange[0]):int(foveaRange[1])]
foveaIndex = np.where(foveaThick == min(foveaThick))
foveaIndex = foveaIndex[0]
foveaIndex = foveaIndex[round(len(foveaIndex)/2)] + foveaRange[0] - 1
# flattening the innerlayer,ilm and rpe
innerLayer = innerLayer.flatten(order='F')
ilm = ilm.flatten(order='F')
rpe = rpe.flatten(order='F')
foveaPercentage = (innerLayer[foveaIndex.astype(int)] - ilm[foveaIndex.astype(int)]) / (rpe[foveaIndex.astype(int)] - ilm[foveaIndex.astype(int)])
# Make the fovea range a constant width
thickness = round(670/lateralRes)
foveaRange[0] = np.max((1,foveaIndex-thickness))
foveaRange[1] = np.min((imageWidth,foveaIndex + thickness))
# print index,range and percentage values
Index = foveaIndex
Range = foveaRange
Percentage = foveaPercentage
return Index,Range,Percentage
def normal_FlattenImage(image,line):
#Get image size
imageHeight,imageWidth = image.shape
#Get the Line to Flatten
#Extrapolate missing values from the line
x = np.array(range(0,imageWidth))
validInd = ~np.isnan(line)
line = savgol_filter(line,151,2)
line = line.ravel(order='F')
# Interpolation
line = (interpolate.interp1d(x[validInd.ravel(order='F')],line[validInd.ravel(order='F')],kind = 'nearest',fill_value='extrapolate'))
line = line(x)
line = np.ceil(line)
# make sure line is not out of Image bounds
line[line < 0] = 0
line[line > imageHeight-1] = imageHeight-1
# Flatten the image based on the line
flattenedImage,pixelShift,invalidIndices,flattenedLine = flattenImage(image,line)
return flattenedImage,pixelShift,invalidIndices
def flattenImage(image,lineToFlatten):
referencePoint =0
fillType = 1
flattenedImage = image
imageHeight, imageWidth = image.shape
invalidImage = np.zeros(image.shape)
invalidIndices = []
mirroredColumn = []
if imageHeight == 1:
reference = round(statistics.mean(lineToFlatten))
pixelShift = reference - lineToFlatten
pixelShift = pixelShift.reshape(1,resizedImageWidth)
flattenedImage = image + pixelShift
invalidIndices = []
flattenedLine = reference * np.ones(image.shape)
else:
reference = round(statistics.mean(lineToFlatten))
pixelShift = reference - lineToFlatten
#pixelShift = scipy.io.loadmat('pixelShift')
# pixelShift = pixelShift["pixelShift"]
pixelShift = pixelShift.astype('int')
#pixelShift = pixelShift.ravel()
#print(pixelShift.shape)
for index in range(0,len(lineToFlatten)):
image_new = np.reshape(image[:,index],(resizedImageHeight,))
flattenedImage[:,index] =np.roll(image_new,pixelShift[index])
# If shifted down
if pixelShift[index] > 0:
# Get locations where pixels have been shifted out. These
#are invalid regions that need to be replaced
invalidIndices =np.arange(0,pixelShift[index])
# Get the mirror image of the valid regions of the column,
#which will be used to replace the invalid regions
mirroredColumn = np.pad(flattenedImage[invalidIndices[-1]:,index],(len(invalidIndices),0),'symmetric')
mirroredColumn = mirroredColumn[0:len(invalidIndices)]
# If shifted up
elif pixelShift[index] < 0:
# Get locations where pixels have been shifted out. These
# are invalid regions that need to be replaced
invalidIndices = np.arange(imageHeight + pixelShift[index],imageHeight)
mirroredColumn = np.pad(flattenedImage[0:invalidIndices[0],index],(0,len(invalidIndices)),'symmetric')
mirroredColumn = mirroredColumn[-len(invalidIndices):,]
else:
invalidIndices = []
mirroredColumn = []
#Replace the invalid indices with the mirror image of the
#valid pixels. This is so that there is no artificial gradient
#created when segmenting the image later on.
flattenedImage[invalidIndices, index] = mirroredColumn
#Keep track of which indices on the image are invlaid
invalidImage[invalidIndices, index] = 1
#Get the indices of the invalid regions
invalidImage = invalidImage.ravel(order = 'F')
invalidIndices = np.where(invalidImage == 1)
#Get the resulting flattened line
flattenedLine = lineToFlatten + pixelShift
return flattenedImage,pixelShift,invalidIndices,flattenedLine
def cart2pol(x, y):
rho = np.linalg.norm([x,y])
phi = np.arctan2(y, x)
return(rho, phi)
#Read Tif Image
dirName = sys.argv[1]
# path = glob.glob(dirName+'/*.tif')
inputImage = cv2.imread(dirName,0)
#medianBlurImage = cv2.medianBlur(inputImage,3)
inputImageHeight,inputImageWidth = inputImage.shape
#X & Y Scale for Resized Image
xResizeScale = LATERAL_RESOLUTION / X_RESOLUTION
yResizeScale = AXIAL_RESOLUTION / Y_RESOLUTION
#Find width & height of Rescaled Image
width = math.ceil(inputImage.shape[1]*xResizeScale)
height = math.ceil(inputImage.shape[0]*yResizeScale)
# Resized Image
dim = (width,height)
resizedImage = cv2.resize(inputImage,dim,interpolation=cv2.INTER_NEAREST)
inputImage = resizedImage
resizedImageHeight,resizedImageWidth = resizedImage.shape
# normal Get BW Image
bwImage = normal_getBWImage(resizedImage)
borders = normalgetBorders(bwImage)
borders = np.sort(borders,axis=0)
rpeTop = borders[2,:]
rpeTop[-1] = rpeTop[-2]
rpeBottom = borders[3,:]
rpeBottom[-1] = rpeBottom[-2]
[flattenedImage,pixelShift,invalidIndices] = normal_FlattenImage(resizedImage,rpeTop)
#Reshape Array
rpeTop1 = rpeTop.reshape(1,rpeTop.shape[0])
rpeBottom1 = rpeBottom.reshape(1,rpeBottom.shape[0])
rpeTop2,_,_,_ = flattenImage(rpeTop1,-pixelShift)
rpeBottom2,_,_,_ = flattenImage(rpeBottom1,-pixelShift)
layers1 = normal_graphCut(flattenedImage,axialRes,lateralRes,rpeTop2,rpeBottom2,invalidIndices,1)
a = np.array([0,2])
layers1 = layers1[a]
#smoothing = np.array([155,155,499,499,499,499,499,499])
smoothing = np.array([151,151,151,749,749,749,749,749])
smoothing = smoothing[a]
layer_PerImage = []
for j in range(0,layers1.shape[0]):
iLayer = layers1[j,:]
iLayer = iLayer.reshape(1,len(iLayer))
layerEach,_,_,_ = flattenImage(iLayer,pixelShift)
#Resample & Smooth Layers
resampledlayers = resampleLayers(layerEach)
y_filtered = savgol_filter(resampledlayers,smoothing[j], 2)
layer_PerImage.append(np.round(y_filtered.ravel(order='F')))
layer_Thickness = layer_PerImage[1] - layer_PerImage[0]
np.savetxt(sys.argv[2]+"/IlmRnflThickness.csv",layer_PerImage,delimiter=',',fmt='%d')
np.savetxt(sys.argv[2]+"/IlmRnflGraph.csv",layer_Thickness,delimiter=',',fmt='%d')
splitFour = np.array_split(layer_Thickness,4)
splitTwelve = np.array_split(layer_Thickness,12)
meanThickness = np.array([np.sum(layer_Thickness) / len(layer_Thickness)])
meanFour = np.zeros(len(splitFour))
meanTwelve = np.zeros(len(splitTwelve))
for i in range(len(splitFour)):
meanFour[i] = np.sum(splitFour[i]) / len(splitFour[i])
for i in range(len(splitTwelve)):
meanTwelve[i] = np.sum(splitTwelve[i]) / len(splitTwelve[i])
thicknessValues = np.concatenate([meanTwelve,meanFour,meanThickness])
thicknessValues = thicknessValues.reshape(1,len(thicknessValues))
np.savetxt(sys.argv[2]+"/ThicknessValues.csv",thicknessValues,delimiter=',',fmt='%f')<file_sep>/README.md
# OCT-Segmentation-Tomograph
2 layer Segmentation
| 1a9c0146449efafcbe5c2784daa28f1e91c6866d | [
"Markdown",
"Python"
] | 2 | Python | mohan-sathiyamoorthi-appasamy/OCT-Segmentation-Tomograph | 9ef6b8f4ab0628a0929053694c88571de31ab234 | 53a50531575ca101979402f952d7d431dc0f446e |
refs/heads/main | <repo_name>Consejo-de-Curso/consejodecurso<file_sep>/pasar_a_produccion.sh
#!/bin/bash
aws s3 sync --cache-control max-age=30 --delete . s3://consejodecurso.cl
aws cloudfront create-invalidation --distribution-id EJYCXVE34GDDN --paths '/*'<file_sep>/blog-retroalimentacion1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Retroalimentación efectiva | Fundación Consejo de Curso</title>
<link href="img/assets/favicon.png" rel="icon" type="image/png">
<link href="css/plugins.css" rel="stylesheet" type="text/css">
<link href="css/theme.css" rel="stylesheet" type="text/css">
<link href="css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/et-line-icons.css" rel="stylesheet" type="text/css">
<link href="css/themify-icons.css" rel="stylesheet" type="text/css">
<link href="fonts/lovelo/stylesheet.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Raleway:100,200,300,400%7COpen+Sans:400,300' rel='stylesheet'
type='text/css'>
<link href="css/custom.css" rel="stylesheet" type="text/css">
<link href="css/colors/blue.css" id="color-scheme" rel="stylesheet" type="text/css">
<!-- Some Open Graph tags -->
<meta name="description" content="Retroalimentación efectiva">
<meta name="author" content="<NAME>">
<meta property="og:locale" content="en_ES"/>
<meta property="og:type" content="article"/>
<meta property="og:title" content="¿Qué preguntas pueden guiar el análisis y la reflexión de tus estudiantes sobre sus
aprendizajes?"/>
<meta property="og:description" content="Retroalimentación efectiva"/>
<meta property="og:url" content="https://consejodecurso.cl/blog-retroalimentacion1.html"/>
<meta property="og:site_name" content="consejodecurso.cl"/>
<meta property="article:publisher" content="https://www.facebook.com/consejodecursoCL"/>
<meta property="article:published_time" content="2021-07-12"/>
<meta property="og:image" content="https://consejodecurso.cl/img/blog/retroalimentacion.jpg"/>
<meta name="twitter:title" content="¿Qué preguntas pueden guiar el análisis y la reflexión de tus estudiantes sobre sus aprendizajes?"/>
<meta name="twitter:description" content="Retroalimentación efectiva"/>
<meta name="twitter:image" content="https://consejodecurso.cl/img/blog/retroalimentacion.jpg"/>
<meta name="twitter:site" content="@consejodecurso"/>
<meta name="twitter:creator" content="@consejodecurso"/>
<meta name="twitter:via" content="consejodecurso"/>
<meta name="twitter:card" content="photo"/>
<meta name="twitter:url" content="https://consejodecurso.cl/blog-retroalimentacion1.html"/>
<!-- <meta name="twitter:image:width" content="550"/>
<meta name="twitter:image:height" content="750"/> -->
<meta name="facebook:title" content="¿Qué preguntas pueden guiar el análisis y la reflexión de tus estudiantes sobre sus aprendizajes?"/>
<meta name="facebook:description" content="Retroalimentación efectiva"/>
<meta name="facebook:image" content="https://consejodecurso.cl/img/blog/retroalimentacion.jpg"/>
<meta name="facebook:site" content="@consejodecurso"/>
<meta name="facebook:creator" content="@consejodecurso"/>
<meta name="facebook:via" content="consejodecurso"/>
<meta name="facebook:card" content="photo"/>
<meta name="facebook:url" content="https://consejodecurso.cl/blog-retroalimentacion1.html"/>
</head>
<body>
<!-- Start Header -->
<nav class="navbar navbar-default fullwidth">
<div class="container">
<div class="navbar-header">
<div class="container">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar top-bar"></span>
<span class="icon-bar middle-bar"></span>
<span class="icon-bar bottom-bar"></span>
</button>
<a class="navbar-brand" href="./index.html"><img src="img/assets/logo_light3.png" class="logo-light"
alt="#"><img src="img/assets/logo_dark3.png" class="logo-dark" alt="#"></a>
</div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<div class="container">
<ul class="nav navbar-nav menu-right">
<li><a href="index.html">Inicio</a></li>
<li class="dropdown"><a class="dropdown-toggle">Programas<i class="ti-angle-down"></i></a>
<ul class="dropdown-menu">
<li><a href="https://aula42.org" target="_blank">Aula 42</a></li>
<li><a href="http://academiadeverano.cl/" target="_blank">Academia de Verano</a></li>
<li><a href="./verano-trampolin.html">Verano Trampolín</a></li>
<li><a>Trampolín a la Lectura</a></li>
<li><a href="https://www.trampolinfm.cl/" target="_blank">Trampolín FM</a></li>
<li><a>Transforma Verano</a></li>
<li><a>Escuela de invierno</a></li>
<li><a href="https://summerfirst.cl/" target="_blank">SummerFirst</a></li>
</ul>
</li>
<li><a href="servicios-ate.html">Servicios ATE</a></li>
<li><a href="sobre-nosotros.html">Sobre Consejo</a></li>
<li class="nav-separator"></li>
<li><a href="contactanos.html">Contacto</a></li>
</ul>
</div>
</div>
</div>
</nav>
<!-- End Header -->
<section class="blog">
<div class="container">
<div class="row justify-content-md-end mb50">
<!-- Blog Content -->
<div class="col-md-8">
<div class="blog-post">
<div class="post-date">
<h4 class="month">Jul</h4>
<h3 class="day">13</h3>
<span class="year">2021</span>
</div>
<img src="./img/blog/retroalimentacion.jpg" class="img-responsive width100" alt="#">
<a class="link-to-post" href="#">
<h3>¿Qué preguntas pueden guiar el análisis y la reflexión de tus estudiantes sobre sus
aprendizajes?
</h3>
</a>
<p>Por: <NAME> | Foto: Susana Adriasola</p>
<p class="blog-post-categories">
<span><i class="ion-ios-pricetags-outline"></i></span>
<a href="#">Educación</a>
<span>,</span>
<a href="#">Habilidades</a>
<span>,</span>
<a href="#">Retroalimentación</a>
</p>
<p>La retroalimentación constante de los aprendizajes a tus estudiantes, favorece el desarrollo
de habilidades de análisis y de reflexión sobre el aprendizaje; mientras más
oportunidades tengan para poner en práctica estas habilidades, lograrán progresivamente
mayor autonomía en su ejecución.</p>
<p>En un principio puedes orientar la retroalimentación mediante preguntas generadoras de
reflexión, las que luego, podrán servir de modelo y guía para que los estudiantes realicen y
reciban retroalimentación, y para que puedan hacer análisis metacognitivo autónomo de sus
aprendizajes.</p>
<p>
<strong>¿Qué preguntas puedes plantear para ayudar a tus estudiantes a pensar en sus
aprendizajes?</strong>
</p>
<blockquote>
<p><strong>Preguntas sobre el conocimiento</strong>
¿Qué conoces del tema? ¿Tienes claro el significado de…? ¿Cómo puedes relacionar la
información con…? ¿Qué conclusiones puedes sacar? ¿Cuánto más sabes ahora sobre…?</p>
<p><strong>Preguntas sobre el proceso</strong>
¿Qué habilidades has desarrollado? ¿Qué pasos debes seguir para…? ¿Qué tipo de
dificultades tienes para…? ¿Cómo puedes resolverlas? ¿En qué partes ocupaste demasiado
tiempo…?</p>
<p><strong>Preguntas sobre actitudes</strong>
¿En qué eres sistemático? ¿Cuánto interés tienes en la tarea? ¿Dedicas suficiente
atención y concentración a lo que haces? ¿Cómo puedes concentrarte más? ¿Cuán constante
fuiste en la tarea?</p>
</blockquote><br>
<p>Si trabajan la capacidad de observarse a sí mismos, irán ganando autonomía para tomar
decisiones y acciones por iniciativa propia; más allá del ámbito académico, este es un
aprendizaje para toda la vida con múltiples consecuencias favorables en el desarrollo
integral de tus estudiantes y que los prepara para autoevaluar cualquier aprendizaje que
quieran lograr.
<p>
<!-- <p><em>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
Nam at velit nisl. Aenean vitae est nisl. Cras molestie molestie nisl vel imperdiet.
Donec vel mi sem.</em></p> -->
</div>
</div>
<div class="col-md-3 sidebar">
<div class="blog-widget">
<h5>Retroalimentación efectiva</h5>
<p>¿Qué preguntas puedes plantear para ayudar a tus estudiantes a pensar en sus aprendizajes? La
retroalimentación constante de los aprendizajes a tus estudiantes es importante, pues
favorece el desarrollo de habilidades de análisis y de reflexión sobre el
aprendizaje. En este artículo puedes encontrar las preguntas clave para generar reflexión en
tu sala de clases.</p>
</div>
<!-- <div class="blog-widget">
<h5>Categories</h5>
<ul class="category-list list-icons">
<li><a href="#"><i class="ion-ios-arrow-right"></i>Travel</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Lifestyle</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Wander</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Graphics</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Other Bits</a></li>
</ul>
</div> -->
<!-- <div class="blog-widget blog-tags">
<h5>Tags</h5>
<ul class="tags-list">
<li><a href="#">Design</a></li>
<li><a href="#">Photography</a></li>
<li><a href="#">Branding</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Web Design</a></li>
<li><a href="#">Apps</a></li>
<li><a href="#">Development</a></li>
</ul>
</div> -->
<div class="blog-widget">
<h5>Archivo publicaciones</h5>
<ul class="category-list list-icons">
<li><a href="#"><i class="ion-ios-arrow-right"></i>Julio 2021</a></li>
<!-- <li><a href="#"><i class="ion-ios-arrow-right"></i>March 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>February 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>January 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>December 2015</a></li> -->
</ul>
</div>
<div class="sidebar-share">
<ul class="list-inline">
<li><a href="#"><i class="ti-twitter-alt"></i></a></li>
<li><a href="#"><i class="ti-facebook"></i></a></li>
<li><a href="#"><i class="ti-linkedin"></i></a></li>
<!-- <li><a href="#"><i class="ti-email"></i></a></li> -->
</ul>
</div>
</div>
<!-- End Sidebar -->
</div>
</div>
</section>
<!-- Footer One -->
<footer id="footer-1">
<div class="footer-columns">
<div class="container">
<div class="row">
<div class="col-md-4">
<img src="img/assets/logo_light-footer.svg" class="img-footer">
<p>Juntos por una educación transformadora.<br><br>
Av. General Bustamante 26, Providencia<br> <NAME><br>
<EMAIL><br><br></p>
<a href="https://www.facebook.com/consejodecursoCL" target=»_blank»><img
src="img/social/facebook.svg" width="5%"></a>
<a href="https://twitter.com/consejodecurso" target=»_blank»><img src="img/social/twitter.svg"
width="5%"></a>
<a href="https://www.instagram.com/consejodecurso/?hl=es-la" target=»_blank»><img
src="img/social/instagram.svg" width="5%"></a>
<a href="https://www.linkedin.com/company/fundaci%C3%B3n-consejo-de-curso/" target=»_blank»><img
src="img/social/linkedin.svg" width="5%"></a>
</div>
<div class="col-md-4 publicaiones-caja">
<h4 class="subheading">Últimas publicaciones</h4>
<ul class="footer-recent-posts">
<li><a href="./blog-retroalimentacion1.html">Retroalimentación efectiva</a>
<p class="recent-post-date">12 de julio,
2021</p>
</li>
<!-- <li><a href="blog.html">El efecto Pigmalión</a>
<p class="recent-post-date">3 de junio,
2017</p>
</li>
<li><a href="blog.html">Mentalidad de crecimiento</a>
<p class="recent-post-date">28 de
mayo, 2017</p>
</li> -->
</ul>
</div>
<div class="col-md-4 registros-caja">
<p>Certificaciones:<br><br></p>
<div class="caja-logos-registro">
<a href="certificado_ate.pdf" target="_blank"><img src="img/assets/ate.svg"></a>
<a href="https://www.ayudamineduc.cl/ficha/uso-de-recursos-sep-12" target=»_blank»><img
src="img/assets/sep.svg"></a>
</div>
</div>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="row">
<div class="text-center">
<p>© 2021 <a href="index.html" class="logo">Fundación Consejo de Curso. </a> Todos los derechos
reservados. </p>
</div>
</div>
</div>
</footer>
<!-- End Footer One -->
<!-- Start Back To Top -->
<a id="back-to-top"><i class="icon ion-chevron-up"></i></a>
<!-- End Back To Top -->
<!-- Scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/scripts.js"></script>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> -->
<script src="./js/function.js"></script>
</body >
</html ><file_sep>/blog-post-template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> - Fundación Consejo de Curso</title>
<link href="img/assets/favicon.png" rel="icon" type="image/png">
<link href="css/plugins.css" rel="stylesheet" type="text/css">
<link href="css/theme.css" rel="stylesheet" type="text/css">
<link href="css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/et-line-icons.css" rel="stylesheet" type="text/css">
<link href="css/themify-icons.css" rel="stylesheet" type="text/css">
<link href="fonts/lovelo/stylesheet.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Raleway:100,200,300,400%7COpen+Sans:400,300' rel='stylesheet' type='text/css'>
<link href="css/custom.css" rel="stylesheet" type="text/css">
<link href="css/colors/blue.css" id="color-scheme" rel="stylesheet" type="text/css">
</head>
<body>
<!-- Start Header -->
<nav class="navbar navbar-default fullwidth">
<div class="container">
<div class="navbar-header">
<div class="container">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar top-bar"></span>
<span class="icon-bar middle-bar"></span>
<span class="icon-bar bottom-bar"></span>
</button>
<a class="navbar-brand" href="./index.html"><img src="img/assets/logo-light.png" class="logo-light" alt="#"><img src="img/assets/logo-dark.png" class="logo-dark" alt="#"></a>
</div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<div class="container">
<ul class="nav navbar-nav menu-right">
<li><a href="index.html">Inicio</a></li>
<li class="dropdown"><a class="dropdown-toggle">Programas<i class="ti-angle-down"></i></a>
<ul class="dropdown-menu">
<li><a href="verano-trampolin.html">Verano Trampolín</a></li>
<li><a href="academia-de-verano.html">Academia de Verano</a></li>
<li><a href="https://aula42.org" target="_blank">Aula 42</a></li>
</ul>
</li>
<li><a href="blog.html">Blog</a></li>
<li><a href="sobre-nosotros.html">Sobre nosotros</a></li>
<li class="nav-separator"></li>
<li><a href="contactanos.html">Contacto</a></li>
</ul>
</div>
</div>
</div>
</nav>
<!-- End Header -->
<section class="blog">
<div class="container">
<div class="row justify-content-md-end">
<!-- el texto no queda alineado al centro con justify-content-center-->
<!-- Blog Content -->
<div class="col-md-8" >
<div class="blog-post">
<div class="post-date">
<h4 class="month">May</h4>
<h3 class="day">28</h3>
<span class="year">2017</span>
</div>
<img src="img/blog/por-que-trabajar-en-verano.png" class="img-responsive width100" alt="#">
<a class="link-to-post" href="#"><h3>Mentalidad de crecimiento</h3></a>
<p class="blog-post-categories">
<span><i class="ion-ios-pricetags-outline"></i></span>
<a href="#">Educación</a>
<span>,</span>
<a href="#">Habilidades</a>
</p>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. <NAME>, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites.</p>
<p>Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. There are many variations of passages of Lorem Ipsum available, but the majority.</p>
<p>Phasellus nibh tortor, varius vitae orci sit amet, placerat ornare quam. Nunc sapien risus, <strong>tictum id orci quis, rutrum cursus ipsum. Phasellus pellentesque ultricies pretium.</strong></p>
<blockquote><p>Phasellus nibh tortor, varius vitae orci sit amet, placerat ornare quam. Nunc sapien risus, tictum id orci quis, rutrum cursus ipsum. ultricies pretium. Phasellus nibh tortor, varius vitae orci sit amet, <strong>placerat ornare quamm, nunc</strong> sapien risus, <strong>tictum id orci quis, rutrum</strong> cursus ipsum. Phasellus pellentesque ultricies pretium, placerat ornare quam</p></blockquote>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo <a href="#">dolores et ea</a> rebum. Stet clita kasd gubergren, no sea takimata sanctus <a href="#">magna aliquyam erat</a>, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.<p>
<p><em>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam at velit nisl. Aenean vitae est nisl. Cras molestie molestie nisl vel imperdiet. Donec vel mi sem.</em></p>
</div>
<div class="comments">
<h4 class="comments-title">4 Comments</h4>
<div class="comment first depth-1">
<a class="pull-left" href="#">
<img class="avatar" src="img/assets/avatar.jpg" alt="">
</a>
<div class="comment-body">
<a class="comment-reply" href="#">Reply</a>
<h4 class="comment-heading"><NAME></h4>
<p class="comment-time">Apr 24, 2016</p>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus magna aliquyam erat, sed diam voluptua. Vesquam ante aliquet lacusemper elit. Cras neque nulla, convallis non commodo et. Vesquam ante aliquet lacusemper elit.</p>
</div>
</div>
<div class="comment depth-2">
<a class="pull-left" href="#">
<img class="avatar" src="img/assets/avatar.jpg" alt="">
</a>
<div class="comment-body">
<a class="comment-reply" href="#">Reply</a>
<h4 class="comment-heading"><NAME></h4>
<p class="comment-time">Apr 26, 2016</p>
<p>Cras neque nulla, convallis non commodo et, euismod nonsese. At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.</p>
</div>
</div>
<div class="comment depth-3">
<a class="pull-left" href="#">
<img class="avatar" src="img/assets/avatar.jpg" alt="">
</a>
<div class="comment-body">
<a class="comment-reply" href="#">Reply</a>
<h4 class="comment-heading"><NAME></h4>
<p class="comment-time">Apr 29, 2016</p>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
</div>
</div>
<div class="comment depth-1">
<a class="pull-left" href="#">
<img class="avatar" src="img/assets/avatar.jpg" alt="">
</a>
<div class="comment-body">
<a class="comment-reply" href="#">Reply</a>
<h4 class="comment-heading"><NAME></h4>
<p class="comment-time">Apr 30, 2016</p>
<p>Lorem ipsum dolor sit amet isse potenti. Vesquam ante aliquet lacusemper elit. Cras neque nulla, convallis non commodo et, euismod nonsese. At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
</div>
</div>
</div>
</div>
End Blog Content -->
<!-- Sidebar
<div class="col-md-3 sidebar">
<div class="blog-widget">
<h5>About</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dui lorem, adipiscing in adipiscing et, interdum nec metus. Mauris ultricies, justo eu convallis placerat.</p>
</div>
<div class="blog-widget">
<h5>Categories</h5>
<ul class="category-list list-icons">
<li><a href="#"><i class="ion-ios-arrow-right"></i>Travel</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Lifestyle</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Wander</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Graphics</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>Other Bits</a></li>
</ul>
</div>
<div class="blog-widget blog-tags">
<h5>Tags</h5>
<ul class="tags-list">
<li><a href="#">Design</a></li>
<li><a href="#">Photography</a></li>
<li><a href="#">Branding</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Web Design</a></li>
<li><a href="#">Apps</a></li>
<li><a href="#">Development</a></li>
</ul>
</div>
<div class="blog-widget">
<h5>Archives</h5>
<ul class="category-list list-icons">
<li><a href="#"><i class="ion-ios-arrow-right"></i>April 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>March 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>February 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>January 2016</a></li>
<li><a href="#"><i class="ion-ios-arrow-right"></i>December 2015</a></li>
</ul>
</div>
<div class="sidebar-share">
<ul class="list-inline">
<li><a href="#"><i class="ti-twitter-alt"></i></a></li>
<li><a href="#"><i class="ti-facebook"></i></a></li>
<li><a href="#"><i class="ti-linkedin"></i></a></li>
<li><a href="#"><i class="ti-pinterest-alt"></i></a></li>
<li><a href="#"><i class="ti-google"></i></a></li>
</ul>
</div>
</div>
End Sidebar
</div>
</div>
</section>
<!-- Footer One -->
<footer id="footer-1">
<div class="footer-columns">
<div class="container">
<div class="row">
<div class="col-md-3">
<h4 class="subheading">Sobre nosotros</h4>
<p>Somos una fundación educacional que busca transformar la educación en Chile y Latinoamérica. Creamos los cursos y experiencias de aprendizaje del futuro. Es una nueva visión del contenido, de la forma y también del propósito de la educación. </p>
</div>
<div class="col-md-3">
<h4 class="subheading">Últimas publicaciones</h4>
<ul class="footer-recent-posts">
<li><a href="blog.html">Aprender por gusto</a><span class="recent-post-date">5 de julio, 2017</span></li>
<li><a href="blog.html">El efecto Pigmalión</a><span class="recent-post-date">3 de junio, 2017</span></li>
<li><a href="blog.html">Mentalidad de crecimiento</a><span class="recent-post-date">28 de mayo, 2017</span></li>
</ul>
</div>
<div class="col-md-3">
<h4 class="subheading"></h4>
<div></div>
</div>
<div class="col-md-3">
<h4 class="subheading">Instagram</h4>
<div id="instagram-feed" data-instagram-username="consejodecurso"><ul></ul></div>
</div>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-12">
<p>© 2017 <a href="index.html" class="logo">Fundación Consejo de Curso. </a> Todos los derechos reservados. </p>
</div>
</div>
</div>
</div>
</footer>
<!-- End Footer One -->
<!-- Start Back To Top -->
<a id="back-to-top"><i class="icon ion-chevron-up"></i></a>
<!-- End Back To Top -->
<!-- Scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/scripts.js"></script>
</body>
</html> | 99f14d18bf539905afe6a2d2701335ec70be27bf | [
"HTML",
"Shell"
] | 3 | Shell | Consejo-de-Curso/consejodecurso | 258ce3471a289ed47eafa455b0ba8392c79b1a21 | 400017e301afacaa257c8875d7a5da8dd5221ae3 |
refs/heads/master | <repo_name>Flipez/advent-of-code-2019<file_sep>/day6/day6.rb
require 'set'
input = File.read('input')
connections = input.split("\n")
orbits = {}
connections.each do |connection|
planet, orbiter = connection.split(')')
orbits[orbiter] = Set.new([planet, orbits[planet].to_a].flatten.compact)
orbits.each do |orbit, current_planet|
if current_planet.include?(orbiter)
orbits[orbit].merge([planet, orbits[planet].to_a].flatten.compact)
end
end
end
puts(orbits.values.inject(0) { |sum, planets| sum + planets.length })
puts((orbits['YOU'] - orbits['SAN']).length + (orbits['SAN'] - orbits['YOU']).length)
<file_sep>/day4/part_1.rb
input = 284639..748759
matching_numbers = 0
input.each do |number|
digits = number.to_s.chars.map(&:to_i)
is_larger = []
digits.each_with_index{|d,i| is_larger << (d >= digits[i-1])}
is_larger = is_larger[1..-1]
next unless is_larger.all?
%w(11 22 33 44 55 66 77 88 99).each do |double|
if number.to_s.include? double
matching_numbers += 1
break
end
end
end
p matching_numbers | 5a5bffc6bbc2db0b10a3a4bc6c7f03774627264f | [
"Ruby"
] | 2 | Ruby | Flipez/advent-of-code-2019 | 5c42167d4b13e69593f8b819cfe3473dad08d13d | 3787bb705b7431b86af685426a5f560f9d3a9b7d |
refs/heads/main | <file_sep>package com.example.timer;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.timer.util.DbManager;
import com.example.timer.util.FeedReaderContract;
import com.example.timer.util.FeedReaderDbHelper;
import com.example.timer.util.Fruit;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class InfoActivity extends AppCompatActivity {
private TextView info_name;
private TextView info_content;
private TextView info_daka;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
Intent intent = getIntent();
String message = intent.getStringExtra(HabitActivity.EXTRA_MESSAGE);
btn = (Button) findViewById(R.id.xxx);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteGoal(message);
}
});
info_name = (TextView) findViewById(R.id.info_name);
info_content = (TextView) findViewById(R.id.info_content);
info_daka = (TextView) findViewById(R.id.info_times);
info_name.setText(message);
display(message);
displayDaka(message);
}
public void display(String message){
SQLiteDatabase db = DbManager.getInstance(this).dbHelper.getWritableDatabase();
String[] projection = {
BaseColumns._ID,
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
FeedReaderContract.FeedEntry.COLUMN_NAME_CONTEXT,
FeedReaderContract.FeedEntry.COLUMN_NAME_TIME,
FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE
};
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE+ " = ?";
String[] selectionArgs = { message };
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
Cursor cursor = db.query(
FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
int itemid = 0;
String itemname = "1";
String itemcontent = "2";
String days = "3";
String isfinished = "4";
while(cursor.moveToNext()) {
itemid = cursor.getInt(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID));
itemname = cursor.getString(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE)
);
itemcontent = cursor.getString(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTEXT)
);
days = cursor.getString(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TIME)
);
isfinished = cursor.getString(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE)
);
}
String str = "没有完成";
if(Integer.parseInt(isfinished)==1)
{
str="已经完成";
}
Toast.makeText(this, isfinished, Toast.LENGTH_LONG).show();
info_content.setText(itemcontent+"\n"+str);
//cursor.close();
}
public void displayDaka(String message){
SQLiteDatabase db = DbManager.getInstance(this).dbHelper.getWritableDatabase();
String context = "";
String[] projection = {"ID","days"};
String selection = "ID"+ " >= ?";
String[] selectionArgs = { "0"};
String sortOrder = "ID" + " DESC";
Cursor cursor = db.query(
message, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
while(cursor.moveToNext()) {
context += cursor.getString(cursor.getColumnIndexOrThrow("days")) + '\n';
}
info_daka.setText((context));
}
public void deleteGoal(String message){
SQLiteDatabase db = DbManager.getInstance(this).dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TAG,1);
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + "= ?";
String[] selectionArgs = { message };
// String[] selectionArgs = { "www" };
db.update("Goal",values,selection,selectionArgs);
}
}<file_sep>package com.example.timer.util;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.timer.R;
import java.util.List;
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
private List<Item> mItemList;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView itemImage;
TextView itemName;
public ViewHolder(View view) {
super(view);
itemImage = (ImageView) view.findViewById(R.id.fruit_image);
itemName = (TextView) view.findViewById(R.id.fruit_name);
}
}
public ItemAdapter(List<Item> itemList) {
mItemList = itemList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
//view.setOnClickListener(this);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Item item = mItemList.get(position);
holder.itemImage.setImageResource(item.getImageId());
holder.itemName.setText(item.getName());
}
@Override
public int getItemCount() {
return mItemList.size();
}
}<file_sep>package com.example.timer;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.timer.util.DbManager;
import com.example.timer.util.FeedReaderContract;
import com.example.timer.util.FeedReaderDbHelper;
import com.example.timer.util.Fruit;
import com.example.timer.util.FruitAdapter;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.List;
import static com.example.timer.util.DbManager.dbHelper;
public class MainActivity extends AppCompatActivity {
private Button btn1;
//private Button btn2;
private Button btn3;
//private FeedReaderDbHelper dbHelper= new FeedReaderDbHelper(this);
//public final FeedReaderDbHelper dbHelper= new FeedReaderDbHelper(this);
//SQLiteDatabase db;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
List<String> mPermissionList = new ArrayList<>();
// private ImageView welcomeImg = null;
private static final int PERMISSION_REQUEST = 1;
// 检查权限
private void checkPermission() {
mPermissionList.clear();
//判断哪些权限未授予
for (int i = 0; i < permissions.length; i++) {
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
mPermissionList.add(permissions[i]);
}
}
/**
* 判断是否为空
*/
if (mPermissionList.isEmpty()) {//未授予的权限为空,表示都授予了
} else {//请求权限方法
String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);
}
}
/**
* 响应授权
* 这里不管用户是否拒绝,都进入首页,不再重复申请权限
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST:
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
protected void onCreate(Bundle savedInstanceState) {
checkPermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//btn1 = (Button) findViewById(R.id.btn_check);
//btn2 = (Button) findViewById(R.id.btn_achieve);
//btn3 = (Button) findViewById(R.id.btn_clk);
// btn1.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent intent = new Intent(MainActivity.this,HabitActivity.class);
// startActivity(intent);
// }
// });
// btn2.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent intent = new Intent(MainActivity.this,AchieveActivity.class);
// startActivity(intent);
// }
// });
// btn3.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent intent = new Intent(MainActivity.this,ClkActivity.class);
// startActivity(intent);
// }
// });
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
//DbManager.getInstance(this);
//db = DbManager.getInstance(this).dbHelper;
//测试数据库
//testDb();
//测试适配器
}
public void testDb(){
//插入信息
// ContentValues values = new ContentValues();
// values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,"Math");
// values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTEXT,"Read the book, 5 pages by day");
// values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TIME,"30");
// values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE,"0");
// SQLiteDatabase db = DbManager.getInstance(this).dbHelper.getWritableDatabase();
// //dbHelper.onUpgrade(db,0,1);
// long newR = db.insert(FeedReaderContract.FeedEntry.TABLE_NAME,null,values);
//创建新表
// String create_table =
// "CREATE TABLE " + "Time_Record" + " (" +
// "time" + " INTEGER" + ")";
// db.execSQL(create_table);
//db.close();
//dbHelper.onUpgrade(db,0,1);
// //读取信息
// String[] projection = {
// BaseColumns._ID,
// FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
// FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE
// };
//
// // Filter results WHERE "title" = 'My Title'
// String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + " = ?";
// String[] selectionArgs = { "Read a Book" };
//
// // How you want the results sorted in the resulting Cursor
// String sortOrder =
// FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";
//
// Cursor cursor = db.query(
// FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
// projection, // The array of columns to return (pass null to get all)
// selection, // The columns for the WHERE clause
// selectionArgs, // The values for the WHERE clause
// null, // don't group the rows
// null, // don't filter by row groups
// sortOrder // The sort order
// );
//
// List itemIds = new ArrayList<>();
// while(cursor.moveToNext()) {
// String itemId = cursor.getString(
// cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE));
// itemIds.add(itemId);
// }
// for (int i = 0; i < itemIds.size(); i++) {
// Log.i("info: ",itemIds.get(i).toString());
// }
// cursor.close();
//删除表
// String delete_table =
// "DROP TABLE IF EXISTS " + "Goal";
//
// db.execSQL(delete_table);
}
}<file_sep># timerApp
* A demo app for habits-getting in Android platform
<file_sep>package com.example.timer.ach_back;
import androidx.lifecycle.ViewModel;
public class AchieveViewModel extends ViewModel {
// TODO: Implement the ViewModel
} | e3f42a82da6315a432b24cbc960d3777d0b7e292 | [
"Markdown",
"Java"
] | 5 | Java | Waynezee/timerApp | 93ea473819c4fb9d365fd455408a61319b9eae5a | 32c28fbf167424fa80075c28d841503740987e08 |
refs/heads/main | <repo_name>ppdubey/practiseTableView<file_sep>/practiseTableView/ViewController.swift
//
// ViewController.swift
// practiseTableView
//
// Created by user196667 on 6/1/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var tableView: UIView!
var names = [ 10, 20, 55, 10, 20, 55, 10, 20, 55,
10, 20, 55, 10, 20, 55, 10, 20, 55, 10, 20, 55, 10, 20, 55, 10, 20, 55, 10, 20, 55,
10, 20, 55,10, 20, 55,10, 20, 55,
10, 20, 55,10, 20, 55,10, 20, 55,
10, 20, 55,10, 20, 55,10, 20, 55]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension ViewController : UITableViewDelegate, UITableViewDataSource {
// MARK : DidSelectRow
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(" selectec items : \(names[indexPath.row])")
tableView.cellForRow(at: indexPath)?.backgroundColor = UIColor.blue
}
// MARK : DidDe-SelectRow
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.backgroundColor = nil
}
// MARK : CellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! myCellClassTableViewCell
cell.setLabel(labelVal: String(names[indexPath.row]))
//cell.textLabel?.text = String(names[indexPath.row])
//cell.imageView?.image = UIImage(named: "birdie")
return cell
}
// MARK : NumberOfRows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
names.count
}
}
<file_sep>/practiseTableView/myCellClassTableViewCell.swift
//
// myCellClassTableViewCell.swift
// practiseTableView
//
// Created by user196667 on 6/1/21.
//
import UIKit
class myCellClassTableViewCell: UITableViewCell {
@IBOutlet weak var myCellLabel: UILabel!
@IBOutlet weak var myCellImage: UIImageView!
func setLabel(labelVal: String) {
myCellLabel?.text = labelVal
myCellImage.image = UIImage(named: "birdie")
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
| b64d0ac97831e4d812aa45507f5629f232aed675 | [
"Swift"
] | 2 | Swift | ppdubey/practiseTableView | ec151b58897eb1f104af73bb49df501dd7062f96 | 5800488279b5fbe6359af1a7577939eaedb6ef5e |
refs/heads/master | <repo_name>weichennewcastle/mesh_interpolator<file_sep>/mmig_open3d.py
import stl
import numpy as np
from scipy.spatial import cKDTree as KDTree
import open3d as o3d
import sys
from multiprocessing import Pool, cpu_count
import functools
from time import time
def process_kdtree_chunk(chunk, kdtree):
return kdtree.query(chunk)
def interpolate(s_p):
s_p[0] = (1 - INTERPOLATION)*s_p[0] + INTERPOLATION*s_p[1]
return s_p
INTERPOLATION = 0.5
if __name__ == '__main__':
start = time()
if len(sys.argv) > 1:
_INTERPOLATION = float(sys.argv[1])
_sphere = sys.argv[2]
_ellipse = sys.argv[3]
else:
_sphere = "sphere.stl"
_ellipse = "ellipse.stl"
_INTERPOLATION = 0.5
_start = time()
print('loading meshes')
sphere = o3d.io.read_triangle_mesh(_sphere)
ellipse = o3d.io.read_triangle_mesh(_ellipse)
sphere.remove_duplicated_triangles()
sphere.remove_duplicated_vertices()
sphere.remove_degenerate_triangles()
ellipse.remove_duplicated_triangles()
ellipse.remove_duplicated_vertices()
ellipse.remove_degenerate_triangles()
sphere_points = np.asarray(sphere.vertices)
ellipse_points = np.asarray(ellipse.vertices)
_end = time()
print(f'finished loading meshes in {_end - _start}')
INTERPOLATION = _INTERPOLATION
kdtree = KDTree(ellipse_points, leafsize=90)
_start = time()
print('about to query')
with Pool(cpu_count()) as p:
locations = p.map(functools.partial(process_kdtree_chunk, kdtree=kdtree), sphere_points, sphere_points.shape[0]//cpu_count())
_end = time()
print(f'finised query in {_end - _start}')
locations = [l[1] for l in locations]
_start = time()
print('about to interpolate')
inter = np.array(np.apply_along_axis(interpolate, 1, np.array([(s_p[1], ellipse_points[locations[s_p[0][0]]][s_p[0][1]]) for s_p in np.ndenumerate(sphere_points)], dtype=object)))
sphere_points[:] = inter[:, 0].reshape((-1,3))
_end = time()
print(f'finised interpolating in {_end - _start}')
sphere.compute_triangle_normals()
o3d.io.write_triangle_mesh("interpolated.stl", sphere)
end = time()
print(f'time taken was: {end-start}')
<file_sep>/README.md
# mesh_interpolator
REQUIREMENTS: numpy, numpy-stl, scipy
An algorithm that will interpolate between two given stl files.
Rename the 'sphere.stl' and 'ellipse.stl' in the code to the meshes you wish to use.
Change the value of 'INTERPOLATION' to choose how far the mesh will be interpolated. (between 0 and 1)
Can use command line arguments to set these values in the order:
python mmig.py 0.5 sphere.stl ellipse.stl
| f5bef4be5b1e20d6706b78030b90f9105a15a952 | [
"Markdown",
"Python"
] | 2 | Python | weichennewcastle/mesh_interpolator | d9a068ce6032ac9028f575072272aa0f8e932f32 | 022c10c5234908d7e87fbd2e9343b5eb85835701 |
refs/heads/master | <repo_name>mingyk/chapter-10-exercises<file_sep>/exercise-2/exercise.R
# Exercise 2: working with data frames
# Create a vector of 100 employees ("Employee 1", "Employee 2", ... "Employee 100")
# Hint: use the `paste()` function and vector recycling to add a number to the word
# "Employee"
vector_1 <- c("Employee")
vector_2 <- 1:100
employee <- c(paste(vector_1, vector_2))
# Create a vector of 100 random salaries for the year 2017
# Use the `runif()` function to pick random numbers between 40000 and 50000
salaries17 <- c(round(runif(100, min = 40000, max = 50000), 2))
# Create a vector of 100 annual salary adjustments between -5000 and 10000.
# (A negative number represents a salary decrease due to corporate greed)
# Again use the `runif()` function to pick 100 random numbers in that range.
salary_adjustments <- c(round(runif(100, min = -5000, max = 10000), 2))
# Create a data frame `salaries` by combining the 3 vectors you just made
# Remember to set `stringsAsFactors=FALSE`!
salaries <- data.frame(employee, salaries17, salary_adjustments, stringAsFactors = FALSE)
# Add a column to the `salaries` data frame that represents each person's
# salary in 2018 (e.g., with the salary adjustment added in).
salaries$salaries18 <- (salaries17 + salary_adjustments)
# Add a column to the `salaries` data frame that has a value of `TRUE` if the
# person got a raise (their salary went up)
salaries$raise <- (salary_adjustments > 0)
### Retrieve values from your data frame to answer the following questions
### Note that you should get the value as specific as possible (e.g., a single
### cell rather than the whole row!)
# What was the 2018 salary of Employee 57
salaries[87, 5]
#$48312.10
# How many employees got a raise?
length(salaries[salaries == TRUE])
#69 employees
# What was the dollar value of the highest raise?
max(salaries[3])
#$9924.65
# What was the "name" of the employee who received the highest raise?
salaries[salaries[3] == 9924.65, 1]
#Employee 38
# What was the largest decrease in salaries between the two years?
min(salaries[3])
#-$4724.44
# What was the name of the employee who recieved largest decrease in salary?
salaries[salaries[3] == -4724.44, 1]
#Employee 49
# What was the average salary change?
round(mean(salaries[[3]]),2)
#$2357.20
# For people who did not get a raise, how much money did they lose on average?
round(mean(salaries[salaries[6] == FALSE, 3]),2)
#-$2587.07
## Consider: do the above averages match what you expected them to be based on
## how you generated the salaries?
# Write a .csv file of your salary data to your working directory
write.csv(salaries, "2017-2018 Salary Adjustments", row.names = FALSE)
| 0c648ab4679982f714f588cba067ce3a46e9ad03 | [
"R"
] | 1 | R | mingyk/chapter-10-exercises | bd73b930528ba09a33b6ee0d7f725f740b47a837 | d6a053dbc19fc74803c7b13db1e6ea26a8fcf8f9 |
refs/heads/master | <repo_name>docovarr2020/dorm_supplies-frontend<file_sep>/README.md
# dorm_supplies-frontend
Frontend file for the dorm delivery app
<file_sep>/app/js/script.js
const register_form = document.forms[0]
const login_form = document.forms[1]
function register_user() {
console.log(document.forms[0].name.value)
const data = {}
if (register_form.name.value) data.name = register_form.name.value
if (register_form.email.value) data.email = register_form.email.value
if (register_form.classYear.value) data.classYear = register_form.classYear.value
if (register_form.address.value) data.address = register_form.address.value
if (register_form.password.value) data.password = <PASSWORD>_form.password.<PASSWORD>
if (register_form.confirm.value) data.confirm = register_form.confirm.value
console.log(data)
fetch('/register', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(data)
}).then(function (res) {
if(!res.ok) {
res.text()
.then(function(message) {
alert(message)
})
}
res.json()
.then(function(user){
window.location = '/items'
alert(JSON.stringify(user))
})
}).catch(function (err) {
console.log(err)
})
}
function openTab(evt, tabName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
function login_user() {
const data = {}
if (login_form.email.value) data.email = login_form.email.value
if (login_form.password.value) data.password = login_form.password.value
fetch('/login', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(data)
}).then(function (res) {
if(!res.ok) {
res.text()
.then(function(message) {
alert(message)
})
}
res.json()
.then(function(data){
alert(JSON.stringify(data))
localStorage.token = data.token
window.location = '/items'
})
}).catch(function (err) {
console.log(err)
})
}
| 10f9a370f5f28a5e3fa83eb174c153982632484d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | docovarr2020/dorm_supplies-frontend | a6f508792beb4d19bcee63c7a804917e3e77f2a6 | eab9e0a7d5670ddfaa7b3a997834e6417ac9a61c |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-16 14:49
from __future__ import unicode_literals
import black.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('black', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='post',
name='photo',
field=models.ImageField(max_length=200, upload_to=black.models.upload_location),
),
]
<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index' ),
url(r'^(?P<pk>\d+)/$', views.post_list, name='post_list'),
url(r'^(?P<pk>\d+)/post/$', views.post, name='post'),
url(r'^(?P<person_pk>\d+)/post/(?P<post_pk>\d+)/$', views.post_detail, name='post_detail')
]<file_sep>from django.db import models
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class People(models.Model):
name=models.CharField(max_length=20)
def upload_location(instance, filename):
return "%s/%s" %(instance.person.name, filename)
class Post(models.Model):
title=models.CharField(max_length=30)
media=models.FileField(upload_to=upload_location, null=True)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content=models.TextField()
person=models.ForeignKey(People, default=1)
writer=models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
class Comment(models.Model):
post=models.ForeignKey(Post)
content=models.TextField()
writer=models.ForeignKey(settings.AUTH_USER_MODEL)
class Like(models.Model):
post=models.ForeignKey(Post)
rating=models.DecimalField(max_digits=2, decimal_places=0, validators=[MinValueValidator(0), MaxValueValidator(10)], help_text='10점 만점, 높을수록 극혐!', blank=True, default=5)
liker=models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-16 17:37
from __future__ import unicode_literals
import black.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('black', '0007_auto_20160817_0117'),
]
operations = [
migrations.AlterField(
model_name='post',
name='photo',
field=models.ImageField(height_field=400, max_length=200, upload_to=black.models.upload_location, width_field=400),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-16 17:39
from __future__ import unicode_literals
import black.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('black', '0008_auto_20160817_0237'),
]
operations = [
migrations.AddField(
model_name='post',
name='height_field',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='post',
name='width_field',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='post',
name='photo',
field=models.ImageField(height_field='height_field', upload_to=black.models.upload_location, width_field='width_field'),
),
]
<file_sep>from django.shortcuts import render, redirect
from black.models import People
# Create your views here.
def home(request):
return render(request, 'index/home.html')<file_sep>from django.shortcuts import render
from .forms import SignupForm
# Create your views here.
def signup(request):
if request.method=='POST':
s=SignupForm(request.POST)
if s.is_valid():
s.save()
return redirect('login')
else:s=SignupForm()
return render(request, 'accounts/signup.html', {'form':s})<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-16 14:08
from __future__ import unicode_literals
import black.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField()),
],
),
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.IntegerField(blank=True)),
('liker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='People',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=30)),
('photo', models.ImageField(upload_to=black.models.upload_location)),
('content', models.TextField()),
('person', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='black.People')),
('writer', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='like',
name='post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='black.Post'),
),
migrations.AddField(
model_name='comment',
name='post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='black.Post'),
),
migrations.AddField(
model_name='comment',
name='writer',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-16 17:47
from __future__ import unicode_literals
import black.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('black', '0009_auto_20160817_0239'),
]
operations = [
migrations.AlterField(
model_name='post',
name='photo',
field=models.ImageField(upload_to=black.models.upload_location),
),
]
<file_sep>from django import forms
from django.forms import ModelForm, NumberInput
from .models import Post, Comment, Like
class PostForm(forms.ModelForm):
class Meta:
model=Post
fields=['title', 'media', 'content']
labels={'title':'제목', 'media':'극혐자료', 'content':'내용'}
class CommentForm(forms.ModelForm):
class Meta:
model=Comment
fields=['content']
labels={'content':'답글'}
class LikeForm(forms.ModelForm):
class Meta:
model=Like
fields=['rating']
labels={'rating':'극혐 정도'}
<file_sep>from django.contrib import admin
from .models import People, Post, Comment, Like
# Register your models here.
admin.site.register(Post)
admin.site.register(People)
admin.site.register(Comment)
admin.site.register(Like)<file_sep>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignupForm(UserCreationForm):
first_name=forms.CharField(max_length=10)
def save(self, commit=True):
user=super(SignupForm, self).save(commit=False)
user.first_name=self.cleaned_data['name']
if commit:
user.save()
return user
class Meta:
model=User
fields=['username', '<PASSWORD>', '<PASSWORD>', 'first_name']
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
self.fields['username'].label = '아이디를 입력하세요.'
self.fields['password1'].label = '비밀번호를 입력하세요.'
self.fields['password2'].label = '비밀번호를 다시 한 번 입력하세요.'
self.fields['first_name'].label = '이름을 적어주세요.'
def clean_name(self):
data=self.cleaned_data['first_name']
if User.objects.filter(first_name=data).exists():
raise forms.ValidationError('이미 회원가입이 완료되었습니다.')
return data<file_sep>from django.shortcuts import render, redirect
from .models import People, Like, Post, Comment
from .forms import PostForm, CommentForm, LikeForm
from django.contrib.auth.decorators import login_required
from django.db.models import Avg
# Create your views here.
def index(request):
people_list=People.objects.all()
return render(request, 'black/index.html', {'people_list':people_list})
def post(request, pk):
instance=People.objects.get(pk=pk)
if request.method=='POST':
p=PostForm(request.POST, request.FILES)
if p.is_valid():
new_post=p.save(commit=False)
new_post.writer=request.user
new_post.person=instance
new_post.save()
return redirect('black:post_detail', person_pk=instance.pk, post_pk=new_post.pk)
else:
p=PostForm()
return render(request, 'black/post.html', {'form':p})
def post_detail(request, person_pk, post_pk):
instance=People.objects.get(pk=person_pk)
post=Post.objects.get(pk=post_pk)
comments=Comment.objects.filter(post=post_pk)
likes=Like.objects.filter(post=post_pk)
num_likes=Like.objects.filter(post=post_pk).count()
avg=Like.objects.filter(post=post_pk).aggregate(Avg('rating')).values()
likes_avg=list(avg)[0]
if request.method=='POST':
if request.POST['form_type'] == u'like':
l=LikeForm(request.POST,)
if l.is_valid():
new_like=l.save(commit=False)
new_like.writer=request.user
new_like.post=post
new_like.save()
return redirect('black:post_detail', person_pk=instance.pk, post_pk=post.pk)
else:
c=CommentForm(request.POST,)
if c.is_valid():
new_comment=c.save(commit=False)
new_comment.writer=request.user
new_comment.post=post
new_comment.save()
return redirect('black:post_detail', person_pk=instance.pk, post_pk=post.pk)
else:
l=LikeForm()
c=CommentForm()
context={'post':post, 'comments':comments, 'likes':likes, 'num_likes':num_likes, 'commentform': c, 'likeform': l, 'avg':likes_avg}
return render(request, 'black/post_detail.html', context)
def post_list(request, pk):
instance=People.objects.get(pk=pk)
post_list=Post.objects.filter(person=pk)
return render(request, 'black/post_list.html', {'person': instance ,'post_list':post_list}) | 90baf49f301f77981c270b5ba50190248d2e3ca0 | [
"Python"
] | 13 | Python | jhmk612/banpo | 0dfccd93b837d740c45ad297b5a7b215db70209e | 7f61e6ab4badfdd304f447057bdce6d29bd7bca2 |
refs/heads/master | <repo_name>powelllens/ffw-alertsystem<file_sep>/ffw-alertmonitor/script/test.sh
#!/bin/bash
case "$1" in
watchdog)
echo "Testing watchdog message ..."
MESSAGE="POCSAG1200: Address: 174896 Function: 0 Alpha: <BS><CAN>"
;;
alert1)
echo "Testing alert message ..."
MESSAGE="POCSAG1200: Address: 158973 Function: 0 Alpha: 11288/bert/Opek/Magen-Darm-Zentrum M/Bismarckplatz 1/MA-Schwetzingerstadt/WB 3 Ida Scipio Heim/Murgstr. 4/MA-Neckarstadt/12, (laut Pflege geht der Bruder zum Bürgermeister sollte es nicht klappen)/"
;;
alert2)
echo "Testing alert message with geo coordinates ..."
MESSAGE="POCSAG1200: Address: 158973 Function: 0 Alpha: 49.324291/08.808761/26/F1 undefiniertes Kleinfeuer//vorm Kindergarten/Industriestraße /Meckesheim// //brennende Mülleimer/"
;;
--help)
echo "Usage: $0 {watchdog | alert1 | alert2 | <message>}"
exit 1
;;
*)
echo "Testing user defined message ..."
MESSAGE="POCSAG1200: Address: 158973 Function: 0 Alpha: $1";
;;
esac
echo $MESSAGE | socat - udp-datagram:192.168.1.255:50000,broadcast
<file_sep>/ffw-alertmonitor/src/ffw/alertmonitor/Watchdog.java
package ffw.alertmonitor;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import ffw.util.ConfigReader;
public class Watchdog {
private DatagramSocket socket;
public Watchdog() {
Date now = new java.util.Date();
SimpleDateFormat sdfDateAndTime = new SimpleDateFormat("dd.MM.yyyy-HH:mm:ss");
String dateAndTime = sdfDateAndTime.format(now);
int port = Integer.parseInt(ConfigReader.getConfigVar("watchdog-port"));
int timeout = Integer.parseInt(ConfigReader.getConfigVar("watchdog-timeout"));
System.out.println("** " + dateAndTime +" start watchdog (timeout: " + timeout + "s)");
try {
this.socket = new DatagramSocket(port);
this.socket.setSoTimeout(1000 * 60 * timeout);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
try {
this.socket.receive(packet);
now = new java.util.Date();
dateAndTime = sdfDateAndTime.format(now);
int length = packet.getLength();
byte[] data = packet.getData();
System.out.println("** " + dateAndTime +" watchdog says: " + new String(data, 0, length));
} catch (SocketTimeoutException e) {
/* TODO call the police or something */
now = new java.util.Date();
dateAndTime = sdfDateAndTime.format(now);
System.out.println("** " + dateAndTime +" watchdog says: oh nooo!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Watchdog();
}
}
<file_sep>/ffw-alertmonitor/html/map.js
function loadMap() {
var directionsDisplay = new google.maps.DirectionsRenderer();
var ffwMoe = new google.maps.LatLng(49.334283, 8.851337);
var mapOptions = {
zoom: 10,
center: ffwMoe,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
directionsDisplay.setMap(map);
var lat = $("#latitude").text();
var lng = $("#longitude").text();
var dest = new google.maps.LatLng(lat, lng);
var request = {
origin: ffwMoe,
destination: dest,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
var totalDistance = 0;
var totalDuration = 0;
var legs = result.routes[0].legs;
for(var i=0; i<legs.length; ++i) {
totalDistance += legs[i].distance.text;
totalDuration += legs[i].duration.text;
}
$("#distance").text(" " + totalDistance);
$("#duration").text("~" + totalDuration);
}
});
}<file_sep>/ffw-alertmonitor/src/ffw/alertmonitor/AlertListener.java
package ffw.alertmonitor;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Queue;
import ffw.util.ConfigReader;
public class AlertListener implements Runnable {
private boolean stopped = false;
private int port;
private DatagramSocket socket;
private StringBuilder buffer;
private Queue<Message> messageQueue = null;
public AlertListener(Queue<Message> messageQueue) {
this.messageQueue = messageQueue;
this.buffer = new StringBuilder();
this.port = Integer.parseInt(ConfigReader.getConfigVar("pocsag-port"));
try {
this.socket = new DatagramSocket(this.port);
this.socket.setSoTimeout(10);
} catch (SocketException e) {
System.err.println("error during socket creation: " + e.getMessage());
}
}
@Override
public void run() {
System.out.println(">> start listening on port " + port);
while (!this.stopped) {
/* listen for alerts */
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
try {
this.socket.receive(packet);
} catch (SocketTimeoutException e) {
continue;
} catch (IOException e) {
e.printStackTrace();
}
/* create new message from recieved string */
int length = packet.getLength();
byte[] data = packet.getData();
String recvStr = new String(data, 0, length);
recvStr = recvStr.replaceAll("[\n\r]", "#");
this.buffer.append(recvStr);
System.out.println(">> received data, buffer is: '" + buffer + "'");
this.checkMessageComplete();
}
this.socket.close();
System.out.println(">> stop listening on port " + port);
}
private void checkMessageComplete() {
while (buffer.indexOf("#") != -1) {
int start = buffer.indexOf("POCSAG1200:");
int end = buffer.indexOf("#");
if (start == -1) {
buffer.setLength(0);
} else if (start > end) {
buffer.delete(0, end+1);
} else if (start < end) {
String pocsag1200Str = buffer.substring(start, end);
this.messageQueue.offer(new Message(pocsag1200Str));
buffer.delete(0, end+1);
System.out.println(">> message complete, buffer is: '" + buffer + "'");
}
}
}
public synchronized void stop() {
this.stopped = true;
}
}
<file_sep>/ffw-alertmonitor/src/ffw/alertmonitor/Message.java
package ffw.alertmonitor;
import java.util.Vector;
public class Message {
private String pocsag1200Str;
private String address = null;
private String function = null;
private String alpha = null;
private boolean isComplete = false;
private boolean hasCoordinates = false;
private String latitude;
private String longitude;
private String shortKeyword;
private String alertLevel;
private Vector<String> keywords = new Vector<String>();
public Message(String pocsag1200Str) {
this.pocsag1200Str = pocsag1200Str;
}
public void evaluateMessageHead() {
//pocsag1200Str.startsWith("POCSAG1200:")
int startIndex, endIndex;
boolean addressExits = pocsag1200Str.contains("Address:");
boolean functionExits = pocsag1200Str.contains("Function:");
boolean alphaExits = pocsag1200Str.contains("Alpha:");
if (addressExits) {
startIndex = pocsag1200Str.indexOf("Address:") + 8;
endIndex = startIndex + 8;
this.address = pocsag1200Str.substring(startIndex, endIndex).trim();
}
if (functionExits) {
startIndex = pocsag1200Str.indexOf("Function:") + 9;
endIndex = startIndex + 3;
this.function = pocsag1200Str.substring(startIndex, endIndex).trim();
}
if (alphaExits) {
startIndex = pocsag1200Str.indexOf("Alpha:") + 6;
this.alpha = pocsag1200Str.substring(startIndex).trim();
}
this.isComplete = addressExits && functionExits && alphaExits;
}
public void evaluateAlphaString() {
if (this.getAlpha() != null) {
String[] alphaStr = this.cleanAlphaString().split("#");
if (isLatOrLong(alphaStr[0]) && isLatOrLong(alphaStr[1])) {
/* alert with latitude and longitude */
this.latitude = alphaStr[0];
this.longitude = alphaStr[1];
// TODO: alphaStr[2] := laufende Einsatznummer
if (this.isShortKeyword(alphaStr[3])) {
this.shortKeyword = alphaStr[3].substring(0, 1);
this.alertLevel = alphaStr[3].substring(1, 2);
} else {
this.shortKeyword = "-";
this.alertLevel = "-";
}
for (int i = 4; i < alphaStr.length; i++) {
this.keywords.add(alphaStr[i]);
}
this.hasCoordinates = true;
} else {
/* TODO: alert without geo coordinates */
}
}
}
private Boolean isShortKeyword(String shortKeyword) {
return shortKeyword.substring(0, 2).matches("[F|B|H|T|G|W][1-7]");
}
private boolean isLatOrLong(String latOrlong) {
return latOrlong.matches("\\d{1,2}\\.\\d{5,}");
}
private String cleanAlphaString() {
String[] alphaStr = this.getAlpha().split("/");
String newAlphaStr = "";
for (int i = 0; i < alphaStr.length; i++) {
String tmp = alphaStr[i].trim();
if (!(tmp.startsWith("<") && tmp.endsWith(">")) &&
tmp.length() != 0) {
newAlphaStr = newAlphaStr.concat(alphaStr[i] + "#");
}
}
return newAlphaStr;
}
/**
* Getter-Methods
*/
public String getPocsag1200Str() {
return this.pocsag1200Str;
}
public String getAddress() {
return this.address;
}
public String getFunction() {
return this.function;
}
public String getAlpha() {
return this.alpha;
}
public boolean isComplete() {
return this.isComplete;
}
public boolean hasCoordinates() {
return this.hasCoordinates;
}
public String getLatitude() {
return this.latitude;
}
public String getLongitude() {
return this.longitude;
}
public String getShortKeyword() {
return this.shortKeyword;
}
public String getAlertLevel() {
return this.alertLevel;
}
public Vector<String> getKeywords() {
return this.keywords;
}
}
<file_sep>/ffw-alertmonitor/script/alert.sh
echo "starting chrome..."
locationOfScript=$(dirname "$(readlink -e "$0")")
# start chrome in fullscreen mode with --kiosk
chromium-browser --kiosk file://$locationOfScript/../$1
<file_sep>/README.md
# ffw-alertsystem
Build requirements:
* current JDK (created with jdk 1.8, lesser should work as well)
* Apache ant
* RXTX library
Linux / Windows:
* run install.sh / install.bat
* the PATH variable must contain your java installation, the path to the ant building tool and
* also the script/alert.{sh|bat} script uses chrome to present the generated html-files, therefore
the path to "chrome.exe" has to be in the PATH variable as well
The RXTX library (for COM port communication) brings platform dependent libs:
* Linux:
* 'sudo apt-get install librxtx-java' for installation (needs 32-bit JVM?)
* use run.sh to execute alertmonitor.jar (which sets some path vars for the JVM)
* Windows: not yet tested
<file_sep>/ffw-alertmonitor/src/ffw/alertmonitor/HtmlBuilder.java
package ffw.alertmonitor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class HtmlBuilder {
private String html = "";
private Document doc;
public HtmlBuilder(Message msg) {
this.loadTemplate("html/template.html");
String timestamp = String.valueOf(new java.util.Date().getTime() / 1000);
this.setElement("#timestamp", timestamp);
this.setElement("#latitude", msg.getLatitude());
this.setElement("#longitude", msg.getLongitude());
this.setElement("#shortKeyword", msg.getShortKeyword());
this.setElement("#alertLevel", msg.getAlertLevel());
for (int i=0; i<msg.getKeywords().size(); i++) {
Element tag = this.doc.select("#furtherKeywords ul").first();
tag.append("<li>" + msg.getKeywords().get(i) + "</li>");
}
}
public String writeTemplate(String path) {
Date now = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy-HH.mm.ss");
String dateAndTime = sdf.format(now);
String fileName = path + dateAndTime + ".html";
FileWriter writer = null;
try {
writer = new FileWriter(new File(fileName));
writer.write(doc.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
return fileName;
}
private void loadTemplate(String templateFile) {
BufferedReader bufReader = null;
try {
bufReader = new BufferedReader(new FileReader(templateFile));
String line;
while((line = bufReader.readLine()) != null) {
this.html = this.html + '\n' + line;
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if(bufReader != null) {
try {
bufReader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
this.doc = Jsoup.parse(this.html);
}
private void setElement(String cssSelector, String content) {
Element tag = this.doc.select(cssSelector).first();
tag.html(content);
}
}
<file_sep>/ffw-alertmonitor/install.sh
if [ ! -d bin ]; then
echo ">> make dir bin"
mkdir bin/
fi
cd html
if [ ! -d alerts ]; then
echo ">> make dir html/alerts"
mkdir alerts
fi
cd ..
if [ ! -d log ]; then
echo ">> make dir log"
mkdir log
fi
echo ">> compiling source files ..."
javac -g:none \
-d bin/ \
-cp "lib/*" \
src/ffw/util/*.java \
src/ffw/alertmonitor/*.java
echo ">> let ant do the building work ..."
ant
<file_sep>/ffw-alertrecv/pocsag.c
rtl_fm -M nfm -s 22050 -f 173.255.000M -A fast -g 49.60 | multimon-ng -t raw -a POCSAG1200 -f alpha /dev/stdin >> /dev/stdout
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
void send(char* message) {
struct sockaddr_in serv_addr;
int sockfd, slen=sizeof(serv_addr);
if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
fprintf(stderr, "socket \n");
exit(1);
}
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(50000);
char addr[] = "192.168.1.255";
if (inet_aton(addr, &serv_addr.sin_addr) == 0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
if (sendto(sockfd, message, 1024, 0, (struct sockaddr*)&serv_addr, slen) == -1) {
fprintf(stderr, "sendto() \n");
exit(1);
}
close(sockfd);
}
<file_sep>/ffw-alertmonitor/html/alert.js
function setAlertKeywordAndLevel() {
var shortKeyword = $("#shortKeyword").text();
shortKeyword = $.trim(shortKeyword);
var alertLevel = $("#alertLevel").text();
var keyword = "";
if (shortKeyword == "F" || shortKeyword == "B") {
keyword = "Brandeinsatz";
} else if (shortKeyword == "H" || shortKeyword == "T") {
keyword = "Technische Hilfeleistung";
} else if (shortKeyword == "G") {
keyword = "Gefahrgutunfall";
} else if (shortKeyword == "W") {
keyword = "Einsatz auf Gewässer";
} else {
keyword = "Unbekannt";
}
$("#shortKeywordDesc").text(keyword);
var levels = new Array("Kleinbrand", "Mittelbrand", "Großbrand",
"TH klein", "TH mittel", "TH groß", "Gefahrgut");
$("#alertLevelDesc").text(levels[alertLevel - 1]);
// TODO: get some more pictures
$("#keywordImage").prepend('<img src="../images/F.png" />')
}<file_sep>/ffw-alertrecv/alertrecv.sh
echo "start receiving" | socat - udp-datagram:192.168.1.255:50000,broadcast
# send output as broadcast message:
rtl_fm -M nfm -s 22050 -f 173.255.000M -A fast -g 49.60 | multimon-ng -t raw -a POCSAG1200 -f alpha /dev/stdin | socat - udp-datagram:192.168.1.255:50000,broadcast
# send decoded string to a well known client:
#rtl_fm -M nfm -s 22050 -f 173.255.000M -A fast -g 49.60 | multimon-ng -t raw -a POCSAG1200 -f alpha /dev/stdin | nc -u 192.168.1.xxx 50000
# for output to bash:
#rtl_fm -M nfm -s 22050 -f 173.255.000M -A fast -g 49.60 | multimon-ng -t raw -a POCSAG1200 -f alpha /dev/stdin >> /dev/stdout
| 7f74ed863a0f34c520a00a4382b64bc524d5aeb5 | [
"JavaScript",
"Markdown",
"Java",
"C",
"Shell"
] | 12 | Shell | powelllens/ffw-alertsystem | 36ac5906137ccee2453bc2ea9a2436a4d2f48131 | 80054dcbf5eb314071e27909b1cd28fac5ea1c9b |
refs/heads/master | <repo_name>bigstupidx/TowerBalance<file_sep>/Assets/_hpmobile/Editor/PreloadSettings.cs
using UnityEngine;
using UnityEditor;
using System.IO;
[InitializeOnLoad]
public class PreloadSettings : MonoBehaviour
{
static PreloadSettings()
{
EditorSettings.externalVersionControl = ExternalVersionControl.Generic;
// if (EditorSettings.serializationMode != SerializationMode.ForceText)
// EditorSettings.serializationMode = SerializationMode.ForceText;
if (PlayerSettings.displayResolutionDialog != ResolutionDialogSetting.HiddenByDefault)
PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.HiddenByDefault;
PlayerSettings.Android.preferredInstallLocation = AndroidPreferredInstallLocation.PreferExternal;
PlayerSettings.accelerometerFrequency = 60;
PlayerSettings.defaultIsFullScreen = true;
PlayerSettings.statusBarHidden = true;
PlayerSettings.stripUnusedMeshComponents = true;
PlayerSettings.strippingLevel = StrippingLevel.UseMicroMSCorlib;
PlayerSettings.companyName = "HappyMobile";
#if UNITY_4_7
PlayerSettings.Android.targetDevice = AndroidTargetDevice.FAT;
#endif
#if UNITY_5_5_OR_NEWER
PlayerSettings.stripEngineCode = true;
#endif
if (PlayerSettings.apiCompatibilityLevel != ApiCompatibilityLevel.NET_2_0_Subset)
PlayerSettings.apiCompatibilityLevel = ApiCompatibilityLevel.NET_2_0_Subset;
Debug.Log("Auto Set Project Settings Finish!");
SetAndroidSettings();
SetIOSSettings();
}
static void SetAndroidSettings()
{
#if UNITY_5_5_OR_NEWER
PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.Android, true);
PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x);
PlayerSettings.Android.androidIsGame = true;
PlayerSettings.Android.androidTVCompatibility = true;
#endif
PlayerSettings.Android.preferredInstallLocation = AndroidPreferredInstallLocation.PreferExternal;
QualitySettings.SetQualityLevel(5, true);
}
static void SetIOSSettings()
{
PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPhoneAndiPad;
PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK;
#if UNITY_5_5_OR_NEWER
// 0 - None, 1 - ARM64, 2 - Universal.
PlayerSettings.SetArchitecture(BuildTargetGroup.iOS, 2);
PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.iOS, true);
PlayerSettings.SetScriptingBackend(BuildTargetGroup.iOS, ScriptingImplementation.IL2CPP);
PlayerSettings.iOS.allowHTTPDownload = true;
PlayerSettings.iOS.appInBackgroundBehavior = iOSAppInBackgroundBehavior.Suspend;
PlayerSettings.iOS.cameraUsageDescription = "Camera";
PlayerSettings.iOS.locationUsageDescription = "Location";
PlayerSettings.iOS.microphoneUsageDescription = "Microphone";
#endif
}
}
<file_sep>/README.md
cloned from
<EMAIL>:Paximillian/TowerBalance.git
 | 02671823815e7a7b734f365ac00cbebf67652ed9 | [
"Markdown",
"C#"
] | 2 | C# | bigstupidx/TowerBalance | 2fadd7ffa3e8e2d3faace65561b7387061bdcd8b | 671ed0576a1335801186fffebcd3587cf405ffec |
refs/heads/master | <file_sep>import firebase from 'firebase';
var firebaseConfig = {
// your firebase config
};
const fire = firebase.initializeApp(firebaseConfig);
export default fire;<file_sep>import React from 'react';
import {Link} from "react-router-dom";
import Navbar from "../components/NavBar/Navbar";
import './about.css';
const AboutPage = () => {
return (
<div className="page">
<div className="navBar">
<Navbar />
</div>
<div className="about-header">
About
</div>
<div className="about-content">
<div className="aboutLeft-content">
<header className="about-contentHeader">
<i class="fas fa-book-open"></i>Information
</header>
<p>
Just a little side project to learn
</p>
<p>
about web development.
</p>
<p style={{fontWeight: "bold"}}>
Current features:
</p>
<p>
Log in and log out
</p>
<p>
Routing to different pages
</p>
</div>
<div className="aboutRight-content">
<header className="about-contentHeader">
<i class="fas fa-clipboard-list"></i>To do list
</header>
<ul>
<li> Integrate a user system for profiles </li>
<li> Profile page set up w/ bio, pic, etc</li>
<li> Search bar and function</li>
<li> Finish contact form (submission)</li>
<li> Decorate each page </li>
<li> Clean up overall look </li>
<li> CSS for mobile</li>
</ul>
</div>
</div>
<div className="footer">
<div className="footerContent">
Being worked on by <NAME>
</div>
</div>
</div>
);
}
export default AboutPage;<file_sep>import React, { Component, useState } from 'react';
import { MenuItems } from "./MenuItems"
import fire from '../fire';
import { Button } from "../Button"
import { Link } from 'react-router-dom';
import './Navbar.css'
class Navbar extends Component {
state = {
clicked: false,
logginedIn: false
}
handleClick = () => {
this.setState({ clicked: !this.state.clicked })
}
render() {
var user = fire.auth().currentUser;
const handleLogOut = () => {
fire.auth().signOut().then(function() {
window.location.reload(false);
})
};
return(
<nav className="NavbarItems">
<h1 className="navbar-logo">
<a className="navbar-logo" href="/">
Social Hub
<i className="fab fa-react"></i>
</a>
</h1>
<div className="menu-icon" onClick={this.handleClick}>
<i className={this.state.clicked ? 'fas fa-times' : 'fas fa-bars'}></i>
</div>
<ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
{MenuItems.map((item, index) => {
return (
<li key={index}>
<Link className={item.cName} to={item.url}>
{item.title}
</Link>
</li>
)
})}
<i class="fas fa-grip-lines-vertical"></i>
</ul>
{user ? (
<Link className="loginBtn" to="/" >
<Button onClick={handleLogOut}>
Log out
</Button>
</Link>
) : (
<Link className="loginBtn" to="/login">
<Button>
Sign in
</Button>
</Link>
)}
</nav>
)
}
}
export default Navbar
<file_sep>import React, {useState} from 'react';
import {Link} from "react-router-dom";
import fire from '../components/fire';
import Navbar from "../components/NavBar/Navbar";
import contactImg from "./contactImg.svg"
import "./contact.css";
const ContactPage = () => {
var user = fire.auth().currentUser;
return (
<div className="page">
<div className="navBar">
<Navbar />
</div>
<div className="contact-header">
Need to contact us? Send us a message to us!
</div>
<div className="contact-content">
<div className="contactLeft-content">
<img src={contactImg} alt="homeImg"/>
</div>
<div className="contactRight-content">
<form className="contact-form">
<div className="form-group">
<h1> Full Name </h1>
<input placeholder="Your name" type="text" className="form-control"/>
</div>
<div className="form-group">
<h1> Email address </h1>
<input placeholder="Your email" type="email" className="form-control" />
</div>
<div className="form-group">
<h1> What are you contacting us for? </h1>
<textarea placeholder="Your message" id="msg" className="form-control" rows="5" />
</div>
<Link to="/contact" style={{textDecoration: "none"}}>
<button type="submit" className="submit">Submit</button>
</Link>
</form>
</div>
</div>
</div>
);
}
export default ContactPage;<file_sep>import React from 'react';
import {Link} from "react-router-dom";
import Navbar from "../components/NavBar/Navbar";
import homeImg from "./homeImg.svg";
import './home.css';
const MainPage = () => {
return (
<div className="page">
<div className="navBar">
<Navbar />
</div>
<div className="home-header">
Home
</div>
<div className="home-content">
<div className="homeLeft-content">
<img src={homeImg} alt="homeImg"/>
</div>
<div className="homeRight-content">
<header className="home-contentHeader">
<i class="fas fa-clipboard-list"></i>The plan
</header>
<p>
Create a website that allows users to compile their social medias
into one place.
</p>
<p style={{fontSize: "20px", marginTop: "10px", marginBottom: "20px", fontWeight: "bold"}}>
Technologies/Frameworks in use at the moment:
</p>
<ul style={{listStyleType: "none"}}>
<li><i className="fab fa-react"></i>React</li>
<li>Firebase</li>
</ul>
<p style={{fontSize: "25px", marginTop: "20px"}}>
Others will be used based off the needs for completion.
</p>
</div>
</div>
</div>
);
}
export default MainPage; | bbe48bbdd6a287f918bdac303bf7bad334ca69ad | [
"JavaScript"
] | 5 | JavaScript | rachoi/Social-Hub | 3ea1912b9a69378310f0ad6788949725ca2514a8 | d06bde568d1325bf3166d669850b9dc2db79e108 |
refs/heads/master | <file_sep>import React from 'react'
export default function UseEffectLab() {
const [windowWidth, setWindowWidth] = React.useState(0);
React.useEffect(() => {
function handleResize() {
setWindowWidth( window.innerWidth)
}
window.addEventListener('resize', handleResize)
})
return (
<div>
<h1>{windowWidth}</h1>
</div>
)
}
<file_sep>## W04D03HW
Follow these steps:
* Create a simple to-do app using React. A user should be able to enter the task items that get displayed as a to-do list in your app.

<file_sep>import React from 'react'
import { ThemeContext } from './UseContextLab';
export default function UseContextChild() {
let value = React.useContext(ThemeContext)
const [value1, setValue1] = React.useState("");
return (
<div className='UseContextChild-div'>
<button value='arabic' onClick={(e)=> setValue1(value.arabic)} >arabic</button>
<button value='english' onClick={(e)=> setValue1(value.english)}>english</button>
<button value='japanese' onClick={(e)=> setValue1(value.japanese)}>japanese</button>
<h1>{value1.text} </h1>
<img width='550px' src={value1.image}/>
</div>
)
}
<file_sep>import React from 'react'
import axios from 'axios';
export default function AxoisLab() {
const [img, setImg] = React.useState('');
const getData = () => {
axios.get(`https://dog.ceo/api/breeds/image/random`)
.then(data => setImg(data.data.message))
.catch(err => console.log(err))
}
return (
<div>
<img className='axoisLab-img' src={img}/>
<button onClick={e => getData()}>NEW IMG</button>
</div>
)
}
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
import Temperature from './Temperature';
import TodoHW from './TodoHW';
import W04D04HW from './W04D04HW';
import UseEffectLab from './useEffectLab';
import AxoisLab from './AxoisLab';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'
import UseContextLab from './UseContextLab';
// class App extends React.Component {
// constructor(props) {
// super(props);
// this.state = { name: 'Ghadah' };
// }
// componentWillMount(){
// console.log('This is executed before rendering')
// console.log(ReactDOM.findDOMNode(this))
// }
// componentDidMount(){
// console.log('This is executed after rendering')
// console.log(ReactDOM.findDOMNode(this))
// }
// render() {
// return <h1>Hello, {this.state.name}</h1>;
// }
// }
function App() {
return (
<Router>
<div className="App">
<h1 className='big-title'> MY HOMEWORKS AND LABS</h1>
<ul className='nav'>
<li><Link to="/TodoHW">TodoHW</Link></li>
<li><Link to="/Temperature">Temperature</Link></li>
<li><Link to="/useEffectLab">UseEffectLab</Link></li>
<li><Link to="/W04D04HW">W04D04HW</Link></li>
<li><Link to="/AxoisLab">AxoisLab</Link></li>
<li><Link to="/UseContextLab">UseContextLab</Link></li>
</ul>
<br/><br/> <hr/>
<Switch>
<div className='switch-div'>
<Route path="/TodoHW"><TodoHW /></Route>
<Route path="/Temperature"><Temperature /></Route>
<Route path="/useEffectLab"><UseEffectLab /></Route>
<Route path="/W04D04HW"><W04D04HW /></Route>
<Route path="/AxoisLab"><AxoisLab /></Route>
<Route path="/UseContextLab"><UseContextLab/></Route>
</div>
</Switch>
</div>
</Router>
);
}
export default App;
<file_sep>import React from 'react'
export default function Temperature() {
const [fahrenheit, setFahrenheit] = React.useState(0);
const [celsius, setCelsius] = React.useState(0);
const convertCTF = num => {
setFahrenheit(((num * 1.8) + 32).toFixed(1))
setCelsius(num)
}
const convertFTC = num => {
setCelsius(((num - 32) * .5556).toFixed(1))
setFahrenheit(num)
}
return (
<div>
<form className='temperature-form'>
<fieldset>
<legend>Enter temperature in Celsius:</legend>
<input value={celsius} onChange={e => convertCTF(e.target.value)}/>
</fieldset>
<fieldset>
<legend>Enter temperature in Fahrenheit:</legend>
<input value={fahrenheit} onChange={e => convertFTC(e.target.value)}/>
</fieldset>
</form>
</div>
)
}
| 5ece564d91901b736d19f14fd03eeb8be3b4fcc0 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | Ghadah-Ahmed/W04D03HW | 14fe00c5cf5b4db71c8cf800e529300a7a8f12af | 58572f1e3cab8185c9edab5d805affddab892c0d |
refs/heads/master | <repo_name>Arun-S-Singh/ga-learner-dsmp-repo<file_sep>/Probability-of-the-Loan-Defaulters/code.py
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load the dataframe
df = pd.read_csv(path)
#Code starts here
### TASK 1
p_a = len(df[df['fico'] > 700])/len(df)
p_b = len(df[df['purpose'] == 'debt_consolidation'])/len(df)
df1 = df[df['purpose'] == 'debt_consolidation']
p_a_b = (len(df1[df1['fico'] > 700])/len(df))/p_b
result = (p_a_b == p_a)
print(result)
### TASK 2
prob_lp = len(df[df['credit.policy']=='Yes'])/len(df)
prob_cs = len(df[df['paid.back.loan']=='Yes'])/len(df)
new_df = df[df['paid.back.loan']=='Yes']
prob_pd_cs = len(new_df[new_df['credit.policy']=='Yes'])/len(new_df)
bayes = (prob_pd_cs*prob_cs)/prob_lp
bayes = np.around(bayes,4)
print(bayes)
### TASK 3
df1 = df[df['paid.back.loan']=='No']
df1.groupby('purpose')['customer.id'].count().sort_values(ascending=False).plot(kind='bar')
plt.title('Distribution of Purpose for loans not paid back')
plt.show()
print(df1.shape)
### TASK 4
inst_median = df['installment'].median()
inst_mean = df['installment'].mean()
df['installment'].hist()
plt.axvline(inst_median, color='k', linestyle='dashed', linewidth=1)
plt.axvline(inst_mean, color='r', linestyle='dashed', linewidth=1)
plt.xlabel('Installment')
plt.title('Frequency of Installment')
plt.show()
df['log.annual.inc'].hist()
plt.axvline(df['log.annual.inc'].median(), color='k', linestyle='dashed', linewidth=1)
plt.axvline(df['log.annual.inc'].mean(), color='r', linestyle='dashed', linewidth=1)
plt.xlabel('Log of Annual income')
plt.title('Frequency of Log of Annual income')
plt.show()
<file_sep>/Numpy---Make-Sense-of-Census/README.md
### Project Overview
Numpy - Census task
<file_sep>/Sprint-2---Loan-Approval-Analysis/README.md
### Project Overview
Loan Approval Analysis
<file_sep>/EDA/code.py
# --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler, LabelEncoder
#Loading the data
data=pd.read_csv(path)
#Code starts here
#Rating>5
data = data[ data['Rating'] <= 5]
#distribution of app ratings
sns.distplot(data['Rating'])
# Check for nulls in data
print(data.isnull().sum())
# Treat - Drop the rows with NAN
data = data.dropna(axis=0)
#Genre
Genres = data['Genres'].unique()
print(Genres)
data['Genres'] = data['Genres'].apply(lambda row: str(row).split(';')[0])
Genres = data['Genres'].unique()
print(Genres)
# Highest/Lowest rating by Genres
grouped = data.groupby('Genres')['Rating'].mean().sort_values(ascending=False)
highest_rating = grouped[0]
lowest_rating = grouped[-1]
# Clean Installs and Price
data['Installs'] = data['Installs'].replace(',','')
data['Price'] = data['Price'].replace('$','')
#Update last updated column
data['Last Updated'] = pd.to_datetime(data['Last Updated'])
<file_sep>/Sprint-1-Python-Handling-Program-Flow/README.md
### Project Overview
Sprint-1-Python-Handling-Program-Flow
<file_sep>/Sprint-3---Matplotlib---Visualization-for-Company-Stakeholders/README.md
### Project Overview
Sprint 3 - Matplotlib - Visualization for Company Stakeholders
<file_sep>/Probability-of-the-Loan-Defaulters/README.md
### Project Overview
Probability of the Loan Defaulters
<file_sep>/Sprint-4---Statistics-Foundations/code.py
# --------------
#Header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#Reading of the file
data=pd.read_csv(path)
"""
In the column Gender, replace '-' with 'Agender' using "replace()" function. Check the distribution of Gender by ploting a graph with proper labels
"""
data['Gender'] = data['Gender'].replace('-','AGender')
sns.countplot(x=data['Gender'])
"""
Next check does good overpower evil or does evil overwhelm good? This can be done by checking the distribution of alignment through a proper chart. - Would there be any change in the majority alignment if the ones in neutral all took one side?
"""
sns.countplot(data['Alignment'])
"""
For any of the members, combat skills are really important to survive when they find themselves in unwanted situtations. Check out if combat relate to person's strength or it's intelligence? Be careful which correlation coefficient to use - Pearson's or Spearman's?
"""
fig, ax = plt.subplots(2, 3,sharex=True,figsize=(15,10))
sns.distplot(data['Combat'],ax=ax[0][0])
sns.distplot(data['Intelligence'],ax=ax[0][1])
sns.distplot(data['Strength'],ax=ax[0][2])
sns.regplot(data=data,x='Combat',y='Intelligence',ax=ax[1][0])
sns.regplot(data=data,x='Combat',y='Strength',ax=ax[1][1])
print('Correlation of Combat and Strength (Spearman)={0}'.format(data['Combat'].corr(data['Strength'],method='spearman')))
print('Correlation of Combat and Intelligence (Spearman)={0}'.format(data['Combat'].corr(data['Intelligence'],method='spearman')))
"""
Find out who are the best of the best in this superhero universe? This can be done by finding the value of quantile = 0.99 for the Total column and subset the dataframe whose Total is higher than this quantile. Create a list of the names from 'Name' associated with this subset and store in super_best_list in form of a list. These are the best of the best in the superhero universe
"""
super_best_names = list(data[data['Total'] > pd.Series(data['Total']).quantile(.99)]['Name'])
print(super_best_names)
"""
Correlation of all the vital parameters
"""
fig, ax = plt.subplots(1, 1,figsize=(5,5))
corr = data[['Intelligence','Strength','Speed','Durability','Power','Combat']].corr()
sns.heatmap(corr,annot=True,linewidths=.3,cmap='YlGnBu',ax=ax)
"""
Boxplots
"""
fig, ax = plt.subplots(3, 2,sharex=True,figsize=(5,5))
sns.boxplot(data['Intelligence'],ax=ax[0][0])
sns.boxplot(data['Strength'],ax=ax[0][1])
sns.boxplot(data['Speed'],ax=ax[1][0])
sns.boxplot(data['Durability'],ax=ax[1][1])
sns.boxplot(data['Power'],ax=ax[2][0])
sns.boxplot(data['Combat'],ax=ax[2][1])
# Code starts here
<file_sep>/Sprint-4---Statistics-Foundations/README.md
Statistics Foundation - Superheros <file_sep>/EDA/README.md
### Project Overview
EDA Project
<file_sep>/Legos/README.md
### Project Overview
Legos price estimation
<file_sep>/Sprint-1-Python-Fundamentals/README.md
### Project Overview
Project for Sprint 1 Python Fundamentals
<file_sep>/Sprint-2---Loan-Approval-Analysis/code.py
# --------------
# Importing header files
import numpy as np
import pandas as pd
from scipy.stats import mode
import warnings
warnings.filterwarnings('ignore')
#Reading file
bank_data = pd.read_csv(path)
#Code starts here
########## STEP 1 ##########
#bank_data.info()
#bank_data.describe()
# Check all categorical values.
categorical_var = bank_data.select_dtypes(include = 'object')
print(categorical_var)
# Check all categorical values.
numerical_var = bank_data.select_dtypes(include= 'number')
print(numerical_var)
########## STEP 2 ##########
# Create new dataframe banks
banks = bank_data.drop('Loan_ID',axis=1)
print(banks.isnull().sum())
bank_mode = banks.mode()
#print(type(bank_mode))
banks.fillna(bank_mode,inplace=True)
for x in banks.columns.values:
# df[x]=df[x].fillna(value=df_mode[x].iloc[0])
banks[x] = banks[x].fillna(value=bank_mode[x].iloc[0])
print(banks.isnull().sum().values.sum())
print(banks.shape)
########## STEP 3 ##########
#avg_loan_amount = banks.groupby(['Gender', 'Married', 'Self_Employed']).agg({'LoanAmount':'mean'})
avg_loan_amount = pd.pivot_table(banks,index=['Gender', 'Married', 'Self_Employed'],values='LoanAmount')
print(avg_loan_amount['LoanAmount'][1])
########## STEP 4 ##########
loan_approved_se = banks[(banks['Self_Employed'] == 'Yes') & (banks['Loan_Status'] == 'Y')].shape[0]
loan_approved_nse = banks[(banks['Self_Employed'] == 'No') & (banks['Loan_Status'] == 'Y')].shape[0]
percentage_se = np.around((loan_approved_se / 614) * 100 , 2)
percentage_nse = np.around((loan_approved_nse / 614) * 100 , 2)
print(percentage_se)
print(percentage_nse)
########## STEP 5 ##########
banks['Loan_Amount_Term'] = banks['Loan_Amount_Term'].apply(lambda x : x / 12)
big_loan_term = banks[ banks['Loan_Amount_Term'] >= 25].shape[0]
print(big_loan_term)
########## STEP 6 ##########
loan_groupby = banks.groupby('Loan_Status')
loan_groupby = loan_groupby['ApplicantIncome', 'Credit_History']
mean_values = loan_groupby.mean()
print(mean_values.iloc[1,0])
<file_sep>/Numpy---Make-Sense-of-Census/code.py
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
#Code starts here
census = np.concatenate((data,new_record),axis=0)
age = census[:,0]
max_age = np.max(age)
min_age = np.min(age)
age_mean = np.around(np.mean(age),2)
age_std = np.around(np.std(age),2)
race_0 = census[census[:,2] == 0]
race_1 = census[census[:,2] == 1]
race_2 = census[census[:,2] == 2]
race_3 = census[census[:,2] == 3]
race_4 = census[census[:,2] == 4]
len_0 = np.size(race_0)
len_1 = np.size(race_1)
len_2 = np.size(race_2)
len_3 = np.size(race_3)
len_4 = np.size(race_4)
min_race = np.min([len_0,len_1,len_2,len_3,len_4])
if len_0 == min_race:
minority_race = 0
elif len_1 == min_race:
minority_race = 1
elif len_2 == min_race:
minority_race = 2
elif len_3 == min_race:
minority_race = 3
elif len_4 == min_race:
minority_race = 4
senior_citizens = census[census[:,0] > 60]
working_hours_sum = np.sum(senior_citizens[:,6])
senior_citizens_len = np.size(senior_citizens,axis = 0)
avg_working_hours = np.around(working_hours_sum / senior_citizens_len ,2)
print(avg_working_hours)
high = census[census[:,1] > 10]
low = census[census[:,1] <= 10]
avg_pay_high = np.around(np.mean(high[:,7]),2)
avg_pay_low = np.around(np.mean(low[:,7]),2)
<file_sep>/Banking-Inference/README.md
### Project Overview
Banking Inference Project
<file_sep>/Banking-Inference/code.py
# --------------
#Importing header files
import pandas as pd
import scipy.stats as stats
import math
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.stats.weightstats import ztest
from statsmodels.stats.weightstats import ztest
from scipy.stats import chi2_contingency
import scipy
import warnings
warnings.filterwarnings('ignore')
#Sample_Size
sample_size=2000
#Z_Critical Score
z_critical = stats.norm.ppf(q = 0.95)
# Critical Value
critical_value = stats.chi2.ppf(q = 0.95, # Find the critical value for 95% confidence*
df = 6) # Df = number of variable categories(in purpose) - 1
#Reading file
data=pd.read_csv(path)
#Code starts here
##Confidence Interval
data_sample = data.sample(n=sample_size,random_state=0)
true_mean = np.around(data['installment'].mean(),2)
sample_mean = data_sample['installment'].mean()
sample_std = data_sample['installment'].std()
error_margin = z_critical * (sample_std/math.sqrt(sample_size))
confidence_interval = np.around((sample_mean - error_margin),2) , np.around((sample_mean + error_margin),2)
in_confidence_interval = ((true_mean >= confidence_interval[0]) & (true_mean <= confidence_interval[1]))
print('z-critical = {0}'.format(z_critical))
print('True mean = {0}'.format(true_mean))
print('Sample size = {0}'.format(sample_size))
print('Sample mean = {0}'.format(sample_mean))
print('Sample std = {0}'.format(sample_std))
print('Margin of error = {0}'.format(error_margin))
print('{0} :: {1} :: {2}'.format(confidence_interval , true_mean ,in_confidence_interval))
## CLT
sample_sizes = [20,50,100]
sample_means = []
for sample_size in sample_sizes:
print(sample_size)
for i in range(1,1001,1):
data_sample = data.sample(n=sample_size)
sample_mean = data_sample['installment'].mean()
sample_means.append(np.around(sample_mean,2))
fig, ax = plt.subplots()
plt.title('Sample Size = {0}'.format(sample_size), fontsize=15)
plt.hist(sample_means,normed=True)
plt.show()
## Small Business Interests
data['int.rate'] = data['int.rate'].str.rstrip('%').astype('float')
sbus = data[data['purpose']=='small_business']
#print(sbus.head())
value = data['int.rate'].mean()
int_population_std = sbus['int.rate'].std()
int_sample_size = sbus.shape[0]
#z_statistic_1, p_value_1 = ztest(x1=sbus['int.rate'],value=12,alternative='larger')
z_statistic_1, p_value_1 = ztest(x1=sbus['int.rate'],value=value,alternative='larger')
print('Small Business Sample Mean = {0}'.format(value))
print('Interest rate Population Deviation = {0} '.format(int_population_std))
print('Interest rate Sample Shape = {0} '.format(int_sample_size))
print('z_statistic_1 = {0}'.format(z_statistic_1))
print('p_value_1 = {0}'.format(p_value_1))
## Installment vs Loan Defaulting
x1 = data[data['paid.back.loan']=='No']['installment']
x2 = data[data['paid.back.loan']=='Yes']['installment']
z_statistic_2, p_value_2 = ztest(x1=x1,x2=x2,alternative='two-sided')
print('Count of not paid back loan = {0}'.format(x1.shape[0]))
print('Count of paid back loan = {0}'.format(x2.shape[0]))
print('z_statistic_2 = {0}'.format(z_statistic_2))
print('p_value_2 = {0}'.format(p_value_2))
## Purpose vs Loan Defaulting
observed = pd.crosstab(data['purpose'],data['paid.back.loan'],margins=False)
print(observed)
chi2, p, dof, ex = stats.chi2_contingency(observed)
print('Chi2 = {0} '.format(chi2))
print('Critical Value = {0}'.format(critical_value))
if chi2 > critical_value:
print('REJECT Null Hypothesis : Distribution of purpose across all customers is same')
else:
print('ACCEPT Null Hypothesis : Distribution of purpose across all customers is same')
| 449eb205f2bc444e115a22afca58e6fbae30a12a | [
"Markdown",
"Python"
] | 16 | Python | Arun-S-Singh/ga-learner-dsmp-repo | 082f1ba5e70e9539aedf80ae4c12618077afd5d3 | d1461f424beb2c406596f3b4390b46d8fda275bf |
refs/heads/master | <repo_name>Monofraps/dotfiles<file_sep>/install.sh
#!/bin/sh
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
COL_YELLOW=$ESC_SEQ"33;01m"
COL_BLUE=$ESC_SEQ"34;01m"
COL_MAGENTA=$ESC_SEQ"35;01m"
COL_CYAN=$ESC_SEQ"36;01m"
CURRENT_USER=$USER
YUM_COMMAND="dnf"
function info() {
echo -e "\n$COL_CYAN[dot] ⇒ $COL_RESET"$1""
}
function ok() {
echo -e "$COL_GREEN[ok]$COL_RESET"
}
function error() {
echo -e "$COL_RED[error]$COL_RESET \n"$1
}
function action() {
echo -en "$COL_YELLOW ⇒$COL_RESET $1..."
}
function require_yum() {
action "$YUM_COMMAND install $1"
STD_ERR="$(sudo $YUM_COMMAND install -q -y $1 2>&1 > /dev/null)"
if [ $? != "0" ]; then
error "failed to install $1! aborting..."
error $STD_ERR
exit -1
fi
ok
}
function require_yum_group() {
action "$YUM_COMMAND groupinstall -y $1"
STD_ERR="$(sudo $YUM_COMMAND groupinstall -q -y \"$1\" 2>&1 > /dev/null)"
if [ $? != "0" ]; then
error "failed to install group $1! aborting..."
error $STD_ERR
exit -1
fi
ok
}
function install_dotfiles() {
action "stow $1"
STD_ERR="$(stow $1 2>&1 > /dev/null)"
if [ $? != "0" ]; then
error "failed to install dotfiles $1! aborting..."
error $STD_ERR
exit -1
fi
ok
}
# Install a few things
sudo -v
info "Installing base packages..."
require_yum stow
require_yum_group "Development Tools"
require_yum automake
require_yum rxvt-unicode
require_yum zsh
require_yum vim-enhanced
require_yum libtool
require_yum gcc-c++
require_yum xclip
# bspwm build
info "Installing bspwm development packages..."
require_yum libxcb-devel
require_yum xcb-util-devel
require_yum xcb-util-wm
require_yum xcb-util-wm-devel
# sxhkd build
info "Installing sxhkd development packages..."
require_yum xcb-util-keysyms
require_yum xcb-util-keysyms-devel
info "Installing tiling wm utility packages..."
require_yum dmenu
require_yum feh
# compton build
info "Installing compton development packages..."
require_yum libX11-devel
require_yum libXcomposite-devel
require_yum libXdamage-devel
require_yum libXfixes-devel
require_yum libXext-devel
require_yum libXrender-devel
require_yum libXrandr-devel
require_yum libXinerama-devel
require_yum libconfig-devel
require_yum libdrm-devel
require_yum libGL-devel
require_yum dbus-devel
require_yum pcre-devel
require_yum asciidoc
# Build bspwm & sxhkd
cd sources
cd bspwm
info "bspwm..."
action "make"
make -s;ok
action "make install"
sudo PREFIX=/usr make -s install;ok
action "Installing desktop description"
sudo cp contrib/freedesktop/bspwm.desktop /usr/share/xsessions/bspwm.desktop;ok
action "Installing session init script"
sudo cp contrib/freedesktop/bspwm-session /usr/bin/bspwm-session;ok
cd .. # sources/bspwm
cd sxhkd
info "sxhkd"
action "make"
make -s;ok
action "make install"
sudo PREFIX=/usr make -s install;ok
cd .. # sources/sxhkd
cd compton
info "compton"
action "make"
make -s;ok
action "make install"
sudo PREFIX=/usr make -s install;ok
cd .. # sources/compton
cd .. # sources
info "Dotfiles: oh-my-zsh"
install_dotfiles zsh
info "Wallpapers"
install_dotfiles wallpapers
info "Fonts"
install_dotfiles fonts
action "fc-cache -f $HOME/.fonts"
STD_ERR="$(fc-cache -vf $HOME/.fonts 2>&1 > /dev/null)"
if [ $? != "0" ]; then
error "failed to update font cache! aborting..."
error $STD_ERR
exit -1
fi
ok
info "Dotfiles: bspwm"
install_dotfiles bspwm
info "Dotfiles: vim"
install_dotfiles vim
info "Additional binaries"
install_ditfiles editor
install_dotfiles git
info "System settings..."
action "Setting login shell to zsh"
sudo chsh -s /bin/zsh $CURRENT_USER 2> /dev/null > /dev/null;ok
<file_sep>/utils/bin/cbcopy
#!/bin/bash
# Copy file or pipe to Xorg clipboard
if [[ $(whoami) == root ]]; then
echo "Must not be root"
exit -1
fi
if ! [ -t 0 ]; then
# Copy stdin
echo -n "$(< /dev/stdin)" | xclip -selection clipboard
else
# Copy file
if [[ ! -f "$@" ]]; then
echo "File ${txtund}$filename${txtrst} doesn't exist" && exit -1
else
xclip -in -selection clipboard "$@"
fi
fi
<file_sep>/zsh/.zshrc
# Path to your oh-my-zsh installation.
export ZSH=$HOME/.oh-my-zsh
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="monofraps"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
export UPDATE_ZSH_DAYS=1
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
ZSH_CUSTOM=$HOME/.oh-my-zsh-custom
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Add wisely, as too many plugins slow down shell startup.
plugins=(git common-aliases dirhistory docker npm python sudo vagrant yum)
# User configuration
export PATH="/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/home/monofraps/bin:/opt/gradle-1.12/bin:/opt/gradle-1.12/bin"
# export MANPATH="/usr/local/man:$MANPATH"
DEV_DIR=$HOME/devel
DEVRC=$DEV_DIR/.devrc
if [ -f $DEVRC ]; then
alias dev="source $DEVRC && cd $DEV_DIR"
fi
source $ZSH/oh-my-zsh.sh
export EDITOR='vim'
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"
alias zrc="zshrc && source ~/.zshrc"
alias ll="ls -lh"
alias la="ls -lAFh"
alias l="ls -lFh"
unset GREP_OPTIONS
alias grep="/usr/bin/grep --color=auto --exclude-dir=.cvs --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn"
<file_sep>/git/bin/git-track
#!/bin/sh
branch=$(git rev-parse --abbrev-ref HEAD)
git branch $branch --set-upstream-to origin/$branch
<file_sep>/zsh/.oh-my-zsh-custom/themes/monofraps.zsh-theme
R=$fg_bold[red]
G=$fg_bold[green]
M=$fg_bold[magenta]
Y=$fg_bold[yellow]
B=$fg_bold[blue]
RESET=$reset_color
function prompt_char {
if [ $UID -eq 0 ]; then echo "#"; else echo $; fi
}
PROMPT='%{$G%}%n %{$B%}%(!.%1~.%~) %_$(prompt_char)%{$reset_color%} '
local return_code="%(?.%{$G%}.%{$R%})%? ↵%{$RESET%}"
RPROMPT='${return_code} %{$M%}[$(current_branch)$(git_prompt_status)%{$M%}]%{$RESET%}'
ZSH_THEME_GIT_PROMPT_PREFIX=""
ZSH_THEME_GIT_PROMPT_SUFFIX=""
ZSH_THEME_GIT_PROMPT_UNMERGED="%{$R%}*"
ZSH_THEME_GIT_PROMPT_DELETED="%{$R%}-"
ZSH_THEME_GIT_PROMPT_RENAMED="%{$M%}*"
ZSH_THEME_GIT_PROMPT_MODIFIED="%{$M%}*"
ZSH_THEME_GIT_PROMPT_ADDED="%{$G%}+"
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$R%}⚡"
ZSH_THEME_GIT_PROMPT_DIRTY="⚡"
<file_sep>/utils/bin/e
#!/bin/sh
if [ "$1" = "" ]; then
exec $EDITOR .
else
exec $EDITOR "$1"
fi
| a2b6d41c10faa2d9e602bb0d1a6db4fb7260d469 | [
"Shell"
] | 6 | Shell | Monofraps/dotfiles | b4fd42b4b64d309b4eb669b0d78c8577221b7283 | a9bd7a3653c7ebf619af325add1da1b843437241 |
refs/heads/main | <repo_name>ISIS-Motion-Control/TwinCAT_StartupCreator<file_sep>/TwinCAT - Startup Creator/Terminals/terminalEl5101.cs
using Windows.UI.Xaml.Controls;
namespace TwinCAT___Startup_Creator
{
public partial class MainPage : Page
{
private GenericTerminal terminalEL5101;
private terminalParameter[] el5101ParameterList = new terminalParameter[]
{
new terminalParameter(false, "Enc settings - Disable filter (0:False 1:True)", "PS", "0", "8000","08"),
new terminalParameter(false, "Enc settings - Enable microincrements (0:False 1:True)","PS","0","8000","0A"),
new terminalParameter(false, "Enc settings - Reversion of rotation (0:False 1:True)","PS","0","8000","0E"),
new terminalParameter(true,"Motor Settings - Max current (mA)","PS","5000","8010","01"),
new terminalParameter(true,"Motor Settings - Reduced current (mA)","PS","2500","8010","02"),
new terminalParameter(true,"Motor Settings - Nominal voltage (mV)","PS","50000","8010","03"),
new terminalParameter(true,"Motor Settings - Coil resistance (0.01Ohm)","PS","100","8010","04")
};
}
}<file_sep>/TwinCAT - Startup Creator/TerminalPage.xaml.cs
using System.ComponentModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace TwinCAT___Startup_Creator
{
/// <summary>
/// A generic page for generating a parameter list and user interface for a given terminal
/// </summary>
public partial class TerminalPage : Page
{
//List of transitions created as source for combobox elements in display
readonly ObservableCollection<string> ListOfTransitions = new ObservableCollection<string>() { "IP", "PS", "SP", "SO", "OS" };
private GenericTerminal _terminal;
/// <summary>
/// Method for accessing the terminal parameter data set by the user
/// </summary>
public GenericTerminal Terminal
{
get { return _terminal; }
set { _terminal = value; }
}
/// <summary>
/// Class constructor. Requires an input of the terminal type to display parameters for
/// </summary>
/// <param name="inputTerminal"></param>
public TerminalPage(GenericTerminal inputTerminal)
{
this.InitializeComponent();
Terminal = inputTerminal;
populatePage();
}
/// <summary>
/// Method for populating the page with XAML elements for user interaction.
/// Uses the local Terminal value
/// </summary>
public void populatePage()
{
int iRow = 1;
foreach (terminalParameter parameter in Terminal)
{
Binding includeBind = new Binding();
Binding commentBind = new Binding();
Binding dataBind = new Binding();
Binding transitionBind = new Binding();
includeBind.Mode = BindingMode.TwoWay;
includeBind.Source = parameter;
includeBind.Path = new PropertyPath("Include");
includeBind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
commentBind.Mode = BindingMode.OneWay;
commentBind.Source = parameter;
commentBind.Path = new PropertyPath("Name");
dataBind.Mode = BindingMode.TwoWay;
dataBind.Source = parameter;
dataBind.Path = new PropertyPath("Data");
dataBind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
transitionBind.Mode = BindingMode.TwoWay;
transitionBind.Source = parameter;
transitionBind.Path = new PropertyPath("Transition");
transitionBind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
//create Include parameter toggles
ToggleSwitch toggleSwitch = new ToggleSwitch();
toggleSwitch.SetValue(Grid.ColumnProperty, 0);
toggleSwitch.SetValue(Grid.RowProperty, iRow);
toggleSwitch.Margin = new Thickness(5, 0, 0, 0);
toggleSwitch.OffContent = string.Empty;
toggleSwitch.OnContent = string.Empty;
//Create textblock for parameter name/comment
TextBlock textBlock = new TextBlock();
textBlock.SetValue(Grid.ColumnProperty, 1);
textBlock.SetValue(Grid.RowProperty, iRow);
textBlock.HorizontalAlignment = HorizontalAlignment.Stretch;
textBlock.VerticalAlignment = VerticalAlignment.Center;
textBlock.Margin = new Thickness(25, 0, 0, 0);
//Create textbox for data manipulation
TextBox textBox = new TextBox();
textBox.SetValue(Grid.ColumnProperty, 2);
textBox.SetValue(Grid.RowProperty, iRow);
textBox.HorizontalAlignment = HorizontalAlignment.Stretch;
textBox.VerticalAlignment = VerticalAlignment.Center;
//Create combobox for transition
ComboBox comboBox = new ComboBox();
comboBox.SetValue(Grid.ColumnProperty, 3);
comboBox.SetValue(Grid.RowProperty, iRow);
comboBox.HorizontalAlignment = HorizontalAlignment.Stretch;
comboBox.VerticalAlignment = VerticalAlignment.Center;
comboBox.Margin = new Thickness(5, 5, 5, 5);
comboBox.ItemsSource = ListOfTransitions;
//Set data binds
BindingOperations.SetBinding(toggleSwitch, ToggleSwitch.IsOnProperty, includeBind);
BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, commentBind);
BindingOperations.SetBinding(textBox, TextBox.TextProperty, dataBind);
BindingOperations.SetBinding(comboBox, ComboBox.SelectedItemProperty, transitionBind);
iRow++;
grid.Children.Add(toggleSwitch);
grid.Children.Add(textBlock);
grid.Children.Add(textBox);
grid.Children.Add(comboBox);
}
}
}
}
<file_sep>/TwinCAT - Startup Creator/Terminals/terminalEL7047.cs
using Windows.UI.Xaml.Controls;
namespace TwinCAT___Startup_Creator
{
public partial class MainPage : Page
{
private GenericTerminal terminalEL7047;
private terminalParameter[] el7047ParameterList = new terminalParameter[]
{
new terminalParameter(false, "Enc settings - Disable filter (0:False 1:True)", "PS", "0", "8000","08"),
new terminalParameter(false, "Enc settings - Enable microincrements (0:False 1:True)","PS","0","8000","0A"),
new terminalParameter(false, "Enc settings - Reversion of rotation (0:False 1:True)","PS","0","8000","0E"),
new terminalParameter(true,"Motor Settings - Max current (mA)","PS","5000","8010","01"),
new terminalParameter(true,"Motor Settings - Reduced current (mA)","PS","2500","8010","02"),
new terminalParameter(true,"Motor Settings - Nominal voltage (mV)","PS","50000","8010","03"),
new terminalParameter(true,"Motor Settings - Coil resistance (0.01Ohm)","PS","100","8010","04"),
new terminalParameter(false,"Motor Settings - Motor EMF (###)","PS","0","8010","05"),
new terminalParameter(true,"Motor Settings - Fullsteps","PS","200","8010","06"),
new terminalParameter(false,"Motor Settings - Encoder Increments (4-fold)","PS","0","8010","07"),
new terminalParameter(false,"Controller Settings - Kp factor (curr) (###)","PS","400","8011","01"),
new terminalParameter(false,"Controller Settings - Ki factor (curr) (###)","PS","4","8011","02"),
new terminalParameter(true,"Features - Speed Range (0:1k, 1:2k, 2:4k, 3:8k, 4:16k, 5:32k)","PS","1","8012","05"),
new terminalParameter(true,"Feedback type (0: encoder, 1: internal counter)","PS","1","8012","08"),
new terminalParameter(true,"Invert motor polarity (0:False 1:True)","PS","0","8012","09"),
new terminalParameter(false, "Error on step lost (0:False 1:True)","PS", "0","8012","0A"),
new terminalParameter(false, "Fan cartridge present (0:False 1:True)","PS","0","8012","0B")
};
}
}<file_sep>/TwinCAT - Startup Creator/MainPage.xaml.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Popups;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace TwinCAT___Startup_Creator
{
/* HOW TO ADD NEW TERMINALS
* Add the terminal name to the ListOfTerminals
* Create a 'Page' instance for the terminal
* Create a new partial class for the parameter information
* Under MainPage() constructor setup the variables and create a terminal page instance with the terminal information as an input
* Write a CASE for the terminal under "generateStartupButton_Click"
* Write a CASE for the frame population under "terminalComboBox_SelectionChanged"
*/
/// <summary>
/// Main display page for the COE startup creation tool
/// </summary>
public partial class MainPage : Page
{
readonly ObservableCollection<string> ListOfTerminals = new ObservableCollection<string>() { "EL7041", "EL7047", "EL5101" }; //List of terminals currently supported in the tool that asks as a source fo combobox in UI
string selectedTerminal; //Stores the value of the combobox (i.e. the user selection for terminal)
const string quoteMark = "\""; //constant used for easier creation of strings where a quotation mark is required
Windows.Storage.StorageFolder folder; //User selected directory for storing the XML output
//Terminal pages - instances created as MainPage initialised
Page el7041Page;
Page el7047Page;
Page el5101Page;
//Need to clean these up or find a better way to declare them - might just move to end or can I create another partial for MainPage and dump them there for ease of access
/// <summary>
/// Constructor for main page. Initialises and instances the terminal pages
/// </summary>
public MainPage()
{
this.InitializeComponent();
terminalEL7041 = new GenericTerminal(el7041ParameterList);
el7041Page = new TerminalPage(terminalEL7041);
terminalEL7047 = new GenericTerminal(el7047ParameterList);
el7047Page = new TerminalPage(terminalEL7047);
terminalEL5101 = new GenericTerminal(el5101ParameterList);
el5101Page = new TerminalPage(terminalEL5101);
}
/// <summary>
/// Method for displaying a string to the user
/// </summary>
/// <param name="text2show"></param>
private async void messageBoxPopup(string text2show)
{
var messageDialog = new MessageDialog(text2show);
await messageDialog.ShowAsync();
}
/// <summary>
/// Method for creating and exporting the startup list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void generateStartupButton_Click(object sender, RoutedEventArgs e)
{
//Check for a folder selection first
if (folder==null)
{
messageBoxPopup("Select a save directory before generating file");
return;
}
List<string> startupString = new List<string>(); //List created for storing the xml startup string
GenericTerminal terminal4Startup; //Creating an object to hold the GenericTerminal output from the TerminalPage instances
Windows.Storage.StorageFile startupFile;
switch (terminalSelectionComboBox.SelectedItem.ToString())
{
case "EL7041":
terminal4Startup = ((TerminalPage)el7041Page).Terminal; //Recast from Page to TerminalPage
terminal4Startup.Reset(); //Reset required as foreach position does not seem to be resetting
startupString = beckhoffBoilerPlateStart(startupString);
//foreach (terminalParameter param in terminalEL7041)
foreach (terminalParameter param in terminal4Startup) //Now we loop through the generic
{
if( param.Include)
{
startupString = beckhoffInitCmd(startupString, param);
}
}
startupString = beckhoffBoilerPlateEnd(startupString);
startupFile = await folder.CreateFileAsync(fileName.Text + @".xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteLinesAsync(startupFile, startupString);
break;
case "EL7047":
terminal4Startup = ((TerminalPage)el7047Page).Terminal;
terminal4Startup.Reset();
startupString = beckhoffBoilerPlateStart(startupString);
foreach (terminalParameter param in terminal4Startup) //Now we loop through the generic
{
if (param.Include)
{
startupString = beckhoffInitCmd(startupString, param);
}
}
startupString = beckhoffBoilerPlateEnd(startupString);
startupFile = await folder.CreateFileAsync(fileName.Text + @".xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteLinesAsync(startupFile, startupString);
break;
case "EL5101":
terminal4Startup = ((TerminalPage)el5101Page).Terminal;
terminal4Startup.Reset();
startupString = beckhoffBoilerPlateStart(startupString);
//foreach (terminalParameter param in terminalEL7041)
foreach (terminalParameter param in terminal4Startup) //Now we loop through the generic
{
if (param.Include)
{
startupString = beckhoffInitCmd(startupString, param);
}
}
startupString = beckhoffBoilerPlateEnd(startupString);
startupFile = await folder.CreateFileAsync(fileName.Text + @".xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteLinesAsync(startupFile, startupString);
break;
}
}
/// <summary>
/// Takes in and returns a startupstring list and adds the generic required beckhoff startup information for starting the xml file
/// </summary>
/// <param name="startupString"></param>
/// <returns></returns>
public List<string> beckhoffBoilerPlateStart(List<string> startupString)
{
startupString.Add(@"<?xml version=" + quoteMark + "1.0" + quoteMark + " encoding=" + quoteMark + "utf-8" + quoteMark + "?>");
startupString.Add(@"<EtherCATMailbox>");
startupString.Add("\t<CoE>");
startupString.Add("\t\t<InitCmds>");
return startupString;
}
/// <summary>
/// Takes in and returns a startupstring list and adds the generic required beckhoff startup information for ending the xml file
/// </summary>
/// <param name="startupString"></param>
/// <returns></returns>
public List<string> beckhoffBoilerPlateEnd(List<string> startupString)
{
startupString.Add("\t\t</InitCmds>");
startupString.Add("\t</CoE>");
startupString.Add(@"</EtherCATMailbox>");
return startupString;
}
/// <summary>
/// Takes in and returns the startuplist string. Adds individual COE parameter xml information to the startup.
/// </summary>
/// <param name="startupString"></param>
/// <param name="parameter"></param>
/// <returns></returns>
public List<string> beckhoffInitCmd(List<string> startupString, terminalParameter parameter)
{
string decIndex = (Convert.ToInt64(parameter.Index, 16)).ToString(); //Address index converted to DEC from HEX
string decSubIndex = (Convert.ToInt64(parameter.SubIndex, 16)).ToString(); //Address subindex converted to DEC from HEX
//Data needs to be converted from DEC to LSB HEX
string dataConversion = Convert.ToInt64(parameter.Data, 10).ToString("x4"); //perform initial conversion to HEX in lower case format ("x4" modifier)
int dataLength = dataConversion.Length; //determine length of data for use in MSB to LSB conversion
char[] flippedData = new char[dataLength]; //create char array for holding the MSB/LSB converted data
//iterate over flipping byte positions, double increment of i required as each byte is two chars
for(int i=0; i<dataLength; i++)
{
flippedData[i] = dataConversion[dataLength -2 - i];
flippedData[i + 1] = dataConversion[dataLength - 1 - i];
i++;
}
string chars2Str = new string(flippedData); //convert char array back to string for entry in to COE startup string
//Populate the startupstring with parameter data
startupString.Add("\t\t\t<InitCmd>");
startupString.Add("\t\t\t\t<Transition>" + parameter.Transition + "</Transition>");
startupString.Add("\t\t\t\t<Timeout>" + parameter.Timeout + "</Timeout>");
startupString.Add("\t\t\t\t<Ccs>" + parameter.CCS + "</Ccs>");
startupString.Add("\t\t\t\t<Comment>" + parameter.Name + "</Comment>");
startupString.Add("\t\t\t\t<Index>" + decIndex+ "</Index>");
startupString.Add("\t\t\t\t<SubIndex>" + decSubIndex + "</SubIndex>");
startupString.Add("\t\t\t\t<Data>" + chars2Str + "</Data>");
startupString.Add("\t\t\t</InitCmd>");
return startupString;
}
/// <summary>
/// Method for repopulating the mainpage terminalframe when a new terminal is selected with the dropdown box.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void terminalComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedTerminal = terminalSelectionComboBox.SelectedItem.ToString();
switch (selectedTerminal)
{
case "EL7041":
terminalFrame.Content = el7041Page;
break;
case "EL7047":
terminalFrame.Content = el7047Page;
break;
case "EL5101":
terminalFrame.Content = el5101Page;
break;
}
}
/// <summary>
/// Method for selecting a directory to export startup xml to
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void folderSelectButton_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FolderPicker folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
}
}
}
/// <summary>
/// Class for a generic terminal that can hold a list of terminal parameters for iterating over with a foreach
/// Doesn't work perfectly as the reset is not implemented properly, something about needing to return a new instance of this as opposed to the instance of it.
/// More googling required. Can be made to work as is just requires a manual reset before iterating over.
/// </summary>
public class GenericTerminal : IEnumerator, IEnumerable
{
private terminalParameter[] _terminalParameterList;
int position = -1;
public GenericTerminal(terminalParameter[] terminalParameterList)
{
_terminalParameterList = terminalParameterList;
}
//IEnumerator and IEnumerable require these methods.
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
//IEnumerator
public bool MoveNext()
{
position++;
return (position < _terminalParameterList.Length);
}
//IEnumerable
public void Reset()
{
position = -1;
}
public object Current
{
get { return _terminalParameterList[position]; }
}
public object parameter(int paramIndex)
{
return _terminalParameterList[paramIndex];
}
}
/// <summary>
/// Class to define elements required for a COE startup parameter
/// </summary>
public class terminalParameter
{
private bool _include = false;
private string _name;
private string _transition;
private string _data;
private string _index;
private string _subindex;
private string _ccs;
private string _timeout;
public terminalParameter(bool Include, string Name, string Transition, string Data, string Index, string SubIndex, string CCS = "1", string Timeout = "0")
{
_include = Include;
_name = Name;
_transition = Transition;
_data = Data;
_index = Index;
_subindex = SubIndex;
_ccs = CCS;
_timeout = Timeout;
}
public bool Include
{
get { return _include; }
set { _include = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Transition
{
get { return _transition; }
set { _transition = value; }
}
public string Data
{
get { return _data; }
set { _data = value; }
}
public string Index
{
get { return _index; }
set { _index = value; }
}
public string SubIndex
{
get { return _subindex; }
set { _subindex = value; }
}
public string CCS
{
get { return _ccs; }
set { _ccs = value; }
}
public string Timeout
{
get { return _timeout; }
set { _timeout = value; }
}
}
public class TerminalEL7041 : IEnumerator,IEnumerable
{
private terminalParameter[] terminalParameterList;
int position = -1;
public TerminalEL7041()
{
terminalParameterList = new terminalParameter[]
{
new terminalParameter(false, "Enc settings - Disable filter (0:False 1:True)", "PS", "0", "8000","08"),
new terminalParameter(false, "Enc settings - Enable microincrements (0:False 1:True)","PS","0","8000","0A"),
new terminalParameter(false, "Enc settings - Reversion of rotation (0:False 1:True)","PS","0","8000","0E"),
new terminalParameter(true,"Motor Settings - Max current (mA)","PS","5000","8010","01"),
new terminalParameter(true,"Motor Settings - Reduced current (mA)","PS","2500","8010","02"),
new terminalParameter(true,"Motor Settings - Nominal voltage (mV)","PS","50000","8010","03"),
new terminalParameter(true,"Motor Settings - Coil resistance (0.01Ohm)","PS","100","8010","04"),
new terminalParameter(false,"Motor Settings - Motor EMF (###)","PS","0","8010","05"),
new terminalParameter(true,"Motor Settings - Fullsteps","PS","200","8010","06"),
new terminalParameter(false,"Motor Settings - Encoder Increments (4-fold)","PS","0","8010","07"),
new terminalParameter(false,"Controller Settings - Kp factor (curr) (###)","PS","400","8011","01"),
new terminalParameter(false,"Controller Settings - Ki factor (curr) (###)","PS","4","8011","02"),
new terminalParameter(false,"Controller Settings - Inner window (###)","PS","0","8011","03"),
new terminalParameter(false,"Controller Settings - Outer window (###)","PS","0","8011","05"),
new terminalParameter(false,"Controller Settings - Filter cut off frequency (###)","PS","0","8011","06"),
new terminalParameter(false,"Controller Settings - Ka factor (curr) (###)","PS","100","8011","07"),
new terminalParameter(false,"Controller Settings - Kd factor (curr) (###)","PS","100","8011","08"),
new terminalParameter(true,"Features - Speed Range (0:1k, 1:2k, 2:4k, 3:8k, 4:16k, 5:32k)","PS","1","8012","05"),
new terminalParameter(true,"Feedback type (0: encoder, 1: internal counter)","PS","1","8012","08"),
new terminalParameter(true,"Invert motor polarity (0:False 1:True)","PS","0","8012","09")
};
}
//IEnumerator and IEnumerable require these methods.
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
//IEnumerator
public bool MoveNext()
{
position++;
return (position < terminalParameterList.Length);
}
//IEnumerable
public void Reset()
{
position = -1;
}
public object Current
{
get { return terminalParameterList[position]; }
}
public object parameter(int paramIndex)
{
return terminalParameterList[paramIndex];
}
}
}
| 1c7180f5851d4ca6b4c4b205e9029f44b7a849b6 | [
"C#"
] | 4 | C# | ISIS-Motion-Control/TwinCAT_StartupCreator | d154d5e66d3b4b6a473a6969d8b1f537c7448e94 | 131430de497703c36a00abf38377efca7f3cc481 |
refs/heads/master | <file_sep># Procedural Texture Test
This is me messing around with [perlin][perlin] and [simplex noise][simplex]. The aim was to use it as a dynamic-size background for something on a website I was making, but it is way too slow for that.
`perlin.js` is taken from [josephg/noisejs][noisejs]. `shaders.js` contains all the interesting stuff that I made. The terminology may be wrong, but I call functions which take as input an `(x, y)` coordinate, and output a `[r, g, b, a]` array *shaders*. I call functions which take as input shaders, and output a shader *blenders*.
There is lots of global state; everything is just hooked up to window. But I don't care, because it was just a test.
[noisejs]: https://github.com/josephg/noisejs
[perlin]: https://en.wikipedia.org/wiki/Perlin_noise
[simplex]: https://en.wikipedia.org/wiki/Simplex_noise
<file_sep>(function() {
/* These shaders return a [r, g, b, a] */
/* If faster performance is required, this can be encoded into a single integer */
function packColour(r, g, b, a) {
return (r<<24|g<<16|b<<8|a);
}
//function unpackColour
window.shaders = {
simplex: function (size) {
return function(x, y) {
var value = noise.simplex2(x/size, y/size);
value = (value+1)*128;
return [value, value, value, 255];
};
},
perlin: function(size) {
return function(x, y) {
var value = noise.perlin2(x/size, y/size);
value = (value+1)*128;
return [value, value, value, 255];
}
},
constant: function(colour) {
return function(x, y) {
return colour;
};
},
grain: function(density) {
return function(x, y) {
return [255, 255, 255, Math.random()*255];
};
}
};
// Blenders are functions that return shaders which combine shaders.
window.blenders = {};
window.blenders.pixelWise = function(combine) {
return function(shaders) { // Blender
return function(x, y) { // Shader
// Evaluate the shaders for the pixel
var pixels = [];
for(var i = 0, length = shaders.length; i < length; i++) {
pixels.push(shaders[i](x, y));
}
// Combine the pixels
return combine(pixels);
}
}
};
// transform is a function which takes 2-n components and combines them into 1 component
window.blenders.componentWise = function(combine) {
return window.blenders.pixelWise(function(pixels) {
var length = pixels.length;
// Transform each component
var components, result = [];
for(var i=0; i <= 3; i++) {
components = [];
for(var j=0; j < length; j++) {
components.push(pixels[j][i]);
}
result[i] = combine(components);
}
return result;
});
};
window.blenders.average = window.blenders.componentWise(function(components) {
var sum = 0;
for(var i = 0, length = components.length; i < length; i++) {
sum += components[i];
}
return sum / length;
});
window.blenders.additive = window.blenders.componentWise(function(components) {
var sum = 0;
for(var i = 0, length = components.length; i < length; i++) {
sum += components[i];
}
return Math.min(255, sum)
});
window.blenders.multiply = window.blenders.componentWise(function(components) {
return (components[0]*components[1])/255;
});
window.blenders.screen = window.blenders.componentWise(function(components) {
return 255 - ((255-components[0])*(255-components[1]))/255;
});
// At the moment, this only blends 2 layers
window.blenders.layer = window.blenders.pixelWise(function(pixels) {
var fg = pixels[0],
bg = pixels[1];
// Performance optimisation
if(fg[3] === 0) {
return bg;
}
var nfg = [fg[0]/255, fg[1]/255, fg[2]/255, fg[3]/255],
nbg = [bg[0]/255, bg[1]/255, bg[2]/255, bg[3]/255];
var out_alpha = nfg[3] + nbg[3] * (1 - nfg[3]);
if(out_alpha === 0) {
return [0, 0, 0, 0];
} else {
var out_pixel = [];
for(var i = 0; i < 3; i++) {
var component = ( nfg[i] * nfg[3] + (nbg[i] * nbg[3]) * ( 1 - nfg[3] ) ) / out_alpha;
out_pixel.push(component*255);
}
out_pixel.push(out_alpha*255);
return out_pixel;
}
});
})();
| 7580f71558b3042b08415c2fe4e4e8e908c35c9e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | cameron-martin/procedural_textures | 3d2be3a2464d1c85c2106ef4620e3c58aa43f6df | f6e01a383c258a3db266858272dc166075cb8d47 |
refs/heads/master | <file_sep>def oxford_comma(array)
if array.size > 2
postion = array.pop
array.push("and #{postion}")
array.join(", ")
elsif array.size == 2
postion = array.pop
array.push(" and #{postion}")
array.join
elsif array.size == 1
array.join
end
end
# array = ["kiwi", "durian", "starfruit"]
# puts oxford_comma(array)
| fceadd038619c07b1c994c4a0a76740dda1cf0a3 | [
"Ruby"
] | 1 | Ruby | 1987suhaib/oxford-comma-re-coded-000 | d8b85665dc81b98a6a89c3c72eb979dda8ec26b4 | e199fc3171e0c886e1b8871916349561c758152d |
refs/heads/master | <repo_name>howardano/QT-Calculator<file_sep>/Calculator.cpp
#include "Calculator.h"
Calculator::Calculator(QWidget* pwgt/*= 0 */) : QWidget(pwgt) {
pvbxLayout = new QVBoxLayout;
m_plcd = new QLCDNumber(12);
m_plcd->setMinimumSize(150, 50);
m_plcd->setMaximumSize(1100, 50);
pvbxLayout->addWidget(m_plcd);
pvbxLayout->setContentsMargins(3, 3, 3, 3);
pvbxLayout->setSpacing(10);
phbxLayout = new QHBoxLayout;
ptopLayoutE = new QGridLayout;
QString aButtonsE[5][4] = {{"sinh", "sin", "e", "x²"},
{ "cosh", "cos", "ln", "x³"},
{"tanh", "tan", "log", "x^y"},
{"n!", "pi", "√", "؆"},
{"pi^x", "Mod", "∛", "e^x"}
};
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 4; ++j) {
ptopLayoutE->addWidget(createButtonNormal(aButtonsE[i][j]), i+1, j);
}
}
QChar aButtons[4][4] = {{'7', '8', '9', '/'},
{'4', '5', '6', '*'},
{'3', '2', '1', '-'},
{'0', '.', '=', '+'}
};
ptopLayout = new QGridLayout;
ptopLayout->addWidget(createButtonNormal("%"), 0, 0);
ptopLayout->addWidget(createButtonNormal("√"), 0, 1);
ptopLayout->addWidget(createButtonNormal("CE"), 0, 3);
ptopLayout->addWidget(createButtonNormal("+/-"), 0, 2);
m_pradNormal = new QRadioButton("&Normal");
m_pradEngineer = new QRadioButton("&Engineer");
m_pradNormal->setChecked(true);
connect(m_pradNormal, SIGNAL(clicked()), SLOT(slotButtonSwitched()));
connect(m_pradEngineer, SIGNAL(clicked()), SLOT(slotButtonSwitched()));
pvbxLayout->addWidget(m_pradNormal, 0);
pvbxLayout->addWidget(m_pradEngineer, 1);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
ptopLayout->addWidget(createButtonNormal(aButtons[i][j]), i+1, j);
}
}
wgt1.setLayout(ptopLayout);
wgt2.setLayout(ptopLayoutE);
m_pradNormal->click();
phbxLayout->addWidget(&wgt2);
phbxLayout->addWidget(&wgt1);
wgt2.setVisible(false);
wgt3.setLayout(phbxLayout);
pvbxLayout->addWidget(&wgt3);
wgt4.setWindowTitle("Calculator (ordinary)");
wgt4.setMinimumSize(550, 400);
wgt4.setMaximumSize(550, 400);
wgt4.setLayout(pvbxLayout);
wgt4.show();
}
QPushButton* Calculator::createButtonNormal(const QString& str) {
QPushButton* pcmd = new QPushButton(str);
pcmd->setMinimumSize(120, 40);
pcmd->setMaximumSize(120, 40);
connect(pcmd, SIGNAL(clicked()), SLOT(slotButtonClicked()));
return pcmd;
}
void Calculator::slotButtonSwitched() {
if (m_pradEngineer->isChecked()) {
wgt2.setVisible(true);
wgt4.setWindowTitle("Calculator (engineer)");
wgt4.resize(1100, 320);
wgt4.setMinimumSize(1100, 400);
wgt4.setMaximumSize(1100, 400);
return;
}
if (m_pradNormal->isChecked()) {
wgt2.setVisible(false);
wgt4.setWindowTitle("Calculator (ordinary)");
wgt4.resize(550, 320);
wgt4.setMinimumSize(550, 400);
wgt4.setMaximumSize(550, 400);
return;
}
}
void Calculator::calculate() {
qreal helper = 0;
qreal fOperand2 = m_stk.pop().toFloat();
QString strOperation = m_stk.pop();
qreal fOperand1 = m_stk.pop().toFloat();
qreal fResult = 0;
if (strOperation == "Mod") {
int a = fOperand1;
int b = fOperand2;
fResult = a % b;
}
if (strOperation == "x^y") {
fResult = pow(fOperand1, fOperand2);
}
if (strOperation == "؆") {
fResult = pow(fOperand1, 1/fOperand2);
}
if (strOperation == "+") {
fResult = fOperand1 + fOperand2;
}
if (strOperation == "-") {
fResult = fOperand1 - fOperand2;
}
if (strOperation == "/") {
fResult = fOperand1 / fOperand2;
}
if (strOperation == "*") {
fResult = fOperand1 * fOperand2;
}
m_strDisplay = fResult;
m_plcd->display(fResult);
}
void Calculator::calculate1() {
qreal helper = 0;
QString strOperation = m_stk.pop();
qreal fOperand1 = m_stk.pop().toFloat();
qreal fResult = 0;
if (strOperation == "n!") {
int lock = 1;
helper++;
for (int i = 0; i < fOperand1; ++i) {
helper *= lock;
lock++;
}
fResult = helper;
}
if (strOperation == "∛") {
helper = pow(fOperand1, 1/3);
fResult = helper;
}
if (strOperation == "log") {
helper = log10(fOperand1);
fResult = helper;
}
if (strOperation == "ln") {
helper = log(fOperand1);
fResult = helper;
}
if (strOperation == "pi^x") {
helper = pow(3.1415926535, fOperand1);
fResult = helper;
}
if (strOperation == "tanh") {
helper = tanh(fOperand1);
fResult = helper;
}
if (strOperation == "tan") {
helper = tan(fOperand1);
fResult = helper;
}
if (strOperation == "cosh") {
helper = cosh(fOperand1);
fResult = helper;
}
if (strOperation == "sinh") {
helper = sinh(fOperand1);
fResult = helper;
}
if (strOperation == "cos") {
helper = cos(fOperand1);
fResult = helper;
}
if (strOperation == "sin") {
helper = sin(fOperand1);
fResult = helper;
}
if (strOperation == "e^x") {
helper++;
for (int i = 0; i < fOperand1; ++i) {
helper *= 2.71828182845904523536;
}
fResult = helper;
}
if (strOperation == "pi") {
helper = 3.1415926535;
fResult = helper;
}
if (strOperation == "e") {
helper = 2.71828182845904523536;
fResult = helper;
}
if (strOperation == "%") {
helper = fOperand1 / 100;
fResult = helper;
}
if (strOperation == "√") {
helper = sqrt(fOperand1);
fResult = helper;
}
if (strOperation == "x²") {
helper = fOperand1 * fOperand1;
fResult = helper;
}
if (strOperation == "x³") {
helper = fOperand1 * fOperand1 * fOperand1;
fResult = helper;
}
if (strOperation == "+/-") {
helper = -1 * fOperand1;
fResult = helper;
}
m_strDisplay = fResult;
m_plcd->display(fResult);
}
void Calculator::slotButtonClicked() {
QString str = ((QPushButton*)sender())->text();
if (str == "CE") {
m_stk.clear();
m_strDisplay = "";
m_plcd->display("0");
return;
}
if (str.contains(QRegExp("[0-9]")) || str == ".") {
m_strDisplay += str;
m_plcd->display(m_strDisplay);
}
else {
if (m_stk.count() >= 2) {
m_stk.push(QString().setNum(m_plcd->value()));
calculate();
m_stk.clear();
m_stk.push(QString().setNum(m_plcd->value()));
if (str != "=") {
m_stk.push(str);
}
}
else {
m_stk.push(QString().setNum(m_plcd->value()));
m_stk.push(str);
if (m_stk[1] != "+" && m_stk[1] != "-" && m_stk[1] != "/" && m_stk[1] != "*" && m_stk[1] != "x^y"
&& m_stk[1] != "x^(1/y)" && m_stk[1] != "Mod" && m_stk[1] != "؆") {
calculate1();
m_stk.clear();
}
m_strDisplay = "";
}
}
}
<file_sep>/Calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <QWidget>
#include <QStackedWidget>
#include <QtWidgets>
#include <QStack>
#include <QApplication>
#include <QLCDNumber>
#include <QGridLayout>
#include <QPalette>
#include <math.h>
#include <QStyle>
//#include "Buttons.h"
class QLCDNumber;
class QPushButton;
class Calculator : public QWidget {
Q_OBJECT
private:
QGridLayout* ptopLayout;
QWidget wgt1;
QWidget wgt2;
QWidget wgt3;
QWidget wgt4;
QGridLayout* ptopLayoutE;
QHBoxLayout * phbxLayout;
QVBoxLayout * pvbxLayout;
QCheckBox* m_pchk;
QRadioButton* m_pradNormal;
QRadioButton* m_pradEngineer;
QLCDNumber * m_plcd;
QStack<QString> m_stk;
QString m_strDisplay;
public:
Calculator(QWidget* pwgt = 0);
QPushButton* createButtonNormal(const QString& str);
void calculate();
void calculate1();
public slots:
void slotButtonClicked();
void slotButtonSwitched();
//void slotRadioButtonClicked();
};
#endif // CALCULATOR_H
| 36642af75f97fa4f01442a714a99b93128897bae | [
"C++"
] | 2 | C++ | howardano/QT-Calculator | 733767fed9e78ab553080e9539665ec2ecae16e5 | d85a22edad1543d5d8e776818f1509ee387f3ca1 |
refs/heads/master | <file_sep>'use strict';
/* Services */
var eventAppServices = angular.module('eventAppServices', []);
//eventAppServices.service('JSONService', function($http){
// return {
// getJSON: function() {
// return $http.get('/db/events.json');
// }
// };
//});
eventAppServices.service('DBEvents', function($http,$templateCache){
var event = this;
event.events = [];
var initEvents = function(){
$http.get('http://localhost:1213/get-events').success(function (data) {
//console.log('response', response);
event.events = data;
});
};
initEvents();
this.getEvents = function(){
return this.events;
};
this.putParticipant = function(event_id,participant){
var data = {id:event_id, participant: participant };
var jdata = 'mydata='+JSON.stringify(data);
$http({
method: 'post',
url: "http://localhost:1213/insert-participant",
data: jdata ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// cache: $templateCache
}).
success(function(response) {
console.log("success");
initEvents();
}).
error(function(response) {
console.log("error");
});
//this.events.push(event);
return true;
}
this.putEvent = function(event){
var jdata = 'mydata='+JSON.stringify(event);
$http({
method: 'post',
url: "http://localhost:1213/insert-events",
data: jdata ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// cache: $templateCache
}).
success(function(response) {
console.log("success");
initEvents();
}).
error(function(response) {
console.log("error");
});
this.events.push(event);
return true;
}
});
//
//eventAppServices.service('FacebookSearchTag', function($http){
//
// var post = this;
// post.posts = [];
//
// this.search = function(tag,until,limit){
//
// if (typeof limit === "undefined"){
// limit = 100;
// }
// if (typeof until === "undefined"){
// var now = new Date();
// until = parseInt(now.valueOf()/1000);
// }
//
// $http.get('https://graph.facebook.com/v1.0/search?access_token=<KEY>&format=json&method=get&q=%23'+tag+'&limit='+limit+'&until='+until).success(function (data) {
// console.log('response', data.data);
// $scope.posts = data.data;
// });
// }
//
// this.getPosts = function(){
// return this.posts;
// }
//});<file_sep>var application_root = __dirname,
express = require("express"),
path = require("path");
var databaseUrl = "events";
var collections = ["events"]
var db = require("mongojs").connect(databaseUrl, collections);
var bodyParser = require('body-parser')
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
//app.use(express.bodyParser());
var methodOverride = require('method-override')
app.use(methodOverride('_method'));
//app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
//app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.get('/api', function (req, res) {
res.send('Ecomm API is running');
});
app.get('/get-events', function (req, res) {
res.header("Access-Control-Allow-Origin", "http://myangular.localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
db.events.find('', function(err, events) {
if( err || !events) console.log("No users found");
else
{
res.writeHead(200, {'Content-Type': 'application/json'});
res.end( JSON.stringify(events));
}
});
});
app.post('/insert-events', function (req, res){
//console.log("POST: ");
res.header("Access-Control-Allow-Origin", "http://myangular.localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
//console.log(req.body.mydata);
var jsonData = JSON.parse(req.body.mydata);
console.log(jsonData);
db.events.save(jsonData, function(err, saved) {
if( err || !saved ) res.end( "Event not saved");
else res.end( "Event saved");
});
});
app.post('/insert-participant', function (req, res){
//console.log("POST: ");
res.header("Access-Control-Allow-Origin", "http://myangular.localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
console.log(req.body.mydata);
var jsonData = JSON.parse(req.body.mydata);
db.events.update(
{ id: jsonData.id },
{ $push: { participants: jsonData.participant } },
function(err, saved) {
if( err || !saved ) res.end( "Participant not added");
else res.end( "Participant added");
});
});
app.post('/delete-event', function (req, res){
//console.log("POST: ");
res.header("Access-Control-Allow-Origin", "http://myangular.localhost");
res.header("Access-Control-Allow-Methods", "GET, POST");
console.log(req.body.mydata);
var jsonData = JSON.parse(req.body.mydata);
db.products.remove( { id: jsonData.id },
function(err, saved) {
if( err || !saved ) res.end( "Event not deleted");
else res.end( "Event deleted");
});
});
app.listen(1213);<file_sep>'use strict';
/* Controllers */
var eventAppControllers = angular.module('eventAppControllers', []);
eventAppControllers.controller("EventsController", ['$http','$scope', 'DBEvents', function($http,$scope,DBEvents) {
$scope.events = DBEvents.getEvents();
this.getStatus = function(event){
var startDate = moment(event.startDate,"DD MMM YYYY HH:mm");
var endDate = moment(event.endDate,"DD MMM YYYY HH:mm");
var now = moment();
if (startDate>now){
return 'Coming';
} else {
if (endDate<now){
return 'Passed';
} else {
return 'In progress';
}
}
};
}]);
eventAppControllers.controller("ParticipantController", ['$cookies', 'DBEvents', function($cookies,DBEvents) {
var $participant = this;
this.participant = {};
//$cookies.user = '';
this.username = $cookies.username;
this.useremail = $cookies.useremail;
console.log(this.username,this.useremail);
this.userIsSubscribed = false;
this.subscribeShow = false;
this.getIsUserSub = function(event){
if (!this.haveParticipants(event)) {
return true;
}
var participants = event.participants;
if (typeof this.username === 'undefined' || typeof this.useremail === 'undefined'){
return true;
} else {
var $return = true;
participants.forEach( function(participant) {
console.log($participant.username,participant.name);
if (typeof participant === 'object' && participant.name == $participant.username && participant.email == $participant.useremail)
{
$return = false;
}
});
}
return $return;
};
this.haveParticipants = function(event){
if (typeof event === 'object' && typeof event.participants === 'undefined')
{
return false;
} else {
return true;
}
};
this.addParticipant = function(event){
if (!this.haveParticipants(event)) {
event.participants = [];
}
console.log(event);
event.participants.push(this.participant);
DBEvents.putParticipant(event.id,this.participant);
$cookies.username = this.participant.name;
$cookies.useremail = this.participant.email;
this.participant = {};
this.subscribeShow = false;
this.userIsSubscribed = true;
};
}]);
eventAppControllers.controller("AddEventController", ['$scope', '$location', 'DBEvents', function($scope, $location,DBEvents) {
this.event = {
startDate: moment().format("DD MMM YYYY HH:mm"),
endDate: moment().format("DD MMM YYYY HH:mm")
};
this.isAnonimous = false;
this.isAuthorParticipant= false;
$scope.startDate = { id: "startDate", name: "startDate", datetime:'' };
$scope.endDate = { id: "endDate", name: "endDate", datetime:'' };
//console.log($scope.startDate);
this.addEvent = function(){
this.event.id = moment(this.event.startDate,"DD MMM YYYY HH:mm:ss").valueOf();
if (this.isAnonimous){
this.event.author = {
name: "Anonymous",
email: ""
};
} else {
if (this.isAuthorParticipant){
this.event.participants = [{
name: this.event.author.name,
email: this.event.author.email
}];
}
}
DBEvents.putEvent(this.event);
this.resetEvent();
//console.log(this.event);
$location.path("/events");
return true;
};
this.resetEvent= function (){
this.event = {
startDate: moment().format("DD MMM YYYY HH:mm"),
endDate: moment().format("DD MMM YYYY HH:mm")
};
//console.log(this.event);
return true;
}
}]);
eventAppControllers.controller("PageController", ['$scope' ,'$location',
function( $scope,$location ){
// Update the rendering of the page.
var render = function(){
// currently selected route.
var renderAction = $location.path();
var renderPath = renderAction.split( "/" );
// Reset the booleans used to set the class
// for the navigation.
var isHome = (renderPath[ 1 ] == "events");
var isAddEvent = (renderPath[ 1 ] == "add-event");
var isFacebook = (renderPath[ 1 ] == "facebook");
// Store the values in the model.
$scope.renderAction = renderAction;
$scope.renderPath = renderPath;
$scope.isHome = isHome;
$scope.isAddEvent = isAddEvent;
$scope.isFacebook = isFacebook;
};
// Listen for changes to the Route. When the route
// changes, let's set the renderAction model value so
// that it can render in the Strong element.
$scope.$on(
"$routeChangeSuccess",
function( $currentRoute, $previousRoute ){
// Update the rendering.
render();
}
);
}]);
eventAppControllers.controller("FacebookController", ['$http','$scope', function($http,$scope) {
$scope.posts = [];
var facebook = this;
facebook.haveResult = false;
this.tag = '';
this.search = function(until,limit){
if (typeof limit === "undefined"){
limit = 100;
}
if (typeof until === "undefined"){
var currentDate = moment().format('DD-MMM-YYYY HH:mm:ss');
console.log(currentDate);
until = parseInt(Date.parse(currentDate)/1000)+11000;
}
console.log(until);
$http.get('https://graph.facebook.com/v1.0/search?access_token=<KEY>G4mJIp0&format=json&method=get&q=%23'+this.tag+'&limit='+limit+'&until='+until).success(function (data) {
console.log('response', data.data);
if (data.data.length)
{
facebook.haveResult = true;
}
$scope.posts = data.data;
});
}
this.getFromPicture = function(post){
if (post.from.id){
return 'https://graph.facebook.com/'+post.from.id+'/picture';
}else
return '';
}
}]);
<file_sep>Events
======
Events is an application created with angular, mongoDB and nodejs
Events List

Add event

Facebook search public hashtags
 | 87382e9d5b730b8a3c13baf8466656a9528bffac | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Zbintiosul/Events | ef1d516feac1d2eba6100ae38b3ba177b2ea5d99 | 3b552e963f38ea9212fcb8943c3b08db4bcf75f4 |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./main.css">
<title>Tab Buttons</title>
</head>
<body>
<div class="container">
<h1 class="heading">Tab Buttons</h1>
<p class="intro">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cum, vero.</p>
<div class="tab-wrapper">
<section class="btns">
<button class="btn active" data-id="art1">Article 1</button>
<button class="btn" data-id="art2">Article 2</button>
<button class="btn" data-id="art3">Article 3</button>
</section>
<section class="articles">
<article class="article active" id="art1">
<h3>Article 1</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos molestiae doloribus itaque adipisci vel
reiciendis facere! Lorem ipsum dolor sit, amet consectetur adipisicing elit. Dolorum, nulla.</p>
</article>
<article class="article" id="art2">
<h3>Article 2</h3>
<p>Quaerat dolorum totam vero, soluta odio similique illo molestiae numquam exercitationem aliquid,
recusandae fugit possimus pariatur aut non tempore laudantium odit? Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Sit, doloremque.</p>
</article>
<article class="article" id="art3">
<h3>Article 3</h3>
<p>Voluptate recusandae blanditiis, corrupti ipsa aperiam aspernatur dicta nam facere quidem, repudiandae
dolore! Deserunt atque dolores reiciendis provident dolorem nostrum eum incidunt qui. Lorem ipsum dolor
sit amet consectetur adipisicing elit. Fugit, numquam.</p>
</article>
</section>
</div>
</div>
<footer><NAME> © 2020</footer>
<script src="./main.js"></script>
</body>
</html><file_sep># tab-buttons
Tab Buttons
<file_sep>const btns = document.querySelectorAll(".btn");
const articles = document.querySelectorAll(".article");
function removeActive(list) {
list.forEach((item) => item.classList.remove("active"));
}
function getAssoArticle(button) {
return document.getElementById(button.dataset.id);
}
btns.forEach(function (btn) {
btn.addEventListener("click", function (e) {
removeActive(btns);
btn.classList.add("active");
removeActive(articles);
const article = getAssoArticle(e.target);
article.classList.add("active");
});
});
| 67e15c475f50a6f91d4d22cbfcfe57c5f736ea69 | [
"Markdown",
"JavaScript",
"HTML"
] | 3 | HTML | hungntgrb/tab-buttons | 6ea8324cbebb06ac6c10987f9a618b827aa43e67 | faf964d487ece8d5c4453ab3e70bf762e228ddaf |
refs/heads/master | <repo_name>MadKimchi/sample-nativescript-ngx-lib<file_sep>/lib/src/components/carousel/interfaces/carousel.interface.ts
import { Type, ReflectiveInjector } from '@angular/core';
export interface ICarouselContent {
component: Type<any>;
dataProvider?: ReflectiveInjector;
}
export interface ICarouselData<T> {
data: T;
pageIndex: number;
}
<file_sep>/lib/src/components/carousel/classes/index.ts
export * from "./carousel-data.class";
<file_sep>/lib/src/components/carousel/carousel.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptCommonModule } from 'nativescript-angular/common';
import { CarouselComponent } from './carousel.component';
@NgModule({
imports: [NativeScriptCommonModule],
providers: [],
exports: [CarouselComponent],
declarations: [CarouselComponent],
schemas: [NO_ERRORS_SCHEMA]
})
export class SnapCarouselModule {}
<file_sep>/src/app/home/home.component.ts
import { Component, OnInit, Injector } from '@angular/core';
import { ICarouselContent } from 'sample-lib';
import { ExampleCarouselContentComponent } from '~/app/home/components/example-carousel-content/example-carousel-content.component';
@Component({
selector: 'Home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public perScreen: number = 4;
public carouselContentItems: Array<ICarouselContent> = [
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
},
{
component: ExampleCarouselContentComponent
}
];
constructor(public injector: Injector) {
// Use the constructor to inject services.
}
ngOnInit(): void {
// Init your component properties here.
}
}
<file_sep>/README.md
# Seed Project For Native Script UI Plugins for Angular Projects
<file_sep>/lib/src/components/carousel/classes/carousel-data.class.ts
export class CarouselData<T> {
data: T;
pageIndex: number;
}
<file_sep>/lib/src/components/carousel/carousel.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { StackLayout } from 'tns-core-modules/ui/layouts/stack-layout/stack-layout';
import {
PanGestureEventData,
GestureStateTypes
} from 'tns-core-modules/ui/gestures/gestures';
import { screen } from 'tns-core-modules/platform';
import { ICarouselContent } from './interfaces';
@Component({
selector: 'Carousel',
moduleId: module.id,
templateUrl: './carousel.component.html',
styleUrls: ['./carousel.component.scss']
})
export class CarouselComponent implements OnInit {
@Input() public carouselContent: ICarouselContent[];
@Input() public countPerScreen: number = 2;
@Input() public gutter: number = 10;
@Input() public offset: number = 10;
public prevDeltaX: number = 0;
public defaultX: number = 0;
public selectedIndex: number = 0;
public origin: number = 0;
public screenWidth: number = screen.mainScreen.widthDIPs;
public carouselWidth: number;
public get halfGutter(): number {
return this.gutter / 2;
}
constructor() {}
public ngOnInit(): void {
this.carouselWidth =
this.screenWidth / this.countPerScreen -
this.gutter -
this.offset / 2;
this.defaultX = this.gutter;
}
public onPanEvent(args: PanGestureEventData, container: StackLayout): void {
const traceX: number =
container.translateX + args.deltaX - this.prevDeltaX;
switch (args.state) {
case GestureStateTypes.changed:
container.translateX = traceX;
this.prevDeltaX = args.deltaX;
break;
case GestureStateTypes.ended:
const originX = this.getOrigin(args.deltaX, container);
container.animate({
translate: { x: originX + this.offset, y: 0 },
duration: 200
});
this.origin = originX;
this.prevDeltaX = 0;
break;
default:
break;
}
}
public setActiveItem(index: number, container: StackLayout): void {
// TODO: double tap bug should be fixed
if (index !== this.selectedIndex) {
const originX = this.getOrigin(
-index * this.carouselWidth,
container
);
container.animate({
translate: { x: originX, y: 0 },
duration: 200
});
this.origin = originX;
this.prevDeltaX = 0;
this.selectedIndex = index;
}
}
private getOrigin(deltaX: number, container: StackLayout): number {
const lastIndex = container.getChildrenCount() - 1;
return deltaX >= 0 ? this.onPanLeft() : this.onPanRight(lastIndex);
}
private onPanLeft(): number {
if (this.selectedIndex > 0) {
this.selectedIndex -= 1;
const newCarouselX = this.selectedIndex * this.carouselWidth;
return -newCarouselX;
}
return 0;
}
// TODO: Refactor this better for the
private onPanRight(lastIndex: number): number {
if (this.countPerScreen === 1) {
if (this.selectedIndex >= lastIndex - 1) {
const newCarouselX = lastIndex * this.carouselWidth;
if (this.selectedIndex <= lastIndex - 1) {
this.selectedIndex += 1;
}
return -newCarouselX;
}
} else if (this.countPerScreen === 2) {
if (this.selectedIndex >= lastIndex - 2) {
const newCarouselX =
(lastIndex - 1) * this.carouselWidth -
this.gutter -
this.halfGutter;
if (this.selectedIndex <= lastIndex - 2) {
this.selectedIndex += 1;
}
return -newCarouselX;
}
} else if (this.countPerScreen === 3) {
if (this.selectedIndex >= lastIndex - 3) {
const newCarouselX =
(lastIndex - 2) * this.carouselWidth - this.gutter * 3;
if (this.selectedIndex <= lastIndex - 3) {
this.selectedIndex += 1;
}
return -newCarouselX;
}
}
this.selectedIndex += 1;
const newCarouselX = this.selectedIndex * this.carouselWidth;
return -newCarouselX;
}
}
<file_sep>/lib/src/public_api.ts
export * from './components/carousel/index';
export * from './components/editor/index';
<file_sep>/lib/src/components/carousel/interfaces/index.ts
export * from './carousel.interface';
<file_sep>/lib/src/components/editor/editor.component.ts
/// <reference path="../../../../node_modules/tns-platform-declarations/ios.d.ts" />
/// <reference path="../../../../node_modules/tns-platform-declarations/android.d.ts" />
import { Component, OnInit } from '@angular/core';
import { ios as iosApp } from 'tns-core-modules/application/application';
@Component({
selector: 'Editor',
moduleId: module.id,
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.scss']
})
export class EditorComponent implements OnInit {
public editorSrc: string;
constructor() {}
public ngOnInit(): void {
this.editorSrc =
'sample-lib/src/components/editor/assets/views/index.html';
}
if(iosApp) {
iosApp.addNotificationObserver(
UIKeyboardWillShowNotification,
(event: NSNotification) => {
// console.log(event);
// this._keyboardHeight = event.userInfo.valueForKey(
// UIKeyboardFrameEndUserInfoKey
// ).CGRectValue.size.height;
// this._element.set('height', this._keyboardHeight);
// console.log('WillShow', typeof event.userInfo, event.userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue.size.height);
// console.log(this.textView.ios.contentSize);
// this.contentSizeStartValue = event.userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue.size.height + 10;
}
);
iosApp.addNotificationObserver(
UIKeyboardDidShowNotification,
(event: NSNotification) => {
// console.log(event);
// const size = this._element.nativeElement.getActualSize().height;
// console.log(size);
}
);
}
}
<file_sep>/src/app/home/components/example-carousel-content/example-carousel-content.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'ExampleCarouselContent',
templateUrl: './example-carousel-content.component.html',
styleUrls: ['./example-carousel-content.component.scss']
})
export class ExampleCarouselContentComponent {
public onTab(): void {
console.log('onTapping');
}
}
| 786fb51cac5dbe5e785f75ccf432a464efd54bee | [
"Markdown",
"TypeScript"
] | 11 | TypeScript | MadKimchi/sample-nativescript-ngx-lib | 4aaf2f380e714d9fa373f12ddf9ad277d0349ab1 | 4b2cad4447eb24ccdf5e956fc7ae3d4cd98bf3a6 |
refs/heads/master | <repo_name>lilongbin/vim_plugins<file_sep>/.vim/tools/python/01commands.py
#! /usr/bin/python
# class subprocess test of python language
# created by longbin <<EMAIL>>
# 2015-01-07
import commands
import os
# get output of shell commands
out = commands.getoutput("ls /home/")
print "\rcommands.getoutput out : ", out, "\n"
# get status and output of shell commands
(status, output) = commands.getstatusoutput("ls /home/")
print "\rstatus : ", status, "\noutput : ", output
print ""
# get return value of shell commands
res = os.system("echo \"hello python\"")
print "os.system res = ", res
# get output of shell commands
res = os.popen("echo \"hello python\"")
print "\nos.popen res.read() : ", res.read()
<file_sep>/.vim/tools/readme.txt
/*
* created by Longbin_Li <<EMAIL>>
* 2014-12-05
* 2015-03-09
*/
we can use these scripts to explorer souce code.
Before doing this, we may need to do following steps:
1. change directory to our home dir.
for instance, /home/mike; and then
$ tar -zxvf vim_cfg_backup.tar.gz -C ~/
2. then change current directory to the source code location.
for instance, kernel source locates /opt/kernel/
$ cd /opt/kernel
and android source locates /home/mike/projects/p1/LINUX/android/
$ cd /home/mike/projects/p1/LINUX/android
then use below commands to generate cscope files and tags in order to exploring source code;
$ /bin/bash ~/.vim/tools/shell/gen_kernel_SrcExpl.sh #for kernel
$ /bin/bash ~/.vim/tools/shell/gen_android_SrcExpl.sh #for android
after this, we could see cscope.out and tags files under the source code directory;
3. use vim to open the file which you want to explorer.
for instance,
$ vim /opt/kernel/driver/input/touchscreen/atmel_mxt_ts.c
then we could do following by
+-------------------------------------------------------------------------------+
| <F2> toggle the taglist window |
| <F3> toggle the SrcExpl window, please do not open in android src |
| <F5> toggle the NERDTree window |
+-------------------------------------------------------------------------------+
SrcExpl is based on ctags' file tags;
Following shottcuts could help us jump freely, but we only recommend you use them
when analysising kernel source;
but for android please do not use them since its source code too large amount;
when analysising android source code please use the find commands which will be
introduced a moment later;
+-------------------------------------------------------------------------------+
| <C-j> show the next definition------>in SrcExpl window; need tags |
| <C-z> back to last location--------->in SrcExpl window; need tags |
+- - - - - - - - - - - - - - - - - - - - -+
| <C-]> jump to definition in the edit window-->need cscope.out/tags |
| <C-t> jump back to the last location--------->need cscope.out/tags |
+-------------------------------------------------------------------------------+
below methods help us to jump to the file or function defination where we want to go;
to jump back we need use <C-t>; and we should have cscope.out file firstly;
It's recommended that to use this method to jump freely, especialy in android;
$ cscope-indexer -r
+-------------------------------------------------------------------------------+
| when the cursor is on the string/filename/function, |
| we could use following key to find something shortcutly; |
| |
| \f find the file and open it |
| \g find global definition |
| \s find this symbol |
| \d find out functions those called by this func |
| \c find functions those calling/reference this func |
| \i find file #include/reference this file |
| \t find text string |
| \e find egrep pattern |
+-------------------------------------------------------------------------------+
| we could also use bellow commands by the underline mode of vim. |
| |
| :cs find f ME find ME and open it; ME is a file such as stdio.h |
| :cs find g ME find ME; ME is a global definition |
| :cs find s ME find ME; ME is a symbol |
| :cs find d ME find who called ME, ME is a func or macro etc. |
| :cs find c ME find the funcs; the funcs is calling/reference ME |
| :cs find i ME find the files; the files #include/reference ME |
| :cs find t ME find ME; ME is a text string |
| :cs find e ME find ME; ME is an egrep pattern |
+-------------------------------------------------------------------------------+
4. auto completion system in vim.
write following into ~/.vimrc file
-----------------------------------------------
let g:neocomplcache_enable_at_startup=1
set completeopt+=longest
let g:neocomplcache_enable_auto_select=1
let g:neocomplcache_disable_auto_complete=1
-----------------------------------------------
when need auto completion just press <C-n> to select which you like;
5. comment or uncomment to the source code.
+-----------------------------------------------------------------------+
| \cc comment * |
| \cu uncomment * |
| \cm comment minimal |
| \ci comment or uncomment |
| \cs comment for block codes sexily * |
| \cA comment to the end and go to insert mode |
| |
| \ca alternate the delimiters will be used |
+-----------------------------------------------------------------------+
6. Other operations in vim.
6.1 We can use following keys to fold and/or unfold the source code session.
+-----------------------------------------------------------------------+
| foldenable |
| zi open/close all fold |
| zo open the fold under current cursor |
| zc close the fold under current cursor |
| <Space> open/close the fold under current sursor |
+-----------------------------------------------------------------------+
6.2 hilight the word by txtbrowser script.
+-----------------------------------------------------------------------+
| txtbrowser |
| \h hilight the word under cursor in current file |
| * search forward for the word under cursor |
| # search backword for the word under cursor |
+-----------------------------------------------------------------------+
6.3 Digraphs
Some characters are not on the keyboard. For example, the copyright character (©).
To type these characters in Vim, you use digraphs, where two characters represent one.
To enter a ©, for example, you press three keys: >
CTRL-K Co
To find out what digraphs are available, use the following command: >
:digraphs
Vim will display the digraph table. Here are three lines of it:
AC ~_ 159 NS | 160 !I ¡ 161 Ct ¢ 162 Pd £ 163 Cu ¤ 164
Ye ¥ 165 BB ¦ 166 SE § 167 ': ¨ 168 Co © 169 -a ª 170
<< « 171 NO ¬ 172 -- 173 Rg ® 174 'm ¯ 175 DG ° 176
+- ± 177 2S ² 178 3S ³ 179
This shows, for example, that the digraph you get by typing CTRL-K Pd is the
character (£). This is character number 163 (decimal).
<file_sep>/.vim/tools/python/stress_test.py
#! /usr/bin/python
#Wayne, f/w update stress test python
import subprocess
import os
import sys, time
def stress_test():
FNULL = open(os.devnull, 'w')
dd_cmd="adb shell dd bs=1048576 if=test1.text of=test2.txt count=1024 "
ck_cmd="adb shell ls test2.txt"
subprocess.call(dd_cmd.split(), stdout=FNULL, stderr=subprocess.STDOUT)
proc_res = subprocess.Popen(ck_cmd.split(), stdout=subprocess.PIPE)
result = proc_res.stdout.readline()
if (result.find("No such file or directory") > -1):
print "could not open file, test2.txt"
return 1
sPopen1 = subprocess.Popen("adb shell md5 test1.txt |awk '{print $1}'", shell=True, stdout=subprocess.PIPE)
output1 = sPopen1.stdout.read()
sPopen1.communicate()
sPopen2 = subprocess.Popen("adb shell md5 test2.txt |awk '{print $1}'", shell=True, stdout=subprocess.PIPE)
output2 = sPopen2.stdout.read()
sPopen2.communicate()
## delete /data/tmp/wayne_test.txt
sub_rm = subprocess.Popen("adb shell rm test2.txt", shell=True, stdout=subprocess.PIPE)
rm_res = sub_rm.stdout.readline()
sub_rm.communicate()
if (rm_res.find("rm failed") != -1):
print "rm failed"
return 1
# print "output1 : %s" % (output1)
# print "output2 : %s" % (output2)
if output1 == output2:
return 0
else:
return 1
print "Start testing ...\n"
count, var, success, failure = 0, 1, 0, 0
while var==1:
count += 1
if stress_test() == 0:
success += 1
else:
failure += 1
print "\rTest circle :",count,"result <success/failure>: ",success,"/",failure," ...",
sys.stdout.flush()
# time.sleep(10)
time.sleep(2)
print "\n Exit while, done for test"
<file_sep>/.vim/tools/shell/gen_android_SrcExpl.sh
#! /bin/bash
# created by Longbin_Li <<EMAIL>>
clear
echo "This script used to generate cscope files and tags for android source code"
FILENAME=cscope.files
function gencscopef()
{
echo "Searching *.h *.c *.cpp ... from $PWD"
find . -name "out" -prune \
-o -iname "*.[hc]" \
-o -iname "*.[hc]pp" \
> ${FILENAME}
# | sed -n "s%^\.%$PWD%p" \
if [[ $? == 0 ]] ;then
[[ -s ${FILENAME} ]] && echo "generate files: " && ls -lh ${FILENAME}
else
echo "error occured, ${FILENAME} not be generated" && exit 1
fi
# sed -n "s/old/new/p"
# sed -n "s%$old%$new%p" use % to replace if used var contains of "/"
echo "generating cscope index files ..."
cscope -bkq -i ${FILENAME}
[[ $? == 0 ]] && echo "generated files: " && ls -lh cscope*
}
function gencscopefi()
{
cscope-indexer -r -v
}
if [[ -f cscope.out ]] ;then
read -p " update cscope files ? <y/n> " select
if [[ "$select" == "y" ]] ;then
rm cscope.out
# gencscopef
gencscopefi
else
echo "not updated cscope files"
fi
else
# gencscopef
gencscopefi
fi
function genctags()
{
echo "generating ctags file ..."
ctags -R \
--langmap=c:+.h \
--languages=c,c++
# --links=yes \
# -I __THROW,__wur,__nonnull+ \
# --c++-kinds=+p --c-kinds=+px-n \
# --fields=+ialtfS --extra=+q \
# --file-scope=yes \
# $PWD
echo "preparations over" && ls -lh tags
}
if [[ -f tags ]] ;then
read -p " update tags file ? <y/n> " select
if [[ "$select" == "y" ]] ;then
rm tags
genctags
else
echo "Do not update tags"
fi
else
genctags
fi
<file_sep>/.vim/tools/shell/find_newfiles.sh
#! /bin/bash
# use this scripts can find out and backup
# the files modified in ndays, and copy them
# to backup_dir then compress to .tgz file
# created by longbin <<EMAIL>>
# v1.0 <2015-01-07>
# v1.1 <2015-01-08>
# v1.2 <2015-01-09>
ndays=-1
tmp_file_name=_findfiles_tmp
backup_file=changed_files
backup_dir="__modified_${USER}"
##find out files which modified in ndays, exclude backup_dir
##findout File's data was last modified ndays*24 hours ago.
echo "finding files modified in ${ndays} * 24 hours ..."
find . -name "${backup_dir}" -prune -o -mtime "$ndays" \
| sed -n "s%^\.\/% %p" \
> $tmp_file_name
sed -i '/^\.$/d' ${tmp_file_name} ## delete lines .
sed -i '/^\.\/$/d' ${tmp_file_name} ## delete lines ./
##delete lines begin with ./__backup
sed -i "/^\.\/${backup_dir}/d" ${tmp_file_name}
##delete lines begin with __backup
sed -i "/${backup_dir}/d" ${tmp_file_name}
sed -i "/${tmp_file_name}/d" ${tmp_file_name}
sed -i "/\.o$/d" ${tmp_file_name}
sed -i "/\.ko$/d" ${tmp_file_name}
sed -i "/\.a$/d" ${tmp_file_name}
sed -i "/\.dep$/d" ${tmp_file_name}
sed -i "/\.depend$/d" ${tmp_file_name}
sed -i "/\.map$/d" ${tmp_file_name}
sed -i "/\.bin$/d" ${tmp_file_name}
sed -i "/cscope/d" ${tmp_file_name}
sed -i "/tags$/d" ${tmp_file_name}
sed -i "/${backup_file}\.tgz/d" ${tmp_file_name} ##delete ${backup_file}.tgz
##delete dir and link name from $tmp_file_name
FILE=`sed -n '1,$'p $tmp_file_name`
line_nu=1
for rm_line in $FILE
do
if [[ -d ${rm_line} ]] || [[ -L ${rm_line} ]] || [[ -x ${rm_line} ]]
then
# echo "delete line : ${rm_line}"
sed -i "${line_nu}d" ${tmp_file_name}
((line_nu-=1))
fi
((line_nu+=1))
done
##get total lines of file
echo "there are "0"`sed -n '$=' ${tmp_file_name}` files changed."
##get file's data as array
FILE=`sed -n '1,$'p $tmp_file_name`
##echo $FILE ##display file's data
if [[ "$FILE" != "" ]]
then
read -p "press <ENTER> to backup the new files."
##backup files ref file's data
[[ -d ${backup_dir} ]] || mkdir ${backup_dir}
count=0
for file in ${FILE}
do
## get file's directory
cp_file_dir=${file%/*}
## get file's name
cp_file_name=${file##*/}
if [[ -d ${cp_file_dir} ]]
then
[[ -d ${backup_dir}/${cp_file_dir} ]] \
|| mkdir -p ${backup_dir}/${cp_file_dir}
echo "cp ${file} ${backup_dir}/${cp_file_dir}/${cp_file_name}"
cp -fdu ${file} ${backup_dir}/${cp_file_dir} && ((count+=1))
else
# if [[ -f ${file} ]] && ! [[ -L ${file} ]]
# then
echo "cp ${file} ${backup_dir}/${file}"
cp -fdu ${file} ${backup_dir} && ((count+=1))
# fi
fi
done
echo "copied ${count} files."
read -p "compress backed up files ? <y/n> " select
if [[ "$select" == "y" ]]
then
tar -zcvf ${backup_file}.tgz ${backup_dir}
echo "bachup files to ${backup_file}.tgz finished."
fi
# tar -zcvf ${backup_file}.tgz ${FILE}
else
echo "no files changed to backup."
fi
[[ -f ${tmp_file_name} ]] && rm -f ${tmp_file_name}
<file_sep>/.vim/vim_plugins_backup/vim_plugins_bk.sh
#! /bin/bash
FILE_NAME=plugins_bk_${USER}
if [[ -f "${FILE_NAME}.zip" ]] ;then
rm -v ${FILE_NAME}.zip
fi
sleep 1
pushd ../
zip -r vim_plugins_backup/${FILE_NAME}.zip doc/ ftplugin/ nerdtree_plugin/ plugin/ syntax/ tools/
popd
<file_sep>/.vim/tools/bible/select.sh
#! /bin/bash
PS3="please select your dir: "
select option in $(ls)
do
if [[ -n "$option" ]] ;then
ls -l $option
break
fi
done
echo "please select one option in 5s "
TMOUT=5
option=ls
select option in \
ls \
"echo hello"
do
case ${REPLY} in
1)
ls
;;
2)
echo "hello"
;;
?)
echo "invalid option ."
;;
esac
echo your option is: ${option}
break
done
echo "reply is: ${REPLY}"
if [[ "${REPLY}" == "" ]] ;then
echo "use default option: $option"
fi
<file_sep>/.vim/tools/shell/unpack_package_file.sh
#! /bin/bash
# created by longbin <<EMAIL>>
# 2015-03-30
## check_user_UID
function check_user_UID(){
if [[ ${UID} -lt 1000 ]] ;then
echo "ERROR: Please don't use root to execute this script."
exit 1
fi
}
# function unpack package file
function unpack_package_file(){
## print current script file name and PID
## echo $0 $$
if [[ $# -lt 2 ]] ;then
echo "function Usage:"
echo -e "\tunpack_package_file -f packagefile [-d destiantion] [-u USER]"
fi
## get install file name
local PKG_FILE_NAME
local PKG_FILE_TAIL
## gain target directory
local DESTINATION_DIR
local USER_UID
local USER_FLAG
## gain options and arguments
# echo "There are $# arguments: $*"
local OPTIND
while getopts "f:d:u:" func_opt
do
case "${func_opt}" in
f)
PKG_FILE_NAME=${OPTARG}
# echo "package file name: ${PKG_FILE_NAME}"
;;
d)
DESTINATION_DIR=${OPTARG}
# echo "unpack destination: ${DESTINATION_DIR}"
;;
u)
USER_UID=${OPTARG}
# echo "unpack user UID: ${USER_UID}"
;;
*)
local ERROR=${*%${OPTARG}}
echo "Unknown option and argument: -${ERROR##*-} ${OPTARG}"
exit 1
;;
esac
done
if [[ "${PKG_FILE_NAME}" == "" ]] ;then
echo "package file name can not be empty."
exit 1
fi
if ! [[ -f "${PKG_FILE_NAME}" ]] ;then
echo "${PKG_FILE_NAME}: package not exists."
exit 1
fi
if [[ "${USER_UID}" == "root" ]] ;then
USER_FLAG=sudo
else
USER_FLAG=""
fi
if [[ "${DESTINATION_DIR}" == "" ]] ;then
DESTINATION_DIR=$(pwd)
fi
if ! [[ -d "${DESTINATION_DIR}" ]] ;then
${USER_FLAG} mkdir -p ${DESTINATION_DIR}
fi
if ! [ -d ${DESTINATION_DIR} -a -w ${DESTINATION_DIR} ] ;then
if ! [[ "${USER_UID}" == "root" ]] ;then
echo "ERROR: ${DESTINATION_DIR} not exists or no permission to write"
exit 1
fi
fi
PKG_FILE_TAIL=$(echo ${PKG_FILE_NAME:0-7} | tr 'A-Z' 'a-z')
PKG_FILE_TAIL=${PKG_FILE_TAIL:=${PKG_FILE_NAME}}
# echo "${PKG_FILE_TAIL}"
case ${PKG_FILE_TAIL} in
*.7z)
which 7z > /dev/null
if [[ $? != 0 ]] ;then
echo "zip command not exists. Please install p7zip-full"
exit
fi
echo "7z x ${PKG_FILE_NAME} -o${DESTINATION_DIR}"
${USER_FLAG} 7z x ${PKG_FILE_NAME} -o${DESTINATION_DIR}
;;
*.zip)
which unzip > /dev/null
if [[ $? != 0 ]] ;then
echo "zip command not exists. Please install zip"
exit
fi
echo "unzip ${PKG_FILE_NAME} -d ${DESTINATION_DIR}"
${USER_FLAG} unzip ${PKG_FILE_NAME} -d ${DESTINATION_DIR}
;;
*.rar)
which unrar > /dev/null
if [[ $? != 0 ]] ;then
echo "unrar command not exists. Please install unrar"
exit
fi
echo "unrar x ${PKG_FILE_NAME} ${DESTINATION_DIR}"
${USER_FLAG} unrar x ${PKG_FILE_NAME} ${DESTINATION_DIR}
;;
*.tar | *.jar)
echo "tar -xvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}"
${USER_FLAG} tar -xvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}
;;
.tar.gz | *.tgz)
echo "tar -zxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}"
${USER_FLAG} tar -zxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}
;;
tar.bz2)
echo "tar -jxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}"
${USER_FLAG} tar -jxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}
;;
.tar.xz)
echo "tar -Jxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}"
${USER_FLAG} tar -Jxvf ${PKG_FILE_NAME} -C ${DESTINATION_DIR}
;;
*.gz | *-gz | *.z | *-z)
if [[ "${DESTINATION_DIR}" != "$(pwd)" ]] ;then
mv ${PKG_FILE_NAME} ${DESTINATION_DIR}
fi
pushd ${DESTINATION_DIR} > /dev/null
echo "gunzip ${PKG_FILE_NAME} ..."
${USER_FLAG} gunzip ${PKG_FILE_NAME}
popd > /dev/null
;;
*)
echo "Unsupported package type."
exit 1
;;
esac
echo "Done."
}
check_user_UID
# unpack_package_file -f $1
unpack_package_file -f $1 -d $2
# unpack_package_file -f $1 -d $2 -u root
<file_sep>/.vim/tools/shell/gen_kernel_SrcExpl.sh
#! /bin/bash
# created by Longbin_Li <<EMAIL>>
clear
echo "use this script to generate cscope files and tags for linux kernel"
FILENAME=cscope.files
function gencscopef()
{
echo "Searching *.h *.c ... from $PWD"
# find . -iname "*.[hc]" \
# | sed -n "s%^\.%$PWD%p" \
# > ${FILENAME}
# if [[ $? == 0 ]] ;then
# [[ -s ${FILENAME} ]] && echo "generate files: " && ls -lh ${FILENAME}
# else
# echo "error occured, ${FILENAME} not be generated" && exit 1
# fi
# sed -n "s/old/new/p"
# sed -n "s%$old%$new%p" use % to replace if used var contains of "/"
echo "generating cscope index files ..."
# cscope -bkq -i ${FILENAME}
cscope-indexer -r
# [[ $? == 0 ]] && echo "generated files: " && ls -lh cscope*
}
if [[ -f cscope.out ]] ;then
read -p " update cscope files ? <y/n> " select
if [[ "$select" == "y" ]] ;then
rm cscope.out
gencscopef
else
echo "not updated cscope files"
fi
else
gencscopef
fi
function genctags()
{
echo "generating tags file ..."
ctags -R *
# --langmap=c:+.h \
# --fields=+lS \
# $PWD
echo "preparations over" && ls -lh tags
}
if [[ -f tags ]] ;then
read -p " update tags file ? <y/n> " select
if [[ "$select" == "y" ]] ;then
rm tags
genctags
else
echo "not updated tags"
fi
else
genctags
fi
<file_sep>/.vim/tools/python/02subprocess.py
#! /usr/bin/python
# class subprocess test of python language
# created by longbin <<EMAIL>>
# 2015-01-07
import subprocess
# use class subprocess to get child's pid,
# return value, stdin, stdout, stderr etc.
sPopen = subprocess.Popen("ls /home/", shell=True, stdout=subprocess.PIPE)
sPopen.wait() # wait for sPopen's process end
print "sPopen.pid :", sPopen.pid
print "sPopen.returncode :", sPopen.returncode
print "sPopen.stdin :", sPopen.stdin
print "sPopen.stdout.read() :", sPopen.stdout.read()
print "sPopen.stderr :", sPopen.stderr
# if ... else statement
if sPopen.pid == sPopen.pid :
print "sPopen.pid == sPopen.pid"
else:
print "sPopen.pid != sPopen.pid"
# communicate can get stderr and stdout
out = sPopen.communicate()
print "sPopen.communicate out :", out
print "sPopen.communicate out[0] = ", out[0]," out[1]", out[1],"\n"
# get return code of shell commands
retcode = subprocess.call("ls ~/", shell=True, stdout=subprocess.PIPE)
print "subprocess.call retcode :", retcode
try:
res = subprocess.check_call(['ls', '-l'])
except err:
print "subprocess.check_call res :", res
res = subprocess.Popen("echo \"hello python\"", shell=True, stdout=subprocess.PIPE)
print "res.stdout.read() :", res.stdout.read()
print "res.returncode :", res.returncode
# while loop example
a=0;b=10
while a < b:
print a,' '
a +=1
else:
print 'a is not less than ', b
# for loop example1
# range(start_number, end_number)
for i in range(-5, 3):
print "range(-5, 3):",i
else:
print "for end."
# for loop example2
# range(start_number, end_number, step)
for i in range(0, 10, 2):
print "range(0, 10, 2):",i
else:
print "range end."
<file_sep>/README.md
# vim_plugins
vim plugins of ubuntu/centos
<file_sep>/.vim/tools/init/my_bash_alias
#! /bin/bash
# ~/.my_bash_alias
# we need add below 3 sentences to ~/.bashrc
# if [ -f ~/.my_bash_alias ] ;then
# . ~/.my_bash_alias
# fi
function __load_and_initialise_recordmydesktop_XXX()
{
if [[ "x$(which recordmydesktop 2>/dev/null)" != "x" ]] ;then
alias recordmydesktop="$(which recordmydesktop) --fps=5 --on-the-fly-encoding --output=video_by_${USER}_$(date +%Y%m%d_%H%M%S)"
alias recordmydesktop_mini='recordmydesktop -x 100 -y 100 --width=400 --height=300'
alias recordmydesktop_full='recordmydesktop '
fi
}
__load_and_initialise_recordmydesktop_XXX
function __load_and_initialise_cindent_XXX()
{
if [ "x$(which indent 2> /dev/null)" != "x" ] ;then
alias cindent='indent -npro -kr -i8 -ts8 -sob -l80 -ss -ncs -br -ce -cdw -brs -brf -bap -cp1 -npsl'
fi
}
__load_and_initialise_cindent_XXX
<file_sep>/.vim/tools/shell/cindent.sh
#! /bin/bash
## /usr/src/kernels/2.6.32-504.el6.i686/scripts/Lindent
## Author: longbin <<EMAIL>>
## Release Date: 2015-05-28
## Release Version: 1.15.723
## Last Modified: 2015-07-23
##
KERNEL_STYLE_PARAM="-npro -kr -i8 -ts8 -sob -l80 -ss -ncs -cp1"
LINUX_STYLE_PARAM="-npro -nbad -bap -nbc -bbo -hnl -br -brs -c33 -cd33 -ncdb -ce -ci4 -cli0 -d0 -di1 -nfc1 -i8 -ip0 -l80 -lp -npcs -nprs -npsl -sai -saf -saw -ncs -nsc -sob -nfca -cp33 -ss -ts8 -il1"
GNU_STYLE_PARAM="-npro -nbad -bap -nbc -bbo -bl -bli2 -bls -ncdb -nce -cp1 -cs -di2 -ndj -nfc1 -nfca -hnl -i2 -ip5 -lp -pcs -nprs -psl -saf -sai -saw -nsc -nsob"
KR_STYLE_PARAM="-npro -nbad -bap -bbo -nbc -br -brs -c33 -cd33 -ncdb -ce -ci4 -cli0 -cp33 -cs -d0 -di1 -nfc1 -nfca -hnl -i4 -ip0 -l75 -lp -npcs -nprs -npsl -saf -sai -saw -nsc -nsob -nss"
VS_STYLE_PARAM="-npro -kr -i8 -ts8 -sob -l80 -ss -ncs -bl -bli0 -nce -bls -blf -bap -cp1 -npsl"
UC_STYLE_PARAM="-npro -kr -i8 -ts8 -sob -l80 -ss -ncs -br -ce -cdw -brs -brf -bap -cp1 -npsl"
DEFAULT_STYLE_PARAM=${UC_STYLE_PARAM}
INDENT_PARAM="${DEFAULT_STYLE_PARAM}"
FILE_TAIL=kr
## function check whether indent exists
function check_which_indent()
{
local ret_val=$(which indent 2>/dev/null)
if [ "x${ret_val}" == "x" ] ;then
echo "ERR (127): Please install indent"
exit 127
fi
}
check_which_indent
## function indent function usage
function indent_func_usage()
{
cat << EOF
Usage:
bash ${0##*/} input_file1.c [input_file2.c ...]
You will get the modified file(s): input_file1.c
EOF
}
## function select indent style and parameters
function select_indent_style()
{
echo "Please select indent style: "
# TMOUT=5
PS3="Type a index number[1]: "
select option in \
"KERNEL STYLE" \
"LINUX STYLE" \
"GNU STYLE" \
"KR STYLE" \
"VS STYLE" \
"UC STYLE"
do
case ${REPLY} in
1)
INDENT_PARAM="${KERNEL_STYLE_PARAM}"
FILE_TAIL=kernel
;;
2)
INDENT_PARAM="${LINUX_STYLE_PARAM}"
FILE_TAIL=linux
;;
3)
INDENT_PARAM="${GNU_STYLE_PARAM}"
FILE_TAIL=gnu
;;
4)
INDENT_PARAM="${KR_STYLE_PARAM}"
FILE_TAIL=kr
;;
5)
INDENT_PARAM="${VS_STYLE_PARAM}"
FILE_TAIL=vs
;;
6)
INDENT_PARAM="${UC_STYLE_PARAM}"
FILE_TAIL=uc
;;
*)
echo "invalid option."
;;
esac
if [ "x${INDENT_PARAM}" != "x" ] ;then
break
fi
done
INDENT_PARAM="${INDENT_PARAM:=${UC_STYLE_PARAM}}"
}
##function set indent parameters
function set_indent_parameters()
{
read -p "Press <Enter> to continue or <y> to reset paramters: " select
if [ "x${select}" == "xy" ] ;then
select_indent_style
fi
INDENT_REV=$(indent --version)
INDENT_REV_1=$(echo ${INDENT_REV} | cut -d' ' -f3 | cut -d'.' -f1)
INDENT_REV_2=$(echo ${INDENT_REV} | cut -d' ' -f3 | cut -d'.' -f2)
INDENT_REV_3=$(echo ${INDENT_REV} | cut -d' ' -f3 | cut -d'.' -f3)
if [ ${INDENT_REV_1} -gt 2 ] ; then
INDENT_PARAM="${INDENT_PARAM} -il0"
elif [ ${INDENT_REV_1} -eq 2 ] ; then
if [ ${INDENT_REV_2} -gt 2 ] ; then
INDENT_PARAM="${INDENT_PARAM} -il0"
elif [ ${INDENT_REV_2} -eq 2 ] ; then
if [ ${INDENT_REV_3} -ge 10 ] ; then
INDENT_PARAM="${INDENT_PARAM} -il0"
fi
fi
fi
if [ "x${INDENT_PARAM}" == "x" ] ;then
echo "Set indent parameter ERROR!"
exit -1
fi
}
function check_and_indent_file()
{
local FILE_LIST=$*
for file in ${FILE_LIST}
do
if ! [ "x${file##*.}" != "xc" -o "x${file##*.}" != "xC" ] ;then
echo "${file}: Not a C program file"
exit -1
fi
echo -e "Formatting ${file} ... \c"
if [ -e "${file}" -a -w "${file}" ] ;then
INDENT_RESULT_FILE=${file%.*}_${FILE_TAIL}_$(date +%Y%m%d%H%M%S).${file##*.}
# echo "indent ${INDENT_PARAM} ${file} -o ${INDENT_RESULT_FILE}"
indent ${INDENT_PARAM} ${file} -o ${INDENT_RESULT_FILE}
mv ${INDENT_RESULT_FILE} ${file}
echo "OK"
else
echo "${file}: No such file or No permission to write"
exit -1
fi
done
}
function check_and_indent_to_stdout()
{
local FILE_LIST=$*
for file in ${FILE_LIST}
do
if ! [ "x${file##*.}" != "xc" -o "x${file##*.}" != "xC" ] ;then
echo "${file}: Not a C program file"
exit -1
fi
if [ -e "${file}" -a -r "${file}" ] ;then
indent ${INDENT_PARAM} -st ${file}
else
echo "${file}: No such file or No permission to read"
exit -1
fi
done
}
## indent file main function
function indent_file_main_func()
{
local CFILES=$*
if [ ${#} -lt 1 ] ;then
echo "ERR: No input file(s)"
indent_func_usage
exit
elif [ ${#} -ge 1 ] ;then
set_indent_parameters
read -p "Press <y> (modify original files) or <Enter> (to screen): " select
if [ "x${select}" == "xy" -o "x${select}" == "xY" ] ;then
check_and_indent_file ${CFILES}
else
check_and_indent_to_stdout ${CFILES}
fi
if [ $? -eq 0 ] ;then
echo "Working done !"
fi
fi
}
## indent [INDENT_PARAM] inputfiles
## indent [INDENT_PARAM] inputfile -o outputfile
## indent [INDENT_PARAM] inputfile -st > outputfile
indent_file_main_func $*
<file_sep>/.vim/tools/shell/make_un_sparse_img.sh
#! /bin/bash
## this scripts is used to make un-sparse image files,
## then could copy the generated files to Windows and
## to make DataIO images
## created by longbin <<EMAIL>>
## 2015-01-24
## 2015-01-27
## 2015-03-06
#######################################################################
#### Global definition segment ########################################
## please define the "EMMC_IMAGES" and "ANDROID_DIR" directory name correctly
## in the following lines.
## define the route of project and image file directories
EMMC_IMAGES=emmc_images
PROJECT_DIR=tc75-factory
PREBURN_DIR=preburn_image-$(date +%Y%m%d)
ANDROID_DIR=${PROJECT_DIR}/LINUX/android
## define the route of un-sparse image source directory
RAW_IMG_OUT_DIR=${ANDROID_DIR}/out/target/product/TC75
VMLINUX_FILE=${RAW_IMG_OUT_DIR}/obj/KERNEL_OBJ/vmlinux
ESSENTIAL_FILES="emmc_appsboot.mbn MPRG8960.hex NON-HLOS.bin rpm.mbn sbl1.mbn sbl2.mbn sbl3.mbn tz.mbn"
LOGO_AND_ENV_BIN="logo1.bin logo2.bin env.bin"
## define the whole route of rawprogram0.xml and path0.xml file in emmc_images
RAW_XML=${EMMC_IMAGES}/rawprogram0.xml
PATCH0_XML=${EMMC_IMAGES}/patch0.xml
## define the whole route of target file in preburn iamge directory
RAW_TEST_XML=${PREBURN_DIR}/rawprogram0.xml
## define un-sparse image type
UN_SPARSE_IMGS="system userdata persist cache"
UN_SPARSE_IMG_TAIL="_test"
## define the size of un-sparse images
## system 1024M
let SYSTEM_SIZE=1024*1024*1024
## userdata 4928M - 80K -512M
let USERDATA_SIZE=1024*1024*4928-1024*80-1024*1024*512
## persist 8M
let PERSIST_SIZE=1024*1024*8
## cache 256M
let CACHE_SIZE=1024*1024*256
#######################################################################
## backup the main directory
MAIN_DIR=$(pwd)
OLD_EMMC_IMAGES=${EMMC_IMAGES}
OLD_PROJECT_DIR=${PROJECT_DIR}
######################
## get_current_script_file_name function can get current
## shell script's filename and return back
function get_current_script_file_name(){
## get current script PID
CUR_PID=$$
## echo "current PID is ${CUR_PID}"
## get current script file name
local cs_file_name=`ps -ef | grep ${CUR_PID} \
| sed -n "/${USER}[ ]*${CUR_PID}/p" \
| awk '{ match($0, /[^ ]*$/)
print substr($0, RSTART, RLENGTH)
}'`
## check current script file's mode
if [[ -f ${cs_file_name} ]] && [[ -w ${cs_file_name} ]] ;then
echo "${cs_file_name}"
fi
}
## update_script_variable_to_value function can update a definition in a file
## this function has 3 options/arguments
## -f filename :filename is in what you want to update definition
## -t definition :definition is the target you want to change
## -v value :value is the value of the target will update to
function update_script_variable_to_value(){
## get options and variables
local OPTIND
while getopts "f:t:v:" func_opt
do
case "${func_opt}" in
f)
target_file=${OPTARG}
# echo "target filename is: ${target_file}"
;;
t)
target_variable=${OPTARG}
# echo "target variable is: ${target_variable}"
;;
v)
target_value=${OPTARG}
# echo "target value is: ${target_value}"
;;
?)
echo "unknown option and argument."
exit 1
;;
esac
done
# echo "there are $# arguments"
# echo "All arguments are: $*"
## check options and values
if [[ "${target_file}" == "" ]] ;then
echo "target filename is: ${target_file}"
echo "get invalid argument: target_file."
exit 1
fi
if [[ "${target_variable}" == "" ]] ;then
echo "target variable is: ${target_variable}"
echo "get invalid argument: target_variable."
exit 1
fi
if [[ "${target_value}" == "" ]] ;then
echo "target value is: ${target_value}"
echo "get invalid argument: target_value."
exit 1
fi
if ! [[ -f ${target_file} ]] || ! [[ -w ${target_file} ]] ;then
echo "No such file, or have no permission"
exit 1
fi
## replace target_variable -> target_value in target_file
## the variable can't include any blank
## and the variable should be defined in one line.
sed -i "/^[\t ]*${target_variable}=[^ ]*$/ s%${target_variable}=[^ ]*$%${target_variable}=${target_value}%g" ${target_file}
echo "${target_variable} updated to ${target_value} in \"${target_file}\"."
return
}
######################
## check file naming availability
## to avoid invalid data
function check_file_naming_availability(){
## availability file name regexp: /^[a-zA-Z0-9()_-]*$/
local res_val=`echo $1 | sed -n "/^[a-zA-Z0-9./_-]*$/p"`
# echo ${res_val}
if [[ "${res_val}" == "" ]] ;then
echo "Invalid parameter."
exit 1
fi
}
## check the "EMMC_IMAGES" and "ANDROID_DIR" directory
## which defined above whether exist.
function check_project_android_dir(){
## check PROJECT_DIR directory
if [[ -d ${PROJECT_DIR} ]] ;then
echo "[project directory] is: ${PROJECT_DIR} "
## check android directory
if [[ -d "${ANDROID_DIR}" ]] ;then
echo "[android directory] is: ${ANDROID_DIR} "
else
echo "android directory \"${ANDROID_DIR}\" no exists."
exit 1
fi
else
echo "project directory \"${PROJECT_DIR}\" error, No such directory"
let TRIED_AGAIN_NUM+=1
if [[ ${TRIED_AGAIN_NUM} -gt 3 ]] ;then
let TRIED_AGAIN_NUM=0
echo "you tried more than 3 times, exit"
exit 1
fi
read -p "type your project directory: " PROJECT_DIR
check_file_naming_availability ${PROJECT_DIR}
if [[ ${PROJECT_DIR} == "" ]] ;then
echo "type error, exit"
exit 1
else
## update tmp variable
ANDROID_DIR=${PROJECT_DIR}/LINUX/android
RAW_IMG_OUT_DIR=${ANDROID_DIR}/out/target/product/TC75
VMLINUX_FILE=${RAW_IMG_OUT_DIR}/obj/KERNEL_OBJ/vmlinux
check_project_android_dir
fi
fi
}
## check emmc_images directory
function check_emmc_images_dir_exits(){
if ! [[ -d ${EMMC_IMAGES} ]] ;then
echo "emmc_images directory \"${EMMC_IMAGES}\" error, No such directory "
let TRIED_AGAIN_NUM+=1
if [[ ${TRIED_AGAIN_NUM} -gt 3 ]] ;then
let TRIED_AGAIN_NUM=0
echo "you tried more than 3 times, exit"
exit 1
fi
read -p "type your project directory: " EMMC_IMAGES
check_file_naming_availability ${EMMC_IMAGES}
if [[ "${EMMC_IMAGES}" == "" ]] ;then
echo "type error, exit"
exit 1
else
## update tmp variable
RAW_XML=${EMMC_IMAGES}/rawprogram0.xml
PATCH0_XML=${EMMC_IMAGES}/patch0.xml
## check emmc images directory again
check_emmc_images_dir_exits
fi
else
echo "[emmc_images directory] is: ${EMMC_IMAGES}"
fi
}
## check out directory and emmc_images directory
function check_defined_dir_exists(){
## get current script file name
local cur_file_name=`get_current_script_file_name`
echo "Current script file name is: ${cur_file_name}"
echo -e "\nCurrent directory is:\n\t ${PWD}\n"
## check project and android directory
check_project_android_dir
## check out directory
if ! [[ -d ${RAW_IMG_OUT_DIR} ]] ;then
echo "image directory ${RAW_IMG_OUT_DIR} not exists"
exit 1
else
echo "[built image directory] is: ${RAW_IMG_OUT_DIR}"
fi
## update PROJECT_DIR to new one in current file
if [[ "${OLD_PROJECT_DIR}" != "${PROJECT_DIR}" ]] ;then
echo "old project directory is: ${OLD_PROJECT_DIR}"
update_script_variable_to_value -f ${cur_file_name} -t PROJECT_DIR -v ${PROJECT_DIR}
if [[ "$?" == "0" ]] ;then
echo "updated project directory is: ${PROJECT_DIR}"
else
echo "updated project directory error"
return
fi
## the PROJECT_DIR will automatically update by user's type
fi
## check emmc_images directory
check_emmc_images_dir_exits
if [[ "${OLD_EMMC_IMAGES}" != "${EMMC_IMAGES}" ]] ;then
echo "old emmc_images directory is: ${OLD_EMMC_IMAGES}"
update_script_variable_to_value -f ${cur_file_name} -t EMMC_IMAGES -v ${EMMC_IMAGES}
if [[ "$?" == "0" ]] ;then
echo "updated project directory is: ${EMMC_IMAGES}"
else
echo "updated project directory error"
return
fi
## the PROJECT_DIR will automatically update by user's type
fi
}
## verify preburn image directory
## if the directory not exists, create and use it;
## if the directory has already exists, notice user whether overwrite or not;
## if user's directory also exists, exit
function check_preburn_image_dir(){
if [[ -d ${PREBURN_DIR} ]] ;then
read -p "directory \"${PREBURN_DIR}\" has exists, overwrite <y/n>? " select
if [[ "$select" != "y" ]] ;then
read -p "please type a new directory name to collect image files: " PREBURN_DIR
check_file_naming_availability ${PREBURN_DIR}
if [[ "${PREBURN_DIR}" == "" ]] ;then
echo "directory name can not be empty !"
exit 1
elif [[ -d "${PREBURN_DIR}" ]] ;then
echo "directory \"${PREBURN_DIR}\" has also exists ."
exit 1
else
mkdir -p ${PREBURN_DIR} && echo "mkdir ${PREBURN_DIR} ..."
fi
fi
else
echo "mkdir ${PREBURN_DIR} ..."
mkdir -p ${PREBURN_DIR}
fi
## test whether target directory exists
if [[ -d ${PREBURN_DIR} ]] && [[ -w ${PREBURN_DIR} ]] ;then
echo "directory \"${PREBURN_DIR}\" checked OK."
else
echo "directory \"${PREBURN_DIR}\" not exists or have no permission to write."
exit 1
fi
}
function copy_logo_and_env_bin_to_preburn_dir(){
## find and copy logo1.bin logo2.bin env.bin
## find files depth==2
echo "finding and copying files: ${LOGO_AND_ENV_BIN}"
for file in ${LOGO_AND_ENV_BIN}
do
file_name=`find ${PREBURN_DIR} -maxdepth 2 -name ${file} |\
sed -n "/${file}/p" | sed -n '1p' `
if [[ "${file_name}" == "" ]] ;then
file_name=`find ./ ${EMMC_IMAGES} -maxdepth 3 -name ${PREBURN_DIR} -prune -o -name ${file} |\
sed -n "/${file}/p" | sed -n '1p' `
fi
if [[ "${file_name##*/}" == "${file}" ]] ;then
echo -e "\tfind out \"${file_name}\" "
if ! [[ -f ${PREBURN_DIR}/${file} ]] ;then
echo -e "\t${file_name} -> ${PREBURN_DIR}/${file_name##*/} ..."
cp -f ${file_name} ${PREBURN_DIR}
else
echo -e "\t\"${file}\" exists in ${PREBURN_DIR}/, no need to copy."
fi
fi
done
lack_file=0
for file in ${LOGO_AND_ENV_BIN}
do
if ! [[ -f ${PREBURN_DIR}/${file} ]] ; then
echo -e "\tCouldn't find file \"${file}\"; \c"
echo -e "Please copy \"${file}\" to dir \"${PREBURN_DIR}\"."
lack_file=1
fi
done
if [[ "${lack_file}" == "1" ]] ;then
echo "ERR occurred, exit."
exit 1
fi
}
## test whether user's directory exists and copy image files
function copy_images_to_preburn_dir(){
## define copy flag -u for update and -v for verbose
# CP_FLAG="-uv"
CP_FLAG="-v"
echo "copying files ..."
## copy file under emmc_images to preburn_image file
if [[ -d ${EMMC_IMAGES} ]] ;then
cp ${CP_FLAG} ${EMMC_IMAGES}/* ${PREBURN_DIR}
fi
## copy built images under out dir to preburn images directory
## exclude system_test.img/userdata_test.img ...
for img_file in `ls ${RAW_IMG_OUT_DIR}/*.img | sed 's/[ ]/\n/p' | sed "/${UN_SPARSE_IMG_TAIL}/d"`
do
[[ -d ${RAW_IMG_OUT_DIR} ]] && cp ${CP_FLAG} ${img_file} ${PREBURN_DIR}
done
## copy emmc_appsboot.mbn
[[ -d ${RAW_IMG_OUT_DIR} ]] && cp ${CP_FLAG} ${RAW_IMG_OUT_DIR}/emmc*.mbn ${PREBURN_DIR}
## copy vmlinux file
[[ -f ${VMLINUX_FILE} ]] && cp ${CP_FLAG} ${VMLINUX_FILE} ${PREBURN_DIR}
## test the completeness of files in ESSENTIAL_FILES list
for file in ${ESSENTIAL_FILES}
do
if ! [[ -f ${PREBURN_DIR}/${file} ]] ;then
let err_flag=1
echo "ERR: \"${PREBURN_DIR}/${file}\" not exists"
fi
done
if [[ "${err_flag}" == "1" ]] ;then
echo "some essential files not exists, please check"
exit 1
else
echo "copy files done."
fi
}
function prepare_images_to_preburn_dir(){
#######################################################################
## copy images to preburn image directory
check_defined_dir_exists
check_preburn_image_dir
read -p "Copy/Update image files to \"${PREBURN_DIR}\" <y/n>? " select
if [[ ${select} == "y" ]] ;then
copy_logo_and_env_bin_to_preburn_dir
copy_images_to_preburn_dir
else
echo "refused by user. Exit"
exit 1
fi
#######################################################################
}
## copy and edit rawprogram0.xml which defined the partition, label and image file
function copy_xml_file_to_preburn_and_modify(){
## copy XML files
if [[ -f ${RAW_XML} ]] ;then
cp -v ${RAW_XML} ${RAW_TEST_XML}
else
echo "copy error, No such file: ${RAW_XML}"
exit 1
fi
if [[ -f ${PATCH0_XML} ]] ;then
cp -v ${PATCH0_XML} ${PREBURN_DIR}
else
echo "copy error, No such file: ${PATCH0_XML}"
exit 1
fi
## edit rawprogram0.xml and path0.xml
echo "editing ${RAW_TEST_XML} ..."
echo -e "\treplace sparse=\"true\" -> sparse=\"false\" "
sed -i "s%sparse=\"true\"%sparse=\"false\"%g" ${RAW_TEST_XML}
## replace system.img to system_test.img etc.
## define the source directory of un-sparse image
if [[ "${UN_SPARSE_IMG_TAIL}" == "" ]] ;then
echo "UN_SPARSE_IMG_TAIL can't be defined as empty."
exit 1
fi
for us_img_name in ${UN_SPARSE_IMGS}
do
## rawprogram0.xml: system.img -> system_test.img
sed -i "s%\"${us_img_name}.img\"%\"${us_img_name}${UN_SPARSE_IMG_TAIL}.img\"%g" ${RAW_TEST_XML}
echo -e "\treplace ${us_img_name}.img -> ${us_img_name}${UN_SPARSE_IMG_TAIL}.img"
done
## add factory.img filename in rawprogram0.xml
## rawprogram0.xml: enterprise -> enterprise.img
if [[ -f ${PREBURN_DIR}/enterprise.img ]] ;then
sed -i "/label=\"enterprise\"/ s%filename=\"[^ ]*\"%filename=\"enterprise.img\"%g" ${RAW_TEST_XML}
echo -e "\tset filename=\"enterprise.img\" "
fi
## rawprogram0.xml: factory -> factory.img
if [[ -f ${PREBURN_DIR}/factory.img ]] ;then
sed -i "/label=\"factory\"/ s%filename=\"[^ ]*\"%filename=\"factory.img\"%g" ${RAW_TEST_XML}
echo -e "\tset filename=\"factory.img\" "
fi
## rawprogram0.xml: environment -> env.bin
if [[ -f ${PREBURN_DIR}/env.bin ]] ;then
sed -i "/label=\"environment\"/ s%filename=\"[^ ]*\"%filename=\"env.bin\"%g" ${RAW_TEST_XML}
echo -e "\tset filename=\"env.bin\" "
fi
## rawprogram0.xml: logo1 -> logo1.bin
if [[ -f ${PREBURN_DIR}/logo1.bin ]] ;then
sed -i "/label=\"logo1\"/ s%filename=\"[^ ]*\"%filename=\"logo1.bin\"%g" ${RAW_TEST_XML}
echo -e "\tset filename=\"logo1.bin\" "
fi
## rawprogram0.xml: logo2 -> logo2.bin
if [[ -f ${PREBURN_DIR}/logo2.bin ]] ;then
sed -i "/label=\"logo2\"/ s%filename=\"[^ ]*\"%filename=\"logo2.bin\"%g" ${RAW_TEST_XML}
echo -e "\tset filename=\"logo2.bin\" "
fi
echo "copy and modify \"${RAW_TEST_XML}\" done. "
}
function deal_with_xml_file(){
#######################################################################
## deal with xml file
read -p "copy ${RAW_XML} to ${RAW_TEST_XML} and modify it <y/n>? " select
if [[ ${select} == "y" ]] ;then
## copy xml file to preburn image directory and
## check whether the image exists in preburn image directory
## whose filename defined in xml
copy_xml_file_to_preburn_and_modify
else
echo "canceled by user, exit."
exit 1
fi
#######################################################################
}
## make un-sparse image file
function check_and_setup_make_ext4fs_command(){
## test whether make_ext4fs command exists
make_ext4fs 2>/dev/null
if [[ "$?" == "127" ]] ;then
if [[ -f ${ANDROID_DIR}/build/envsetup.sh ]] ;then
## setup environment so that we could use "make_ext4fs" command
echo "setup make_ext4fs command ..."
cd ${ANDROID_DIR}
echo ${PWD}
source build/envsetup.sh
sleep 1
choosecombo
cd ${MAIN_DIR}
else
echo -e "\tmake_ext4fs: command not found"
echo -e "\tplease execute following commands:"
echo -e "\t +---------------------------------+"
echo -e "\t | cd ${ANDROID_DIR} "
echo -e "\t | source build/envsetup.sh |"
echo -e "\t | choosecombo |"
echo -e "\t +---------------------------------+"
exit 1
fi
elif [[ "$?" != 0 ]] ;then
echo "make_ext4fs command exists, please use it correctly."
fi
}
function check_un_sparse_image_vs_xml(){
## check whether rawprogram0.xml includes the records about
## un-sparse image file which are made by above steps
echo "checking whether xml defined all un-sparse images ..."
#sleep 1
err_flag=0
for file in `ls ${PREBURN_DIR}/*${UN_SPARSE_IMG_TAIL}.img`
do
if [[ $(sed -n "/${file##*/}/p" ${RAW_TEST_XML}) == "" ]] ;then
echo "WARNING: ${RAW_TEST_XML} not defined ${file}"
err_flag=1
fi
done
if [[ "${err_flag}" == "1" ]] ;then
echo -e "\n---------------Warning-------------------"
echo "please check if ${RAW_TEST_XML} defined all un-sparse image filename"
exit 1
else
echo "all un-sparse images have defined in \"${RAW_TEST_XML}\"."
fi
}
function check_xml_vs_image_files(){
## check whether image exists which named in rawprogram0.xml
## gain the filename list in the file rawprogram0.xml
echo "Verifying whether \"${RAW_TEST_XML}\" matches \"${PREBURN_DIR}/*.img\" ... "
#sleep 1
# CONTENT_FILENAMES=$(sed 's/[ ]/\n/g' ${RAW_TEST_XML} | \
# sed -n '/filename=\"[^ ]\{1,\}\"/p' | \
# cut -d "\"" -f 2 )
CONTENT_FILENAMES=$(awk '{match($0, /filename=\"[^ ]*\"/)
split(substr($0, RSTART, RLENGTH), arr, /\"/)
if(arr[2]!="")
print arr[2]
}' ${RAW_TEST_XML})
test_res_flag=0
## test whether the image filename which define in rawprogram0.xml
## exists in the preburn_image directory
## echo "files:"
## echo "${CONTENT_FILENAMES}"
for test_file in ${CONTENT_FILENAMES}
do
# echo -e "\tVerifying \"${test_file}\" ...\n\c"
if ! [[ -f ${PREBURN_DIR}/${test_file} ]] ;then
echo "ERR: \"${RAW_TEST_XML}\" defined \"${test_file}\", but No such file: ${PREBURN_DIR}/${test_file} "
let test_res_flag=1
else
echo -e "\tVerifying OK. Exists \"${PREBURN_DIR}/${test_file}\" "
fi
done
if [[ "${test_res_flag}" == "1" ]] ;then
echo "Not all image files does match \"${RAW_TEST_XML}\" !"
exit 1
else
echo -e "\tVerified over, no error."
fi
}
function make_ext4fs_and_copy_to_preburn_image(){
echo "make ext4 fs ..."
check_and_setup_make_ext4fs_command
## make ext4 fs for system/ data/ persist/ cache
echo -e "\nmake_ext4fs ...\n"
echo -e "\nmake_ext4fs: system${UN_SPARSE_IMG_TAIL}.img\n"
make_ext4fs -l ${SYSTEM_SIZE} -a system ${RAW_IMG_OUT_DIR}/system${UN_SPARSE_IMG_TAIL}.img ${RAW_IMG_OUT_DIR}/system
echo -e "\nmake_ext4fs: userdata${UN_SPARSE_IMG_TAIL}.img\n"
make_ext4fs -l ${USERDATA_SIZE} -a userdata ${RAW_IMG_OUT_DIR}/userdata${UN_SPARSE_IMG_TAIL}.img ${RAW_IMG_OUT_DIR}/data
echo -e "\nmake_ext4fs: persist${UN_SPARSE_IMG_TAIL}.img\n"
make_ext4fs -l ${PERSIST_SIZE} -a persist ${RAW_IMG_OUT_DIR}/persist${UN_SPARSE_IMG_TAIL}.img ${RAW_IMG_OUT_DIR}/persist
echo -e "\nmake_ext4fs: cache${UN_SPARSE_IMG_TAIL}.img\n"
make_ext4fs -l ${CACHE_SIZE} -a cache ${RAW_IMG_OUT_DIR}/cache${UN_SPARSE_IMG_TAIL}.img ${RAW_IMG_OUT_DIR}/cache
## copy un-sparse image files to preburn image directory
if [[ "$?" == "0" ]] ;then
echo -e "make_ext4fs finished .\ncopying image files ..."
cp -v ${RAW_IMG_OUT_DIR}/*${UN_SPARSE_IMG_TAIL}.img ${PREBURN_DIR}
echo "-------------------------------------"
ls -lh ${PREBURN_DIR}/*${UN_SPARSE_IMG_TAIL}.img
echo "-------------------------------------"
fi
check_un_sparse_image_vs_xml
check_xml_vs_image_files
}
function make_un_sparse_image(){
#######################################################################
## make un-sparse images
read -p "make ext4fs from \"${RAW_IMG_OUT_DIR}\" <y/n>? " select
if [[ "${select}" == "y" ]] ;then
echo " system size: $SYSTEM_SIZE"
echo " userdata size: $USERDATA_SIZE"
echo " persist size: $PERSIST_SIZE"
echo " cache size: $CACHE_SIZE"
read -p "Are all the image sizes correct <y/n>? " select
if [[ "${select}" == "y" ]] ;then
make_ext4fs_and_copy_to_preburn_image
else
echo "Image size error, exit ." && exit
fi
else
echo "Refused by user, make ext4fs exit."
exit 1
fi
#######################################################################
}
function generate_flash_img_shell_script(){
flash_name=${PREBURN_DIR}/flash_img-by-${USER}.sh
echo -e "generating flash image shell script for Linux ..."
if ! [[ -f ${flash_name} ]] ;then
## add script head
echo -e "#! /bin/bash\n# This script is automatically generated in Ubuntu" > ${flash_name}
echo -e "# Bourne-Again shell script, ASCII text executable" >> ${flash_name}
echo -e "# $(date +%Y-%m-%d\ %H:%M:%S)" >> ${flash_name}
## apend fastboot oem unlock
sed -i "$ a \\\\nadb devices" ${flash_name}
sed -i "$ a adb reboot bootloader" ${flash_name}
sed -i "$ a fastboot oem unlock moto_pollux\n" ${flash_name}
## generate shell script
if [[ -f ${RAW_TEST_XML} ]] ;then
awk '{match($0, /filename.*label=\"[^ ]*\"/)
split(substr($0, RSTART, RLENGTH), arr, "\"")
if (arr[2]!="")
print ("fastboot flash "arr[4], arr[2])
}' ${RAW_TEST_XML} >> ${flash_name}
fi
## replace system_test.img -> system.img ...
for file in ${UN_SPARSE_IMGS}
do
sed -i "/${file}${UN_SPARSE_IMG_TAIL}\.img/ s/${file}${UN_SPARSE_IMG_TAIL}\.img/${file}\.img/g" ${flash_name}
done
## modify shell script
if [[ -f ${flash_name} ]] ;then
## comment command include gpt partition
sed -i "/^.*gpt.*\.bin.*$/ s/^/#/g" ${flash_name}
## apend "fastboot reboot"
sed -i "$ a \\\\nfastboot reboot\n" ${flash_name}
fi
## show message
echo -e "\ngenerate shell script \"${flash_name}\" done.\n"
else
echo -e "WARNING: \"${flash_name}\" has already exist."
read -p "Overwrite \"${flash_name}\" <y/n>? " select
if [[ "${select}" == "y" ]] ;then
rm -vf ${flash_name} && echo "remove old file \"${flash_name}\" done."
generate_flash_img_shell_script
else
echo -e "\nNO operate update \"${flash_name}\" file.\n"
fi
fi
}
function pack_and_compress_preburn_images(){
## to pack and compress the image files to zip file
read -p "press <ENTER> to compress directory \"${PREBURN_DIR}\" to \"${PREBURN_DIR##*/}.zip\" file. "
zip -r ${PREBURN_DIR##*/}.zip ${PREBURN_DIR} && echo "generate \"${PREBURN_DIR##*/}.zip\" finished."
if [[ "$?" == "0" ]] ;then
echo "Now you can copy \"${PREBURN_DIR}(.zip)\" to windows system to Make DataIO format images."
else
[[ -f ${PREBURN_DIR##*/}.zip ]] && rm -v ${PREBURN_DIR##*/}.zip
echo "generate \"${PREBURN_DIR##*/}.zip\" file failed."
exit 1
fi
}
## execution tracing
#set -x
#set +x
clear
prepare_images_to_preburn_dir
deal_with_xml_file
make_un_sparse_image
generate_flash_img_shell_script
pack_and_compress_preburn_images
echo "Make Preburn images Done, goodbye !"
<file_sep>/.vim/tools/shell/centos_env_embed_setup_6.X.sh
#! /bin/bash
# Author: longbin <<EMAIL>>
# Created Date: 2014-06-24
# Release Version: 1.15.805
# Last Modified: 2015-08-05
# this script is available for centos to configure embedded environment
#list the software need to be installed to the variable FILELIST
CENTOS_BASIC_TOOLS="axel vim ctags cscope curl rar unrar zip unzip ghex nautilus-open-terminal p7zip p7zip-plugins tree meld tofrodos python-markdown subversion filezilla gedit firefox "
CENTOS_CODE_TOOLS="indent git-core gitk libtool cmake automake flex bison gperf graphviz gnupg gettext gcc gcc-c++ zlib-devel emacs "
# EMBED_TOOLS="ckermit minicom putty tftp-hpa tftpd-hpa uml-utilities nfs-kernel-server "
CENTOS_EMBED_TOOLS="xinetd ckermit minicom putty tftp tftp-server nfs4-acl-tools nfs-utils nfs-utils-lib "
UBUNTU_BUILD_ANDROID_U12="git gnupg flex bison gperf python-markdown build-essential zip curl ia32-libs libc6-dev libncurses5-dev:i386 xsltproc x11proto-core-dev libx11-dev:i386 libreadline6-dev:i386 libgl1-mesa-dev g++-multilib mingw32 tofrodos libxml2-utils zlib1g-dev:i386 "
#libgl1-mesa-dri:i386 libgl1-mesa-glx:i386
UBUNTU_BUILD_ANDROID_U14_ESSENTIAL="git gperf python-markdown g++-multilib libxml2-utils "
UBUNTU_BUILD_ANDROID_U14_TOOLS="git-core flex bison gperf gnupg build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev lib32z1 x11proto-core-dev libx11-dev libreadline-gplv2-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc libxml-simple-perl"
UBUNTU_AI_TOOLS="build-dep python python-numpy python-scipy python-setuptools matplotlib"
UBUNTU_PROXY_TOOLS="ntlmaps"
## apt-cache search opencv
# OPEN_CV="$(apt-cache search opencv | awk '{print $1}')"
# OPEN_CV="libgtk2.0-dev pkg-config"
## g++ `pkg-config opencv --cflags --libs` my_example.cpp -o my_example
## bison and flex is the analyzer of programmer and spell
## textinfo is a tool to read manual like man
## automake is used to help create Makefile
## libtool helps to deal with the dependency of libraries
## cvs, cvsd and subversion are used to control version
CENTOS_6_FILELIST="${CENTOS_BASIC_TOOLS} ${CENTOS_CODE_TOOLS} ${CENTOS_EMBED_TOOLS} ${CENTOS_AI_TOOLS}"
INSTALL_CHECK_FLAG="-y"
## check_user_UID
function check_user_UID() {
# if [[ ${UID} -lt 500 ]] ;then
# echo "ERROR: Please don't use root to execute this script."
# exit 1
# fi
# echo "Please input your password "
sudo ls > /dev/null
if [[ "x$?" == "x1" ]] ;then
echo -e "\tThere is a configuration/permission problem."
echo -e "\tPlease ensure that you have permission to use sudo"
exit 1
fi
if [ "x${UID}" == "x0" ] ;then
SUDO=''
else
SUDO=sudo
fi
}
check_user_UID
## check whether system is centos or not
function check_system_distributor() {
## get system distributor ID: centos ?
LINUX_DISTRIBUTOR=$(cat /etc/issue |tr 'A-Z' 'a-z'|awk ' /release/ {print $1}' | sed -n "1p")
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(lsb_release -i |tr 'A-Z' 'a-z'|awk '/distributor/ {print $3}')}
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/\<release\>/ {print $1}'|sed -n '1p')}
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/distrib_id=/ {print $1}'|sed 's/distrib_id=//'|sed -n '1p')}
echo "checking system distributor and release ID ..."
if [[ "${LINUX_DISTRIBUTOR}" == "centos" ]] ;then
echo -e "\tCurrent OS Distributor: ${LINUX_DISTRIBUTOR}"
else
echo -e "\tCurrent OS is not centos"
echo -e "\tCurrent OS Distributor: ${LINUX_DISTRIBUTOR}"
exit 1
fi
}
## check whether system is centos 6.5 or 6.6
function check_system_release_version() {
## get system release version: 6.5/6.6 ?
LINUX_RELEASE_VERSION=$(cat /etc/issue | awk '/release/ {print $3}'| sed -n '1p')
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(lsb_release -r | tr 'A-Z' 'a-z' | awk '/release/ {print $2}')}
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/\<release\>/ {print $3}'|sed -n '1p')}
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/distrib_release=/ {print $1}'|sed 's/distrib_release=//'|sed -n '1p')}
case ${LINUX_RELEASE_VERSION:0:5} in
6.*)
echo -e "\tCurrent OS Version: ${LINUX_RELEASE_VERSION}"
FILELIST=${CENTOS_6_FILELIST}
;;
*)
echo "Only support CentOS 6.X Version, eg: 6.5/6.6 ..."
exit 1
;;
esac
echo "checked OK, preparing to setup softwares ..."
# sleep 2
}
## update and upgrade system
function update_upgrade_centos() {
read -p " update yum cache <y/N>? " select
if [[ "${select}" == "y" ]] ;then
echo "sudo yum clean all"
${SUDO} yum clean all
#update the source.list
echo "sudo yum makecache"
${SUDO} yum makecache
fi
read -p " update system <y/N>? " select
if [[ "${select}" == "y" ]] ;then
echo "sudo yum update"
#upgrade the software have installed on the system
${SUDO} yum update
fi
}
## function yum groupinstall software
function yum_groupinstall_supports() {
echo -e "\tsudo yum groupinstall \"Base\""
${SUDO} yum groupinstall "Base"
echo -e "\tInstalling Development tools ..."
${SUDO} yum groupinstall "Development tools"
echo -e "\tInstalling X Window System ..."
${SUDO} yum groupinstall "X Window System"
echo -e "\tInstalling Desktop ..."
${SUDO} yum groupinstall "Desktop"
echo -e "\tInstalling Chinese Support ..."
${SUDO} yum groupinstall "Chinese Support"
}
## function initial vim
function vim_initialize_viminfo() {
if [[ "${UID}" -ge 500 ]] ;then
local VIMINFO_HOME=${HOME}
echo "Initializing viminfo file ..."
${SUDO} rm -f ${VIMINFO_HOME}/.viminfo
# touch ${VIMINFO_HOME}/.viminfo
fi
}
#install one software every cycle
function install_soft_for_each() {
echo "Will install below software for your system:"
local soft_num=0
local cur_num=0
for file in ${FILELIST}
do
let soft_num+=1
echo -e "${file} \c"
done
echo ""
TMOUT=10
read -p " Install above softwares <Y/n>? " select
if [[ "x${select}" == "xn" ]] ;then
return
fi
# FILELIST=$(echo ${FILELIST} | sed 's/[\t ]/\n/g'| sort -u)
for file in ${FILELIST}
do
let cur_num+=1
let cur_persent=cur_num*100/soft_num
# echo "${cur_persent}%"
trap 'echo -e "\nAborted by user, exit";exit' INT
echo "========================="
echo " [${cur_persent}%] installing $file ..."
echo "-------------------------"
${SUDO} yum install ${file} ${INSTALL_CHECK_FLAG}
# sleep 1
echo "$file installed ."
done
vim_initialize_viminfo
}
read -p "Setup build environment for CentOS, press <Enter> to continue "
check_system_distributor
check_system_release_version
update_upgrade_centos
yum_groupinstall_supports
install_soft_for_each
echo "Finished !"
<file_sep>/.vim/tools/shell/mk_self_extract_pkg.sh
#! /bin/bash
## self unpackage script header
## created by longbin <<EMAIL>>
## 2015-05-16
##################################################
##################################################
## This script can generate a package file and
## create a script head and tail to extract itself.
## You can write INSTALL.sh which can finish your
## job, and insert into the final script.
TMP_PKG_FILE=.__XXXtmp_$(date +%Y%m%d%H%M%S)
INSERT_SCRIPT_FILE=INSTALL.sh
function show_usage(){
echo "*************************************"
echo "* Usage: bash $0 Target_File File_Or_Dir[List]"
echo "* e.g.: bash $0 test.sh tmp/test.* "
echo "*************************************"
}
DEST_FILE=$1
if [[ -z "$*" ]] ; then
echo Parameter is null.
show_usage
exit 1
fi
shift
if [[ -z "$*" ]] ; then
echo Parameter is null.
show_usage
exit 1
fi
if [[ ! -f "$DEST_FILE" ]] && [[ -e "$DEST_FILE" ]] ;then
echo "Parameter invalid, ${DEST_FILE} is not a normal file."
show_usage
exit
fi
if [[ -f "$DEST_FILE" ]] ; then
read -p "$DEST_FILE has already exists, delete <y/n> ? " ANS
if [ "$ANS" == "Y" -o "$ANS" == "y" ] ; then
rm -vf $DEST_FILE || exit 1
else
exit 1
fi
fi
echo "Preparing to compress files ..."
tar -zcvf $TMP_PKG_FILE.tgz $*
if [[ "$?" != "0" ]] ;then
if [[ -f "${TMP_PKG_FILE}.tgz" ]] ;then
rm -vf ${TMP_PKG_FILE}.tgz
fi
fi
function get_self_extract_header_comment(){
cat > ${DEST_FILE} << EOF
#! /bin/bash
## self unpackage script header
## created by longbin <<EMAIL>>
## $(date +%Y-%m-%d\ %H:%M:%S)
EOF
}
function get_self_extract_header_content(){
## change $ --> \$
cat >>${DEST_FILE} <<EOF
DST_DIR=\$HOME
read -p "Please type the dir you will extract to Or press <Enter> to use current dir: " DST_DIR
DST_DIR=\$(echo \${DST_DIR%/} | sed "/^~/ s#~#\${HOME}#")
CUR_DIR=\$(pwd)
TMP_PKG_FILE=.__XXXtmp_\$(date +%Y%m%d%H%M%S)
############################################################
############################################################
## restore package file
function restore_package_file(){
local LINE_NUM=\$(cat \$0 | wc -l | awk '{print \$1}')
local n=1
local SCRIPT_LINE=0
while [[ \${n} -le \${LINE_NUM} ]] ; do
local RET_VAL=""
RET_VAL=\$(sed -n "\${n} p" \$0 |sed -n '/^##_THIS_IS_SCRIPT_FILE_END_TAG_XXX\$/p')
if [[ "\${RET_VAL}" != "" ]] ;then
SCRIPT_LINE=\${n}
# echo "Current script file has \${SCRIPT_LINE} lines."
break
fi
let n+=1
done
if [[ "\${SCRIPT_LINE}" != "0" ]] ;then
let SCRIPT_LINE+=1
# tail -n +\${SCRIPT_LINE} \$0 > \${PKG_FILE}.tgz
if [[ "\${DST_DIR}" == "" ]] ;then
DST_DIR=.
fi
if ! [[ -d "\${DST_DIR}" ]] ;then
mkdir -p \${DST_DIR}
if [[ "\$?" != "0" ]] ;then
echo "mkdir \${DST_DIR} ERROR."
exit
fi
fi
## restore package file
echo "restoring files from line \${SCRIPT_LINE} ..."
echo "tail -n +\${SCRIPT_LINE} \$0 |tar -zxv -C \${DST_DIR}"
# tail -n +\${SCRIPT_LINE} \$0 > \${TMP_PKG_FILE}.tgz
# tar -zxvf \${TMP_PKG_FILE}.tgz -C \${DST_DIR}
tail -n +\${SCRIPT_LINE} \$0 |tar -zxv -C \${DST_DIR}
if [[ "\$?" == "0" ]] ;then
echo "Restore file finished."
rm -f \${TMP_PKG_FILE}.tgz
else
echo "Restore file ERROR."
exit
fi
else
echo "No package file was found."
fi
}
############################################################
############################################################
# restore_package_file
EOF
}
function insert_script_content_to_file(){
read -p "Please type the script to insert [${INSERT_SCRIPT_FILE}]: " select
if [[ "${select}" != "" ]] ;then
INSERT_SCRIPT_FILE=${select}
fi
if ! [[ -f "${INSERT_SCRIPT_FILE}" && -r "${INSERT_SCRIPT_FILE}" ]] ;then
echo "${INSERT_SCRIPT_FILE} no such file or no permission to read."
rm -f ${TMP_PKG_FILE}.tgz
rm -f ${DEST_FILE}
exit
# return
fi
# local LINE_NUMBER=$(cat ${INSERT_SCRIPT_FILE} |wc -l |awk '{print $1}')
# for (( cur_line=1; cur_line<=${LINE_NUMBER}; cur_line++ )) ;do
# one_line=$(sed -n "${cur_line} p" ${INSERT_SCRIPT_FILE})
# # echo ${cur_line}: $one_line
# sed -i -e "\$ a ${one_line:=\ }" ${DEST_FILE}
# sed -i -e '$ s/^[ ]*$//g' ${DEST_FILE}
# done
# echo "Insert ${INSERT_SCRIPT_FILE} (total ${LINE_NUMBER} lines) OK."
cat ${INSERT_SCRIPT_FILE} >> ${DEST_FILE}
echo "Insert ${INSERT_SCRIPT_FILE} OK."
read -p "Press <Enter> to continue"
}
function create_text_header_to_file(){
get_self_extract_header_comment
get_self_extract_header_content
}
function append_self_extract_tail_to_file(){
read -p "Insert SCRIPT to the file <y/n>? " select
if [[ "${select}" == "y" ]] ;then
read -p "Insert the script before/after extract package <b/a>? " select
if [[ "${select}" == "a" ]] ;then
echo "restore_package_file" >> ${DEST_FILE}
insert_script_content_to_file
elif [[ "${select}" == "b" ]] ;then
insert_script_content_to_file
echo "restore_package_file" >> ${DEST_FILE}
fi
else
echo "restore_package_file" >> ${DEST_FILE}
fi
echo "exit" >> ${DEST_FILE}
echo "##_THIS_IS_SCRIPT_FILE_END_TAG_XXX" >> ${DEST_FILE}
cat ${TMP_PKG_FILE}.tgz >> ${DEST_FILE}
rm -f ${TMP_PKG_FILE}.tgz
}
function change_self_extract_file_mode(){
chmod a+x ${DEST_FILE}
echo "Done."
ls -lh ${DEST_FILE}
}
create_text_header_to_file
append_self_extract_tail_to_file
change_self_extract_file_mode
exit 0
##################################################
##################################################
<file_sep>/.vim/tools/python/python_Image_process.py
#! /usr/bin/python
import Image
import ImageDraw
import ImageEnhance
## resize image
def resize_img(raw_img, new_img='new_img.jpg', length=800, width=600):
img = Image.open(raw_img)
tmp_img = img.resize((length, width), Image.BILINEAR)
tmp_img.save(new_img)
# print img.info
# resize_img(raw_img='img12-green.jpg', new_img='new_img.jpg', length=256, width=256)
# resize_img(raw_img='img12-green.jpg', new_img='new_img.jpg')
def rotate_img(img_name, new_img, rotate=45):
img = Image.open(img_name)
tmp_img = img.rotate(rotate)
tmp_img.save(new_img)
# rotate_img(img_name='img12-green.jpg', new_img='new_img.jpg', rotate=60)
def format_img(img_name, to_format='bmp'):
img = Image.open(img_name)
img.save(img_name[:-4] + '.' + to_format)
# format_img(img_name='img12-green.jpg', to_format='png')
def histogram_img(img_name):
img = Image.open(img_name)
print img.histogram()
# histogram_img(img_name='img12-green.jpg')
def draw_img(img_name, new_img):
img = Image.open(img_name).resize((800, 600), Image.BILINEAR)
draw_img = ImageDraw.Draw(img)
width, height = img.size
## draw croos line
## draw_img.line((point1, point2), color)
draw_img.line(((0, 0), (width-1, height-1)), (0, 0, 0))
draw_img.line(((0, height-1), (width-1, 0)), (0, 0, 0))
## draw circle line
draw_img.arc((0, 0, width - 1, height - 1), 0, 360, 255)
img.show()
img.save(new_img)
# draw_img(img_name='img12-green.jpg', new_img='new_img.jpg')
def brightness_img(img_name, new_img='new_img.jpg'):
bright_img = Image.open(img_name)
## brightness
brightness = ImageEnhance.Brightness(bright_img)
tmp_img = brightness.enhance(1.2)
tmp_img.save(new_img)
# brightness_img(img_name='img12-green.jpg', new_img='new_img.jpg')
def sharpness_img(img_name, new_img='new_img.jpg'):
img = Image.open(img_name)
sharpness = ImageEnhance.Sharpness(img)
sharp_img = sharpness.enhance(7.0)
sharp_img.save(new_img)
# sharpness_img(img_name='img12-green.jpg', new_img='new_img.jpg')
def contrast_img(img_name, new_img='new_img.jpg'):
img = Image.open(img_name)
contrast = ImageEnhance.Contrast(img)
contrast_img = contrast.enhance(2.0)
contrast_img.save(new_img)
# contrast_img(img_name='img12-green.jpg', new_img='new_img.jpg')
<file_sep>/.vim/tools/shell/ubuntu1204_1404_embed_env_setup.sh
#! /bin/bash
# Author: longbin <<EMAIL>>
# Created Date: 2014-06-24
# Release Version: 1.15.805
# Last Modified: 2015-08-05
# this script is available for ubuntu to configure embedded environment
#list the software need to be installed to the variable FILELIST
BASIC_TOOLS="axel vim vim-gnome vim-doc vim-scripts ctags cscope gawk curl rar unrar zip unzip ghex nautilus-open-terminal p7zip-full tree uml-utilities meld gimp dos2unix unix2dos tofrodos python-markdown subversion filezilla indent "
CODE_TOOLS="build-essential git-core gitk libtool cmake automake flex bison gperf graphviz gnupg mingw32 gettext libc6-dev libc++-dev lib32stdc++6 libncurses5-dev lib32bz2-1.0 lib32bz2-dev gcc g++ g++-multilib "
EMBED_TOOLS="ckermit minicom putty tftp-hpa tftpd-hpa uml-utilities nfs-kernel-server "
BUILD_ANDROID_U12="git gnupg flex bison gperf python-markdown build-essential zip curl ia32-libs libc6-dev libncurses5-dev:i386 xsltproc x11proto-core-dev libx11-dev:i386 libreadline6-dev:i386 libgl1-mesa-dev g++-multilib mingw32 tofrodos libxml2-utils zlib1g-dev:i386 "
#libgl1-mesa-dri:i386 libgl1-mesa-glx:i386
BUILD_ANDROID_U14_ESSENTIAL="git gperf python-markdown g++-multilib libxml2-utils "
BUILD_ANDROID_U14_TOOLS="git-core flex bison gperf gnupg build-essential zip curl zlib1g-dev libc6-dev lib32ncurses5-dev lib32z1 x11proto-core-dev libx11-dev libreadline-gplv2-dev lib32z-dev libgl1-mesa-dev g++-multilib mingw32 tofrodos python-markdown libxml2-utils xsltproc libxml-simple-perl"
AI_TOOLS="build-dep python python-numpy python-scipy python-setuptools matplotlib"
PROXY_TOOLS="ntlmaps"
## apt-cache search opencv
# OPEN_CV="$(apt-cache search opencv | awk '{print $1}')"
# OPEN_CV="libgtk2.0-dev pkg-config"
## g++ `pkg-config opencv --cflags --libs` my_example.cpp -o my_example
## bison and flex is the analyzer of programmer and spell
## textinfo is a tool to read manual like man
## automake is used to help create Makefile
## libtool helps to deal with the dependency of libraries
## cvs, cvsd and subversion are used to control version
## ubuntu 12.04 software installing list
U1204_FILELIST="${BASIC_TOOLS} ${CODE_TOOLS} ${EMBED_TOOLS} \
${BUILD_ANDROID_U12}"
## ubuntu 14.04 software installing list
U1404_FILELIST="${BASIC_TOOLS} ${CODE_TOOLS} ${EMBED_TOOLS} \
${BUILD_ANDROID_U14_ESSENTIAL} \
${BUILD_ANDROID_U14_TOOLS}"
INSTALL_CHECK_FLAG="-y"
## check_user_UID
function check_user_UID() {
# if [[ ${UID} -lt 1000 ]] ;then
# echo "ERROR: Please don't use root to execute this script."
# exit 1
# fi
sudo ls > /dev/null
if [[ "x$?" == "x1" ]] ;then
echo -e "\tThere is a configuration/permission problem."
echo -e "\tPlease ensure that you have permission to use sudo"
exit 1
fi
if [ "x${UID}" == "x0" ] ;then
SUDO=''
else
SUDO=sudo
fi
}
## check whether system is Ubuntu or not
function check_system_distributor() {
## get system distributor ID: Ubuntu ?
LINUX_DISTRIBUTOR=$(cat /etc/issue |tr 'A-Z' 'a-z'|awk ' /release/ {print $1}' | sed -n "1p")
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(lsb_release -i |tr 'A-Z' 'a-z'|awk '/distributor/ {print $3}')}
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/\<release\>/ {print $1}'|sed -n '1p')}
LINUX_DISTRIBUTOR=${LINUX_DISTRIBUTOR:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/distrib_id=/ {print $1}'|sed 's/distrib_id=//'|sed -n '1p')}
echo "checking system distributor and release ID ..."
if [[ "${LINUX_DISTRIBUTOR}" == "ubuntu" ]] ;then
echo -e "\tCurrent OS Distributor: ${LINUX_DISTRIBUTOR}"
else
echo -e "\tCurrent OS is not ubuntu"
echo -e "\tCurrent OS Distributor: ${LINUX_DISTRIBUTOR}"
exit 1
fi
}
## check whether system is Ubuntu 12.04 or 14.04
function check_system_release_version() {
## get system release version: 12.04/14.04 ?
LINUX_RELEASE_VERSION=$(cat /etc/issue | awk '/release/ {print $3}'| sed -n '1p')
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(lsb_release -r | tr 'A-Z' 'a-z' | awk '/release/ {print $2}')}
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/\<release\>/ {print $3}'|sed -n '1p')}
LINUX_RELEASE_VERSION=${LINUX_RELEASE_VERSION:=$(cat /etc/*release |tr 'A-Z' 'a-z'|awk '/distrib_release=/ {print $1}'|sed 's/distrib_release=//'|sed -n '1p')}
case ${LINUX_RELEASE_VERSION:0:5} in
12.04)
echo -e "\tCurrent OS Version: ${LINUX_RELEASE_VERSION}"
FILELIST=${U1204_FILELIST}
;;
14.04|16.04|18.04)
echo -e "\tCurrent OS Version: ${LINUX_RELEASE_VERSION}"
FILELIST=${U1404_FILELIST}
;;
*)
echo "Only support Ubuntu LTS version, eg: 12.04/14.04 ..."
exit 1
;;
esac
# sleep 2
}
## check linux system environment
function check_linux_system_env() {
check_system_distributor
check_system_release_version
check_user_UID
echo "checked OK, preparing to setup softwares ..."
}
## update and upgrade system
function update_upgrade_ubuntu() {
read -p " update software source.list <y/N>? " select
if [[ "x${select}" == "xy" ]] ;then
echo "sudo apt-get update"
#update the source.list
${SUDO} apt-get update
fi
read -p " upgrade system <y/N>? " select
if [[ "x${select}" == "xy" ]] ;then
echo "sudo apt-get upgrade"
#upgrade the software have installed on the system
${SUDO} apt-get upgrade
fi
}
## function initial vim
function vim_initialize_viminfo() {
if [[ "${UID}" -ge 1000 ]] ;then
local VIMINFO_HOME=${HOME}
echo "initializing viminfo file ..."
${SUDO} rm -f ${VIMINFO_HOME}/.viminfo
# touch ${VIMINFO_HOME}/.viminfo
fi
}
#install one software every cycle
function install_soft_for_each() {
trap 'echo -e "\nAborted by user, exit";exit' INT
echo "Will install below software for your system:"
local soft_num=0
local cur_num=0
for file in ${FILELIST}
do
let soft_num+=1
echo -e "${file} \c"
done
echo ""
TMOUT=10
read -p " Install above softwares <Y/n>? " select
if [[ "x${select}" == "xn" ]] ;then
return
fi
# FILELIST=$(echo ${FILELIST} | sed 's/[\t ]/\n/g'| sort -u)
for file in ${FILELIST}
do
let cur_num+=1
let cur_percent=cur_num*100/soft_num
# echo "${cur_percent}%"
echo "========================="
echo " [${cur_percent}%] installing $file ..."
echo "-------------------------"
${SUDO} apt-get install ${file} ${INSTALL_CHECK_FLAG}
# sleep 1
echo "$file installed ."
done
vim_initialize_viminfo
}
function create_link_mesa_libGL_so() {
LIB_GL_SO=/usr/lib/i386-linux-gnu/libGL.so
LIB_GL_SO_1=/usr/lib/i386-linux-gnu/mesa/libGL.so.1
if ! [[ -f "${LIB_GL_SO_1}" ]] ;then
return
fi
${SUDO} ln -s -f ${LIB_GL_SO_1} ${LIB_GL_SO}
}
## install ibus input method frame
function install_ibus_pinyin_for_ubuntu(){
read -p "press <Enter> to install and setup ibus-pinyin "
${SUDO} apt-get install ibus ibus-clutter ibus-gtk ibus-gtk3 ibus-qt4 -y
## install ibus pinyin
${SUDO} apt-get install ibus-pinyin -y
sleep 3
read -p "Press <Enter> to select ibus-pinyin as the defalut input method "
im-config
## restart ibus-pinyin
##try below command to repair ibus-pinyin:
#ibus-daemon -drx
ibus-daemon -drx
if [[ -f ~/.bashrc ]] ;then
local IS_EXIST=$(cat ~/.bashrc | sed -n '/ibus-daemon/p')
if [[ "${IS_EXIST}" == "" ]] ;then
cp ~/.bashrc ~/.bashrc_$(date +%Y%m%d_%H%M%S)
echo "ibus-daemon -drx" >> ~/.bashrc
fi
fi
## ibus-setup
## add ibus-pinyin input method to the input method list
read -p "Press <Enter> to select and add ibus-pinyin "
ibus-setup
## configure ibus pinyin
if [[ "${LINUX_RELEASE_VERSION}" == "12.04" ]] ;then
/usr/lib/ibus-pinyin/ibus-setup-pinyin
elif [[ "${LINUX_RELEASE_VERSION}" == "14.04" ]] ;then
/usr/lib/ibus/ibus-setup-pinyin
fi
echo "====================================================="
echo -e "\tSetup ibus input method OK, please re-login your system and execute below commands to configure it. "
echo -e "\t\t/usr/lib/ibus-pinyin/ibus-setup-pinyin #for ubuntu1204"
echo -e "\t\t/usr/lib/ibus/ibus-setup-pinyin #for ubuntu1404 or later version"
echo "====================================================="
}
function remove_ibus_pinyin_from_ubuntu() {
## remove ibus-pinyin will lead some problems, repair our OS by below command:
## ${SUDO} apt-get install ibus-pinyin unity-control-center \
## unity-control-center-signon webaccounts-extension-common xul-ext-webaccounts
## remove ibus-pinyin
read -p "Press <Enter> to remove ibus "
${SUDO} apt-get purge ibus
${SUDO} apt-get autoremove
## repair OS when removed ibus pinyin
${SUDO} apt-get install unity-control-center unity-control-center-signon webaccounts-extension-common xul-ext-webaccounts
}
function install_fcitx_pinyin_for_ubuntu() {
remove_ibus_pinyin_from_ubuntu
## install fcitx pinyin
echo "installing fcitx ..."
${SUDO} apt-get install fcitx fcitx-pinyin
read -p "Press <Enter> to select your input method [fcitx] "
im-config
read -p "Press <Enter> to add your input method [pinyin] "
fcitx-config-gtk3
echo "====================================================="
echo -e "\tSetup fcitx input method OK, please re-login your system and execute below commands to configure it. "
echo -e "\t\tim-config"
echo -e "\t\tfcitx-config-gtk3"
echo "====================================================="
}
function countdown_select_for_each() {
#################################
local DEFAULT_OPTION=
local TIME_SELECT_TIMEOUT=9
local PROMTE_MESSAGE_HEADER="$1"
local PROMTE_MESSAGE_TAIL=" in ${TIME_SELECT_TIMEOUT}s: "
#################################
#################################
local OPTIONS=$(echo 'This_is_your_OPTIONS')
#################################
local PROMTE_MESSAGES=${PROMTE_MESSAGE_HEADER:="Please select"}${PROMTE_MESSAGE_TAIL}
echo "Will use a default value if you choosed none in ${TIME_SELECT_TIMEOUT}s. "
for ((countdown=${TIME_SELECT_TIMEOUT}-1; countdown>=1; countdown--))
do
trap 'exit 0' HUP
sleep 1; echo -e "\r${PROMTE_MESSAGE_HEADER} in ${countdown}s: \c"
done &
local BG_PID=$!
local TMOUT=${TIME_SELECT_TIMEOUT}
local option=${DEFAULT_OPTION}
PS3="${PROMTE_MESSAGES}"
trap 'kill ${BG_PID}; echo; exit' INT
select option in "ibus-pinyin" "fcitx-pinyin" "Use default input method"
do
if [[ "x${option}" != "x" ]] ;then
break
else
echo "Invalid option, try again."
fi
done
(kill -HUP ${BG_PID} &>/dev/null)
echo
if [[ "x${option}" != "x" ]] ;then
echo "You select: ${option}"
else
echo "You select none."
fi
trap 'exit' INT
}
function install_ibus_or_fcitx_pinyin() {
REPLY=
countdown_select_for_each "Please select your input method"
case ${REPLY} in
1)
echo "Preparing install_ibus_pinyin_for_ubuntu ..."
install_ibus_pinyin_for_ubuntu
;;
2)
echo "Preparing install_fcitx_pinyin_for_ubuntu ..."
install_fcitx_pinyin_for_ubuntu
;;
*)
echo "Use default input method. "
;;
esac
}
function install_ubuntu_multimedia_supports() {
TMOUT=
read -p " Install multimedia libs <y/N>? " select
if [[ "${select}" == "y" ]] ;then
echo "This will take you a long time to download."
${SUDO} apt-get install ubuntu-restricted-addons
${SUDO} apt-get install ubuntu-restricted-extras
else
return
fi
}
read -p "Setup build environment for ubuntu 12.04/14.04, press <Enter> to continue "
check_linux_system_env
update_upgrade_ubuntu
install_soft_for_each
create_link_mesa_libGL_so
install_ibus_or_fcitx_pinyin
install_ubuntu_multimedia_supports
echo "Finished !"
<file_sep>/.vim/tools/shell/countdown_select_for_each.sh
#! /bin/bash
# 2015-03-28
OPTION_LIST_MSG='start
hai hao ma
wo hen hao
good morning
good afternoon
end
'
function get_text_msg(){
cat << EOF
${OPTION_LIST_MSG}
EOF
}
function show_array_list(){
local LINE_NUMBER=$(get_text_msg | sed -n '$=')
local cur_line=0
for ((cur_line=1; cur_line<=${LINE_NUMBER}; cur_line++))
do
local one_line=$(get_text_msg |sed -n "${cur_line} p" |sed '/^[ \t]*$/d')
echo $cur_line $one_line
OPTION_LSTS[cur_line-1]=${one_line}
echo \"${OPTION_LSTS[cur_line-1]}\"
done
}
function countdown_select_for_each(){
#################################
local DEFAULT_OPTION=
local TIME_SELECT_TIMEOUT=5
local PROMTE_MESSAGE_HEADER="$1"
local PROMTE_MESSAGE_TAIL=" in ${TIME_SELECT_TIMEOUT}s: "
#################################
#################################
# local OPTION_LSTS=$(echo 'This_is_your_OPTIONS')
local OPTION_LSTS=$(echo 'This_is_your_OPTIONS')
#################################
local PROMTE_MESSAGES=${PROMTE_MESSAGE_HEADER:="Please select"}${PROMTE_MESSAGE_TAIL}
echo "Will use a default value if you choosed none in ${TIME_SELECT_TIMEOUT}s. "
for ((countdown=${TIME_SELECT_TIMEOUT}-1; countdown>=1; countdown--))
do
trap 'exit 0' HUP
sleep 1; echo -e "\r${PROMTE_MESSAGE_HEADER} in ${countdown}s: \c"
done &
local BG_PID=$!
local TMOUT=${TIME_SELECT_TIMEOUT}
local option=${DEFAULT_OPTION}
PS3="${PROMTE_MESSAGES}"
trap 'kill ${BG_PID}; echo; exit' INT
## modify ${OPTION_LSTS} as your selections
select option in ${OPTION_LSTS}
do
if [[ "${option}" != "" ]] ;then
break
else
echo "Invalid option, try again."
fi
done
(kill -HUP ${BG_PID} &>/dev/null)
echo
if [[ "${option}" != "" ]] ;then
echo "You select: ${option}"
else
echo "You select none."
fi
}
function test_func(){
REPLY=
countdown_select_for_each "Please select your option"
echo ${REPLY}
case ${REPLY} in
1)
echo 1
break;
;;
2)
echo 2
break
;;
*)
echo "Invalid option."
;;
esac
}
test_func
<file_sep>/.vim/tools/shell/catch_bugreport_logcat.sh
#! /bin/bash
echo "adb wait-for-device"
adb wait-for-device
adb devices
sleep 2
CUR_TIME=$(date +%Y%m%d_%H%M%S)
BUGREPORT_FILE=bugreport_${CUR_TIME}.bugreport
LOGCAT_FILE=logcat_${CUR_TIME}.logcat
(adb bugreport |tee ${BUGREPORT_FILE})
clear
(adb logcat -v time |tee ${LOGCAT_FILE})
| cb51b684639cd8b67a1e8fef983b47b78a97d73c | [
"Markdown",
"Python",
"Text",
"Shell"
] | 20 | Python | lilongbin/vim_plugins | 6b12adc3a058ad6c9845cdb4922a0013162caa39 | afd6929c1e48b9f4ba738640facfcb5399218e40 |
refs/heads/master | <file_sep>import React from "react";
import "./style.css";
// Using the datalist element we can create autofill suggestions based on the props.breeds array
function SearchForm(props) {
return (
<form className="search row justify-content-center">
<div className="form-group col-6 ">
<input
value={props.search}
onChange = {props.handleInputChange}
name='oil-name'
list='oils'
type="text"
className="form-control"
placeholder="Search by recipe..."
id="oil-name"
/>
<datalist id="oils">
{props.recipes.map(recipe => (
<option value={recipe.name} key={recipe.id} />
))}
</datalist>
<button type="submit" onClick={props.handleFormSubmit} className="btn btn-light">
Search
</button>
</div>
</form>
);
}
export default SearchForm;
<file_sep># Essential Oil Recipes
Essential oil recipe directory made with [Create React App](https://github.com/facebook/create-react-app)
>[Link to website](https://limitless-journey-87355.herokuapp.com)
## Table of Contents
* [Description](#Description)
* [General Info](#General-Info)
* [Features](#Features)
* [View Page](#View)
* [Status](#Status)
* [Developer Notes](#Developer-Notes)
## Description
Given a list of recipes, you will be able to 'favorite' a recipe or search one by name. You can also access all of your favorite recipes.
## General Info
Made with React. This single-page application allows you to view 15 recipes, add or remove them to your favorites list and find a recipe by name.
## Features
* search bar
* add to favorites button
* view favorite recipes
## View
<p>
<img src='public/allrecipes.png' width='25%'/>
<img src='public/favorites.png' width='25%' />
</p>
### Status
_In Progress_
### Developer Notes
- create additional rows while mapping through recipe cards.
<file_sep>import React, { Component } from "react";
import Hero from "../components/Hero";
import Navbar from '../components/Navbar';
import Wrapper from '../components/Wrapper';
import Container from "../components/Container";
import Row from "../components/Row";
import Col from "../components/Col";
import Card from '../components/Card';
import CardBtn from "../components/CardBtn";
import CardText from '../components/CardText';
import SearchForm from '../components/SearchForm';
import Footer from '../components/Footer';
import oils from '../oils.json';
class Home extends Component {
state = {
oils: oils,
search: '',
view: 'All Recipes'
}
handleNavBtn = data => {
let value = (data.target.getAttribute('value'));
if(value === 'favorites') {
let favFilter = this.state.oils.filter(oils => (oils.favorite !== false))
console.log(favFilter)
this.setState({oils: favFilter, view: 'Favorites'})
}
else {
this.setState({oils: oils, view: 'All Recipes'})
}
}
handleInputChange = event => {
this.setState({search: event.target.value});
}
handleFormSubmit = event => {
event.preventDefault();
let searchInput = oils.filter(oils => (oils.name === this.state.search))
console.log(searchInput)
this.setState({oils: searchInput})
}
handleBtnClick = item => {
if(item.favorite === true) {
console.log(item.favorite)
item.favorite = false
}
else {
item.favorite = true
}
this.setState(this.state.oils)
};
render() {
console.log(oils)
return (
<div>
<Navbar onClick={(event) => this.handleNavBtn(event)}/>
<Wrapper>
<Hero backgroundImage="https://completehomespa.com/wp-content/uploads/2020/04/what-is-an-aromatherapy-diffuser.jpg">
<h1>15 Essential Oil</h1>
<h2>Diffuser Recipes</h2>
<SearchForm
handleFormSubmit={this.handleFormSubmit}
handleInputChange={this.handleInputChange}
recipes={oils}
/>
</Hero>
<Col size='12' style={{ textAlign: 'center', marginTop: 30, color: 'white'}}>
<h2>{this.state.view}</h2>
</Col>
<Container fluid={true} style={{ marginTop: 30 }}>
<Row fluid={true}>
<Col size="s-12">
{this.state.oils.map(item => (
<Card title={item.name} key={item.id}>
<CardText
oils={item.oils}
id={item.id}
/>
<CardBtn
onClick={() => this.handleBtnClick(item)}
data-value={item.favorite ? 'favorite' : ''}
/>
</Card>
))}
</Col>
</Row>
</Container>
</Wrapper>
<Footer/>
</div>
);
}
}
export default Home;
| e89caff78b33d58273770eec661abc4e98ea1ad4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | CrystaJeffcoat/Recipe_directory-React | fbbb8b857aa30b44810be645f95b95718257b96a | 8ef7139122770c0951613ae40b03429fc42c81b9 |
refs/heads/master | <repo_name>haozi23333/inkpaint<file_sep>/src/polyfill/Doc.js
import { isBrowser } from "browser-or-node";
import PSCanvas from "./Canvas";
const Doc = {
createElement(tag) {
let element;
switch (tag) {
case "canvas":
element = new PSCanvas(1, 1);
break;
default:
element = new PSCanvas(1, 1);
break;
}
return element;
}
};
export default isBrowser ? window.document : Doc;
<file_sep>/examples/source/node/masks/sprite.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
module.exports = app;
app.stage.interactive = true;
var bg = InkPaint.Sprite.fromImage(paths('source/assets/bg_plane.jpg'));
app.stage.addChild(bg);
var cells = InkPaint.Sprite.fromImage(paths('source/assets/cells.png'));
cells.scale.set(1.5);
var mask = InkPaint.Sprite.fromImage(paths('source/assets/flowerTop.png'));
mask.anchor.set(0.5);
mask.x = 310;
mask.y = 190;
cells.mask = mask;
app.stage.addChild(mask, cells);
var target = new InkPaint.Point();
reset();
function reset() {
target.x = Math.floor(Math.random() * 550);
target.y = Math.floor(Math.random() * 300);
}
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
mask.x += (target.x - mask.x) * 0.1;
mask.y += (target.y - mask.y) * 0.1;
if (Math.abs(mask.x - target.x) < 1) {
reset();
}
});
<file_sep>/src/resource/constant.js
const STATUS_FLAGS = {
NONE: 0,
DATA_URL: 1 << 0,
COMPLETE: 1 << 1,
LOADING: 1 << 2
};
const LOAD_TYPE = {
XHR: 1,
IMAGE: 2,
AUDIO: 3,
VIDEO: 4
};
const XHR_RESPONSE_TYPE = {
DEFAULT: "text",
BUFFER: "arraybuffer",
BLOB: "blob",
DOCUMENT: "document",
JSON: "json",
TEXT: "text"
};
const XHR_TYPE_MAP = {
// xml
xhtml: XHR_RESPONSE_TYPE.DOCUMENT,
html: XHR_RESPONSE_TYPE.DOCUMENT,
htm: XHR_RESPONSE_TYPE.DOCUMENT,
xml: XHR_RESPONSE_TYPE.DOCUMENT,
tmx: XHR_RESPONSE_TYPE.DOCUMENT,
svg: XHR_RESPONSE_TYPE.DOCUMENT,
tsx: XHR_RESPONSE_TYPE.DOCUMENT,
fnt: XHR_RESPONSE_TYPE.DOCUMENT,
// images
gif: XHR_RESPONSE_TYPE.BLOB,
png: XHR_RESPONSE_TYPE.BLOB,
bmp: XHR_RESPONSE_TYPE.BLOB,
jpg: XHR_RESPONSE_TYPE.BLOB,
jpeg: XHR_RESPONSE_TYPE.BLOB,
tif: XHR_RESPONSE_TYPE.BLOB,
tiff: XHR_RESPONSE_TYPE.BLOB,
webp: XHR_RESPONSE_TYPE.BLOB,
tga: XHR_RESPONSE_TYPE.BLOB,
// json
json: XHR_RESPONSE_TYPE.JSON,
// text
text: XHR_RESPONSE_TYPE.TEXT,
txt: XHR_RESPONSE_TYPE.TEXT,
// fonts
ttf: XHR_RESPONSE_TYPE.BUFFER,
otf: XHR_RESPONSE_TYPE.BUFFER
};
const LOAD_TYPE_MAP = {
// images
gif: LOAD_TYPE.IMAGE,
png: LOAD_TYPE.IMAGE,
bmp: LOAD_TYPE.IMAGE,
jpg: LOAD_TYPE.IMAGE,
jpeg: LOAD_TYPE.IMAGE,
tif: LOAD_TYPE.IMAGE,
tiff: LOAD_TYPE.IMAGE,
webp: LOAD_TYPE.IMAGE,
tga: LOAD_TYPE.IMAGE,
svg: LOAD_TYPE.IMAGE,
// audio
mp3: LOAD_TYPE.AUDIO,
ogg: LOAD_TYPE.AUDIO,
wav: LOAD_TYPE.AUDIO,
// videos
mp4: LOAD_TYPE.VIDEO,
webm: LOAD_TYPE.VIDEO
};
export {
STATUS_FLAGS,
LOAD_TYPE,
XHR_RESPONSE_TYPE,
XHR_TYPE_MAP,
LOAD_TYPE_MAP
};
<file_sep>/examples/source/js/textures/render-texture-basic.js
var app = new InkPaint.Application(800, 600, { backgroundColor: 0x008000 });
document.body.appendChild(app.view);
var container = new InkPaint.Container();
app.stage.addChild(container);
var texture = InkPaint.Texture.fromImage('source/assets/bunny.png');
for (var i = 0; i < 25; i++) {
var bunny = new InkPaint.Sprite(texture);
bunny.x = (i % 5) * 30;
bunny.y = Math.floor(i / 5) * 30;
bunny.rotation = Math.random() * (Math.PI * 2);
container.addChild(bunny);
}
var brt = new InkPaint.BaseRenderTexture(300, 300, InkPaint.SCALE_MODES.LINEAR, 1);
var rt = new InkPaint.RenderTexture(brt);
var sprite = new InkPaint.Sprite(rt);
sprite.x = 450;
sprite.y = 60;
app.stage.addChild(sprite);
container.x = 100;
container.y = 60;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
// app.renderer.render(container, rt);
});
<file_sep>/examples/source/js/textures/texture.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
var base = InkPaint.BaseTexture.fromImage("source/assets/flowerTop.png");
var frame = new InkPaint.Rectangle(0, 0, 100, 100);
var orig = new InkPaint.Rectangle(0, 0, 119, 181);
var trim = new InkPaint.Rectangle(0, 0, 300, 300);
var texture = new InkPaint.Texture(base, frame, orig);
var width = app.screen.width;
var height = app.screen.height;
var graphics = new InkPaint.Graphics();
graphics.beginFill(0xde3249);
graphics.drawRect(width / 2 - 50, height / 2 - 50, 100, 100);
graphics.endFill();
var dude1 = new InkPaint.Sprite(texture);
dude1.anchor.set(0.5);
dude1.x = width / 2;
dude1.y = height / 2;
var dude2 = new InkPaint.Sprite(
InkPaint.Texture.fromImage("source/assets/flowerTop.png")
);
dude2.anchor.set(0.5);
dude2.x = width / 2 + 150;
dude2.y = height / 2;
app.stage.addChild(graphics);
app.stage.addChild(dude1);
//app.stage.addChild(dude2);
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
});
<file_sep>/src/renderers/webgl/managers/StencilManager.js
import WebGLManager from "./WebGLManager";
export default class StencilManager extends WebGLManager {
constructor(renderer) {
super(renderer);
this.stencilMaskStack = null;
}
setMaskStack(stencilMaskStack) {
this.stencilMaskStack = stencilMaskStack;
const gl = this.renderer.gl;
if (stencilMaskStack.length === 0) {
gl.disable(gl.STENCIL_TEST);
} else {
gl.enable(gl.STENCIL_TEST);
}
}
pushStencil(graphics) {
this.renderer.setObjectRenderer(this.renderer.plugins.graphics);
this.renderer._activeRenderTarget.attachStencilBuffer();
const gl = this.renderer.gl;
const prevMaskCount = this.stencilMaskStack.length;
if (prevMaskCount === 0) {
gl.enable(gl.STENCIL_TEST);
}
this.stencilMaskStack.push(graphics);
// Increment the reference stencil value where the new mask overlaps with the old ones.
gl.colorMask(false, false, false, false);
gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
this.renderer.plugins.graphics.render(graphics);
this._useCurrent();
}
popStencil() {
this.renderer.setObjectRenderer(this.renderer.plugins.graphics);
const gl = this.renderer.gl;
const graphics = this.stencilMaskStack.pop();
if (this.stencilMaskStack.length === 0) {
// the stack is empty!
gl.disable(gl.STENCIL_TEST);
gl.clear(gl.STENCIL_BUFFER_BIT);
gl.clearStencil(0);
} else {
// Decrement the reference stencil value where the popped mask overlaps with the other ones
gl.colorMask(false, false, false, false);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
this.renderer.plugins.graphics.render(graphics);
this._useCurrent();
}
}
_useCurrent() {
const gl = this.renderer.gl;
gl.colorMask(true, true, true, true);
gl.stencilFunc(
gl.EQUAL,
this.stencilMaskStack.length,
this._getBitwiseMask()
);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
}
_getBitwiseMask() {
return (1 << this.stencilMaskStack.length) - 1;
}
destroy() {
WebGLManager.prototype.destroy.call(this);
this.stencilMaskStack.stencilStack = null;
}
}
<file_sep>/src/resource/Resource.js
import { readFile } from "fs";
import Signal from "mini-signals";
import superagent from "superagent";
import PsImage from "../polyfill/Image";
import { isBrowser } from "browser-or-node";
import {
STATUS_FLAGS,
LOAD_TYPE,
XHR_TYPE_MAP,
LOAD_TYPE_MAP
} from "./constant";
function _noop() {}
const EMPTY_GIF =
"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
export default class Resource {
constructor(name, url, options = {}) {
if (typeof name !== "string" || typeof url !== "string") {
throw new Error("Both name and url are required.");
}
this._flags = 0;
this.setflag(STATUS_FLAGS.DATA_URL, url.indexOf("data:") === 0);
this.name = name;
this.url = url;
this.extension = this._getExt();
this.data = null;
this.crossOrigin =
options.crossOrigin === true ? "anonymous" : options.crossOrigin;
this.timeout = options.timeout || 0;
this.loadType = options.loadType || this._determineLoadType();
this.xhrType = options.xhrType;
this.error = null;
this.children = [];
this.type = Resource.TYPE.UNKNOWN;
this.progressChunk = 0;
this._dequeue = _noop;
this._onLoadBinding = null;
this._elementTimer = 0;
this.metadata = options.metadata || {};
this.onStart = new Signal();
this.onProgress = new Signal();
this.onComplete = new Signal();
this.onAfterMiddleware = new Signal();
this._onComplete = this._onComplete.bind(this);
this._onError = this._onError.bind(this);
this._onTimeout = this._onTimeout.bind(this);
this._onXhrLoad = this._onXhrLoad.bind(this);
}
get isDataUrl() {
return this.hasflag(STATUS_FLAGS.DATA_URL);
}
get isComplete() {
return this.hasflag(STATUS_FLAGS.COMPLETE);
}
get isLoading() {
return this.hasflag(STATUS_FLAGS.LOADING);
}
complete() {
this._clearEvents();
this._finish();
}
load(cb) {
const { isLoading, loadType, isComplete } = this;
if (isLoading) return;
if (isComplete) {
if (cb) setTimeout(() => cb(this), 1);
return;
} else if (cb) {
this.onComplete.once(cb);
}
this.setflag(STATUS_FLAGS.LOADING, true);
this.onStart.dispatch(this);
switch (loadType) {
case LOAD_TYPE.IMAGE:
this.type = Resource.TYPE.IMAGE;
this._loadImage();
break;
case LOAD_TYPE.XHR:
default:
this._loadOtherFile();
break;
}
}
abort(message) {
if (this.error) return;
this.error = new Error(message);
this._clearEvents();
if (this.data) {
// single source
if (this.data.src) {
this.data.src = EMPTY_GIF;
}
// multi-source
else {
while (this.data.firstChild) {
this.data.removeChild(this.data.firstChild);
}
}
}
this._finish();
}
destroy() {
this.removeHandler();
this.data = null;
this.name = null;
this.url = null;
this.metadata = null;
this.onStart = null;
this.onProgress = null;
this.onComplete = null;
this.onAfterMiddleware = null;
this.children = null;
this._dequeue = null;
this._onLoadBinding = null;
this._flags = 0;
this._onComplete = null;
this._onError = null;
this._onTimeout = null;
this._onXhrLoad = null;
}
_loadOtherFile() {
const isNetWork = this._isNetWork(this.url);
if (isNetWork || isBrowser) {
this._loadXhr();
} else {
this._loadLocalFile();
}
}
_loadLocalFile() {
readFile(this.url, (err, data) => {
if (err) {
this._onError(err);
} else {
const body = JSON.parse(data);
this._onXhrLoad(body);
}
});
}
_loadXhr() {
superagent.get(this.url).end((err, res) => {
if (err) {
this._onError(err);
} else {
this._onXhrLoad(res.body);
}
});
}
_isNetWork(url) {
if (/^\s*https?:\/\//.test(url)) return true;
return false;
}
_onXhrLoad(data) {
this.data = data;
this.type = Resource.TYPE.JSON;
this.complete();
}
hasflag(flag) {
return (this._flags & flag) !== 0;
}
setflag(flag, value) {
this._flags = value ? this._flags | flag : this._flags & ~flag;
}
removeHandler() {
if (!this.data) return;
this.data.onerror = null;
this.data.onload = null;
}
_clearEvents() {
clearTimeout(this._elementTimer);
this.removeHandler();
}
_finish() {
if (this.isComplete) return;
this.setflag(STATUS_FLAGS.COMPLETE, true);
this.setflag(STATUS_FLAGS.LOADING, false);
this.onComplete.dispatch(this);
}
_loadImage() {
this.data = new PsImage();
this.data.onerror = this._onError;
this.data.onload = this._onComplete;
if (this.crossOrigin) this.data.crossOrigin = this.crossOrigin;
this.data.src = this.url;
if (this._isNetWork(this.url)) {
this.data.network = true;
} else {
this.data.network = false;
}
if (this.timeout) {
this._elementTimer = setTimeout(this._onTimeout, this.timeout);
}
}
_onError(event) {
this.abort(`Failed to load element using: ${event}`);
}
_onTimeout() {
this.abort(`Load timed out.`);
}
_onComplete(e) {
this.complete();
}
_determineLoadType() {
return LOAD_TYPE_MAP[this.extension] || LOAD_TYPE.XHR;
}
_getExt() {
let url = this.url;
let ext = "";
if (this.isDataUrl) {
const slashIndex = url.indexOf("/");
ext = url.substring(slashIndex + 1, url.indexOf(";", slashIndex));
} else {
const queryStart = url.indexOf("?");
const hashStart = url.indexOf("#");
const index = Math.min(
queryStart > -1 ? queryStart : url.length,
hashStart > -1 ? hashStart : url.length
);
url = url.substring(0, index);
ext = url.substring(url.lastIndexOf(".") + 1);
}
return ext.toLowerCase();
}
static setExtensionLoadType(extname, loadType) {
setExtMap(LOAD_TYPE_MAP, extname, loadType);
}
static setExtensionXhrType(extname, xhrType) {
setExtMap(XHR_TYPE_MAP, extname, xhrType);
}
}
Resource.TYPE = {
UNKNOWN: 0,
JSON: 1,
XML: 2,
IMAGE: 3,
AUDIO: 4,
VIDEO: 5,
TEXT: 6
};
function setExtMap(map, extname, val) {
if (extname && extname.indexOf(".") === 0) {
extname = extname.substring(1);
}
if (!extname) {
return;
}
map[extname] = val;
}
<file_sep>/examples/source/js/graphics/dynamic.js
var app = new InkPaint.Application(800, 600, { antialias: true });
document.body.appendChild(app.view);
app.stage.interactive = true;
var graphics = new InkPaint.Graphics();
// set a fill and line style
graphics.beginFill(0xFF3300);
graphics.lineStyle(10, 0xffd900, 1);
// draw a shape
graphics.moveTo(50, 50);
graphics.lineTo(250, 50);
graphics.lineTo(100, 100);
graphics.lineTo(250, 220);
graphics.lineTo(50, 220);
graphics.lineTo(50, 50);
graphics.endFill();
// set a fill and line style again
graphics.lineStyle(10, 0xFF0000, 0.8);
graphics.beginFill(0xFF700B, 1);
// draw a second shape
graphics.moveTo(210, 300);
graphics.lineTo(450, 320);
graphics.lineTo(570, 350);
graphics.quadraticCurveTo(600, 0, 480, 100);
graphics.lineTo(330, 120);
graphics.lineTo(410, 200);
graphics.lineTo(210, 300);
graphics.endFill();
// draw a rectangle
graphics.lineStyle(2, 0x0000FF, 1);
graphics.drawRect(50, 250, 100, 100);
// draw a circle
graphics.lineStyle(0);
graphics.beginFill(0xFFFF0B, 0.5);
graphics.drawCircle(470, 200, 100);
graphics.endFill();
graphics.lineStyle(20, 0x33FF00);
graphics.moveTo(30, 30);
graphics.lineTo(600, 300);
app.stage.addChild(graphics);
// let's create a moving shape
var thing = new InkPaint.Graphics();
app.stage.addChild(thing);
thing.x = 800 / 2;
thing.y = 600 / 2;
var count = 0;
// Just click on the stage to draw random lines
window.app = app;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
count += 0.1;
thing.clear();
thing.lineStyle(10, 0xff0000, 1);
thing.beginFill(0xffFF00, 0.5);
thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count) * 20);
thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count) * 20);
thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count) * 20);
thing.lineTo(-120 + Math.cos(count) * 20, 100 + Math.sin(count) * 20);
thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count) * 20);
thing.rotation = count * 0.1;
});
<file_sep>/examples/source/js/demos-advanced/slots.js
var app = new InkPaint.Application(800, 600, { backgroundColor: 0x1099bb });
document.body.appendChild(app.view);
InkPaint.loader
.add("source/assets/eggHead.png", "source/assets/eggHead.png")
.add("source/assets/flowerTop.png", "source/assets/flowerTop.png")
.add("source/assets/helmlok.png", "source/assets/helmlok.png")
.add("source/assets/skully.png", "source/assets/skully.png")
.load(onAssetsLoaded);
var REEL_WIDTH = 160;
var SYMBOL_SIZE = 150;
// onAssetsLoaded handler builds the example.
function onAssetsLoaded() {
var slotTextures = [
InkPaint.Texture.fromImage("source/assets/eggHead.png"),
InkPaint.Texture.fromImage("source/assets/flowerTop.png"),
InkPaint.Texture.fromImage("source/assets/helmlok.png"),
InkPaint.Texture.fromImage("source/assets/skully.png")
];
// Build the reels
var reels = [];
var reelContainer = new InkPaint.Container();
for (var i = 0; i < 5; i++) {
var rc = new InkPaint.Container();
rc.x = i * REEL_WIDTH;
reelContainer.addChild(rc);
var reel = {
container: rc,
symbols: [],
position: 0,
previousPosition: 0,
blur: new InkPaint.filters.BlurFilter()
};
reel.blur.blurX = 0;
reel.blur.blurY = 0;
rc.filters = [reel.blur];
// Build the symbols
for (var j = 0; j < 4; j++) {
var symbol = new InkPaint.Sprite(
slotTextures[Math.floor(Math.random() * slotTextures.length)]
);
// Scale the symbol to fit symbol area.
symbol.y = j * SYMBOL_SIZE;
symbol.scale.x = symbol.scale.y = Math.min(
SYMBOL_SIZE / symbol.width,
SYMBOL_SIZE / symbol.height
);
symbol.x = Math.round((SYMBOL_SIZE - symbol.width) / 2);
reel.symbols.push(symbol);
rc.addChild(symbol);
}
reels.push(reel);
}
app.stage.addChild(reelContainer);
// Build top & bottom covers and position reelContainer
var margin = (app.screen.height - SYMBOL_SIZE * 3) / 2;
reelContainer.y = margin;
reelContainer.x = Math.round(app.screen.width - REEL_WIDTH * 5);
var top = new InkPaint.Graphics();
top.beginFill(0, 1);
top.drawRect(0, 0, app.screen.width, margin);
var bottom = new InkPaint.Graphics();
bottom.beginFill(0, 1);
bottom.drawRect(0, SYMBOL_SIZE * 3 + margin, app.screen.width, margin);
// Add play text
var style = new InkPaint.TextStyle({
fontFamily: "Arial",
fontSize: 36,
fontStyle: "italic",
fontWeight: "bold",
fill: ["#ffffff", "#00ff99"], // gradient
stroke: "#4a1850",
strokeThickness: 5,
dropShadow: true,
dropShadowColor: "#000000",
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
wordWrap: true,
wordWrapWidth: 440
});
var playText = new InkPaint.Text("Spin the wheels!", style);
playText.x = Math.round((bottom.width - playText.width) / 2);
playText.y =
app.screen.height - margin + Math.round((margin - playText.height) / 2);
bottom.addChild(playText);
// Add header text
var headerText = new InkPaint.Text("InkPaint MONSTER SLOTS!", style);
headerText.x = Math.round((top.width - headerText.width) / 2);
headerText.y = Math.round((margin - headerText.height) / 2);
top.addChild(headerText);
app.stage.addChild(top);
app.stage.addChild(bottom);
// Set the interactivity.
bottom.interactive = true;
bottom.buttonMode = true;
bottom.addListener("pointerdown", function() {
startPlay();
});
var running = false;
// Function to start playing.
function startPlay() {
if (running) return;
running = true;
for (var i = 0; i < reels.length; i++) {
var r = reels[i];
var extra = Math.floor(Math.random() * 3);
tweenTo(
r,
"position",
r.position + 10 + i * 5 + extra,
2500 + i * 600 + extra * 600,
backout(0.5),
null,
i === reels.length - 1 ? reelsComplete : null
);
}
}
// Reels done handler.
function reelsComplete() {
running = false;
}
ticker.add(function(delta) {
app.render();
// Update the slots.
for (var i = 0; i < reels.length; i++) {
var r = reels[i];
// Update blur filter y amount based on speed.
// This would be better if calculated with time in mind also. Now blur depends on frame rate.
r.blur.blurY = (r.position - r.previousPosition) * 8;
r.previousPosition = r.position;
// Update symbol positions on reel.
for (var j = 0; j < r.symbols.length; j++) {
var s = r.symbols[j];
var prevy = s.y;
s.y =
((r.position + j) % r.symbols.length) * SYMBOL_SIZE -
SYMBOL_SIZE;
if (s.y < 0 && prevy > SYMBOL_SIZE) {
// Detect going over and swap a texture.
// This should in proper product be determined from some logical reel.
s.texture =
slotTextures[
Math.floor(Math.random() * slotTextures.length)
];
s.scale.x = s.scale.y = Math.min(
SYMBOL_SIZE / s.texture.width,
SYMBOL_SIZE / s.texture.height
);
s.x = Math.round((SYMBOL_SIZE - s.width) / 2);
}
}
}
});
}
// Very simple tweening utility function. This should be replaced with a proper tweening library in a real product.
var tweening = [];
function tweenTo(object, property, target, time, easing, onchange, oncomplete) {
var tween = {
object: object,
property: property,
propertyBeginValue: object[property],
target: target,
easing: easing,
time: time,
change: onchange,
complete: oncomplete,
start: Date.now()
};
tweening.push(tween);
return tween;
}
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
var now = Date.now();
var remove = [];
for (var i = 0; i < tweening.length; i++) {
var t = tweening[i];
var phase = Math.min(1, (now - t.start) / t.time);
t.object[t.property] = lerp(
t.propertyBeginValue,
t.target,
t.easing(phase)
);
if (t.change) t.change(t);
if (phase === 1) {
t.object[t.property] = t.target;
if (t.complete) t.complete(t);
remove.push(t);
}
}
for (var i = 0; i < remove.length; i++) {
tweening.splice(tweening.indexOf(remove[i]), 1);
}
});
// Basic lerp funtion.
function lerp(a1, a2, t) {
return a1 * (1 - t) + a2 * t;
}
// Backout function from tweenjs.
// https://github.com/CreateJS/TweenJS/blob/master/src/tweenjs/Ease.js
function backout(amount) {
return function(t) {
return --t * t * ((amount + 1) * t + amount) + 1;
};
}
<file_sep>/src/polyfill/Image.js
import poly from "./poly";
import { createCanvas, Image as CImage } from "../canvas-gl";
import EventEmitter from "eventemitter3";
import { isBrowser } from "browser-or-node";
let myCanvas;
class PsImage extends poly(CImage) {
constructor(...args) {
super(...args);
this.isPsImage = true;
}
addEventListener(name, cb) {
if (!this._eventemitter) {
this._eventemitter = new EventEmitter();
}
this._eventemitter.once(name, cb);
}
static convertToImageData(image, flip = false) {
const { width, height } = image;
if (!myCanvas) myCanvas = createCanvas(width, height);
myCanvas.width = width;
myCanvas.height = height;
const ctx = myCanvas.getContext("2d");
if (flip) {
ctx.scale(1, -1);
ctx.translate(0, -height);
}
ctx.clearRect(width, height);
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, width, height);
}
static convertToCanvas(imgData, width, height) {
const can = createCanvas(width, height);
const ctx = can.getContext("2d");
ctx.putImageData(imgData, 0, 0);
return can;
}
}
export default isBrowser ? window.Image : PsImage;
<file_sep>/examples/source/js/filters/blur.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
var littleDudes = InkPaint.Sprite.fromImage(
"source/assets/pixi-filters/depth_blur_dudes.jpg"
);
littleDudes.x = app.screen.width / 2 - 315;
littleDudes.y = 200;
app.stage.addChild(littleDudes);
var littleRobot = InkPaint.Sprite.fromImage(
"source/assets/pixi-filters/depth_blur_moby.jpg"
);
littleRobot.x = app.screen.width / 2 - 200;
littleRobot.y = 100;
app.stage.addChild(littleRobot);
var blurFilter1 = new InkPaint.filters.BlurFilter();
var blurFilter2 = new InkPaint.filters.BlurFilter();
littleDudes.filters = [blurFilter1];
var count = 0;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
count += 0.005;
littleRobot.blur = 30 * Math.sin(count * 4);
var blurAmount = Math.cos(count);
var blurAmount2 = Math.sin(count);
blurFilter1.blur = 20 * blurAmount;
blurFilter2.blur = 20 * blurAmount2;
});
<file_sep>/examples/source/js/textures/texture-orig.js
var texture;
var app = new InkPaint.Application();
document.body.appendChild(app.view);
InkPaint.loader.add("flowerTop1", "source/assets/flowerTop1.png");
InkPaint.loader.load(function(loader, resources) {
texture = resources.flowerTop1.texture;
loaded();
});
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
});
// 0, 0, 119, 181
function loaded() {
// 1
var sprite1 = new InkPaint.Sprite(texture);
sprite1.x = 100;
sprite1.y = 150;
app.stage.addChild(sprite1);
//////////////////////////////////////////////////////
var width = 40;
var height = 190;
var frame = new InkPaint.Rectangle(0, 0, 119, 181);
var orig = new InkPaint.Rectangle(0, 0, width, height);
var trim = new InkPaint.Rectangle(0, 0, width, height);
var result = getSourceRect(width, height);
// 2
//////////////////////////////////////////////////////
var texture2 = new InkPaint.Texture(texture.baseTexture, result, orig, trim);
var sprite2 = new InkPaint.Sprite(texture2);
sprite2.x = 300;
sprite2.y = 150;
app.stage.addChild(sprite2);
// 3
//////////////////////////////////////////////////////
var sprite3 = new InkPaint.Sprite(InkPaint.Texture.newEmpty());
sprite3.x = 410;
sprite3.y = 150;
app.stage.addChild(sprite3);
// 4
//////////////////////////////////////////////////////
var width = 60;
var height = 240;
var texture4;
var sprite4 = new InkPaint.Sprite(InkPaint.Texture.newEmpty());
sprite4.x = 600;
sprite4.y = 150;
sprite4.width = width;
sprite4.height = height;
app.stage.addChild(sprite4);
var orig = new InkPaint.Rectangle(0, 0, width, height);
var trim = new InkPaint.Rectangle(0, 0, width, height);
var result = getSourceRect(width, height);
var i = 0;
setTimeout(() => {
if (!texture4) {
texture4 = new InkPaint.Texture(
new InkPaint.BaseTexture(),
result,
orig,
trim
);
texture4.id = "xxx";
sprite4.texture = texture4;
sprite4.width = width;
sprite4.height = height;
sprite3.texture = texture.clone();
}
}, 200);
setInterval(() => {
//////////////////////////////////////////////////////
if (++i > 3) i = 1;
sprite4.texture.updateSource(`source/assets/flowerTop${i}.png`);
sprite3.texture.updateSource(
`source/assets/flowerTop${3 - i}.png`,
true
);
}, 800);
}
function getSourceRect(width, height) {
let w, h, x, y;
const ow = 119;
const oh = 181;
const s1 = width / height;
const s2 = ow / oh;
if (s1 >= s2) {
w = ow;
h = (ow / s1) >> 0;
x = 0;
y = ((oh - h) / 2) >> 0;
} else {
h = oh;
w = (oh * s1) >> 0;
y = 0;
x = ((ow - w) / 2) >> 0;
}
return new InkPaint.Rectangle(x, y, w, h);
}
<file_sep>/src/index.js
import "./polyfill/requestAnimationFrame";
import { utils } from "./core";
utils.mixins.performMixins();
import * as filters from "./filters";
import { loader, Loader, Resource } from "./loaders";
// node-canvas and headless-gl api
export {
gl,
Canvas,
Context2d,
CanvasRenderingContext2D,
CanvasGradient,
CanvasPattern,
Image,
ImageData,
PNGStream,
PDFStream,
JPEGStream,
DOMMatrix,
DOMPoint,
registerFont,
deregisterAllFonts,
parseFont,
createCanvas,
createImageData,
loadImage
} from "./canvas-gl";
// inkpaint engine core api
export {
settings,
utils,
ticker,
Ticker,
CanvasRenderer,
WebGLRenderer,
Bounds,
ProxyObj,
DisplayObject,
Container,
Transform,
TransformStatic,
Sprite,
AnimatedSprite,
CanvasSpriteRenderer,
CanvasTinter,
SpriteRenderer,
Text,
TextStyle,
TextMetrics,
Graphics,
GraphicsRenderer,
Texture,
TextureMatrix,
BaseTexture,
Shader,
Spritesheet,
WebGLManager,
ObjectRenderer,
Quad,
SpriteMaskFilter,
Filter,
RenderTexture,
BaseRenderTexture,
Rectangle,
Application
} from "./core";
// inkpaint pugins
export * from "./const";
export * from "./math";
export { filters, loader, Loader, Resource };
export {
TextureCache,
BaseTextureCache,
addToTextureCache,
removeFromTextureCache,
removeFromBaseTextureCache,
addToBaseTextureCache,
destroyAllTextureCache,
deleteAllTextureCache,
destroyAndCleanAllCache
} from "./utils/cache";
global.InkPaint = exports;
<file_sep>/src/loaders/loader.js
import EventEmitter from "eventemitter3";
import textureParser from "./textureParser";
import { inherit } from "../utils";
import { Resource, ResourceLoader } from "../resource";
import spritesheetParser from "./spritesheetParser";
export default class Loader extends ResourceLoader {
constructor(baseUrl, concurrency) {
super(baseUrl, concurrency);
EventEmitter.call(this);
for (let i = 0; i < Loader._pixiMiddleware.length; ++i) {
this.use(Loader._pixiMiddleware[i]());
}
this.onStart.add(l => this.emit("start", l));
this.onLoad.add((l, r) => this.emit("load", l, r));
this.onProgress.add((l, r) => this.emit("progress", l, r));
this.onError.add((e, l, r) => this.emit("error", e, l, r));
this.onComplete.add((l, r) => this.emit("complete", l, r));
}
static addPixiMiddleware(fn) {
Loader._pixiMiddleware.push(fn);
}
destroy() {
this.removeAllListeners();
super.destroy();
}
}
inherit(Loader, EventEmitter);
Loader._pixiMiddleware = [textureParser, spritesheetParser];
<file_sep>/src/textures/Texture.js
import BaseTexture from "./BaseTexture";
import settings from "../settings";
import TextureUvs from "./TextureUvs";
import EventEmitter from "eventemitter3";
import { Rectangle, Point } from "../math";
import { getResolutionOfUrl, uuidvx } from "../utils";
import {
TextureCache,
addToTextureCache,
removeFromTextureCache,
addToBaseTextureCache,
destroyBaseTextureCache
} from "../utils/cache";
export default class Texture extends EventEmitter {
constructor(baseTexture, frame, orig, trim, rotate, anchor) {
super();
if (frame) {
this.hasDefaultFrame = true;
} else {
this.hasDefaultFrame = false;
frame = new Rectangle(0, 0, 1, 1);
}
this._uvs = null;
this._cache = [];
this.valid = false;
this.destroyed = false;
this.requiresUpdate = false;
this.cutout = false;
this.cutoutColors = null;
this.trim = trim;
this.orig = orig || frame;
this._frame = frame;
this._rotate = Number(rotate || 0);
this._updateID = 0;
this.transform = null;
this.textureCacheIds = [];
if (rotate === true) {
this._rotate = 2;
} else if (this._rotate % 2 !== 0) {
throw new Error("attempt to use diamond-shaped UVs.");
}
this.id = uuidvx();
this.initBaseTexture(baseTexture, frame);
this.defaultAnchor = anchor
? new Point(anchor.x, anchor.y)
: new Point(0, 0);
}
initBaseTexture(baseTexture, frame) {
if (baseTexture instanceof Texture) baseTexture = baseTexture.baseTexture;
this.baseTexture = baseTexture;
this.setCutoutToBaseTexture();
this.addToCache(baseTexture.imageUrl);
if (baseTexture.hasLoaded) {
if (!this.hasDefaultFrame) {
// from 1,1 -> w,h
const { width, height } = baseTexture;
this.frame = new Rectangle(0, 0, width, height);
baseTexture.on("update", this.onBaseTextureUpdated, this);
} else {
this.frame = frame;
}
baseTexture.adaptedNodeCanvas();
} else {
baseTexture.once("loaded", this.onBaseTextureLoaded, this);
}
baseTexture.on("error", this.onBaseTextureError, this);
}
update() {
this.baseTexture.update();
}
addToCache(imageUrl) {
if (!imageUrl) return;
if (this._cache.indexOf(imageUrl) < 0) this._cache.push(imageUrl);
}
updateSource(imageUrl, useCache = false) {
if (this.baseTexture.imageUrl === imageUrl) return;
if (useCache) {
this.addToCache(imageUrl);
this.baseTexture = BaseTexture.fromImage(imageUrl);
this.setCutoutToBaseTexture();
this.baseTexture.adaptedNodeCanvas();
} else {
this.baseTexture.updateSource(imageUrl);
}
}
setCutoutColor(min, max) {
this.cutout = true;
this.cutoutColors = { min, max };
this.setCutoutToBaseTexture();
}
setCutoutToBaseTexture() {
if (!this.baseTexture) return;
this.baseTexture.cutout = this.cutout;
this.baseTexture.cutoutColors = this.cutoutColors;
}
getImageUrl() {
return this.baseTexture.imageUrl;
}
onBaseTextureLoaded(baseTexture) {
this._updateID++;
if (!this.hasDefaultFrame) {
// from 1,1 -> w,h
const { width, height } = baseTexture;
this.frame = new Rectangle(0, 0, width, height);
} else {
this.frame = this._frame;
}
baseTexture.adaptedNodeCanvas();
this.baseTexture.on("update", this.onBaseTextureUpdated, this);
this.emit("update", this);
}
onBaseTextureError(e) {
this.emit("error", e);
}
onBaseTextureUpdated(baseTexture) {
this._updateID++;
if (!this.hasDefaultFrame) {
this._frame.width = baseTexture.width;
this._frame.height = baseTexture.height;
}
baseTexture.adaptedNodeCanvas();
this.emit("update", this);
}
destroy(destroyBase) {
if (this.destroyed) return;
if (this.baseTexture) {
if (destroyBase) {
const { imageUrl } = this.baseTexture;
if (TextureCache[imageUrl]) {
removeFromTextureCache(imageUrl);
}
for (let i = 0; i < this._cache.length; i++) {
const urlKey = this._cache[i];
destroyBaseTextureCache(urlKey);
}
this.baseTexture.destroy();
}
this.baseTexture.off("update", this.onBaseTextureUpdated, this);
this.baseTexture.off("loaded", this.onBaseTextureLoaded, this);
this.baseTexture.off("error", this.onBaseTextureError, this);
this.baseTexture = null;
}
this._cache.length = 0;
this._cache = null;
this._frame = null;
this._uvs = null;
this.trim = null;
this.orig = null;
this.valid = false;
this.cutout = false;
this.cutoutColors = null;
this.destroyed = true;
removeFromTextureCache(this);
this.textureCacheIds = null;
}
clone() {
return new Texture(
this.baseTexture,
this.frame,
this.orig,
this.trim,
this.rotate,
this.defaultAnchor
);
}
_updateUvs() {
if (!this._uvs) this._uvs = new TextureUvs();
this._uvs.set(this._frame, this.baseTexture, this.rotate);
this._updateID++;
}
get frame() {
return this._frame;
}
set frame(frame) {
this._frame = frame;
this.hasDefaultFrame = true;
const { x, y, width, height } = frame;
const xNotFit = x + width > this.baseTexture.width;
const yNotFit = y + height > this.baseTexture.height;
if (xNotFit || yNotFit) {
const relationship = xNotFit && yNotFit ? "and" : "or";
const errorX = `X: ${x} + ${width} = ${x + width} > ${
this.baseTexture.width
}`;
const errorY = `Y: ${y} + ${height} = ${y + height} > ${
this.baseTexture.height
}`;
throw new Error(
"Texture Error: frame does not fit inside the base Texture dimensions: " +
`${errorX} ${relationship} ${errorY}`
);
}
this.valid = width && height && this.baseTexture.hasLoaded;
if (!this.trim && !this.rotate) {
this.orig = frame;
}
if (this.valid) this._updateUvs();
}
get rotate() {
return this._rotate;
}
set rotate(rotate) {
this._rotate = rotate;
if (this.valid) this._updateUvs();
}
get width() {
return this.orig.width;
}
get height() {
return this.orig.height;
}
static newEmpty() {
return new Texture(new BaseTexture());
}
static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) {
let texture = TextureCache[imageUrl];
if (texture) return texture;
if (crossorigin instanceof Rectangle) {
texture = new Texture(
BaseTexture.fromImage(imageUrl),
crossorigin,
scaleMode,
sourceScale
);
} else {
texture = new Texture(
BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)
);
}
addToTextureCache(texture, imageUrl);
return texture;
}
static fromFrame(frameId) {
const texture = TextureCache[frameId];
if (!texture) {
throw new Error(`The frameId "${frameId}" does not exist in cache`);
}
return texture;
}
static fromCanvas(canvas, scaleMode, origin = "canvas") {
return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin));
}
static from(source) {
if (typeof source === "string") {
const texture = TextureCache[source];
if (texture) return texture;
return Texture.fromImage(source);
} else if (source instanceof Texture) {
return source;
} else if (source instanceof HTMLImageElement) {
return new Texture(BaseTexture.from(source));
} else if (source instanceof HTMLCanvasElement) {
return Texture.fromCanvas(
source,
settings.SCALE_MODE,
"HTMLCanvasElement"
);
} else if (source instanceof BaseTexture) {
return new Texture(source);
}
return source;
}
static fromLoader(source, imageUrl, name) {
const baseTexture = new BaseTexture(
source,
undefined,
getResolutionOfUrl(imageUrl)
);
const texture = new Texture(baseTexture);
baseTexture.imageUrl = imageUrl;
if (!name) name = imageUrl;
addToBaseTextureCache(texture.baseTexture, name);
addToTextureCache(texture, name);
if (name !== imageUrl) {
addToBaseTextureCache(texture.baseTexture, imageUrl);
addToTextureCache(texture, imageUrl);
}
return texture;
}
}
function removeAllHandlers(tex) {
tex.destroy = () => {};
tex.on = () => {};
tex.once = () => {};
tex.emit = () => {};
}
Texture.EMPTY = new Texture(new BaseTexture());
removeAllHandlers(Texture.EMPTY);
removeAllHandlers(Texture.EMPTY.baseTexture);
<file_sep>/src/utils/createIndicesForQuads.js
export default function createIndicesForQuads(size) {
const totalIndices = size * 6;
const indices = new Uint16Array(totalIndices);
for (let i = 0, j = 0; i < totalIndices; i += 6, j += 4) {
indices[i + 0] = j + 0;
indices[i + 1] = j + 1;
indices[i + 2] = j + 2;
indices[i + 3] = j + 0;
indices[i + 4] = j + 2;
indices[i + 5] = j + 3;
}
return indices;
}
<file_sep>/src/autoRenderer.js
import CanvasRenderer from "./renderers/canvas/CanvasRenderer";
import WebGLRenderer from "./renderers/webgl/WebGLRenderer";
export function autoRenderer(options = {}) {
const useGL = options.useGL;
if (useGL) return new WebGLRenderer(options);
return new CanvasRenderer(options);
}
<file_sep>/examples/source/js/plugin-filters/outline.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
app.stage.position.set(400, 300);
var outlineFilterBlue = new InkPaint.filters.OutlineFilter(2, 0x99ff99);
var outlineFilterRed = new InkPaint.filters.GlowFilter(15, 2, 1, 0xff9999, 0.5);
function filterOn() {
this.filters = [outlineFilterRed];
}
function filterOff() {
this.filters = [outlineFilterBlue];
}
for (var i = 0; i < 20; i++) {
var bunny = InkPaint.Sprite.fromImage("source/assets/bunny.png");
// bunny.anchor.set(0.5);
bunny.interactive = true;
bunny.position.set(
((Math.random() * 2 - 1) * 300) | 0,
((Math.random() * 2 - 1) * 200) | 0
);
bunny.scale.x = ((Math.random() * 3) | (0 * 0.1)) + 1;
bunny.on("pointerover", filterOn).on("pointerout", filterOff);
filterOff.call(bunny);
app.stage.addChild(bunny);
}
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
});
<file_sep>/src/utils/cache.js
export const TextureCache = Object.create(null);
export const BaseTextureCache = Object.create(null);
export function addToTextureCache(texture, id) {
if (!id) return;
if (texture.textureCacheIds.indexOf(id) === -1)
texture.textureCacheIds.push(id);
TextureCache[id] = texture;
}
export function removeFromTextureCache(texture) {
if (typeof texture === "string") {
const textureFromCache = TextureCache[texture];
if (textureFromCache) {
const index = textureFromCache.textureCacheIds.indexOf(texture);
if (index > -1) textureFromCache.textureCacheIds.splice(index, 1);
delete TextureCache[texture];
return textureFromCache;
}
} else if (texture && texture.textureCacheIds) {
for (let i = 0; i < texture.textureCacheIds.length; ++i) {
if (TextureCache[texture.textureCacheIds[i]] === texture) {
delete TextureCache[texture.textureCacheIds[i]];
}
}
texture.textureCacheIds.length = 0;
return texture;
}
return null;
}
export function addToBaseTextureCache(baseTexture, id) {
if (!id) return;
if (baseTexture.textureCacheIds.indexOf(id) === -1) {
baseTexture.textureCacheIds.push(id);
}
BaseTextureCache[id] = baseTexture;
}
export function removeFromBaseTextureCache(baseTexture) {
if (typeof baseTexture === "string") {
const baseTextureFromCache = BaseTextureCache[baseTexture];
if (baseTextureFromCache) {
const index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
if (index > -1) {
baseTextureFromCache.textureCacheIds.splice(index, 1);
}
delete BaseTextureCache[baseTexture];
return baseTextureFromCache;
}
} else if (baseTexture && baseTexture.textureCacheIds) {
for (let i = 0; i < baseTexture.textureCacheIds.length; ++i) {
delete BaseTextureCache[baseTexture.textureCacheIds[i]];
}
baseTexture.textureCacheIds.length = 0;
return baseTexture;
}
return null;
}
export function destroyAllTextureCache() {
let key;
for (key in TextureCache) {
TextureCache[key].destroy();
}
for (key in BaseTextureCache) {
BaseTextureCache[key].destroy();
}
}
export function deleteAllTextureCache() {
let key;
for (key in TextureCache) {
delete TextureCache[key];
}
for (key in BaseTextureCache) {
delete BaseTextureCache[key];
}
}
export function destroyAndCleanAllCache() {
destroyAllTextureCache();
deleteAllTextureCache();
}
export function destroyBaseTextureCache(key) {
if (!BaseTextureCache[key]) return;
BaseTextureCache[key].destroy();
delete BaseTextureCache[key];
}
export function destroyTextureCache(key) {
if (!TextureCache[key]) return;
TextureCache[key].destroy();
delete TextureCache[key];
}
<file_sep>/src/math/GroupD8.js
import Matrix from "./Matrix";
const ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1];
const uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1];
const vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1];
const vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1];
const tempMatrices = [];
const mul = [];
function signum(x) {
if (x < 0) {
return -1;
}
if (x > 0) {
return 1;
}
return 0;
}
function init() {
for (let i = 0; i < 16; i++) {
const row = [];
mul.push(row);
for (let j = 0; j < 16; j++) {
const _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]);
const _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]);
const _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]);
const _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]);
for (let k = 0; k < 16; k++) {
if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) {
row.push(k);
break;
}
}
}
}
for (let i = 0; i < 16; i++) {
const mat = new Matrix();
mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0);
tempMatrices.push(mat);
}
}
init();
const GroupD8 = {
E: 0,
SE: 1,
S: 2,
SW: 3,
W: 4,
NW: 5,
N: 6,
NE: 7,
MIRROR_VERTICAL: 8,
MIRROR_HORIZONTAL: 12,
uX: ind => ux[ind],
uY: ind => uy[ind],
vX: ind => vx[ind],
vY: ind => vy[ind],
inv: rotation => {
if (rotation & 8) {
return rotation & 15;
}
return -rotation & 7;
},
add: (rotationSecond, rotationFirst) => mul[rotationSecond][rotationFirst],
sub: (rotationSecond, rotationFirst) =>
mul[rotationSecond][GroupD8.inv(rotationFirst)],
rotate180: rotation => rotation ^ 4,
isVertical: rotation => (rotation & 3) === 2,
byDirection: (dx, dy) => {
if (Math.abs(dx) * 2 <= Math.abs(dy)) {
if (dy >= 0) {
return GroupD8.S;
}
return GroupD8.N;
} else if (Math.abs(dy) * 2 <= Math.abs(dx)) {
if (dx > 0) {
return GroupD8.E;
}
return GroupD8.W;
} else if (dy > 0) {
if (dx > 0) {
return GroupD8.SE;
}
return GroupD8.SW;
} else if (dx > 0) {
return GroupD8.NE;
}
return GroupD8.NW;
},
matrixAppendRotationInv: (matrix, rotation, tx = 0, ty = 0) => {
// Packer used "rotation", we use "inv(rotation)"
const mat = tempMatrices[GroupD8.inv(rotation)];
mat.tx = tx;
mat.ty = ty;
matrix.append(mat);
}
};
export default GroupD8;
<file_sep>/examples/source/js/demos-advanced/star-warp.js
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x000000,
});
document.body.appendChild(app.view);
var stats = new Stats();
stats.showPanel(1);
document.body.appendChild(stats.dom);
var starTexture = InkPaint.Texture.fromImage("source/assets/star.png");
var count = 1000;
var cameraZ = 0;
var fov = 20;
var baseSpeed = 0.025;
var speed = 0;
var warpSpeed = 0;
var starStretch = 5;
var starBaseSize = 0.05;
var stars = [];
for (var i = 0; i < count; i++) {
var star = {
sprite: new InkPaint.Sprite(starTexture),
z: 0,
x: 0,
y: 0
};
star.sprite.anchor.x = 0.5;
star.sprite.anchor.y = 0.7;
randomizeStar(star, true);
app.stage.addChild(star.sprite);
stars.push(star);
}
function randomizeStar(star, initial) {
star.z = initial
? Math.random() * 2000
: cameraZ + Math.random() * 1000 + 2000;
var deg = Math.random() * Math.PI * 2;
var distance = Math.random() * 50 + 1;
star.x = Math.cos(deg) * distance;
star.y = Math.sin(deg) * distance;
}
setInterval(function() {
warpSpeed = warpSpeed > 0 ? 0 : 1;
}, 5000);
requestAnimationFrame(animate);
function animate() {
//stats.begin();
requestAnimationFrame(animate);
render(1);
//stats.end();
}
function render(delta) {
app.render();
speed += (warpSpeed - speed) / 20;
cameraZ += delta * 10 * (speed + baseSpeed);
for (var i = 0; i < count; i++) {
var star = stars[i];
var screen = app.renderer.screen;
if (star.z < cameraZ) randomizeStar(star);
var z = star.z - cameraZ;
star.sprite.x = star.x * (fov / z) * screen.width + screen.width / 2;
star.sprite.y = star.y * (fov / z) * screen.width + screen.height / 2;
var dxCenter = star.sprite.x - screen.width / 2;
var dyCenter = star.sprite.y - screen.height / 2;
var distanceCenter = Math.sqrt(
dxCenter * dxCenter + dyCenter + dyCenter
);
var distanceScale = Math.max(0, (2000 - z) / 2000);
star.sprite.scale.x = distanceScale * starBaseSize;
star.sprite.scale.y =
distanceScale * starBaseSize +
(distanceScale * speed * starStretch * distanceCenter) /
screen.width;
star.sprite.rotation = Math.atan2(dyCenter, dxCenter) + Math.PI / 2;
}
}
<file_sep>/src/utils/determineCrossOrigin.js
export default function determineCrossOrigin(url) {
return "anonymous";
}
<file_sep>/test/core/Texture.js
'use strict';
const URL = 'foo.png';
const NAME = 'foo';
const NAME2 = 'bar';
function cleanCache()
{
delete InkPaint.utils.BaseTextureCache[URL];
delete InkPaint.utils.BaseTextureCache[NAME];
delete InkPaint.utils.BaseTextureCache[NAME2];
delete InkPaint.utils.TextureCache[URL];
delete InkPaint.utils.TextureCache[NAME];
delete InkPaint.utils.TextureCache[NAME2];
}
describe('InkPaint.Texture', function ()
{
it('should register Texture from Loader', function ()
{
cleanCache();
const image = new Image();
const texture = InkPaint.Texture.fromLoader(image, URL, NAME);
expect(texture.baseTexture.imageUrl).to.equal('foo.png');
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
expect(InkPaint.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
expect(InkPaint.utils.TextureCache[URL]).to.equal(texture);
expect(InkPaint.utils.BaseTextureCache[URL]).to.equal(texture.baseTexture);
});
it('should remove Texture from cache on destroy', function ()
{
cleanCache();
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
InkPaint.Texture.addToCache(texture, NAME);
InkPaint.Texture.addToCache(texture, NAME2);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(texture);
texture.destroy();
expect(texture.textureCacheIds).to.equal(null);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(undefined);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(undefined);
});
it('should be added to the texture cache correctly, '
+ 'and should remove only itself, not effecting the base texture and its cache', function ()
{
cleanCache();
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
InkPaint.BaseTexture.addToCache(texture.baseTexture, NAME);
InkPaint.Texture.addToCache(texture, NAME);
expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(InkPaint.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
InkPaint.Texture.removeFromCache(NAME);
expect(texture.baseTexture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
expect(InkPaint.utils.BaseTextureCache[NAME]).to.equal(texture.baseTexture);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(undefined);
});
it('should remove Texture from entire cache using removeFromCache (by Texture instance)', function ()
{
cleanCache();
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
InkPaint.Texture.addToCache(texture, NAME);
InkPaint.Texture.addToCache(texture, NAME2);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(texture);
InkPaint.Texture.removeFromCache(texture);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(-1);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(undefined);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(undefined);
});
it('should remove Texture from single cache entry using removeFromCache (by id)', function ()
{
cleanCache();
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
InkPaint.Texture.addToCache(texture, NAME);
InkPaint.Texture.addToCache(texture, NAME2);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(1);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(texture);
InkPaint.Texture.removeFromCache(NAME);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
expect(texture.textureCacheIds.indexOf(NAME2)).to.equal(0);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(undefined);
expect(InkPaint.utils.TextureCache[NAME2]).to.equal(texture);
});
it('should not remove Texture from cache if Texture instance has been replaced', function ()
{
cleanCache();
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
const texture2 = new InkPaint.Texture(new InkPaint.BaseTexture());
InkPaint.Texture.addToCache(texture, NAME);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture);
InkPaint.Texture.addToCache(texture2, NAME);
expect(texture2.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture2);
InkPaint.Texture.removeFromCache(texture);
expect(texture.textureCacheIds.indexOf(NAME)).to.equal(-1);
expect(texture2.textureCacheIds.indexOf(NAME)).to.equal(0);
expect(InkPaint.utils.TextureCache[NAME]).to.equal(texture2);
});
it('destroying a destroyed texture should not throw an error', function ()
{
const texture = new InkPaint.Texture(new InkPaint.BaseTexture());
texture.destroy(true);
texture.destroy(true);
});
it('should clone a texture', function ()
{
const baseTexture = new InkPaint.BaseTexture();
const frame = new InkPaint.Rectangle();
const orig = new InkPaint.Rectangle();
const trim = new InkPaint.Rectangle();
const rotate = 2;
const anchor = new InkPaint.Point(1, 0.5);
const texture = new InkPaint.Texture(baseTexture, frame, orig, trim, rotate, anchor);
const clone = texture.clone();
expect(clone.baseTexture).to.equal(baseTexture);
expect(clone.defaultAnchor.x).to.equal(texture.defaultAnchor.x);
expect(clone.defaultAnchor.y).to.equal(texture.defaultAnchor.y);
expect(clone.frame).to.equal(texture.frame);
expect(clone.trim).to.equal(texture.trim);
expect(clone.orig).to.equal(texture.orig);
expect(clone.rotate).to.equal(texture.rotate);
clone.destroy();
texture.destroy(true);
});
});
<file_sep>/src/polyfill/requestAnimationFrame.js
const ONE_FRAME_TIME = 16;
// Date.now
if (!(Date.now && Date.prototype.getTime)) {
Date.now = function now() {
return new Date().getTime();
};
}
// performance.now
if (!(global.performance && global.performance.now)) {
const startTime = Date.now();
if (!global.performance) {
global.performance = {};
}
global.performance.now = () => Date.now() - startTime;
}
// requestAnimationFrame
let lastTime = Date.now();
const vendors = ["ms", "moz", "webkit", "o"];
for (let x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) {
const p = vendors[x];
global.requestAnimationFrame = global[`${p}RequestAnimationFrame`];
global.cancelAnimationFrame =
global[`${p}CancelAnimationFrame`] ||
global[`${p}CancelRequestAnimationFrame`];
}
if (!global.requestAnimationFrame) {
global.requestAnimationFrame = callback => {
if (typeof callback !== "function") {
throw new TypeError(`${callback}is not a function`);
}
const currentTime = Date.now();
let delay = ONE_FRAME_TIME + lastTime - currentTime;
if (delay < 0) {
delay = 0;
}
lastTime = currentTime;
return setTimeout(() => {
lastTime = Date.now();
callback(performance.now());
}, delay);
};
}
if (!global.cancelAnimationFrame) {
global.cancelAnimationFrame = id => clearTimeout(id);
}
<file_sep>/test/prepare/CountLimiter.js
'use strict';
describe('InkPaint.prepare.CountLimiter', function ()
{
it('should limit to specified number per beginFrame()', function ()
{
const limit = new InkPaint.prepare.CountLimiter(3);
limit.beginFrame();
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.false;
limit.beginFrame();
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.true;
expect(limit.allowedToUpload()).to.be.false;
});
});
<file_sep>/examples/source/js/text/text.js
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
var basicText = new InkPaint.Text("Basic 没有字体 text in pixi");
basicText.x = 50;
basicText.y = 100;
app.stage.addChild(basicText);
var text = new InkPaint.Text("Basic text in 没有字体 pixi");
text.updateStyle({
fill: "#ffffff",
backgroundColor: "#ff0000",
padding: 10
});
text.x = 250;
text.y = 200;
app.stage.addChild(text);
var text1 = new InkPaint.Text("你好周杰伦! 哈哈");
text1.updateStyle({
fill: "#ffffff",
backgroundColor: "#00eeee",
padding: 10
});
text1.x = 450;
text1.y = 300;
app.stage.addChild(text1);
var bunny = InkPaint.Sprite.fromImage("source/assets/eggHead.png");
bunny.x = 500;
bunny.y = 400;
app.stage.addChild(bunny);
var style = new InkPaint.TextStyle({
fontFamily: "Arial",
fontSize: 36,
fontStyle: "italic",
fontWeight: "bold",
fill: ["#ffffff", "#00ff99"], // gradient
stroke: "#4a1850",
strokeThickness: 5,
dropShadow: true,
dropShadowColor: "#000000",
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
wordWrap: true,
wordWrapWidth: 440
});
var richText = new InkPaint.Text(
"FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例。",
style
);
richText.x = 50;
richText.y = 350;
app.stage.addChild(richText);
var length = 10;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
length -= 0.1;
if (length <= -5) length = 10;
text1.text = "你好周杰伦! 哈哈".substr(0, Math.max(0, length) >> 0);
});
<file_sep>/examples/src/js/inkpaint-examples.js
$(document).ready(function($) {
var bpc = bpc || {};
bpc.allowedVersions = [4];
bpc.pixiVersionString = "v4.x";
bpc.majorPixiVersion = 4;
bpc.exampleUrl = "";
bpc.exampleFilename = "";
bpc.exampleTitle = "";
bpc.exampleSourceCode = "";
bpc.exampleRequiredPlugins = [];
bpc.exampleValidVersions = [];
bpc.editorOptions = {
mode: "javascript",
lineNumbers: true,
styleActiveLine: true,
matchBrackets: true,
viewportMargin: Infinity,
lineWrapping: true
};
bpc.clickType = "click";
bpc.animTime = 0.15;
bpc.resize = function() {};
bpc.scriptsToLoad = ["https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"];
bpc.scriptsLoaded = 0;
bpc.loadScriptsAsync = function() {
for (var i = 0; i < bpc.scriptsToLoad.length; i++) {
$.ajax({
url: bpc.scriptsToLoad[i],
dataType: "script",
cache: true,
async: true,
success: bpc.fileLoaded
});
}
if (bpc.scriptsToLoad.length === 0) {
bpc.loadComplete();
}
};
bpc.fileLoaded = function() {
bpc.scriptsLoaded++;
if (bpc.scriptsLoaded === bpc.scriptsToLoad.length) {
bpc.loadComplete();
}
};
bpc.loadComplete = function() {
$.getJSON("source/manifest.json", function(data) {
var sections = Object.keys(data);
for (var i = 0; i < sections.length; i++) {
var html =
'<span class="section" data-section="' +
sections[i] +
'">' +
sections[i] +
'</span><ul data-section="' +
sections[i] +
'">';
var items = data[sections[i]];
for (var j = 0; j < items.length; j++) {
var plugins = typeof items[j].plugins !== "undefined" ? items[j].plugins.join(",") : "";
var validVersions =
typeof items[j].validVersions !== "undefined" ? items[j].validVersions.join(",") : "";
html +=
'<li data-src="' +
items[j].entry +
'" data-plugins="' +
plugins +
'" data-validVersions="' +
validVersions +
'">' +
items[j].title +
"</li>";
}
html += "</ul>";
$(".main-menu").append(html);
}
bpc.initNav();
});
};
bpc.initNav = function() {
$(".main-menu .section").on(bpc.clickType, function() {
$(this)
.next("ul")
.slideToggle(250);
$(this).toggleClass("open");
});
$(".main-menu li").on(bpc.clickType, function() {
if (!$(this).hasClass("selected")) {
$(".main-menu li.selected").removeClass("selected");
$(this).addClass("selected");
// load data
bpc.closeMobileNav();
var page =
"/" +
$(this)
.parent()
.attr("data-section") +
"/" +
$(this).attr("data-src");
bpc.exampleTitle = $(this).text();
window.location.hash = page;
document.title = bpc.exampleTitle + " - PixiJS Examples";
bpc.exampleUrl =
"source/js/" +
$(this)
.parent()
.attr("data-section") +
"/" +
$(this).attr("data-src");
bpc.exampleFilename = $(this).attr("data-src");
var plugins = $(this).attr("data-plugins");
bpc.exampleRequiredPlugins = plugins === "" ? [] : plugins.split(",");
var validVersions = $(this).attr("data-validVersions");
bpc.exampleValidVersions =
validVersions === ""
? [4]
: validVersions.split(",").map(function(v) {
return parseInt(v, 10);
});
$.ajax({
url:
"source/js/" +
$(this)
.parent()
.attr("data-section") +
"/" +
$(this).attr("data-src"),
dataType: "text",
success: function(data) {
bpc.exampleSourceCode = data;
bpc.generateIFrameContent();
}
});
}
});
bpc.generateIFrameContent = function() {
// Remove all iFrames and content
var iframes = document.querySelectorAll("iframe");
for (var i = 0; i < iframes.length; i++) {
iframes[i].parentNode.removeChild(iframes[i]);
}
$("#example").html('<iframe id="preview" src="blank.html"></iframe>');
$(".CodeMirror").remove();
$(".main-content #code").html(bpc.exampleSourceCode);
// Generate HTML and insert into iFrame
var pixiUrl = "../dist/inkpaint.js";
var html = "<!DOCTYPE html><html><head><style>";
html += "body,html{margin:0px;height:100%;overflow:hidden;}canvas{width:100%;height:100%;}";
html += "</style></head><body>";
html += '<script src="vendor/jquery-3.3.1.min.js"></script>';
html += '<script src="vendor/tween.umd.js"></script>';
html += '<script src="vendor/Stats.min.js"></script>';
html += '<script src="' + pixiUrl + '"></script>';
bpc.editor = CodeMirror.fromTextArea(document.getElementById("code"), bpc.editorOptions);
if (bpc.exampleRequiredPlugins.length) {
$("#code-header").text("Example Code (plugins used: " + bpc.exampleRequiredPlugins.toString() + ")");
} else {
$("#code-header").text("Example Code");
}
var screenshotsScript = `
var removed = true;
var img = new Image();
img.style.width= "100%";
img.style.height= "100%";
document.body.onclick = function(){
if(document.body.noclick) return;
var dataURL = app.view.toDataURL('image/png');
img.src = dataURL;
img.width = app.view.width;
img.height = app.view.height;
if(removed){
document.body.removeChild(app.view);
document.body.appendChild(img);
}else{
document.body.appendChild(app.view);
document.body.removeChild(img);
}
removed = !removed;
}
`;
if (!bpc.exampleValidVersions.length || bpc.exampleValidVersions.indexOf(bpc.majorPixiVersion) > -1) {
$("#example-title").html(bpc.exampleTitle);
html += `<script>window.onload = function(){
${bpc.exampleSourceCode}
${screenshotsScript}
}</script></body></html>`;
$(".example-frame").show();
} else {
$("#example-title").html(
bpc.exampleTitle +
"<br><br><br><br><br><br><br>" +
"The selected version of PixiJS does not work with this example." +
"<br><br>" +
"Selected version: v" +
bpc.majorPixiVersion +
"<br><br>" +
"Required version: v" +
bpc.exampleValidVersions.toString() +
"<br><br><br><br><br>"
);
$(".example-frame").hide();
}
var iframe = document.getElementById("preview");
var frameDoc = iframe.contentDocument || iframe.contentWindow.document;
frameDoc.open();
frameDoc.write(html);
frameDoc.close();
};
bpc.openMobileNav = function() {
TweenMax.to("#line1", bpc.animTime, {
y: 0,
ease: Linear.easeNone
});
TweenMax.to("#line2", 0, {
alpha: 0,
ease: Linear.easeNone,
delay: bpc.animTime
});
TweenMax.to("#line3", bpc.animTime, {
y: 0,
ease: Linear.easeNone
});
TweenMax.to("#line1", bpc.animTime, {
rotation: 45,
ease: Quart.easeOut,
delay: bpc.animTime
});
TweenMax.to("#line3", bpc.animTime, {
rotation: -45,
ease: Quart.easeOut,
delay: bpc.animTime
});
$(".main-nav").addClass("mobile-open");
};
bpc.closeMobileNav = function() {
TweenMax.to("#line1", bpc.animTime, {
rotation: 0,
ease: Linear.easeNone,
delay: 0
});
TweenMax.to("#line3", bpc.animTime, {
rotation: 0,
ease: Linear.easeNone,
delay: 0
});
TweenMax.to("#line2", 0, {
alpha: 1,
ease: Quart.easeOut,
delay: bpc.animTime
});
TweenMax.to("#line1", bpc.animTime, {
y: -8,
ease: Quart.easeOut,
delay: bpc.animTime
});
TweenMax.to("#line3", bpc.animTime, {
y: 8,
ease: Quart.easeOut,
delay: bpc.animTime
});
$(".main-nav").removeClass("mobile-open");
};
bpc.updateMenu = function() {
$(".main-nav .main-menu ul li").each(function() {
var validVersions = $(this).attr("data-validVersions");
var exampleValidVersions =
validVersions === ""
? [4]
: validVersions.split(",").map(function(v) {
return parseInt(v, 10);
});
if (exampleValidVersions.indexOf(bpc.majorPixiVersion) === -1) {
$(this).addClass("invalid");
} else {
$(this).removeClass("invalid");
}
});
};
bpc.updateMenu();
$(".main-header .hamburger").on(bpc.clickType, function(e) {
e.preventDefault();
if ($(".main-nav").hasClass("mobile-open")) {
bpc.closeMobileNav();
} else {
bpc.openMobileNav();
}
return false;
});
// Deep link
if (window.location.hash !== "") {
var hash = window.location.hash.replace("#/", "");
var arr = hash.split("/");
var dom = '.main-menu .section[data-section="' + arr[0] + '"]';
if (arr.length > 1) {
if ($(dom).length > 0) {
$(dom).trigger(bpc.clickType);
if (
$(dom)
.next()
.find('li[data-src="' + arr[1] + '"]').length > 0
) {
$(dom)
.next()
.find('li[data-src="' + arr[1] + '"]')
.trigger(bpc.clickType);
}
}
}
} else {
$(".main-menu .section")
.eq(0)
.trigger(bpc.clickType);
$(".main-menu li")
.eq(0)
.trigger(bpc.clickType);
}
// Refresh Button
$(".reload").on(bpc.clickType, function() {
bpc.exampleSourceCode = bpc.editor.getValue();
bpc.generateIFrameContent();
});
};
bpc.init = function() {
$(window).resize(bpc.resize);
bpc.loadScriptsAsync();
};
bpc.init();
});
<file_sep>/src/renderers/SystemRenderer.js
import { hex2string, hex2rgb } from "../utils";
import { Matrix, Rectangle } from "../math";
import { RENDERER_TYPE } from "../const";
import EventEmitter from "eventemitter3";
import Doc from "../polyfill/Doc";
import settings from "../settings";
import Container from "../display/Container";
import RenderTexture from "../textures/RenderTexture";
const tempMatrix = new Matrix();
export default class SystemRenderer extends EventEmitter {
constructor(system, options, arg2, arg3) {
super();
if (typeof options === "number") {
options = Object.assign(
{
width: options,
height: arg2 || settings.RENDER_OPTIONS.height
},
arg3
);
}
options = Object.assign({}, settings.RENDER_OPTIONS, options);
this.options = options;
this.type = RENDERER_TYPE.UNKNOWN;
this.screen = new Rectangle(0, 0, options.width, options.height);
this.view = options.view || Doc.createElement("canvas");
this.resolution = options.resolution || settings.RESOLUTION;
this.transparent = options.transparent;
this.autoResize = options.autoResize || false;
this.blendModes = null;
this.preserveDrawingBuffer = options.preserveDrawingBuffer;
this.clearBeforeRender = options.clearBeforeRender;
this.roundPixels = options.roundPixels;
this._backgroundColor = 0x000000;
this._backgroundColorRgba = [0, 0, 0, 0];
this._backgroundColorString = "#000000";
this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter
this._tempDisplayObjectParent = new Container();
this._lastObjectRendered = this._tempDisplayObjectParent;
}
get width() {
return this.view.width;
}
get height() {
return this.view.height;
}
resize(screenWidth, screenHeight) {
this.screen.width = screenWidth;
this.screen.height = screenHeight;
this.view.width = screenWidth * this.resolution;
this.view.height = screenHeight * this.resolution;
if (this.autoResize) {
this.view.style.width = `${screenWidth}px`;
this.view.style.height = `${screenHeight}px`;
}
}
destroy(removeView) {
if (removeView && this.view.parentNode) {
this.view.parentNode.removeChild(this.view);
}
this.type = RENDERER_TYPE.UNKNOWN;
this.view = null;
this.screen = null;
this.resolution = 0;
this.transparent = false;
this.autoResize = false;
this.blendModes = null;
this.options = null;
this.preserveDrawingBuffer = false;
this.clearBeforeRender = false;
this.roundPixels = false;
this._backgroundColor = 0;
this._backgroundColorRgba = null;
this._backgroundColorString = null;
this._tempDisplayObjectParent = null;
this._lastObjectRendered = null;
}
get backgroundColor() {
return this._backgroundColor;
}
set backgroundColor(value) {
this._backgroundColor = value;
this._backgroundColorString = hex2string(value);
hex2rgb(value, this._backgroundColorRgba);
}
}
<file_sep>/src/filters/fxaa/FXAAFilter.js
import settings from "../../settings";
import Filter from "../../renderers/webgl/filters/Filter";
import { readFileSync } from "fs";
import { join } from "path";
export default class FXAAFilter extends Filter {
constructor() {
super(
// vertex shader
readFileSync(join(__dirname, "./fxaa.vert"), "utf8"),
// fragment shader
readFileSync(join(__dirname, "./fxaa.frag"), "utf8")
);
}
}
<file_sep>/examples/source/node/graphics/advanced.js
var app = new InkPaint.Application(800, 600, { antialias: true });
document.body.appendChild(app.view);
module.exports = app;
var sprite = InkPaint.Sprite.fromImage(paths('source/assets/bg_rotate.jpg'));
// // BEZIER CURVE ////
// information: https://en.wikipedia.org/wiki/Bézier_curve
var realPath = new InkPaint.Graphics();
realPath.lineStyle(2, 0xFFFFFF, 1);
realPath.moveTo(0, 0);
realPath.lineTo(100, 200);
realPath.lineTo(200, 200);
realPath.lineTo(240, 100);
realPath.position.x = 50;
realPath.position.y = 50;
app.stage.addChild(realPath);
var bezier = new InkPaint.Graphics();
bezier.lineStyle(5, 0xAA0000, 1);
bezier.bezierCurveTo(100, 200, 200, 200, 240, 100);
bezier.position.x = 50;
bezier.position.y = 50;
app.stage.addChild(bezier);
// // BEZIER CURVE 2 ////
var realPath2 = new InkPaint.Graphics();
realPath2.lineStyle(2, 0xFFFFFF, 1);
realPath2.moveTo(0, 0);
realPath2.lineTo(0, -100);
realPath2.lineTo(150, 150);
realPath2.lineTo(240, 100);
realPath2.position.x = 320;
realPath2.position.y = 150;
app.stage.addChild(realPath2);
var bezier2 = new InkPaint.Graphics();
bezier2.bezierCurveTo(0, -100, 150, 150, 240, 100);
bezier2.position.x = 320;
bezier2.position.y = 150;
app.stage.addChild(bezier2);
// // ARC ////
var arc = new InkPaint.Graphics();
arc.lineStyle(5, 0xAA00BB, 1);
arc.arc(600, 100, 50, Math.PI, 2 * Math.PI);
app.stage.addChild(arc);
// // ARC 2 ////
var arc2 = new InkPaint.Graphics();
arc2.lineStyle(6, 0x3333DD, 1);
arc2.arc(650, 270, 60, 2 * Math.PI, 3 * Math.PI / 2);
app.stage.addChild(arc2);
// // ARC 3 ////
var arc3 = new InkPaint.Graphics();
arc3.arc(650, 420, 60, 2 * Math.PI, 2.5 * Math.PI / 2);
app.stage.addChild(arc3);
// / Hole ////
var rectAndHole = new InkPaint.Graphics();
rectAndHole.beginFill(0x00FF00);
rectAndHole.drawRect(350, 350, 150, 150);
rectAndHole.drawCircle(375, 375, 25);
rectAndHole.drawCircle(425, 425, 25);
rectAndHole.drawCircle(475, 475, 25);
rectAndHole.endFill();
app.stage.addChild(rectAndHole);
// // Line Texture Style ////
var beatifulRect = new InkPaint.Graphics();
beatifulRect.beginFill(0xFF0000);
beatifulRect.drawRect(80, 350, 150, 150);
beatifulRect.endFill();
app.stage.addChild(beatifulRect);
app.render();
<file_sep>/src/math/shapes/Rectangle.js
import { SHAPES } from "../../const";
export default class Rectangle {
constructor(x = 0, y = 0, width = 0, height = 0) {
this.x = Number(x);
this.y = Number(y);
this.width = Number(width);
this.height = Number(height);
this.type = SHAPES.RECT;
}
get left() {
return this.x;
}
get right() {
return this.x + this.width;
}
get top() {
return this.y;
}
get bottom() {
return this.y + this.height;
}
static get EMPTY() {
return new Rectangle(0, 0, 0, 0);
}
clone() {
return new Rectangle(this.x, this.y, this.width, this.height);
}
copy(rectangle) {
this.x = rectangle.x;
this.y = rectangle.y;
this.width = rectangle.width;
this.height = rectangle.height;
return this;
}
contains(x, y) {
if (this.width <= 0 || this.height <= 0) {
return false;
}
if (x >= this.x && x < this.x + this.width) {
if (y >= this.y && y < this.y + this.height) {
return true;
}
}
return false;
}
pad(paddingX, paddingY) {
paddingX = paddingX || 0;
paddingY = paddingY || (paddingY !== 0 ? paddingX : 0);
this.x -= paddingX;
this.y -= paddingY;
this.width += paddingX * 2;
this.height += paddingY * 2;
}
fit(rectangle) {
const x1 = Math.max(this.x, rectangle.x);
const x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width);
const y1 = Math.max(this.y, rectangle.y);
const y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height);
this.x = x1;
this.width = Math.max(x2 - x1, 0);
this.y = y1;
this.height = Math.max(y2 - y1, 0);
}
/**
* Enlarges this rectangle to include the passed rectangle.
*
* @param {InkPaint.Rectangle} rectangle - The rectangle to include.
*/
enlarge(rectangle) {
const x1 = Math.min(this.x, rectangle.x);
const x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width);
const y1 = Math.min(this.y, rectangle.y);
const y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height);
this.x = x1;
this.width = x2 - x1;
this.y = y1;
this.height = y2 - y1;
}
ceil(resolution = 1, eps = 0.001) {
const x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
const y2 =
Math.ceil((this.y + this.height - eps) * resolution) / resolution;
this.x = Math.floor((this.x + eps) * resolution) / resolution;
this.y = Math.floor((this.y + eps) * resolution) / resolution;
this.width = x2 - this.x;
this.height = y2 - this.y;
}
toString() {
return `Rect:: ${this.x}_${this.y}_${this.width}_${this.height}`;
}
}
<file_sep>/examples/source/node/textures/gradient-basic.js
// This demo uses canvas2d gradient API
// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient
var app = new InkPaint.Application(800, 600, { antialias: true });
document.body.appendChild(app.view);
module.exports = app;
function createGradTexture() {
// adjust it if somehow you need better quality for very very big images
var quality = 256;
var canvas = new InkPaint.Canvas();
canvas.width = quality;
canvas.height = 1;
var ctx = canvas.getContext("2d");
// use canvas2d API to create gradient
var grd = ctx.createLinearGradient(0, 0, quality, 0);
grd.addColorStop(0, "rgba(255, 255, 255, 0.0)");
grd.addColorStop(0.3, "cyan");
grd.addColorStop(0.7, "red");
grd.addColorStop(1, "green");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, quality, 1);
return InkPaint.Texture.fromCanvas(canvas);
}
var gradTexture = createGradTexture();
var sprite = new InkPaint.Sprite(gradTexture);
sprite.position.set(100, 100);
sprite.rotation = Math.PI / 8;
sprite.width = 500;
sprite.height = 50;
app.stage.addChild(sprite);
app.render();
<file_sep>/examples/source/node/text/fontfamily.js
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb
});
document.body.appendChild(app.view);
module.exports = app;
const font1 = paths("source/assets/font/font.ttf");
const font2 = paths("source/assets/font/font2.ttf");
InkPaint.registerFont(font1, { family: "font1" });
InkPaint.registerFont(font2, { family: "font2" });
var basicText = new InkPaint.Text("Basic 你好 text in pixi");
basicText.x = 50;
basicText.y = 100;
app.stage.addChild(basicText);
var text = new InkPaint.Text("Basic text in 你好 pixi");
text.updateStyle({
fill: "#ffffff",
backgroundColor: "#ff0000",
padding: 10,
fontFamily: "font1"
});
text.x = 250;
text.y = 200;
app.stage.addChild(text);
var text = new InkPaint.Text("你好周杰伦! 哈哈");
text.updateStyle({
fill: "#ffffff",
backgroundColor: "#00eeee",
padding: 10,
fontFamily: "font2"
});
text.x = 450;
text.y = 300;
app.stage.addChild(text);
var style = new InkPaint.TextStyle({
fontFamily: "Arial",
fontSize: 36,
fontStyle: "italic",
fontWeight: "bold",
fill: ["#ffffff", "#00ff99"], // gradient
stroke: "#4a1850",
strokeThickness: 5,
dropShadow: true,
dropShadowColor: "#000000",
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
wordWrap: true,
wordWrapWidth: 420
});
var richText = new InkPaint.Text(
"FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例。",
style
);
richText.x = 50;
richText.y = 250;
var logo = InkPaint.Sprite.fromImage(paths("source/assets/logo/logo2.png"));
logo.x = 400;
logo.y = 50;
logo.anchor.set(0.5);
logo.scale.set(0.5);
app.stage.addChild(logo);
var bunny = InkPaint.Sprite.fromImage(paths("source/assets/eggHead.png"));
bunny.x = 500;
bunny.y = 400;
app.stage.addChild(bunny);
app.stage.addChild(richText);
app.render();
<file_sep>/src/filters/index.js
export { default as FXAAFilter } from './fxaa/FXAAFilter';
export { default as NoiseFilter } from './noise/NoiseFilter';
export { default as DisplacementFilter } from './displacement/DisplacementFilter';
export { default as BlurFilter } from './blur/BlurFilter';
export { default as BlurXFilter } from './blur/BlurXFilter';
export { default as BlurYFilter } from './blur/BlurYFilter';
export { default as ColorMatrixFilter } from './colormatrix/ColorMatrixFilter';
export { default as AlphaFilter } from './alpha/AlphaFilter';
<file_sep>/examples/source/js/sprite/animatedsprite-explosion.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
app.stop();
InkPaint.loader
.add("spritesheet", "source/assets/spritesheet/mc.json")
.load(onAssetsLoaded);
function onAssetsLoaded(loader, res) {
var textures = [];
var i;
for (i = 0; i < 26; i++) {
var texture = InkPaint.Texture.fromFrame(
"Explosion_Sequence_A " + (i + 1) + ".png"
);
textures.push(texture);
}
for (i = 0; i < 3; i++) {
var explosion = new InkPaint.AnimatedSprite(textures);
explosion.x = Math.random() * app.screen.width;
explosion.y = Math.random() * app.screen.height;
explosion.anchor.set(0.5);
explosion.rotation = Math.random() * Math.PI;
explosion.scale.set(0.75 + Math.random() * 0.5);
explosion.gotoAndPlay(Math.random() * 27);
app.stage.addChild(explosion);
}
ticker.start();
}
var ticker = new InkPaint.Ticker();
ticker.add(function() {
app.render();
});
<file_sep>/examples/source/node/textures/texture-canvas.js
var app = new InkPaint.Application();
var ctx, canvas;
var width = app.screen.width;
var height = app.screen.height;
ctx = createCanvas(400, 400);
var sprite = new InkPaint.Sprite();
sprite.anchor.set(0.5);
sprite.x = width / 2;
sprite.y = height / 2;
app.stage.addChild(sprite);
setTimeout(() => {
var texture = InkPaint.Texture.fromCanvas(canvas);
sprite.texture = texture;
sprite.width = 200;
sprite.height = 200;
}, 100);
var x = 0;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
drawBall((x += 0.5));
});
function createCanvas(width, height) {
canvas = InkPaint.createCanvas(width, height);
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
return ctx;
}
function drawBall(x) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, 200, 100, 0, Math.PI * 2, true);
ctx.fillStyle = "rgb(0, 0, 255)";
ctx.fill();
}
module.exports = app;
<file_sep>/test/index.js
"use strict";
/* eslint-disable global-require */
const InkPaint = require("../dist/inkpaint");
global.InkPaint = InkPaint;
describe("InkPaint", function() {
it("should exist as a global object", function() {
expect(InkPaint).to.be.an("object");
});
require("./core");
require("./loaders");
require("./renders");
require("./prepare");
});
<file_sep>/src/filters/alpha/AlphaFilter.js
import settings from "../../settings";
import Filter from "../../renderers/webgl/filters/Filter";
import { readFileSync } from "fs";
import { join } from "path";
export default class AlphaFilter extends Filter {
constructor(alpha = 1.0) {
super(
// vertex shader
readFileSync(join(__dirname, "../fragments/default.vert"), "utf8"),
// fragment shader
readFileSync(join(__dirname, "./alpha.frag"), "utf8")
);
this.alpha = alpha;
this.glShaderKey = "alpha";
}
/**
* Coefficient for alpha multiplication
*
* @member {number}
* @default 1
*/
get alpha() {
return this.uniforms.uAlpha;
}
set alpha(value) {
this.uniforms.uAlpha = value;
}
}
<file_sep>/examples/source/js/demos-basic/container.js
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
useGL: true
});
document.body.appendChild(app.view);
var container = new InkPaint.Container();
// Create a new texture
var base64 =
"data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAgMDAwMDBAcFBAQEBAkGBwUHCgkLCwoJCgoMDREODAwQDAoKDhQPEBESExMTCw4UFhQSFhESExL/2wBDAQMDAwQEBAgFBQgSDAoMEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhL/wgARCAACAAIDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACP/EABUBAQEAAAAAAAAAAAAAAAAAAAcJ/9oADAMBAAIQAxAAAAA6BlU//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPwB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPwB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPwB//9k=";
var texture1 = InkPaint.Texture.fromImage("source/assets/bunny.png");
var texture2 = InkPaint.Texture.fromImage("source/assets/bg_rotate2.jpg");
var texture2 = InkPaint.Texture.fromImage(base64);
var bg = new InkPaint.Sprite();
bg.anchor.set(0.5);
bg.width = 300;
bg.height = 300;
bg.x = app.screen.width / 2;
bg.y = app.screen.height / 2;
bg.texture = texture2;
app.stage.addChild(bg);
app.stage.addChild(container);
// Create a 5x5 grid of bunnies
for (var i = 0; i < 25; i++) {
var bunny = new InkPaint.Sprite(texture1);
bunny.anchor.set(0.5);
bunny.x = (i % 5) * 40;
bunny.y = Math.floor(i / 5) * 40;
bunny.rotation = Math.random() * 3.14;
bunny.speed = Math.random();
container.addChild(bunny);
}
// Move container to the center
container.x = app.screen.width / 2;
container.y = app.screen.height / 2;
// Center bunny sprite in local container coordinates
container.pivot.x = container.width / 2;
container.pivot.y = container.height / 2;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
container.rotation -= 0.01 * delta;
for (var i = 0; i < container.children.length; i++) {
var bunny = container.children[i];
bunny.rotation -= 0.05 * bunny.speed;
}
});
<file_sep>/src/sprites/canvas/CanvasTinter.js
import PsImage from "../../polyfill/Image";
import { hex2rgb, rgb2hex } from "../../utils";
import canUseNewCanvasBlendModes from "../../renderers/canvas/utils/canUseNewCanvasBlendModes";
const CanvasTinter = {
getTintedTexture: (sprite, color) => {
const texture = sprite._texture;
color = CanvasTinter.roundColor(color);
const stringColor = `#${`00000${(color | 0).toString(16)}`.substr(-6)}`;
texture.tintCache = texture.tintCache || {};
const cachedTexture = texture.tintCache[stringColor];
let canvas;
if (cachedTexture) {
if (cachedTexture.tintId === texture._updateID) {
return texture.tintCache[stringColor];
}
canvas = texture.tintCache[stringColor];
} else {
canvas = CanvasTinter.canvas;
}
CanvasTinter.tintMethod(texture, color, canvas);
canvas.tintId = texture._updateID;
if (CanvasTinter.convertTintToImage) {
const tintImage = new PsImage();
tintImage.src = canvas.toDataURL();
texture.tintCache[stringColor] = tintImage;
} else {
texture.tintCache[stringColor] = canvas;
CanvasTinter.canvas = null;
}
return canvas;
},
tintWithMultiply: (texture, color, canvas) => {
const context = canvas.getContext("2d");
const crop = texture._frame.clone();
const resolution = texture.baseTexture.resolution;
crop.x *= resolution;
crop.y *= resolution;
crop.width *= resolution;
crop.height *= resolution;
canvas.width = Math.ceil(crop.width);
canvas.height = Math.ceil(crop.height);
context.save();
context.fillStyle = `#${`00000${(color | 0).toString(16)}`.substr(-6)}`;
context.fillRect(0, 0, crop.width, crop.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height
);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height
);
context.restore();
},
tintWithOverlay(texture, color, canvas) {
const context = canvas.getContext("2d");
const crop = texture._frame.clone();
const resolution = texture.baseTexture.resolution;
crop.x *= resolution;
crop.y *= resolution;
crop.width *= resolution;
crop.height *= resolution;
canvas.width = Math.ceil(crop.width);
canvas.height = Math.ceil(crop.height);
context.save();
context.globalCompositeOperation = "copy";
context.fillStyle = `#${`00000${(color | 0).toString(16)}`.substr(-6)}`;
context.fillRect(0, 0, crop.width, crop.height);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height
);
// context.globalCompositeOperation = 'copy';
context.restore();
},
tintWithPerPixel: (texture, color, canvas) => {
const context = canvas.getContext("2d");
const crop = texture._frame.clone();
const resolution = texture.baseTexture.resolution;
crop.x *= resolution;
crop.y *= resolution;
crop.width *= resolution;
crop.height *= resolution;
canvas.width = Math.ceil(crop.width);
canvas.height = Math.ceil(crop.height);
context.save();
context.globalCompositeOperation = "copy";
context.drawImage(
texture.baseTexture.source,
crop.x,
crop.y,
crop.width,
crop.height,
0,
0,
crop.width,
crop.height
);
context.restore();
const rgbValues = hex2rgb(color);
const r = rgbValues[0];
const g = rgbValues[1];
const b = rgbValues[2];
const pixelData = context.getImageData(0, 0, crop.width, crop.height);
const pixels = pixelData.data;
for (let i = 0; i < pixels.length; i += 4) {
pixels[i + 0] *= r;
pixels[i + 1] *= g;
pixels[i + 2] *= b;
}
context.putImageData(pixelData, 0, 0);
},
roundColor: color => {
const step = CanvasTinter.cacheStepsPerColorChannel;
const rgbValues = hex2rgb(color);
rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step);
rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step);
rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step);
return rgb2hex(rgbValues);
},
cacheStepsPerColorChannel: 8,
convertTintToImage: false,
canUseMultiply: canUseNewCanvasBlendModes(),
tintMethod: 0
};
CanvasTinter.tintMethod = CanvasTinter.canUseMultiply
? CanvasTinter.tintWithMultiply
: CanvasTinter.tintWithPerPixel;
export default CanvasTinter;
<file_sep>/src/renderers/webgl/utils/RenderTarget.js
import { Rectangle, Matrix } from "../../../math";
import { SCALE_MODES } from "../../../const";
import settings from "../../../settings";
import { GLFramebuffer } from "pixi-gl-core";
export default class RenderTarget {
constructor(gl, width, height, scaleMode, resolution, root) {
this.gl = gl;
this.frameBuffer = null;
this.texture = null;
this.clearColor = [0, 0, 0, 0];
this.size = new Rectangle(0, 0, 1, 1);
this.resolution = resolution || settings.RESOLUTION;
this.projectionMatrix = new Matrix();
this.transform = null;
this.frame = null;
this.defaultFrame = new Rectangle();
this.destinationFrame = null;
this.sourceFrame = null;
this.stencilBuffer = null;
this.stencilMaskStack = [];
this.filterData = null;
this.filterPoolKey = "";
/**
* The scale mode.
*
* @member {number}
* @default InkPaint.settings.SCALE_MODE
* @see InkPaint.SCALE_MODES
*/
this.scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
/**
* Whether this object is the root element or not
*
* @member {boolean}
* @default false
*/
this.root = root || false;
if (!this.root) {
this.frameBuffer = GLFramebuffer.createRGBA(gl, 100, 100);
if (this.scaleMode === SCALE_MODES.NEAREST) {
this.frameBuffer.texture.enableNearestScaling();
} else {
this.frameBuffer.texture.enableLinearScaling();
}
this.texture = this.frameBuffer.texture;
} else {
// make it a null framebuffer..
this.frameBuffer = new GLFramebuffer(gl, 100, 100);
this.frameBuffer.framebuffer = null;
}
this.setFrame();
this.resize(width, height);
}
/**
* Clears the filter texture.
*
* @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer
*/
clear(clearColor) {
const cc = clearColor || this.clearColor;
this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a);
}
/**
* Binds the stencil buffer.
*
*/
attachStencilBuffer() {
if (!this.root) {
this.frameBuffer.enableStencil();
}
}
/**
* Sets the frame of the render target.
*
* @param {Rectangle} destinationFrame - The destination frame.
* @param {Rectangle} sourceFrame - The source frame.
*/
setFrame(destinationFrame, sourceFrame) {
this.destinationFrame =
destinationFrame || this.destinationFrame || this.defaultFrame;
this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame;
}
/**
* Binds the buffers and initialises the viewport.
*
*/
activate() {
// TODO refactor usage of frame..
const gl = this.gl;
// make sure the texture is unbound!
this.frameBuffer.bind();
this.calculateProjection(this.destinationFrame, this.sourceFrame);
if (this.transform) {
this.projectionMatrix.append(this.transform);
}
// TODO add a check as them may be the same!
if (this.destinationFrame !== this.sourceFrame) {
gl.enable(gl.SCISSOR_TEST);
gl.scissor(
this.destinationFrame.x | 0,
this.destinationFrame.y | 0,
(this.destinationFrame.width * this.resolution) | 0,
(this.destinationFrame.height * this.resolution) | 0
);
} else {
gl.disable(gl.SCISSOR_TEST);
}
// TODO - does not need to be updated all the time??
gl.viewport(
this.destinationFrame.x | 0,
this.destinationFrame.y | 0,
(this.destinationFrame.width * this.resolution) | 0,
(this.destinationFrame.height * this.resolution) | 0
);
}
calculateProjection(destinationFrame, sourceFrame) {
const pm = this.projectionMatrix;
sourceFrame = sourceFrame || destinationFrame;
pm.identity();
// TODO: make dest scale source
if (!this.root) {
pm.a = (1 / destinationFrame.width) * 2;
pm.d = (1 / destinationFrame.height) * 2;
pm.tx = -1 - sourceFrame.x * pm.a;
pm.ty = -1 - sourceFrame.y * pm.d;
} else {
pm.a = (1 / destinationFrame.width) * 2;
pm.d = (-1 / destinationFrame.height) * 2;
pm.tx = -1 - sourceFrame.x * pm.a;
pm.ty = 1 - sourceFrame.y * pm.d;
}
}
resize(width, height) {
width = width | 0;
height = height | 0;
if (this.size.width === width && this.size.height === height) {
return;
}
this.size.width = width;
this.size.height = height;
this.defaultFrame.width = width;
this.defaultFrame.height = height;
this.frameBuffer.resize(width * this.resolution, height * this.resolution);
const projectionFrame = this.frame || this.size;
this.calculateProjection(projectionFrame);
}
/**
* Destroys the render target.
*
*/
destroy() {
if (this.frameBuffer.stencil) {
this.gl.deleteRenderbuffer(this.frameBuffer.stencil);
}
this.frameBuffer.destroy();
this.frameBuffer = null;
this.texture = null;
}
}
<file_sep>/src/utils/pluginTarget.js
function pluginTarget(obj) {
obj.__plugins = {};
obj.registerPlugin = function registerPlugin(pluginName, ctor) {
obj.__plugins[pluginName] = ctor;
};
obj.prototype.initPlugins = function initPlugins() {
this.plugins = this.plugins || {};
for (const o in obj.__plugins) {
this.plugins[o] = new obj.__plugins[o](this);
}
};
obj.prototype.destroyPlugins = function destroyPlugins() {
for (const o in this.plugins) {
this.plugins[o].destroy();
this.plugins[o] = null;
}
this.plugins = null;
};
}
export default {
mixin: function mixin(obj) {
pluginTarget(obj);
}
};
<file_sep>/src/sprites/Sprite.js
import { Point, ObservablePoint, Rectangle } from "../math";
import { sign } from "../utils";
import { BLEND_MODES } from "../const";
import Texture from "../textures/Texture";
import Container from "../display/Container";
import { TextureCache } from "../utils/cache";
const tempPoint = new Point();
export default class Sprite extends Container {
constructor(texture) {
super();
this._anchor = new ObservablePoint(
this._onAnchorUpdate,
this,
texture ? texture.defaultAnchor.x : 0,
texture ? texture.defaultAnchor.y : 0
);
this._texture = null;
this._width = 0;
this._height = 0;
this._tint = null;
this._tintRGB = null;
this.tint = 0xffffff;
this.blendMode = BLEND_MODES.NORMAL;
this.shader = null;
this.cachedTint = 0xffffff;
this.texture = texture || Texture.EMPTY;
this.vertexData = new Float32Array(8);
this.vertexTrimmedData = null;
this._transformID = -1;
this._textureID = -1;
this._transformTrimmedID = -1;
this._textureTrimmedID = -1;
this.pluginName = "sprite";
this.log = false;
}
_onTextureUpdate() {
this._textureID = -1;
this._textureTrimmedID = -1;
this.cachedTint = 0xffffff;
if (this._width) {
this.scale.x =
(sign(this.scale.x) * this._width) / this._texture.orig.width;
}
if (this._height) {
this.scale.y =
(sign(this.scale.y) * this._height) / this._texture.orig.height;
}
}
_onAnchorUpdate() {
this._transformID = -1;
this._transformTrimmedID = -1;
}
calculateVertices() {
if (
this._transformID === this.transform._worldID &&
this._textureID === this._texture._updateID
) {
return;
}
this._transformID = this.transform._worldID;
this._textureID = this._texture._updateID;
const texture = this._texture;
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const vertexData = this.vertexData;
const trim = texture.trim;
const orig = texture.orig;
const anchor = this._anchor;
let w0 = 0;
let w1 = 0;
let h0 = 0;
let h1 = 0;
if (trim) {
w1 = trim.x - anchor._x * orig.width;
w0 = w1 + trim.width;
h1 = trim.y - anchor._y * orig.height;
h0 = h1 + trim.height;
} else {
w1 = -anchor._x * orig.width;
w0 = w1 + orig.width;
h1 = -anchor._y * orig.height;
h0 = h1 + orig.height;
}
// xy
vertexData[0] = a * w1 + c * h1 + tx;
vertexData[1] = d * h1 + b * w1 + ty;
// xy
vertexData[2] = a * w0 + c * h1 + tx;
vertexData[3] = d * h1 + b * w0 + ty;
// xy
vertexData[4] = a * w0 + c * h0 + tx;
vertexData[5] = d * h0 + b * w0 + ty;
// xy
vertexData[6] = a * w1 + c * h0 + tx;
vertexData[7] = d * h0 + b * w1 + ty;
}
calculateTrimmedVertices() {
if (!this.vertexTrimmedData) {
this.vertexTrimmedData = new Float32Array(8);
} else if (
this._transformTrimmedID === this.transform._worldID &&
this._textureTrimmedID === this._texture._updateID
) {
return;
}
this._transformTrimmedID = this.transform._worldID;
this._textureTrimmedID = this._texture._updateID;
// lets do some special trim code!
const texture = this._texture;
const vertexData = this.vertexTrimmedData;
const orig = texture.orig;
const anchor = this._anchor;
// lets calculate the new untrimmed bounds..
const wt = this.transform.worldTransform;
const a = wt.a;
const b = wt.b;
const c = wt.c;
const d = wt.d;
const tx = wt.tx;
const ty = wt.ty;
const w1 = -anchor._x * orig.width;
const w0 = w1 + orig.width;
const h1 = -anchor._y * orig.height;
const h0 = h1 + orig.height;
// xy
vertexData[0] = a * w1 + c * h1 + tx;
vertexData[1] = d * h1 + b * w1 + ty;
// xy
vertexData[2] = a * w0 + c * h1 + tx;
vertexData[3] = d * h1 + b * w0 + ty;
// xy
vertexData[4] = a * w0 + c * h0 + tx;
vertexData[5] = d * h0 + b * w0 + ty;
// xy
vertexData[6] = a * w1 + c * h0 + tx;
vertexData[7] = d * h0 + b * w1 + ty;
}
_renderWebGL(renderer) {
this.calculateVertices();
renderer.setObjectRenderer(renderer.plugins[this.pluginName]);
renderer.plugins[this.pluginName].render(this);
}
_renderCanvas(renderer) {
renderer.plugins[this.pluginName].render(this);
}
_calculateBounds() {
const trim = this._texture.trim;
const orig = this._texture.orig;
if (!trim || (trim.width === orig.width && trim.height === orig.height)) {
this.calculateVertices();
this._bounds.addQuad(this.vertexData);
} else {
this.calculateTrimmedVertices();
this._bounds.addQuad(this.vertexTrimmedData);
}
}
updateBaseTexture(imageUrl, useCache = false) {
if (!this.texture) return;
this.texture.updateSource(imageUrl, useCache);
}
getLocalBounds(rect) {
// we can do a fast local bounds if the sprite has no children!
if (this.children.length === 0) {
this._bounds.minX = this._texture.orig.width * -this._anchor._x;
this._bounds.minY = this._texture.orig.height * -this._anchor._y;
this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
if (!rect) {
if (!this._localBoundsRect) {
this._localBoundsRect = new Rectangle();
}
rect = this._localBoundsRect;
}
return this._bounds.getRectangle(rect);
}
return super.getLocalBounds.call(this, rect);
}
containsPoint(point) {
this.worldTransform.applyInverse(point, tempPoint);
const width = this._texture.orig.width;
const height = this._texture.orig.height;
const x1 = -width * this.anchor.x;
let y1 = 0;
if (tempPoint.x >= x1 && tempPoint.x < x1 + width) {
y1 = -height * this.anchor.y;
if (tempPoint.y >= y1 && tempPoint.y < y1 + height) {
return true;
}
}
return false;
}
destroy(options) {
if (this.destroyed) return;
super.destroy(options);
this._texture.off("update", this._onTextureUpdate, this);
this._anchor = null;
const destroyTexture =
typeof options === "boolean" ? options : options && options.texture;
if (destroyTexture) {
const destroyBaseTexture =
typeof options === "boolean" ? options : options && options.baseTexture;
this._texture.destroy(!!destroyBaseTexture);
}
this._texture = null;
this.shader = null;
}
static from(source) {
return new Sprite(Texture.from(source));
}
static fromFrame(frameId) {
const texture = TextureCache[frameId];
if (!texture) throw new Error(`The frameId "${frameId}" does not exist`);
return new Sprite(texture);
}
static fromImage(imageId, crossorigin, scaleMode) {
return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode));
}
get width() {
return Math.abs(this.scale.x) * this._texture.orig.width;
}
set width(value) {
const s = sign(this.scale.x) || 1;
this.scale.x = (s * value) / this._texture.orig.width;
this._width = value;
}
get height() {
return Math.abs(this.scale.y) * this._texture.orig.height;
}
set height(value) {
const s = sign(this.scale.y) || 1;
this.scale.y = (s * value) / this._texture.orig.height;
this._height = value;
}
get anchor() {
return this._anchor;
}
set anchor(value) {
this._anchor.copy(value);
}
get tint() {
return this._tint;
}
set tint(value) {
this._tint = value;
this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
}
get texture() {
return this._texture;
}
set texture(value) {
if (this._texture === value) return;
this._texture = value || Texture.EMPTY;
this.cachedTint = 0xffffff;
this._textureID = -1;
this._textureTrimmedID = -1;
if (!value) return;
if (value.baseTexture.hasLoaded) {
this._onTextureUpdate();
} else {
value.once("update", this._onTextureUpdate, this);
}
}
}
<file_sep>/test/core/filters.js
'use strict';
describe('InkPaint.filters', function ()
{
it('should correctly form uniformData', function ()
{
const sprite = new InkPaint.Sprite(InkPaint.Texture.EMPTY);
const displ = new InkPaint.filters.DisplacementFilter(sprite);
expect(!!displ.uniformData.scale).to.be.true;
expect(!!displ.uniformData.filterMatrix).to.be.true;
expect(!!displ.uniformData.mapSampler).to.be.true;
// it does have filterClamp, but it is handled by FilterManager
expect(!!displ.uniformData.filterClamp).to.be.false;
const fxaa = new InkPaint.filters.FXAAFilter();
// it does have filterArea, but it is handled by FilterManager
expect(!!fxaa.uniformData.filterArea).to.be.false;
});
});
<file_sep>/examples/source/node/graphics/simple.js
var app = new InkPaint.Application(800, 600, { antialias: true });
document.body.appendChild(app.view);
module.exports = app;
var graphics = new InkPaint.Graphics();
// Rectangle
graphics.beginFill(0xDE3249);
graphics.drawRect(50, 50, 100, 100);
graphics.endFill();
// Rectangle + line style 1
graphics.lineStyle(2, 0xFEEB77, 1);
graphics.beginFill(0x650A5A);
graphics.drawRect(200, 50, 100, 100);
graphics.endFill();
// Rectangle + line style 2
graphics.lineStyle(10, 0xFFBD01, 1);
graphics.beginFill(0xC34288);
graphics.drawRect(350, 50, 100, 100);
graphics.endFill();
// Rectangle 2
graphics.lineStyle(2, 0xFFFFFF, 1);
graphics.beginFill(0xAA4F08);
graphics.drawRect(530, 50, 140, 100);
graphics.endFill();
// Circle
graphics.lineStyle(0); // draw a circle, set the lineStyle to zero so the circle doesn't have an outline
graphics.beginFill(0xDE3249, 1);
graphics.drawCircle(100, 250, 50);
graphics.endFill();
// Circle + line style 1
graphics.lineStyle(2, 0xFEEB77, 1);
graphics.beginFill(0x650A5A, 1);
graphics.drawCircle(250, 250, 50);
graphics.endFill();
// Circle + line style 2
graphics.lineStyle(10, 0xFFBD01, 1);
graphics.beginFill(0xC34288, 1);
graphics.drawCircle(400, 250, 50);
graphics.endFill();
// Ellipse + line style 2
graphics.lineStyle(2, 0xFFFFFF, 1);
graphics.beginFill(0xAA4F08, 1);
graphics.drawEllipse(600, 250, 80, 50);
graphics.endFill();
// draw a shape
graphics.beginFill(0xFF3300);
graphics.lineStyle(4, 0xffd900, 1);
graphics.moveTo(50, 350);
graphics.lineTo(250, 350);
graphics.lineTo(100, 400);
graphics.lineTo(50, 350);
graphics.endFill();
// draw a rounded rectangle
graphics.lineStyle(2, 0xFF00FF, 1);
graphics.beginFill(0x650A5A, 0.25);
graphics.drawRoundedRect(50, 440, 100, 100, 16);
graphics.endFill();
// draw star
graphics.lineStyle(2, 0xFFFFFF);
graphics.beginFill(0x35CC5A, 1);
graphics.drawStar(360, 370, 5, 50);
graphics.endFill();
// draw star 2
graphics.lineStyle(2, 0xFFFFFF);
graphics.beginFill(0xFFCC5A, 1);
graphics.drawStar(280, 510, 7, 50);
graphics.endFill();
// draw star 3
graphics.lineStyle(4, 0xFFFFFF);
graphics.beginFill(0x55335A, 1);
graphics.drawStar(470, 450, 4, 50);
graphics.endFill();
// draw polygon
var path = [600, 370, 700, 460, 780, 420, 730, 570, 590, 520];
graphics.lineStyle(0);
graphics.beginFill(0x3500FA, 1);
graphics.drawPolygon(path);
graphics.endFill();
app.stage.addChild(graphics);
app.render();
<file_sep>/examples/source/js/sprite/animatedsprite-animationspeed.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
app.stop();
InkPaint.loader
.add("spritesheet", "source/assets/spritesheet/0123456789.json")
.load(onAssetsLoaded);
function onAssetsLoaded(loader, resources) {
var textures = [];
var i;
for (i = 0; i < 10; i++) {
var framekey = "0123456789 " + i + ".ase";
var texture = InkPaint.Texture.fromFrame(framekey);
var time = resources.spritesheet.data.frames[framekey].duration;
textures.push({ texture: texture, time: time });
}
var scaling = 4;
// create a slow AnimatedSprite
var slow = new InkPaint.AnimatedSprite(textures);
slow.anchor.set(0.5);
slow.scale.set(scaling);
slow.animationSpeed = 0.5;
slow.x = (app.screen.width - slow.width) / 2;
slow.y = app.screen.height / 2;
slow.play();
app.stage.addChild(slow);
// create a fast AnimatedSprite
var fast = new InkPaint.AnimatedSprite(textures);
fast.anchor.set(0.5);
fast.scale.set(scaling);
fast.x = (app.screen.width + fast.width) / 2;
fast.y = app.screen.height / 2;
fast.play();
app.stage.addChild(fast);
// start animating
ticker.start();
}
var ticker = new InkPaint.Ticker();
ticker.add(function() {
app.render();
});
<file_sep>/src/graphics/GraphicsData.js
export default class GraphicsData {
constructor(
lineWidth,
lineColor,
lineAlpha,
fillColor,
fillAlpha,
fill,
nativeLines,
shape,
lineAlignment
) {
this.lineWidth = lineWidth;
this.lineAlignment = lineAlignment;
this.nativeLines = nativeLines;
this.lineColor = lineColor;
this.lineAlpha = lineAlpha;
this._lineTint = lineColor;
/**
* the color of the fill
* @member {number}
*/
this.fillColor = fillColor;
/**
* the alpha of the fill
* @member {number}
*/
this.fillAlpha = fillAlpha;
/**
* cached tint of the fill
* @member {number}
* @private
*/
this._fillTint = fillColor;
/**
* whether or not the shape is filled with a colour
* @member {boolean}
*/
this.fill = fill;
this.holes = [];
/**
* The shape object to draw.
* @member {InkPaint.Circle|InkPaint.Ellipse|InkPaint.Polygon|InkPaint.Rectangle|InkPaint.RoundedRectangle}
*/
this.shape = shape;
/**
* The type of the shape, see the Const.Shapes file for all the existing types,
* @member {number}
*/
this.type = shape.type;
}
/**
* Creates a new GraphicsData object with the same values as this one.
*
* @return {InkPaint.GraphicsData} Cloned GraphicsData object
*/
clone() {
return new GraphicsData(
this.lineWidth,
this.lineColor,
this.lineAlpha,
this.fillColor,
this.fillAlpha,
this.fill,
this.nativeLines,
this.shape,
this.lineAlignment
);
}
/**
* Adds a hole to the shape.
*
* @param {InkPaint.Rectangle|InkPaint.Circle} shape - The shape of the hole.
*/
addHole(shape) {
this.holes.push(shape);
}
/**
* Destroys the Graphics data.
*/
destroy() {
this.shape = null;
this.holes = null;
}
}
<file_sep>/examples/source/node/demos-basic/network.js
InkPaint.loader.add(
"bunny",
"https://www.pixijs.com/wp/wp-content/uploads/pixijs-v5-logo-1.png"
);
InkPaint.loader.add(
"bg",
"https://www.pixijs.com/wp/wp-content/uploads/feature-multiplatform.png"
);
InkPaint.loader.add(
"ws",
"http://qzonestyle.gtimg.cn/qz-proj/weishi-pc/img/index/logo-l@2x.png"
);
InkPaint.loader.add("txws", paths("source/assets/txlogo.png"));
InkPaint.loader.add("bunny2", paths("source/assets/bunny.png"));
InkPaint.loader.load(setup);
InkPaint.loader.on("error", error => {
console.log(error);
});
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
resolution: 2
});
function setup(l, resources) {
document.body.appendChild(app.view);
var bunny = new InkPaint.Sprite(resources.bunny.texture);
var bg = new InkPaint.Sprite(resources.bg.texture);
var ws = new InkPaint.Sprite(resources.ws.texture);
var txws = new InkPaint.Sprite(resources.txws.texture);
bunny.anchor.set(0.5);
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
bg.anchor.set(0.5);
bg.scale.set(10);
bg.x = app.screen.width / 2;
bg.y = app.screen.height / 2;
ws.x = 100;
ws.y = 100;
txws.x = 200;
txws.y = 100;
app.stage.addChild(bg);
app.stage.addChild(bunny);
app.stage.addChild(ws);
app.stage.addChild(txws);
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
// just for fun, let's rotate mr rabbit a little
bunny.rotation += 0.1;
bg.rotation -= 0.01;
});
}
module.exports = app;
<file_sep>/examples/source/js/demos-basic/resize.js
InkPaint.loader.add("t1", "source/assets/bg_grass.jpg");
InkPaint.loader.add("bg_rotate", "source/assets/bg_rotate2.jpg");
InkPaint.loader.add("bunny", "source/assets/bunny.png");
InkPaint.loader.load(setup);
var app, bg_rotate;
function setup(l, resources) {
app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
document.body.noclick = true;
var bunny = new InkPaint.Sprite(resources.bunny.texture);
var bg_rotate = new InkPaint.Sprite(resources.bg_rotate.texture);
bunny.anchor.set(0.5);
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
bg_rotate.anchor.set(0.5);
bg_rotate.x = app.screen.width / 2;
bg_rotate.y = app.screen.height / 2;
app.stage.addChild(bg_rotate);
app.stage.addChild(bunny);
app.view.addEventListener("mousedown", mousedown);
new TWEEN.Tween(bunny).to({ x: 10, y: 10 }, 10000).start();
new TWEEN.Tween(bg_rotate).to({ rotation: 3.14 * 3 }, 10000).start();
animate();
}
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
app.render();
}
function mousedown() {
var width = (Math.random() * 800) >> 0;
var height = (Math.random() * 600) >> 0;
app.renderer.resize(width, height);
app.renderer.view.style.width = width + "px";
app.renderer.view.style.height = height + "px";
console.log(width, height);
}
<file_sep>/src/display/DisplayObject.js
import EventEmitter from "eventemitter3";
import { TRANSFORM_MODE } from "../const";
import Bounds from "./Bounds";
import settings from "../settings";
import Transform from "./Transform";
import { uuidvx } from "../utils";
import { Rectangle, Point } from "../math";
import TransformStatic from "./TransformStatic";
import FXAAFilter from "../filters/fxaa/FXAAFilter";
import BlurFilter from "../filters/blur/BlurFilter";
export default class DisplayObject extends EventEmitter {
constructor() {
super();
const TransformClass =
settings.TRANSFORM_MODE === TRANSFORM_MODE.STATIC
? TransformStatic
: Transform;
this.tempDisplayObjectParent = null;
this.transform = new TransformClass();
this.alpha = 1;
this.visible = true;
this.renderable = true;
this.parent = null;
this.worldAlpha = 1;
this.filterArea = null;
this.initScale = new Point(1, 1);
this.filters = null;
this._enabledFilters = null;
this._bounds = new Bounds();
this._boundsID = 0;
this._lastBoundsID = -1;
this._boundsRect = null;
this._localBoundsRect = null;
this._mask = null;
this._blur = 0;
this._fxaa = false;
this.maskEnabled = true;
this.destroyed = false;
this.id = uuidvx();
}
get _tempDisplayObjectParent() {
if (this.tempDisplayObjectParent === null) {
this.tempDisplayObjectParent = new DisplayObject();
}
return this.tempDisplayObjectParent;
}
updateTransform() {
this.transform.updateTransform(this.parent.transform);
this.worldAlpha = this.alpha * this.parent.worldAlpha;
this._bounds.updateID++;
}
_recursivePostUpdateTransform() {
if (this.parent) {
this.parent._recursivePostUpdateTransform();
this.transform.updateTransform(this.parent.transform);
} else {
this.transform.updateTransform(this._tempDisplayObjectParent.transform);
}
}
getBounds(skipUpdate, rect) {
if (!skipUpdate) {
if (!this.parent) {
this.parent = this._tempDisplayObjectParent;
this.updateTransform();
this.parent = null;
} else {
this._recursivePostUpdateTransform();
this.updateTransform();
}
}
if (this._boundsID !== this._lastBoundsID && this.maskEnabled) {
this.calculateBounds();
}
if (!rect) {
if (!this._boundsRect) {
this._boundsRect = new Rectangle();
}
rect = this._boundsRect;
}
return this._bounds.getRectangle(rect);
}
getLocalBounds(rect) {
const transformRef = this.transform;
const parentRef = this.parent;
this.parent = null;
this.transform = this._tempDisplayObjectParent.transform;
if (!rect) {
if (!this._localBoundsRect) {
this._localBoundsRect = new Rectangle();
}
rect = this._localBoundsRect;
}
const bounds = this.getBounds(false, rect);
this.parent = parentRef;
this.transform = transformRef;
return bounds;
}
toGlobal(position, point, skipUpdate = false) {
if (!skipUpdate) {
this._recursivePostUpdateTransform();
if (!this.parent) {
this.parent = this._tempDisplayObjectParent;
this.displayObjectUpdateTransform();
this.parent = null;
} else {
this.displayObjectUpdateTransform();
}
}
return this.worldTransform.apply(position, point);
}
getGlobalPosition(point, skipUpdate = false) {
if (this.parent) {
this.parent.toGlobal(this.position, point, skipUpdate);
} else {
point.x = this.position.x;
point.y = this.position.y;
}
return point;
}
toLocal(position, from, point, skipUpdate) {
if (from) {
position = from.toGlobal(position, point, skipUpdate);
}
if (!skipUpdate) {
this._recursivePostUpdateTransform();
if (!this.parent) {
this.parent = this._tempDisplayObjectParent;
this.displayObjectUpdateTransform();
this.parent = null;
} else {
this.displayObjectUpdateTransform();
}
}
return this.worldTransform.applyInverse(position, point);
}
copyFromProxy(proxyObj) {
const copyFunc = key => {
if (proxyObj[key] !== null) {
this[key] = proxyObj[key];
}
};
copyFunc("x");
copyFunc("y");
copyFunc("text");
copyFunc("style");
copyFunc("width");
copyFunc("height");
copyFunc("alpha");
copyFunc("rotation");
copyFunc("blendMode");
this.scale.copy(proxyObj.scale);
this.anchor.copy(proxyObj.anchor);
}
substitute(proxyObj) {
this.copyFromProxy(proxyObj);
const { parent } = proxyObj;
if (parent) {
const index = parent.getChildIndex(proxyObj);
parent.removeChild(proxyObj);
parent.addChildAt(this, index);
}
proxyObj.destroy();
proxyObj = null;
}
renderWebGL(renderer) {
// OVERWRITE;
}
renderCanvas(renderer) {
// OVERWRITE;
}
setParent(container) {
if (!container || !container.addChild) {
throw new Error("setParent: Argument must be a Container");
}
container.addChild(this);
return container;
}
setTransform(
x = 0,
y = 0,
scaleX = 1,
scaleY = 1,
rotation = 0,
skewX = 0,
skewY = 0,
pivotX = 0,
pivotY = 0
) {
this.position.x = x;
this.position.y = y;
this.scale.x = !scaleX ? 1 : scaleX;
this.scale.y = !scaleY ? 1 : scaleY;
this.rotation = rotation;
this.skew.x = skewX;
this.skew.y = skewY;
this.pivot.x = pivotX;
this.pivot.y = pivotY;
return this;
}
setScaleToInit() {
this.initScale.copy(this.scale);
}
copyScaleAndInit(scale) {
this.scale.copy(scale);
this.initScale.copy(scale);
}
attr(attrs) {
const scaleInitX = this.initScale.x;
const scaleInitY = this.initScale.y;
for (let key in attrs) {
const val = attrs[key];
switch (key) {
case "scale":
this.scale.x = val * scaleInitX;
this.scale.y = val * scaleInitY;
break;
case "skew":
this.skew.x = val;
this.skew.y = val;
break;
case "rotate":
this.rotation = val;
break;
default:
this[key] = val;
}
}
}
getAttr(key) {
let attr;
switch (key) {
case "scale":
attr = this.scale.x;
break;
case "rotate":
attr = this.rotation;
break;
default:
attr = this[key];
}
return attr;
}
get x() {
return this.position.x;
}
set x(value) {
this.transform.position.x = value;
}
get y() {
return this.position.y;
}
set y(value) {
this.transform.position.y = value;
}
get worldTransform() {
return this.transform.worldTransform;
}
get localTransform() {
return this.transform.localTransform;
}
get position() {
return this.transform.position;
}
set position(value) {
this.transform.position.copy(value);
}
get scale() {
return this.transform.scale;
}
set scale(value) {
this.transform.scale.copy(value);
}
get pivot() {
return this.transform.pivot;
}
set pivot(value) {
this.transform.pivot.copy(value);
}
get skew() {
return this.transform.skew;
}
set skew(value) {
this.transform.skew.copy(value);
}
get rotation() {
return this.transform.rotation;
}
set rotation(value) {
this.transform.rotation = value;
}
get worldVisible() {
let item = this;
do {
if (!item.visible) {
return false;
}
item = item.parent;
} while (item);
return true;
}
get mask() {
return this._mask;
}
set mask(value) {
if (this._mask) {
this._mask.renderable = true;
this._mask.isMask = false;
}
this._mask = value;
if (this._mask) {
this._mask.renderable = false;
this._mask.isMask = true;
}
}
hasFilters() {
if (this.filters && this.filters.length) {
return true;
} else {
return false;
}
}
set blur(blur = 0) {
this._blur = blur;
if (blur <= 0) {
this.filters = null;
return;
}
if (!this.filters) {
this.filters = [new BlurFilter()];
}
this.filters[0].blur = blur;
}
set fxaa(fxaa) {
if (fxaa === false) {
this.filters = null;
return;
}
if (!this.filters) {
this.filters = [new FXAAFilter()];
}
}
get fxaa() {
return this._fxaa;
}
get blur() {
return this._blur;
}
destroy() {
if (this.destroyed) return;
this.removeAllListeners();
if (this.parent) {
this.parent.removeChild(this);
}
this.blur = 0;
this.fxaa = false;
this.filters = null;
this.transform = null;
this.initScale = null;
this.parent = null;
this._bounds = null;
this._currentBounds = null;
this._mask = null;
this.filterArea = null;
this.interactive = false;
this.interactiveChildren = false;
this.destroyed = true;
}
}
// performance increase to avoid using call.. (10x faster)
DisplayObject.prototype.displayObjectUpdateTransform =
DisplayObject.prototype.updateTransform;
<file_sep>/src/filters/noise/NoiseFilter.js
import settings from "../../settings";
import Filter from "../../renderers/webgl/filters/Filter";
import { readFileSync } from "fs";
import { join } from "path";
export default class NoiseFilter extends Filter {
constructor(noise = 0.5, seed = Math.random()) {
super(
// vertex shader
readFileSync(join(__dirname, "../fragments/default.vert"), "utf8"),
// fragment shader
readFileSync(join(__dirname, "./noise.frag"), "utf8")
);
this.noise = noise;
this.seed = seed;
}
get noise() {
return this.uniforms.uNoise;
}
set noise(value) {
this.uniforms.uNoise = value;
}
get seed() {
return this.uniforms.uSeed;
}
set seed(value) {
this.uniforms.uSeed = value;
}
}
<file_sep>/examples/source/js/textures/render-texture-advanced.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
// create two render textures... these dynamic textures will be used to draw the scene into itself
var renderTexture = InkPaint.RenderTexture.create(
app.screen.width,
app.screen.height
);
var renderTexture2 = InkPaint.RenderTexture.create(
app.screen.width,
app.screen.height
);
var currentTexture = renderTexture;
// create a new sprite that uses the render texture we created above
var outputSprite = new InkPaint.Sprite(currentTexture);
// align the sprite
outputSprite.x = 400;
outputSprite.y = 300;
outputSprite.anchor.set(0.5);
// add to stage
app.stage.addChild(outputSprite);
var stuffContainer = new InkPaint.Container();
stuffContainer.x = 400;
stuffContainer.y = 300;
app.stage.addChild(stuffContainer);
// create an array of image ids..
var fruits = [
"source/assets/rt_object_01.png",
"source/assets/rt_object_02.png",
"source/assets/rt_object_03.png",
"source/assets/rt_object_04.png",
"source/assets/rt_object_05.png",
"source/assets/rt_object_06.png",
"source/assets/rt_object_07.png",
"source/assets/rt_object_08.png"
];
// create an array of items
var items = [];
// now create some items and randomly position them in the stuff container
for (var i = 0; i < 20; i++) {
var item = InkPaint.Sprite.fromImage(fruits[i % fruits.length]);
item.x = Math.random() * 400 - 200;
item.y = Math.random() * 400 - 200;
item.anchor.set(0.5);
stuffContainer.addChild(item);
items.push(item);
}
// used for spinning!
var count = 0;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
for (var i = 0; i < items.length; i++) {
// rotate each item
var item = items[i];
item.rotation += 0.1;
}
count += 0.01;
var text = new InkPaint.Text("你好周杰伦! 哈哈");
text.updateStyle({
fill: "#ffffff",
backgroundColor: "#00eeee",
padding: 10
});
text.x = 100;
text.y = 100;
app.stage.addChild(text);
// swap the buffers ...
var temp = renderTexture;
renderTexture = renderTexture2;
renderTexture2 = temp;
// set the new texture
outputSprite.texture = renderTexture;
// twist this up!
stuffContainer.rotation -= 0.01;
outputSprite.scale.set(1 + Math.sin(count) * 0.2);
// render the stage to the texture
// the 'true' clears the texture before the content is rendered
app.renderer.render(app.stage, renderTexture2, false);
});
<file_sep>/examples/source/js/filters/fxaa.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
var bg = InkPaint.Sprite.fromImage(
"source/assets/pixi-filters/bg_depth_blur.jpg"
);
bg.width = app.screen.width;
bg.height = app.screen.height;
app.stage.addChild(bg);
var littleDudes = InkPaint.Sprite.fromImage(
"source/assets/pixi-filters/depth_blur_dudes.jpg"
);
littleDudes.x = app.screen.width / 2;
littleDudes.y = 300;
app.stage.addChild(littleDudes);
var littleRobot = InkPaint.Sprite.fromImage(
"source/assets/pixi-filters/depth_blur_moby.jpg"
);
littleRobot.x = app.screen.width / 2;
littleRobot.y = 250;
app.stage.addChild(littleRobot);
InkPaint.settings.PRECISION_FRAGMENT = InkPaint.PRECISION.HIGH;
var blurFilter1 = new InkPaint.filters.FXAAFilter();
var blurFilter2 = new InkPaint.filters.FXAAFilter();
littleDudes.filters = [blurFilter1];
littleRobot.filters = [blurFilter2];
var count = 0;
littleDudes.anchor.x = 0.5;
littleDudes.anchor.y = 0.5;
littleRobot.anchor.x = 0.5;
littleRobot.anchor.y = 0.5;
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
littleDudes.rotation += 0.005;
littleRobot.rotation -= 0.01;
});
<file_sep>/src/text/Text.js
import Sprite from "../sprites/Sprite";
import Texture from "../textures/Texture";
import { sign } from "../utils";
import { Rectangle } from "../math";
import { TEXT_GRADIENT } from "../const";
import settings from "../settings";
import TextStyle from "./TextStyle";
import TextMetrics from "./TextMetrics";
import trimCanvas from "../utils/trimCanvas";
import Doc from "../polyfill/Doc";
import { addToTextureCache } from "../utils/cache";
const defaultDestroyOptions = {
texture: true,
children: false,
baseTexture: true
};
export default class Text extends Sprite {
constructor(text, style, canvas) {
canvas = canvas || Doc.createElement("canvas");
canvas.width = 3;
canvas.height = 3;
const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, "text");
texture.orig = new Rectangle();
texture.trim = new Rectangle();
super(texture);
addToTextureCache(
this._texture,
this._texture.baseTexture.textureCacheIds[0]
);
this.canvas = canvas;
this.context = this.canvas.getContext("2d");
this.resolution = settings.RESOLUTION;
this._text = null;
this._style = null;
this._styleListener = null;
this._font = "";
this.text = text;
this.style = style;
this.localStyleID = -1;
}
updateText(respectDirty) {
const style = this._style;
if (this.localStyleID !== style.styleID) {
this.dirty = true;
this.localStyleID = style.styleID;
}
if (!this.dirty && respectDirty) {
return;
}
this._font = this._style.toFontString();
const context = this.context;
const measured = TextMetrics.measureText(
this._text,
this._style,
this._style.wordWrap,
this.canvas
);
const width = measured.width;
const height = measured.height;
const lines = measured.lines;
const lineHeight = measured.lineHeight;
const lineWidths = measured.lineWidths;
const maxLineWidth = measured.maxLineWidth;
const fontProperties = measured.fontProperties;
this.canvas.width = Math.ceil(
(Math.max(1, width) + style.padding * 2) * this.resolution
);
this.canvas.height = Math.ceil(
(Math.max(1, height) + style.padding * 2) * this.resolution
);
context.scale(this.resolution, this.resolution);
context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawBackground(style);
context.font = this._font;
context.strokeStyle = style.stroke;
context.lineWidth = style.strokeThickness;
context.textBaseline = style.textBaseline;
context.lineJoin = style.lineJoin;
context.miterLimit = style.miterLimit;
let linePositionX;
let linePositionY;
if (style.dropShadow) {
context.fillStyle = style.dropShadowColor;
context.globalAlpha = style.dropShadowAlpha;
context.shadowBlur = style.dropShadowBlur;
if (style.dropShadowBlur > 0) {
context.shadowColor = style.dropShadowColor;
}
const xShadowOffset =
Math.cos(style.dropShadowAngle) * style.dropShadowDistance;
const yShadowOffset =
Math.sin(style.dropShadowAngle) * style.dropShadowDistance;
for (let i = 0; i < lines.length; i++) {
linePositionX = style.strokeThickness / 2;
linePositionY =
style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent;
if (style.align === "right") {
linePositionX += maxLineWidth - lineWidths[i];
} else if (style.align === "center") {
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.fill) {
this.drawLetterSpacing(
lines[i],
linePositionX + xShadowOffset + style.padding,
linePositionY + yShadowOffset + style.padding
);
if (style.stroke && style.strokeThickness) {
context.strokeStyle = style.dropShadowColor;
this.drawLetterSpacing(
lines[i],
linePositionX + xShadowOffset + style.padding,
linePositionY + yShadowOffset + style.padding,
true
);
context.strokeStyle = style.stroke;
}
}
}
}
context.shadowBlur = 0;
context.globalAlpha = 1;
context.fillStyle = this._generateFillStyle(style, lines);
// draw lines line by line
for (let i = 0; i < lines.length; i++) {
linePositionX = style.strokeThickness / 2;
linePositionY =
style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent;
if (style.align === "right") {
linePositionX += maxLineWidth - lineWidths[i];
} else if (style.align === "center") {
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.stroke && style.strokeThickness) {
this.drawLetterSpacing(
lines[i],
linePositionX + style.padding,
linePositionY + style.padding,
true
);
}
if (style.fill) {
this.drawLetterSpacing(
lines[i],
linePositionX + style.padding,
linePositionY + style.padding
);
}
}
this.updateTexture();
}
drawBackground(style) {
const background = style.background || style.backgroundColor;
if (!background) return;
const { context, canvas, text } = this;
const ftext = String(text).trim();
if (ftext) {
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
} else {
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
drawLetterSpacing(text, x, y, isStroke = false) {
const style = this._style;
// letterSpacing of 0 means normal
const letterSpacing = style.letterSpacing;
if (letterSpacing === 0) {
if (isStroke) {
this.context.strokeText(text, x, y);
} else {
this.context.fillText(text, x, y);
}
return;
}
const characters = String.prototype.split.call(text, "");
let currentPosition = x;
let index = 0;
let current = "";
let previousWidth = this.context.measureText(text).width;
let currentWidth = 0;
while (index < text.length) {
current = characters[index++];
if (isStroke) {
this.context.strokeText(current, currentPosition, y);
} else {
this.context.fillText(current, currentPosition, y);
}
currentWidth = this.context.measureText(text.substring(index)).width;
currentPosition += previousWidth - currentWidth + letterSpacing;
previousWidth = currentWidth;
}
}
updateStyle(style) {
for (let key in style) {
let newKey = this.camelCase(key);
if (newKey === "color") newKey = "fill";
this.style[newKey] = style[key];
}
}
camelCase(name) {
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
const MOZ_HACK_REGEXP = /^moz([A-Z])/;
return name
.replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
})
.replace(MOZ_HACK_REGEXP, "Moz$1");
}
updateTexture() {
const canvas = this.canvas;
if (this._style.trim) {
const trimmed = trimCanvas(canvas);
if (trimmed.data) {
canvas.width = trimmed.width;
canvas.height = trimmed.height;
this.context.putImageData(trimmed.data, 0, 0);
}
}
const texture = this._texture;
const style = this._style;
const padding = style.trim ? 0 : style.padding;
const baseTexture = texture.baseTexture;
baseTexture.hasLoaded = true;
baseTexture.resolution = this.resolution;
baseTexture.realWidth = canvas.width;
baseTexture.realHeight = canvas.height;
baseTexture.width = canvas.width / this.resolution;
baseTexture.height = canvas.height / this.resolution;
texture.trim.width = texture._frame.width = canvas.width / this.resolution;
texture.trim.height = texture._frame.height =
canvas.height / this.resolution;
texture.trim.x = -padding;
texture.trim.y = -padding;
texture.orig.width = texture._frame.width - padding * 2;
texture.orig.height = texture._frame.height - padding * 2;
// call sprite onTextureUpdate to update scale if _width or _height were set
this._onTextureUpdate();
baseTexture.emit("update", baseTexture);
this.dirty = false;
}
renderWebGL(renderer) {
if (this.resolution !== renderer.resolution) {
this.resolution = renderer.resolution;
this.dirty = true;
}
this.updateText(true);
super.renderWebGL(renderer);
}
_renderCanvas(renderer) {
if (this.resolution !== renderer.resolution) {
this.resolution = renderer.resolution;
this.dirty = true;
}
this.updateText(true);
super._renderCanvas(renderer);
}
getLocalBounds(rect) {
this.updateText(true);
return super.getLocalBounds.call(this, rect);
}
_calculateBounds() {
this.updateText(true);
this.calculateVertices();
// if we have already done this on THIS frame.
this._bounds.addQuad(this.vertexData);
}
_onStyleChange() {
this.dirty = true;
}
_generateFillStyle(style, lines) {
if (!Array.isArray(style.fill)) {
return style.fill;
}
let gradient;
let totalIterations;
let currentIteration;
let stop;
const width = this.canvas.width / this.resolution;
const height = this.canvas.height / this.resolution;
const fill = style.fill.slice();
const fillGradientStops = style.fillGradientStops.slice();
if (!fillGradientStops.length) {
const lengthPlus1 = fill.length + 1;
for (let i = 1; i < lengthPlus1; ++i) {
fillGradientStops.push(i / lengthPlus1);
}
}
fill.unshift(style.fill[0]);
fillGradientStops.unshift(0);
fill.push(style.fill[style.fill.length - 1]);
fillGradientStops.push(1);
if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) {
gradient = this.context.createLinearGradient(
width / 2,
0,
width / 2,
height
);
totalIterations = (fill.length + 1) * lines.length;
currentIteration = 0;
for (let i = 0; i < lines.length; i++) {
currentIteration += 1;
for (let j = 0; j < fill.length; j++) {
if (typeof fillGradientStops[j] === "number") {
stop = fillGradientStops[j] / lines.length + i / lines.length;
} else {
stop = currentIteration / totalIterations;
}
gradient.addColorStop(stop, fill[j]);
currentIteration++;
}
}
} else {
gradient = this.context.createLinearGradient(
0,
height / 2,
width,
height / 2
);
totalIterations = fill.length + 1;
currentIteration = 1;
for (let i = 0; i < fill.length; i++) {
if (typeof fillGradientStops[i] === "number") {
stop = fillGradientStops[i];
} else {
stop = currentIteration / totalIterations;
}
gradient.addColorStop(stop, fill[i]);
currentIteration++;
}
}
return gradient;
}
destroy(options) {
if (this.destroyed) return;
if (typeof options === "boolean") {
options = { children: options };
}
options = Object.assign({}, defaultDestroyOptions, options);
super.destroy(options);
this.context = null;
this.canvas = null;
this._style = null;
}
get width() {
this.updateText(true);
return Math.abs(this.scale.x) * this._texture.orig.width;
}
set width(value) {
this.updateText(true);
const s = sign(this.scale.x) || 1;
this.scale.x = (s * value) / this._texture.orig.width;
this._width = value;
}
get height() {
this.updateText(true);
return Math.abs(this.scale.y) * this._texture.orig.height;
}
set height(value) {
this.updateText(true);
const s = sign(this.scale.y) || 1;
this.scale.y = (s * value) / this._texture.orig.height;
this._height = value;
}
get font() {
return this._font;
}
get style() {
return this._style;
}
set style(style) {
style = style || {};
if (style instanceof TextStyle) {
this._style = style;
} else {
this._style = new TextStyle(style);
}
this.localStyleID = -1;
this.dirty = true;
}
get text() {
return this._text;
}
set text(text) {
text = String(
text === "" || text === null || text === undefined ? " " : text
);
if (this._text === text) return;
this._text = text;
this.dirty = true;
}
}
<file_sep>/src/ticker/index.js
import Ticker from "./Ticker";
const shared = new Ticker();
shared.autoStart = true;
shared.destroy = () => {};
export { shared, Ticker };
<file_sep>/src/resource/Loader.js
import Signal from "mini-signals";
import parseUri from "parse-uri";
import * as async from "./async";
import Resource from "./Resource";
const MAX_PROGRESS = 100;
const rgxExtractUrlHash = /(#[\w-]+)?$/;
export default class ResourceLoader {
constructor(baseUrl = "", concurrency = 10) {
this.baseUrl = baseUrl;
this.progress = 0;
this.loading = false;
this.defaultQueryString = "";
this._beforeMiddleware = [];
this._afterMiddleware = [];
this._resourcesParsing = [];
this._boundLoadResource = (r, d) => this._loadResource(r, d);
this._queue = async.queue(this._boundLoadResource, concurrency);
this._queue.pause();
this.resources = {};
this.onProgress = new Signal();
this.onError = new Signal();
this.onLoad = new Signal();
this.onStart = new Signal();
this.onComplete = new Signal();
for (let i = 0; i < ResourceLoader._defaultBeforeMiddleware.length; ++i) {
this.pre(ResourceLoader._defaultBeforeMiddleware[i]);
}
for (let i = 0; i < ResourceLoader._defaultAfterMiddleware.length; ++i) {
this.use(ResourceLoader._defaultAfterMiddleware[i]);
}
}
add(name, url, options, cb) {
if (Array.isArray(name)) {
for (let i = 0; i < name.length; ++i) {
this.add(name[i]);
}
return this;
}
// if an object is passed instead of params
if (typeof name === "object") {
cb = url || name.callback || name.onComplete;
options = name;
url = name.url;
name = name.name || name.key || name.url;
}
if (this.resources[name]) {
return;
}
// case where no name is passed shift all args over by one.
if (typeof url !== "string") {
cb = options;
options = url;
url = name;
}
// now that we shifted make sure we have a proper url.
if (typeof url !== "string") {
throw new Error("No url passed to add resource to loader.");
}
// options are optional so people might pass a function and no options
if (typeof options === "function") {
cb = options;
options = null;
}
// if loading already you can only add resources that have a parent.
if (this.loading && (!options || !options.parentResource)) {
throw new Error("Cannot add resources the loader is running.");
}
url = this._prepareUrl(url);
this.resources[name] = new Resource(name, url, options);
if (typeof cb === "function") {
this.resources[name].onAfterMiddleware.once(cb);
}
// if actively loading, make sure to adjust progress chunks for that parent and its children
if (this.loading) {
const parent = options.parentResource;
const incompleteChildren = [];
for (let i = 0; i < parent.children.length; ++i) {
if (!parent.children[i].isComplete) {
incompleteChildren.push(parent.children[i]);
}
}
const fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
const eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
parent.children.push(this.resources[name]);
parent.progressChunk = eachChunk;
for (let i = 0; i < incompleteChildren.length; ++i) {
incompleteChildren[i].progressChunk = eachChunk;
}
this.resources[name].progressChunk = eachChunk;
}
this._queue.push(this.resources[name]);
return this;
}
pre(fn) {
this._beforeMiddleware.push(fn);
return this;
}
use(fn) {
this._afterMiddleware.push(fn);
return this;
}
reset() {
this.progress = 0;
this.loading = false;
this._queue.kill();
this._queue.pause();
for (const k in this.resources) {
const res = this.resources[k];
if (res._onLoadBinding) res._onLoadBinding.detach();
if (res.isLoading) res.abort();
delete this.resources[k];
}
this.resources = {};
return this;
}
destroy() {
this.progress = 0;
this.loading = false;
this._queue.kill();
this._queue.pause();
for (const key in this.resources) {
const res = this.resources[key];
if (res.destroy) res.destroy();
delete this.resources[key];
}
this.baseUrl = "";
this.defaultQueryString = "";
this._beforeMiddleware = null;
this._afterMiddleware = null;
this._resourcesParsing = null;
this._boundLoadResource = null;
this._queue = null;
this.resources = null;
this.onProgress = null;
this.onLoad = null;
this.onError = null;
this.onStart = null;
this.onComplete = null;
}
loadAsync() {
return new Promise((resolve, reject) => {
this.load(resolve);
});
}
load(cb) {
if (typeof cb === "function") this.onComplete.once(cb);
if (this.loading) return this;
if (this._queue.idle()) {
this._onStart();
this._onComplete();
} else {
const numTasks = this._queue._tasks.length;
const chunk = MAX_PROGRESS / numTasks;
for (let i = 0; i < this._queue._tasks.length; ++i) {
this._queue._tasks[i].data.progressChunk = chunk;
}
this._onStart();
this._queue.resume();
}
return this;
}
get concurrency() {
return this._queue.concurrency;
}
set concurrency(concurrency) {
this._queue.concurrency = concurrency;
}
_prepareUrl(url) {
const parsedUrl = parseUri(url, { strictMode: true });
let result;
// absolute url, just use it as is.
if (parsedUrl.protocol || !parsedUrl.path || url.indexOf("//") === 0) {
result = url;
}
// if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween
else if (
this.baseUrl.length &&
this.baseUrl.lastIndexOf("/") !== this.baseUrl.length - 1 &&
url.charAt(0) !== "/"
) {
result = `${this.baseUrl}/${url}`;
} else {
result = this.baseUrl + url;
}
// if we need to add a default querystring, there is a bit more work
if (this.defaultQueryString) {
const hash = rgxExtractUrlHash.exec(result)[0];
result = result.substr(0, result.length - hash.length);
if (result.indexOf("?") !== -1) {
result += `&${this.defaultQueryString}`;
} else {
result += `?${this.defaultQueryString}`;
}
result += hash;
}
return result;
}
_loadResource(resource, dequeue) {
resource._dequeue = dequeue;
async.eachSeries(
this._beforeMiddleware,
(fn, next) => {
fn.call(this, resource, () => {
next(resource.isComplete ? {} : null);
});
},
() => {
if (resource.isComplete) {
this._onLoad(resource);
} else {
resource._onLoadBinding = resource.onComplete.once(
this._onLoad,
this
);
resource.load();
}
},
true
);
}
_onStart() {
this.progress = 0;
this.loading = true;
this.onStart.dispatch(this);
}
_onComplete() {
this.progress = MAX_PROGRESS;
this.loading = false;
this.onComplete.dispatch(this, this.resources);
}
_onLoad(resource) {
resource._onLoadBinding = null;
this._resourcesParsing.push(resource);
resource._dequeue();
async.eachSeries(
this._afterMiddleware,
(fn, next) => {
fn.call(this, resource, next);
},
() => {
resource.onAfterMiddleware.dispatch(resource);
this.progress = Math.min(
MAX_PROGRESS,
this.progress + resource.progressChunk
);
this.onProgress.dispatch(this, resource);
if (resource.error) {
this.onError.dispatch(resource.error, this, resource);
} else {
this.onLoad.dispatch(this, resource);
}
this._resourcesParsing.splice(
this._resourcesParsing.indexOf(resource),
1
);
// do completion check
if (this._queue.idle() && this._resourcesParsing.length === 0) {
this._onComplete();
}
},
true
);
}
}
ResourceLoader._defaultBeforeMiddleware = [];
ResourceLoader._defaultAfterMiddleware = [];
ResourceLoader.pre = function LoaderPreStatic(fn) {
ResourceLoader._defaultBeforeMiddleware.push(fn);
return ResourceLoader;
};
ResourceLoader.use = function LoaderUseStatic(fn) {
ResourceLoader._defaultAfterMiddleware.push(fn);
return ResourceLoader;
};
<file_sep>/examples/source/js/demos-advanced/replace.js
InkPaint.loader.add("t1", "source/assets/bg_grass.jpg");
InkPaint.loader.add("bg_rotate", "source/assets/bg_rotate2.jpg");
InkPaint.loader.add("bunny", "source/assets/bunny.png");
InkPaint.loader.load(setup);
var app;
function setup(l, resources) {
app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
var bunny = new InkPaint.Sprite(resources.bunny.texture);
var bg_rotate = new InkPaint.Sprite(resources.bg_rotate.texture);
bunny.anchor.set(0.5);
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
bunny.scale.set(5);
bg_rotate.anchor.set(0.5);
bg_rotate.x = app.screen.width / 2;
bg_rotate.y = app.screen.height / 2;
app.stage.addChild(bg_rotate);
var style = {
fontFamily: "Arial",
fontSize: 36,
fontStyle: "italic",
fontWeight: "bold",
fill: ["#ffffff", "#00ff99"], // gradient
stroke: "#4a1850",
strokeThickness: 5,
dropShadow: true,
dropShadowColor: "#000000",
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
wordWrap: true,
wordWrapWidth: 440
};
var richText = new InkPaint.ProxyObj();
richText.text =
"FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例,FFCreator文字多行的示例。";
richText.updateStyle(style);
richText.x = 150;
richText.y = 300;
app.stage.addChild(richText);
app.stage.addChild(bunny);
var oldRichText = richText;
richText = new InkPaint.Text();
richText.substitute(oldRichText);
oldRichText = null;
console.log(app.stage);
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
// just for fun, let's rotate mr rabbit a little
bunny.rotation += 0.1;
bg_rotate.rotation -= 0.01;
});
}
<file_sep>/examples/source/node/filters/custom.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
module.exports = app;
// Create background image
var background = InkPaint.Sprite.fromImage(paths('source/assets/bg_grass.jpg'));
background.width = app.screen.width;
background.height = app.screen.height;
app.stage.addChild(background);
// Stop application wait for load to finish
app.stop();
InkPaint.loader.add('shader', 'source/assets/pixi-filters/shader.frag')
.load(onLoaded);
var filter;
// Handle the load completed
function onLoaded(loader, res) {
// Create the new filter, arguments: (vertexShader, framentSource)
filter = new InkPaint.Filter(null, res.shader.data);
// Add the filter
background.filters = [filter];
// Resume application update
app.start();
}
// Animate the filter
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
filter.uniforms.customUniform += 0.04 * delta;
});
<file_sep>/src/loaders/index.js
import Loader from "./loader";
import { Resource } from "../resource";
const shared = new Loader();
shared.destroy = () => {};
const loader = shared || null;
export {
default as spritesheetParser,
getResourcePath
} from "./spritesheetParser";
export { default as textureParser } from "./textureParser";
export { shared, loader, Loader, Resource };
<file_sep>/src/polyfill/poly.js
class Foo {}
export default function poly(Class) {
return Class || Foo;
}
<file_sep>/src/math/Maths.js
const Maths = {
sign(x) {
x = Number(x);
if (x === 0 || isNaN(x)) {
return x;
}
return x > 0 ? 1 : -1;
}
};
export default Maths;
<file_sep>/examples/source/js/demos-basic/network.js
InkPaint.loader.add(
"bunny",
"https://www.pixijs.com/wp/wp-content/uploads/pixijs-v5-logo-1.png",
{ crossOrigin: "anonymous" }
);
InkPaint.loader.add(
"bg",
"https://www.pixijs.com/wp/wp-content/uploads/feature-multiplatform.png",
{ crossOrigin: "anonymous" }
);
InkPaint.loader.add(
"ws",
"'http://qzonestyle.gtimg.cn/qz-proj/weishi-pc/img/index/logo-l@2x.png'",
{ crossOrigin: "anonymous" }
);
InkPaint.loader.load(setup);
InkPaint.loader.on("error", error => {
console.log(error);
});
var app;
function setup(l, resources) {
app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
var bunny = new InkPaint.Sprite(resources.ws.texture);
var bg = new InkPaint.Sprite(resources.bg.texture);
// center the sprite's anchor point
bunny.anchor.set(0.5);
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
bg.anchor.set(0.5);
bg.x = app.screen.width / 2;
bg.y = app.screen.height / 2;
app.stage.addChild(bg);
app.stage.addChild(bunny);
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
// just for fun, let's rotate mr rabbit a little
bunny.rotation += 0.1;
bg.rotation -= 0.01;
});
}
<file_sep>/examples/source/node/sprite/basic.js
var loader = new InkPaint.Loader();
loader.add("t1", paths("source/assets/bg_grass.jpg"));
loader.add("bg_rotate", paths("source/assets/bg_rotate2.jpg"));
loader.add("bunny", paths("source/assets/bunny.png"));
loader.load(setup);
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb
});
var index = 0;
var now = Date.now();
function setup(l, resources) {
const texture1 = resources.bunny.texture;
const texture2 = resources.bg_rotate.texture;
const texture3 = resources.t1.texture;
console.log(texture1.frame.toString());
console.log(texture2.frame.toString());
console.log(texture3.frame.toString());
var bunny1 = new InkPaint.Sprite(resources.bunny.texture);
var bunny2 = new InkPaint.Sprite(resources.bunny.texture);
var bunny3 = new InkPaint.Sprite(resources.bunny.texture);
var bg = new InkPaint.Sprite(resources.bg_rotate.texture);
// center the sprite's anchor point
bunny1.anchor.set(0.5);
bunny2.anchor.set(0.5);
bunny3.anchor.set(0.5);
// move the sprite to the center of the screen
bunny1.x = app.screen.width / 2 - 200;
bunny1.y = app.screen.height / 2 - 200;
bunny2.x = 100;
bunny2.y = 100;
bunny3.x = 100;
bunny3.y = 150;
bunny3.rotation = 3.14 / 2;
app.stage.addChild(bg);
app.stage.addChild(bunny1);
app.stage.addChild(bunny2);
app.stage.addChild(bunny3);
// Listen for animate update
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
bunny1.rotation += 0.1 * delta;
index++;
if (index >= 20) {
//console.log("耗时", Date.now() - now);
now = Date.now();
index = 0;
}
});
}
module.exports = app;
<file_sep>/examples/source/js/filters/custom.js
var app = new InkPaint.Application();
document.body.appendChild(app.view);
var background = InkPaint.Sprite.fromImage("source/assets/bg_grass.jpg");
background.width = app.screen.width;
background.height = app.screen.height;
app.stage.addChild(background);
InkPaint.loader
.add("shader", "source/assets/pixi-filters/shader.frag")
.load(onLoaded);
var filter;
function onLoaded(loader, res) {
filter = new InkPaint.Filter(null, res.shader.data);
background.filters = [filter];
ticker.start();
}
var ticker = new InkPaint.Ticker();
ticker.add(function(delta) {
if (filter) filter.uniforms.customUniform += 0.04 * delta;
app.render();
});
<file_sep>/examples/source/js/sprite/basic.js
InkPaint.loader.add("t1", "source/assets/bg_grass.jpg");
InkPaint.loader.add("bg_rotate", "source/assets/bg_rotate2.jpg");
InkPaint.loader.add("bunny", "source/assets/bunny.png");
InkPaint.loader.load(setup);
var app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
function setup(l, resources) {
var bunny1 = new InkPaint.Sprite(resources.bunny.texture);
var bunny2 = new InkPaint.Sprite(resources.bunny.texture);
var bunny3 = new InkPaint.Sprite(resources.bunny.texture);
var bg = new InkPaint.Sprite(resources.bg_rotate.texture);
// center the sprite's anchor point
bunny1.anchor.set(0.5);
bunny2.anchor.set(0.5);
bunny3.anchor.set(0.5);
// move the sprite to the center of the screen
bunny1.x = app.screen.width / 2 - 200;
bunny1.y = app.screen.height / 2 - 200;
bunny2.x = 100;
bunny2.y = 100;
bunny3.x = 100;
bunny3.y = 150;
bunny3.rotation = 3.14 / 2;
app.stage.addChild(bg);
app.stage.addChild(bunny1);
app.stage.addChild(bunny2);
app.stage.addChild(bunny3);
// Listen for animate update
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function(delta) {
app.render();
// just for fun, let's rotate mr rabbit a little
// delta is 1 if running at 100% performance
// creates frame-independent transformation
bunny1.rotation += 0.1 * delta;
});
}
<file_sep>/examples/source/js/demos-basic/transparent-background.js
InkPaint.loader.add("t1", "source/assets/bg_grass.jpg");
InkPaint.loader.add("bg_rotate", "source/assets/bg_rotate2.jpg");
InkPaint.loader.add("bunny", "source/assets/bunny.png");
InkPaint.loader.load(setup);
// InkPaint.settings.RESOLUTION = 3;
// InkPaint.settings.SCALE_MODE = InkPaint.SCALE_MODES.NEAREST;
var app;
function setup(l, resources) {
app = new InkPaint.Application(800, 600, {
backgroundColor: 0x1099bb,
//antialias: true,
preserveDrawingBuffer: true
});
document.body.appendChild(app.view);
// create a new Sprite from an image path.
var bunny = new InkPaint.Sprite(resources.bunny.texture);
var bg_rotate = new InkPaint.Sprite(resources.bg_rotate.texture);
// center the sprite's anchor point
bunny.anchor.set(0.5);
bunny.x = app.screen.width / 2;
bunny.y = app.screen.height / 2;
bg_rotate.anchor.set(0.5);
bg_rotate.x = app.screen.width / 2;
bg_rotate.y = app.screen.height / 2;
app.stage.addChild(bg_rotate);
app.stage.addChild(bunny);
var ticker = new InkPaint.Ticker();
ticker.start();
ticker.add(function() {
app.render();
// just for fun, let's rotate mr rabbit a little
bunny.rotation += 0.1;
bg_rotate.rotation -= 0.01;
});
}
<file_sep>/src/textures/BaseTexture.js
import PsImage from "../polyfill/Image";
import settings from "../settings";
import bitTwiddle from "bit-twiddle";
import EventEmitter from "eventemitter3";
import {
uid,
rgb2hsl,
getUrlFileExt,
decomposeDataUri,
getResolutionOfUrl
} from "../utils";
import {
TextureCache,
BaseTextureCache,
addToBaseTextureCache,
removeFromBaseTextureCache
} from "../utils/cache";
export default class BaseTexture extends EventEmitter {
constructor(source, scaleMode, resolution) {
super();
this.uid = uid();
this.touched = 0;
this.width = 100;
this.height = 100;
this.realWidth = 100;
this.realHeight = 100;
this.resolution = resolution || settings.RESOLUTION;
this.scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
this.hasLoaded = false;
this.isLoading = false;
this.image = null;
this.source = null;
this.imageType = null;
this.sourceScale = 1.0;
this.premultipliedAlpha = true;
this.imageUrl = null;
this.isPowerOfTwo = false;
this.cutout = false;
this.cutoutColors = null;
this.mipmap = settings.MIPMAP_TEXTURES;
this.wrapMode = settings.WRAP_MODE;
this._glTextures = {};
this._enabled = 0;
this._virtalBoundId = -1;
this.destroyed = false;
this.textureCacheIds = [];
this.loadSource(source);
}
updateSource(imageUrl) {
if (!this.image) this.image = new PsImage();
this.resetImage(this.image);
this.loadSource(this.image);
this.image.src = imageUrl;
this.imageUrl = imageUrl;
this.resolution = getResolutionOfUrl(imageUrl);
}
loadSource(source) {
if (!source) return;
const wasLoading = this.isLoading;
this.hasLoaded = false;
this.isLoading = false;
if (wasLoading && this.source) this.removeHandler(this.source);
const firstLoaded = !this.source;
this.source = source;
// source resources loaded
const { src, width, height, complete, getContext, network } = source;
const hasSize = width && height;
if (((src && complete) || (network && complete) || getContext) && hasSize) {
this._updateImageType();
this._sourceLoaded();
if (firstLoaded) this.emit("loaded", this);
}
// the resource is not loaded
else if (!getContext) {
this.isLoading = true;
source.onload = () => {
this._updateImageType();
this.removeHandler(source);
if (!this.isLoading) return;
this.isLoading = false;
this._sourceLoaded();
this.emit("loaded", this);
};
source.onerror = () => {
this.removeHandler(source);
if (!this.isLoading) return;
this.isLoading = false;
this.emit("error", this);
};
if (complete && src) {
this.removeHandler(source);
this.isLoading = false;
if (width && height) {
this._sourceLoaded();
if (wasLoading) this.emit("loaded", this);
} else if (wasLoading) {
this.emit("error", this);
}
}
}
}
removeHandler(source) {
source.onload = null;
source.onerror = null;
}
resetImage(image) {
image.src = "";
image.width = 0;
image.height = 0;
}
adaptedNodeCanvas() {
const { source, cutout, cutoutColors } = this;
if (source && source instanceof PsImage && source.isPsImage) {
this.source = PsImage.convertToImageData(source);
if (cutout) {
const { min, max } = cutoutColors;
this.cutoutImageData({ pixel: this.source, min, max });
}
}
}
cutoutImageData({ pixel, min, max }) {
const { data } = pixel;
const length = data.length;
for (let i = 0; i < length; i += 4) {
const r = data[i + 0];
const g = data[i + 1];
const b = data[i + 2];
const [h, s, l] = rgb2hsl(r, g, b);
if (h > min && h < max) {
data[i + 3] = 0;
}
}
}
update() {
if (this.imageType !== "svg") {
this.realWidth =
this.source.naturalWidth || this.source.videoWidth || this.source.width;
this.realHeight =
this.source.naturalHeight ||
this.source.videoHeight ||
this.source.height;
// update width and height
this._updateDimensions();
}
this.emit("update", this);
}
_updateDimensions() {
this.width = this.realWidth / this.resolution;
this.height = this.realHeight / this.resolution;
this.isPowerOfTwo =
bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight);
}
_updateImageType() {
if (!this.imageUrl) return;
const dataUri = decomposeDataUri(this.imageUrl);
let imageType;
if (dataUri && dataUri.mediaType === "image") {
const firstSubType = dataUri.subType.split("+")[0];
imageType = getUrlFileExt(`.${firstSubType}`);
} else {
imageType = getUrlFileExt(this.imageUrl);
}
this.imageType = imageType || "png";
}
_sourceLoaded() {
this.hasLoaded = true;
this.update();
}
destroy() {
if (this.imageUrl) {
delete TextureCache[this.imageUrl];
this.imageUrl = null;
this.source.src = "";
this.removeHandler(this.source);
}
if (this.image) {
this.image.src = "";
this.image = null;
}
this.source = null;
this.dispose();
removeFromBaseTextureCache(this);
this.textureCacheIds = null;
this.destroyed = true;
this.cutout = false;
this.cutoutColors = null;
}
dispose() {
this.emit("dispose", this);
}
static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) {
let baseTexture = BaseTextureCache[imageUrl];
if (!baseTexture) {
const image = new PsImage();
baseTexture = new BaseTexture(image, scaleMode);
baseTexture.imageUrl = imageUrl;
if (sourceScale) baseTexture.sourceScale = sourceScale;
baseTexture.resolution = getResolutionOfUrl(imageUrl);
image.src = imageUrl;
addToBaseTextureCache(baseTexture, imageUrl);
}
return baseTexture;
}
static fromCanvas(canvas, scaleMode, origin = "canvas") {
if (!canvas.__paintId) canvas.__paintId = `${origin}_${uid()}`;
let baseTexture = BaseTextureCache[canvas.__paintId];
if (!baseTexture) {
baseTexture = new BaseTexture(canvas, scaleMode);
addToBaseTextureCache(baseTexture, canvas.__paintId);
}
return baseTexture;
}
static from(source, scaleMode, sourceScale) {
if (typeof source === "string") {
return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale);
} else if (source instanceof HTMLImageElement) {
const imageUrl = source.src;
let baseTexture = BaseTextureCache[imageUrl];
if (!baseTexture) {
baseTexture = new BaseTexture(source, scaleMode);
baseTexture.imageUrl = imageUrl;
if (sourceScale) {
baseTexture.sourceScale = sourceScale;
}
baseTexture.resolution = getResolutionOfUrl(imageUrl);
addToBaseTextureCache(baseTexture, imageUrl);
}
return baseTexture;
} else if (source instanceof HTMLCanvasElement) {
return BaseTexture.fromCanvas(source, scaleMode);
}
return source;
}
}
<file_sep>/src/Application.js
import settings from "./settings";
import Container from "./display/Container";
import { autoRenderer } from "./autoRenderer";
import { shared, Ticker } from "./ticker";
import { UPDATE_PRIORITY } from "./const";
export default class Application {
constructor(options, arg2, arg3, arg4, arg5) {
if (typeof options === "number") {
options = Object.assign(
{
width: options,
height: arg2 || settings.RENDER_OPTIONS.height,
useGL: !!arg4,
sharedTicker: !!arg5
},
arg3
);
}
this._options = options = Object.assign(
{
autoStart: true,
sharedTicker: false,
useGL: false,
sharedLoader: false,
autoRender: false
},
options
);
this.renderer = autoRenderer(options);
this.stage = new Container();
this.stage.isStage = true;
this._ticker = null;
if (options.autoRender) {
this.ticker = options.sharedTicker ? shared : new Ticker();
}
if (options.autoStart) {
this.start();
}
}
set ticker(ticker) {
if (this._ticker) this._ticker.remove(this.render, this);
this._ticker = ticker;
if (ticker) ticker.add(this.render, this, UPDATE_PRIORITY.LOW);
}
get ticker() {
return this._ticker;
}
render() {
this.renderer.render(this.stage);
}
stop() {
this.ticker && this.ticker.stop();
}
start() {
this.ticker && this.ticker.start();
}
get view() {
return this.renderer.view;
}
get screen() {
return this.renderer.screen;
}
destroyChildren(options) {
this.stage.destroyChildren(options);
}
destroy(removeView, stageOptions) {
if (this._ticker) {
const oldTicker = this._ticker;
this.ticker = null;
oldTicker.destroy();
}
this.stage.destroy(stageOptions);
this.renderer.destroy(removeView);
this.renderer = null;
this._options = null;
this.stage = null;
}
}
<file_sep>/examples/source/js/text/webfont.js
var app = new InkPaint.Application(800, 600, { backgroundColor: 0x1099bb });
document.body.appendChild(app.view);
// // Load them google fonts before starting...!
window.WebFontConfig = {
google: {
families: ['Snippet', 'Arvo:700italic', 'Podkova:700']
},
active: function() {
init();
}
};
// include the web-font loader script
(function() {
var wf = document.createElement('script');
wf.src = (document.location.protocol === 'https:' ? 'https' : 'http')
+ '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
}());
function init() {
// create some white text using the Snippet webfont
var textSample = new InkPaint.Text('Pixi.js text using the\ncustom "Snippet" Webfont', {
fontFamily: 'Snippet',
fontSize: 50,
fill: 'white',
align: 'left'
});
textSample.position.set(50, 200);
app.stage.addChild(textSample);
app.render();
}
<file_sep>/README.md
# InkPaint — canvas graphics rendering library for node.js
<p align="center">
<img src="./examples/img/logo.png" />
</p>
<div align="center">
<a href="https://www.npmjs.com/inkpaint" target="_blank"><img src="https://img.shields.io/npm/v/inkpaint.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/inkpaint" target="_blank"><img src="https://img.shields.io/npm/l/inkpaint.svg" alt="Package License" /></a>
<a href="https://github.com/prettier/prettier" target="_blank"><img src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg" alt="Code Style"></a>
<a href="https://github.com/tnfe/inkpaint/pulls" target="_blank"><img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg" alt="PRs"/></a>
<a href="https://nodejs.org" target="_blank"><img src="https://img.shields.io/badge/node-%3E%3D%208.0.0-brightgreen.svg" alt="Node Version" /></a>
</div>
## Overview
InkPaint is a lightweight node.js canvas graphics animation library. It forks from the famous canvas engine pixi.js. You can use it to do server-side image synthesis.
InkPaint has a lot of performance optimization and code refactoring. One of its application Demo is FFCreator [https://github.com/tnfe/FFCreator](https://github.com/tnfe/FFCreator) video processing library.
At the same time, inkpaint is a common library between node.js and the browser, and it can still run normally on the browser side.
## Current features
- WebGL renderer (headless-gl)
- Canvas renderer (node-canvas)
- Super easy to use API
- Support for texture atlases
- Asset loader / sprite sheet loader
- Support multiple text effects
- Various Sprite effects and animations
- Masking and Filters
## Basic Usage
```sh
npm install inkpaint
```
```js
const fs = require("fs-extra");
const { Application, Sprite, Ticker, Loader } = require("inkpaint");
const width = 800;
const height = 600;
const app = new Application(width, height);
const loader = new Loader();
loader.add("boy", "./assets/boy.png");
loader.load(loaded);
function loaded(loader, resources) {
const boy = new Sprite(resources.boy.texture);
boy.x = width / 2;
boy.y = height / 2;
boy.anchor.set(0.5);
app.stage.addChild(boy);
}
const ticker = new Ticker();
ticker.start();
ticker.add(() => {
app.render();
boy.x += 0.1;
});
// save image
const buffer = app.view.toBuffer("image/png");
fs.outputFile("./hello.png", buffer);
```
## Save Image
InkPaint supports saving pictures in multiple formats, you can refer to the api of node-canvas [https://github.com/Automattic/node-canvas#canvastobuffer](). You can save any animated graphics supported by the browser on the server side.
## Installation
### Install `node-canvas` and `headless-gl` dependencies
> ##### If it is a computer with a display device, such as a personal `pc` computer with `windows`, `Mac OSX` system, or a `server` server with a graphics card or display device, you can skip this step without installing this dependency.
If you are using `Centos`, `Redhat`, `Fedora` system, you can use `yum` to install.
```shell
sudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel
```
Install[`Xvfb`](https://linux.die.net/man/1/xvfb) and [`Mesa`](http://www.sztemple.cc/articles/linux%E4%B8%8B%E7%9A%84opengl-mesa%E5%92%8Cglx%E7%AE%80%E4%BB%8B)
```shell
sudo yum install mesa-dri-drivers Xvfb libXi-devel libXinerama-devel libX11-devel
```
If you are using `Debian`, `ubuntu` system, you can use `apt` to install.
```shell
sudo apt-get install libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++
sudo apt-get install libgl1-mesa-dev xvfb libxi-dev libx11-dev
```
## Start Up
> If it is a computer with a display device, such as a personal pc computer or a server server with a graphics card or display device, start normally `npm start`
#### Otherwise, You must use the `xvfb-run` script command to start the program to use webgl under the Linux server
xvfb-run more detailed command parameters [http://manpages.ubuntu.com/manpages/xenial/man1/xvfb-run.1.html](http://manpages.ubuntu.com/manpages/xenial/man1/xvfb-run.1.html)
```shell
xvfb-run -s "-ac -screen 0 1280x1024x24" npm start
```
## How to build
Note that for most users you don't need to build this project. If all you want is to use InkPaint, then
just download one of our [prebuilt releases](https://github.com/tnfe/inkpaint/releases). Really
the only time you should need to build InkPaint is if you are developing it.
If you don't already have Node.js and NPM, go install them. Then, in the folder where you have cloned
the repository, install the build dependencies using npm:
```sh
npm install
```
Compile the node.js package
```sh
npm run lib
```
At the same time, inkpaint is a common library between node.js and the browser, and it can still run normally on the browser side.
If you want to view the example on the browser side, please execute
```sh
npm run web
```
To execute the example under node.js, execute
```sh
npm run examples
```
### License
This content is released under the (http://opensource.org/licenses/MIT) MIT License.
<file_sep>/src/utils/mapPremultipliedBlendModes.js
import { BLEND_MODES } from "../const";
export default function mapPremultipliedBlendModes() {
const pm = [];
const npm = [];
for (let i = 0; i < 32; i++) {
pm[i] = i;
npm[i] = i;
}
pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL;
pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD;
pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN;
npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM;
npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM;
npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM;
const array = [];
array.push(npm);
array.push(pm);
return array;
}
<file_sep>/src/renderers/webgl/WebGLRenderer.js
import SystemRenderer from "../SystemRenderer";
import MaskManager from "./managers/MaskManager";
import StencilManager from "./managers/StencilManager";
import FilterManager from "./managers/FilterManager";
import RenderTarget from "./utils/RenderTarget";
import ObjectRenderer from "./utils/ObjectRenderer";
import TextureManager from "./TextureManager";
import BaseTexture from "../../textures/BaseTexture";
import TextureGarbageCollector from "./TextureGarbageCollector";
import WebGLState from "./WebGLState";
import mapWebGLDrawModesToPixi from "./utils/mapWebGLDrawModesToPixi";
import validateContext from "./utils/validateContext";
import { pluginTarget } from "../../utils";
import glCore from "pixi-gl-core";
import { RENDERER_TYPE } from "../../const";
let CONTEXT_UID = 0;
export default class WebGLRenderer extends SystemRenderer {
constructor(options, arg2, arg3) {
super("WebGL", options, arg2, arg3);
this.legacy = this.options.legacy;
if (this.legacy) {
glCore.VertexArrayObject.FORCE_NATIVE = true;
}
this.type = RENDERER_TYPE.WEBGL;
this.handleContextLost = this.handleContextLost.bind(this);
this.handleContextRestored = this.handleContextRestored.bind(this);
this.view.addEventListener(
"webglcontextlost",
this.handleContextLost,
false
);
this.view.addEventListener(
"webglcontextrestored",
this.handleContextRestored,
false
);
this._contextOptions = {
alpha: this.transparent,
antialias: this.options.antialias,
premultipliedAlpha:
this.transparent && this.transparent !== "notMultiplied",
stencil: true,
preserveDrawingBuffer: this.options.preserveDrawingBuffer,
powerPreference: this.options.powerPreference
};
this._backgroundColorRgba[3] = this.transparent ? 0 : 1;
this.maskManager = new MaskManager(this);
this.stencilManager = new StencilManager(this);
this.emptyRenderer = new ObjectRenderer(this);
this.currentRenderer = this.emptyRenderer;
this.textureManager = null;
this.filterManager = null;
this.initPlugins();
if (this.options.context) {
validateContext(this.options.context);
}
this.gl =
this.options.context ||
glCore.createContext(this.view, this._contextOptions);
this.CONTEXT_UID = CONTEXT_UID++;
this.state = new WebGLState(this.gl);
this.renderingToScreen = true;
this.boundTextures = null;
this._activeShader = null;
this._activeVao = null;
this._activeRenderTarget = null;
this._initContext();
this.drawModes = mapWebGLDrawModesToPixi(this.gl);
this._nextTextureLocation = 0;
this.setBlendMode(0);
}
_initContext() {
const gl = this.gl;
if (gl.isContextLost() && gl.getExtension("WEBGL_lose_context")) {
gl.getExtension("WEBGL_lose_context").restoreContext();
}
const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
this._activeShader = null;
this._activeVao = null;
this.boundTextures = new Array(maxTextures);
this.emptyTextures = new Array(maxTextures);
this._unknownBoundTextures = false;
// create a texture manager...
this.textureManager = new TextureManager(this);
this.filterManager = new FilterManager(this);
this.textureGC = new TextureGarbageCollector(this);
this.state.resetToDefault();
this.rootRenderTarget = new RenderTarget(
gl,
this.width,
this.height,
null,
this.resolution,
true
);
this.rootRenderTarget.clearColor = this._backgroundColorRgba;
this.bindRenderTarget(this.rootRenderTarget);
const emptyGLTexture = new glCore.GLTexture.fromData(gl, null, 1, 1);
const tempObj = { _glTextures: {} };
tempObj._glTextures[this.CONTEXT_UID] = {};
for (let i = 0; i < maxTextures; i++) {
const empty = new BaseTexture();
empty._glTextures[this.CONTEXT_UID] = emptyGLTexture;
this.boundTextures[i] = tempObj;
this.emptyTextures[i] = empty;
this.bindTexture(null, i);
}
this.emit("context", gl);
this.resize(this.screen.width, this.screen.height);
}
render(displayObject, renderTexture, clear, transform, skipUpdateTransform) {
this.renderingToScreen = !renderTexture;
this.emit("prerender");
if (!this.gl || this.gl.isContextLost()) return;
this._nextTextureLocation = 0;
if (!renderTexture) {
this._lastObjectRendered = displayObject;
}
if (!skipUpdateTransform) {
const cacheParent = displayObject.parent;
displayObject.parent = this._tempDisplayObjectParent;
displayObject.updateTransform();
displayObject.parent = cacheParent;
}
this.bindRenderTexture(renderTexture, transform);
this.currentRenderer.start();
if (clear !== undefined ? clear : this.clearBeforeRender) {
this._activeRenderTarget.clear();
}
displayObject.renderWebGL(this);
this.currentRenderer.flush();
this.textureGC.update();
this.emit("postrender");
}
setObjectRenderer(objectRenderer) {
if (this.currentRenderer === objectRenderer) {
return;
}
this.currentRenderer.stop();
this.currentRenderer = objectRenderer;
this.currentRenderer.start();
}
flush() {
this.setObjectRenderer(this.emptyRenderer);
}
resize(screenWidth, screenHeight) {
SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight);
this.rootRenderTarget.resize(screenWidth, screenHeight);
if (this._activeRenderTarget === this.rootRenderTarget) {
this.rootRenderTarget.activate();
if (this._activeShader) {
this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(
true
);
}
}
}
setBlendMode(blendMode) {
this.state.setBlendMode(blendMode);
}
deleteTexture(texture) {
this.gl.deleteTexture(texture);
}
clear(clearColor) {
this._activeRenderTarget.clear(clearColor);
}
setTransform(matrix) {
this._activeRenderTarget.transform = matrix;
}
clearRenderTexture(renderTexture, clearColor) {
const baseTexture = renderTexture.baseTexture;
const renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID];
if (renderTarget) {
renderTarget.clear(clearColor);
}
return this;
}
bindRenderTexture(renderTexture, transform) {
let renderTarget;
if (renderTexture) {
const baseTexture = renderTexture.baseTexture;
if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) {
this.textureManager.updateTexture(baseTexture, 0);
}
this.unbindTexture(baseTexture);
renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID];
renderTarget.setFrame(renderTexture.frame);
} else {
renderTarget = this.rootRenderTarget;
}
renderTarget.transform = transform;
this.bindRenderTarget(renderTarget);
return this;
}
bindRenderTarget(renderTarget) {
if (renderTarget !== this._activeRenderTarget) {
this._activeRenderTarget = renderTarget;
renderTarget.activate();
if (this._activeShader) {
this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(
true
);
}
this.stencilManager.setMaskStack(renderTarget.stencilMaskStack);
}
return this;
}
bindShader(shader, autoProject) {
// TODO cache
if (this._activeShader !== shader) {
this._activeShader = shader;
shader.bind();
// `autoProject` normally would be a default parameter set to true
// but because of how Babel transpiles default parameters
// it hinders the performance of this method.
if (autoProject !== false) {
// automatically set the projection matrix
shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(
true
);
}
}
return this;
}
bindTexture(texture, location, forceLocation) {
texture = texture || this.emptyTextures[location];
texture = texture.baseTexture || texture;
texture.touched = this.textureGC.count;
if (!forceLocation) {
// TODO - maybe look into adding boundIds.. save us the loop?
for (let i = 0; i < this.boundTextures.length; i++) {
if (this.boundTextures[i] === texture) {
return i;
}
}
if (location === undefined) {
this._nextTextureLocation++;
this._nextTextureLocation %= this.boundTextures.length;
location = this.boundTextures.length - this._nextTextureLocation - 1;
}
} else {
location = location || 0;
}
const gl = this.gl;
const glTexture = texture._glTextures[this.CONTEXT_UID];
if (!glTexture) {
// this will also bind the texture..
this.textureManager.updateTexture(texture, location);
} else {
// bind the current texture
this.boundTextures[location] = texture;
gl.activeTexture(gl.TEXTURE0 + location);
gl.bindTexture(gl.TEXTURE_2D, glTexture.texture);
}
return location;
}
unbindTexture(texture) {
const gl = this.gl;
texture = texture.baseTexture || texture;
if (this._unknownBoundTextures) {
this._unknownBoundTextures = false;
// someone changed webGL state,
// we have to be sure that our texture does not appear in multitexture renderer samplers
for (let i = 0; i < this.boundTextures.length; i++) {
if (this.boundTextures[i] === this.emptyTextures[i]) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(
gl.TEXTURE_2D,
this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture
);
}
}
}
for (let i = 0; i < this.boundTextures.length; i++) {
if (this.boundTextures[i] === texture) {
this.boundTextures[i] = this.emptyTextures[i];
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(
gl.TEXTURE_2D,
this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture
);
}
}
return this;
}
createVao() {
return new glCore.VertexArrayObject(this.gl, this.state.attribState);
}
bindVao(vao) {
if (this._activeVao === vao) {
return this;
}
if (vao) {
vao.bind();
} else if (this._activeVao) {
// TODO this should always be true i think?
this._activeVao.unbind();
}
this._activeVao = vao;
return this;
}
reset() {
this.setObjectRenderer(this.emptyRenderer);
this.bindVao(null);
this._activeShader = null;
this._activeRenderTarget = this.rootRenderTarget;
this._unknownBoundTextures = true;
for (let i = 0; i < this.boundTextures.length; i++) {
this.boundTextures[i] = this.emptyTextures[i];
}
// bind the main frame buffer (the screen);
this.rootRenderTarget.activate();
this.state.resetToDefault();
return this;
}
handleContextLost(event) {
event.preventDefault();
}
handleContextRestored() {
this.textureManager.removeAll();
this.filterManager.destroy(true);
this._initContext();
}
destroy(removeView) {
this.destroyPlugins();
// remove listeners
this.view.removeEventListener("webglcontextlost", this.handleContextLost);
this.view.removeEventListener(
"webglcontextrestored",
this.handleContextRestored
);
this.textureManager.destroy();
super.destroy(removeView);
this.uid = 0;
// destroy the managers
this.maskManager.destroy();
this.stencilManager.destroy();
this.filterManager.destroy();
this.maskManager = null;
this.filterManager = null;
this.textureManager = null;
this.currentRenderer = null;
this.handleContextLost = null;
this.handleContextRestored = null;
this._contextOptions = null;
this.gl.useProgram(null);
if (this.gl.getExtension("WEBGL_lose_context")) {
this.gl.getExtension("WEBGL_lose_context").loseContext();
}
this.gl = null;
}
}
pluginTarget.mixin(WebGLRenderer);
<file_sep>/src/renderers/webgl/managers/BlendModeManager.js
import WebGLManager from "./WebGLManager";
export default class BlendModeManager extends WebGLManager {
constructor(renderer) {
super(renderer);
this.currentBlendMode = 99999;
}
setBlendMode(blendMode) {
if (this.currentBlendMode === blendMode) {
return false;
}
this.currentBlendMode = blendMode;
const mode = this.renderer.blendModes[this.currentBlendMode];
this.renderer.gl.blendFunc(mode[0], mode[1]);
return true;
}
}
<file_sep>/test/core/util.js
"use strict";
describe("InkPaint.utils", function() {
describe("uid", function() {
it("should exist", function() {
expect(InkPaint.utils.uid).to.be.a("function");
});
it("should return a number", function() {
expect(InkPaint.utils.uid()).to.be.a("number");
});
});
describe("hex2rgb", function() {
it("should exist", function() {
expect(InkPaint.utils.hex2rgb).to.be.a("function");
});
// it('should properly convert number to rgb array');
});
describe("hex2string", function() {
it("should exist", function() {
expect(InkPaint.utils.hex2string).to.be.a("function");
});
// it('should properly convert number to hex color string');
});
describe("rgb2hex", function() {
it("should exist", function() {
expect(InkPaint.utils.rgb2hex).to.be.a("function");
});
it("should calculate correctly", function() {
expect(InkPaint.utils.rgb2hex([0.3, 0.2, 0.1])).to.equals(0x4c3319);
});
// it('should properly convert rgb array to hex color string');
});
describe("getResolutionOfUrl", function() {
it("should exist", function() {
expect(InkPaint.utils.getResolutionOfUrl).to.be.a("function");
});
// it('should return the correct resolution based on a URL');
});
describe("decomposeDataUri", function() {
it("should exist", function() {
expect(InkPaint.utils.decomposeDataUri).to.be.a("function");
});
it("should decompose a data URI", function() {
const dataUri = InkPaint.utils.decomposeDataUri(
"data:image/png;base64,94Z9RWUN77ZW"
);
expect(dataUri).to.be.an("object");
expect(dataUri.mediaType).to.equal("image");
expect(dataUri.subType).to.equal("png");
expect(dataUri.charset).to.be.an("undefined");
expect(dataUri.encoding).to.equal("base64");
expect(dataUri.data).to.equal("94Z9RWUN77ZW");
});
it("should decompose a data URI with charset", function() {
const dataUri = InkPaint.utils.decomposeDataUri(
"data:image/svg+xml;charset=utf8;base64,PGRpdiB4bWxucz0Pg=="
);
expect(dataUri).to.be.an("object");
expect(dataUri.mediaType).to.equal("image");
expect(dataUri.subType).to.equal("svg+xml");
expect(dataUri.charset).to.equal("utf8");
expect(dataUri.encoding).to.equal("base64");
expect(dataUri.data).to.equal("PGRpdiB4bWxucz0Pg==");
});
it("should decompose a data URI with charset without encoding", function() {
const dataUri = InkPaint.utils.decomposeDataUri(
"data:image/svg+xml;charset=utf8,PGRpdiB4bWxucz0Pg=="
);
expect(dataUri).to.be.an("object");
expect(dataUri.mediaType).to.equal("image");
expect(dataUri.subType).to.equal("svg+xml");
expect(dataUri.charset).to.equal("utf8");
expect(dataUri.encoding).to.be.an("undefined");
expect(dataUri.data).to.equal("PGRpdiB4bWxucz0Pg==");
});
it("should return undefined for anything else", function() {
const dataUri = InkPaint.utils.decomposeDataUri("foo");
expect(dataUri).to.be.an("undefined");
});
});
describe("getUrlFileExtension", function() {
it("should exist", function() {
expect(InkPaint.utils.getUrlFileExtension).to.be.a("function");
});
it("should return extension of URL in lower case", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG"
);
expect(imageType).to.equal("png");
});
it("should return extension of URL when absolute", function() {
const imageType = InkPaint.utils.getUrlFileExtension("/you/baz.PNG");
expect(imageType).to.equal("png");
});
it("should return extension of URL when relative", function() {
const imageType = InkPaint.utils.getUrlFileExtension("me/baz.PNG");
expect(imageType).to.equal("png");
});
it("should return extension of URL when just an extension", function() {
const imageType = InkPaint.utils.getUrlFileExtension(".PNG");
expect(imageType).to.equal("png");
});
it("should work with a hash on the url", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG#derp"
);
expect(imageType).to.equal("png");
});
it("should work with a hash path on the url", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG#derp/this/is/a/path/me.jpg"
);
expect(imageType).to.equal("png");
});
it("should work with a query string on the url", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG?v=1&file=me.jpg"
);
expect(imageType).to.equal("png");
});
it("should work with a hash and query string on the url", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG?v=1&file=me.jpg#not-today"
);
expect(imageType).to.equal("png");
});
it("should work with a hash path and query string on the url", function() {
const imageType = InkPaint.utils.getUrlFileExtension(
"http://foo.bar/baz.PNG?v=1&file=me.jpg#path/s/not-today.svg"
);
expect(imageType).to.equal("png");
});
});
describe("getSvgSize", function() {
it("should exist", function() {
expect(InkPaint.utils.getSvgSize).to.be.a("function");
});
it("should return a size object with width and height from an SVG string", function() {
const svgSize = InkPaint.utils.getSvgSize(
'<svg height="32" width="64"></svg>'
);
expect(svgSize).to.be.an("object");
expect(svgSize.width).to.equal(64);
expect(svgSize.height).to.equal(32);
});
it("should return a size object from an SVG string with inverted quotes", function() {
var svgSize = InkPaint.utils.getSvgSize(
"<svg height='32' width='64'></svg>"
); // eslint-disable-line quotes
expect(svgSize).to.be.an("object");
expect(svgSize.width).to.equal(64);
expect(svgSize.height).to.equal(32);
});
it("should work with px values", function() {
const svgSize = InkPaint.utils.getSvgSize(
'<svg height="32px" width="64px"></svg>'
);
expect(svgSize).to.be.an("object");
expect(svgSize.width).to.equal(64);
expect(svgSize.height).to.equal(32);
});
it("should return an empty object when width and/or height is missing", function() {
const svgSize = InkPaint.utils.getSvgSize('<svg width="64"></svg>');
expect(Object.keys(svgSize).length).to.equal(0);
});
});
describe("sign", function() {
it("should return 0 for 0", function() {
expect(InkPaint.utils.sign(0)).to.be.equal(0);
});
it("should return -1 for negative numbers", function() {
for (let i = 0; i < 10; i += 1) {
expect(InkPaint.utils.sign(-Math.random())).to.be.equal(-1);
}
});
it("should return 1 for positive numbers", function() {
for (let i = 0; i < 10; i += 1) {
expect(InkPaint.utils.sign(Math.random() + 0.000001)).to.be.equal(
1
);
}
});
});
describe(".removeItems", function() {
it("should exist", function() {
expect(InkPaint.utils.removeItems).to.be.a("function");
});
});
describe("EventEmitter", function() {
it("should exist", function() {
expect(InkPaint.utils.EventEmitter).to.be.a("function");
});
});
describe("earcut", function() {
it("should exist", function() {
expect(InkPaint.utils.earcut).to.be.a("function");
});
});
});
<file_sep>/src/renderers/webgl/filters/Filter.js
import extractUniformsFromSrc from "./extractUniformsFromSrc";
import { uid } from "../../../utils";
import { BLEND_MODES } from "../../../const";
import settings from "../../../settings";
const SOURCE_KEY_MAP = {};
export default class Filter {
constructor(vertexSrc, fragmentSrc, uniformData) {
this.vertexSrc = vertexSrc || Filter.defaultVertexSrc;
this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc;
this._blendMode = BLEND_MODES.NORMAL;
this.uniformData =
uniformData ||
extractUniformsFromSrc(
this.vertexSrc,
this.fragmentSrc,
"projectionMatrix|uSampler"
);
this.uniforms = {};
for (const i in this.uniformData) {
this.uniforms[i] = this.uniformData[i].value;
if (this.uniformData[i].type) {
this.uniformData[i].type = this.uniformData[i].type.toLowerCase();
}
}
this.glShaders = {};
if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) {
SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = uid();
}
this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc];
this.padding = 4;
this.resolution = settings.FILTER_RESOLUTION;
this.enabled = true;
this.autoFit = true;
}
apply(filterManager, input, output, clear, currentState) {
filterManager.applyFilter(this, input, output, clear);
}
get blendMode() {
return this._blendMode;
}
set blendMode(value) {
this._blendMode = value;
}
static get defaultVertexSrc() {
return [
"attribute vec2 aVertexPosition;",
"attribute vec2 aTextureCoord;",
"uniform mat3 projectionMatrix;",
"uniform mat3 filterMatrix;",
"varying vec2 vTextureCoord;",
"varying vec2 vFilterCoord;",
"void main(void){",
" gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);",
" vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;",
" vTextureCoord = aTextureCoord ;",
"}"
].join("\n");
}
static get defaultFragmentSrc() {
return [
"varying vec2 vTextureCoord;",
"varying vec2 vFilterCoord;",
"uniform sampler2D uSampler;",
"uniform sampler2D filterSampler;",
"void main(void){",
" vec4 masky = texture2D(filterSampler, vFilterCoord);",
" vec4 sample = texture2D(uSampler, vTextureCoord);",
" vec4 color;",
" if(mod(vFilterCoord.x, 1.0) > 0.5)",
" {",
" color = vec4(1.0, 0.0, 0.0, 1.0);",
" }",
" else",
" {",
" color = vec4(0.0, 1.0, 0.0, 1.0);",
" }",
// ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);',
" gl_FragColor = mix(sample, masky, 0.5);",
" gl_FragColor *= sample.a;",
"}"
].join("\n");
}
}
<file_sep>/src/sprites/webgl/BatchBuffer.js
export default class Buffer {
constructor(size) {
this.vertices = new ArrayBuffer(size);
this.float32View = new Float32Array(this.vertices);
this.uint32View = new Uint32Array(this.vertices);
}
destroy() {
this.vertices = null;
this.positions = null;
this.uvs = null;
this.colors = null;
}
}
<file_sep>/src/math/ObservablePoint.js
export default class ObservablePoint {
constructor(cb, scope, x = 0, y = 0) {
this._x = x;
this._y = y;
this.cb = cb;
this.scope = scope;
}
clone(cb = null, scope = null) {
const _cb = cb || this.cb;
const _scope = scope || this.scope;
return new ObservablePoint(_cb, _scope, this._x, this._y);
}
set(x, y) {
const _x = x || 0;
const _y = y || (y !== 0 ? _x : 0);
if (this._x !== _x || this._y !== _y) {
this._x = _x;
this._y = _y;
this.cb.call(this.scope);
}
}
copy(point) {
if (this._x !== point.x || this._y !== point.y) {
this._x = point.x;
this._y = point.y;
this.cb.call(this.scope);
}
}
equals(p) {
return p.x === this._x && p.y === this._y;
}
get x() {
return this._x;
}
set x(value) {
if (this._x !== value) {
this._x = value;
this.cb.call(this.scope);
}
}
get y() {
return this._y;
}
set y(value) {
if (this._y !== value) {
this._y = value;
this.cb.call(this.scope);
}
}
dot(p) {
this.x = this.x * p.x;
this.x = this.y * p.y;
}
}
| c0d77a364dfe769d5f3974eec3d30a88135bb9da | [
"JavaScript",
"Markdown"
] | 77 | JavaScript | haozi23333/inkpaint | 3bcccecba9da847893802ff8783c7116a72f5f14 | 0614af2c7c229146601fa9290fe081c6329cf87f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.