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>//Copyright (c) 2016 Hitachi Data Systems, Inc.
//All Rights Reserved.
//
// 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.
//
//Author: <NAME> <<EMAIL>>
//
(function()
{
freeboard.loadDatasourcePlugin({
"type_name" : "mongodb_datasource_plugin",
"display_name": "MongoDB",
"description" : "Retrieve document from a mongo server with rest api.",
"external_scripts" : [
""
],
"settings" : [
{
"name" : "rest",
"display_name" : "REST server",
"type" : "text",
"description" : "RESTHeart server \"hostname:port\"",
"required" : true
},
{
"name" : "rest_api",
"display_name" : "REST API",
"type" : "text",
"required" : true,
"description" : "/?filter='\{\"property\"\:\"value\"\}'"
},
{
"name" : "refresh_time",
"display_name" : "Refresh Time",
"type" : "text",
"description" : "In milliseconds",
"default_value": 1000
}
],
newInstance : function(settings, newInstanceCallback, updateCallback)
{
newInstanceCallback(new MongodbDatasourcePlugin(settings, updateCallback));
}
});
var MongodbDatasourcePlugin = function(settings, updateCallback)
{
var self = this;
var currentSettings = settings;
// The getData() is to retrieve latest data within the specified time window as "Refresh Time" from MongoDB.
function getData()
{
var currentTime = new Date().getTime();
var refresh_time = currentSettings.refresh_time;
// The url has an url as a REST API of RESTHeart to retrieve data, which is a REST API server for MongoDB.
var url = "http://";
url += currentSettings.rest;
//
// Support the following operators used for filtering data in a MongoDB collection.
// {"$gt"|"$gte"|"$eq"|"$date":"$latest"}
//
// The $gt, $gte, $eq and $date operators are from RESTHeart and handled by RESTHeart.
// The $latest operator is added and handled by this plugin. It is replaced with a time in interger value or ISO string format.
//
var regexp = /\{\s*(['"])(\$gt|\$gte|\$eq|\$date)['"]\s*:\s*(['"]\$latest['"])\s*\}/g;
var rest_api = currentSettings.rest_api;
url += rest_api.replace(regexp, function(match, p1, p2, p3, offset, string) {
if (p2 == "$gt" || p2 == "$gte" || p2 == "$eq") {
// If $latest is specified with $gt, $gte or $eq, then replace it with an interger value representing a previous expiration time.
var thresholdTime = currentTime - refresh_time;
return "{" + p1 + p2 + p1 + ":" + thresholdTime + "}";
} else if (p2 == "$date") {
// If $latest is specified with $date, then replace it with a string in ISO format representing a previous expiration time.
var thresholdTime = new Date(currentTime - refresh_time).toISOString();
return "{" + p1 + p2 + p1 + ":" + p1 + thresholdTime +p1 + "}";
} else {
return match;
}
});
// Import rest api modules provided by the external package "rest".
var rest = require('rest/client/xhr');
var defaultRequest = require('rest/interceptor/defaultRequest');
var client = rest.wrap(defaultRequest, {method: 'GET', headers:{'Content-Type':'application/json'}});
// Invoke a REST API of RESTHeart to retrieve data.
client(url).then(function(response) {
var message = JSON.parse(response.entity);
if (message._returned > 0) {
// Pass data to Freeboard.
updateCallback(message);
}
});
}
// Create an interval timer to update Freeboard view with latest data every the interval specified by "Refresh Time".
var refreshTimer;
function createRefreshTimer(interval)
{
if(refreshTimer)
{
clearInterval(refreshTimer);
}
refreshTimer = setInterval(function() {
getData();
}, interval);
}
self.onSettingsChanged = function(newSettings)
{
currentSettings = newSettings;
createRefreshTimer(currentSettings.refresh_time);
}
self.updateNow = function()
{
getData();
}
self.onDispose = function()
{
clearInterval(refreshTimer);
refreshTimer = undefined;
}
createRefreshTimer(currentSettings.refresh_time);
}
}());
<file_sep># Freeboard-plugin-for-MongoDB
A Freeboard plugin for MongoDB.
This plugin enables Freeboard to retrieve latest data for every specified interval from MongoDB via the RESTHeart a REST API server for MongoDB.
Refer to [Freeboard GitHub] (https://github.com/Freeboard/freeboard) for Freeboard specifics.
Refer to [MongoDB GitHub] (https://github.com/mongodb/mongo) for MongoDB specifics.
##Prerequisites
###Server side
* [RESTHeart](http://restheart.org)
###Development environment to build this plugin
* [Node.js](https://nodejs.org/en/)
* [Browserify](http://browserify.org)
* [UglifyJS](https://github.com/mishoo/UglifyJS)
##Install
To make this plugin, execute the following commands.
```sh
$ git clone https://github.com/Hitachi-Data-Systems/Freeboard-plugin-for-MongoDB.git
$ npm install
$ ls mongodb.plugin.js
mongodb.plugin.js
```
To load the plugin in your Freeboard, copy to "mongodb.plugin.js" to your plugin folder for Freeboard, and add it to the list in your index.html used to initialize Freeboard. Below is an example of index.html to load this plugin.
```html
<script type="text/javascript">
head.js("js/freeboard_plugins.min.js",
"plugins/thirdparty/mongodb.plugin.js",
// *** Load more plugins here ***
function(){
$(function()
{ //DOM Ready
freeboard.initialize(true);
...
});
});
```
##Usage
Choose the data source "MongoDB".
###NAME
Name the data source.
###REST SERVER
Specify the hostname/address and port of your RESTHeart server where your RESTHeart server binds.
###REST API
Specify a REST API query according to RESTHeart query format to retrieve data from MongoDB via RESTHeart server. Below is an example of query:
```uri
/kaa/logs_48635001004582290736/?count&sort_by=-header.timestamp&pagesize=1
```
This plugin supports an additional filtering operator "$latest" adding to the operators supported by RESTHeart.
The $latest operator is interpreted as time, which is your specified refresh time behind than current time.
This operator must be specified with the following filtering operators.
```text
"$gt", "$gte", "$eq", "$date"
```
Below is an example of query with a filtering operator:
```text
/kaa/logs_48635001004582290736/?filter={"header.timestamp.long":{"$gt":"$latest"}}
```
###REFRESH TIME
Specify an interval of refresh timer used to retrieve data and update Freeboard.

|
064c39e59ba8cad4816db7700141907a3c9f817f
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
Hitachi-Data-Systems/Freeboard-plugin-for-MongoDB
|
31b8c4c051e415ea4e22d1aaf771204451be5af3
|
336c45ed8ea50ef2c89c8c0d62f39926fe14d0f7
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import Input from '../Input/Input';
import Button from '../Button/Button';
import { FormattedMessage } from "react-intl";
import Close from '../Close/Close';
import './Form.css';
import Div from "../../Div/Div";
class Form extends Component {
// Registration popup
render() {
return (
<div style = {{display:this.props.display}}>
<div className="form" >
<h2>{<FormattedMessage id="addContact"/>}</h2>
<Close callback = {this.props.close} />
<div className="inp_edit">
<Input id="full" type="text" classLabel="label" text={<FormattedMessage id="fullName"/>} placeholder="Full Name" callback = {this.props.callback} val = {this.props.name}/>
<Input id="company" type="text" classLabel="label" text={<FormattedMessage id="company"/>} placeholder="Company Name" callback = {this.props.callback} val = {this.props.company}/>
<Input id="emailaddress" type="text" classLabel="label" text={<FormattedMessage id="email"/>} placeholder="Email" callback = {this.props.callback} val = {this.props.emailaddress}/>
<Input id="country" type="test" classLabel="label" text={<FormattedMessage id="counrty"/>} placeholder="Country" callback = {this.props.callback} val = {this.props.country}/>
<Input id="position" type="text" classLabel="label" text={<FormattedMessage id="position"/>} placeholder="Position" callback = {this.props.callback} val = {this.props.position}/>
</div>
<Div className = "warningText" display = {this.props.warningDisplay} name = {this.props.warningText}/>
<Button className={ "CB1 popupBtn" } name = {<FormattedMessage id="addContact"/>} click = {this.props.click }/>
</div>
</div>
);
}
}
export default Form;
<file_sep>export default {
en: {
"contacts":"Contacts",
"button.delete":"Delete Selected",
"addToMailList":"Add to Mail List",
"addContact": "Add Contact",
"sendEmail": "Send Email",
"createMailingList":"Create Mailing List",
"mailinglist": "Mailing List",
"select":"Select",
"fullName":"<NAME>",
"company":"Company Name",
"position":"Position",
"counrty":"Counrty",
"email":"Email",
"edit":"Edit",
"editContact":"Edit contact",
"delete":"Delete",
"selectTemplate":"Send Email",
"cancel":"Cancel",
"save":"Save",
"mailListName":"Name",
"deleteAll":"Delete All Selected Contacts?",
"deleteRow":"Delete Contact?",
"deleteList":"Delete Mailing List?",
"happyA":"Happy Anniversary!",
"happyBD":"Happy Birthday!",
"marryChristmas":"Merry Christmas!",
"messageEdit":"Please Enter Valid Text",
"emailSent": "Email has been sent",
"validEmail":"Please Enter Valid Email Address",
"template":"Please select template"
},
am: {
"contacts":"Կոնտակտներ",
"button.delete":"Ջնջել նշվածը",
"addToMailList":"Ավելացնել ցանկում",
"addContact": "Ավելացնել կոնտակտ",
"sendEmail": "Ուղղարկել",
"createMailingList":"Ստեղծել ցուցակ",
"mailinglist": "Փոստերի ցանկ",
"select": "Ընտրել",
"fullName":"<NAME>",
"company":"Աշխատավայր",
"position":"Պաշտոն",
"counrty":"Երկիր",
"email":"էլփոստ",
"edit":"Խմբագրել",
"editContact":"Խմբագրել կոնտակտը",
"delete":"Ջնջել",
"selectTemplate":"Ուղարկել Էլ-նամակ",
"cancel":"Չեղարկել",
"save":"Պահպանել",
"mailListName":"Անվանումը",
"deleteAll":"Ջնջել բոլոր ընտրվածները?",
"deleteRow":"Ջնջել տողը?",
"deleteList":"Ջնջել ցուցակը?",
"happyA":"Ուրախ տարեդարձ",
"happyBD":"Ծնունդդ շնորհավոր",
"marryChristmas":"Շնորհավոր Սուրբ Ծնունդ",
"messageEdit":"Մուտքագրեք վավեր տեքստ",
"emailSent": "էլ-նամակ ուղարկվել է",
"validEmail":"Մուտքագրեք վավեր էլ-փոստ",
"template":"Ընտրեք իրադարձությունը"
}
}<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import { Provider } from 'react-redux';
import { addLocaleData } from "react-intl";
import en from "react-intl/locale-data/en";
import am from "react-intl/locale-data/am";
import './index.css';
import App from './App';
import '../node_modules/font-awesome/css/font-awesome.min.css';
import * as serviceWorker from './serviceWorker';
import rootReducer from "./Redusers/rootReducer";
import { localeSet } from "./Actions/locale";
addLocaleData(en);
addLocaleData(am);
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
if (localStorage.alhubLang) {
store.dispatch(localeSet(localStorage.alhubLang))
}
ReactDOM.render(
<Provider store = {store}><App /></Provider>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
<file_sep>import React, { Component } from 'react';
import Input from '../Input/Input';
import Button from '../Button/Button';
import './MailingList.css';
class MailingListPopup extends Component {
render() {
return (
<div>
<div className="form">
<h1>New Mail List</h1>
<Input id="full" type="text" placeholder="New Mailist" callback = {this.callback}/>
<Button className= {"CB1 popupBtn"} name = "Create"/>
<Button className= {"CB1 popupBtn"} name = "Cencel"/>
</div>
</div>
);
}
}
export default MailingListPopup;<file_sep>import React, { Component } from 'react';
import './Close.css';
class Close extends Component {
callback = () => this.props.callback;
render() {
return (
<div className= "close" onClick = {this.props.callback}><i className="fa fa-times" aria-hidden="true"></i></div>
);
}
}
export default Close;
<file_sep>import React, { Component } from 'react';
import Input from '../Input/Input';
import Button from '../Button/Button';
import Close from '../Close/Close';
import './Edit.css';
class Edit extends Component {
state = {
display: ""
}
callback = () => this.props.callback;
close = () => {
this.setState({display:"none"})
}
// Edit popup
render() {
return (
<div className="popup" style = {{display:this.state.display}}>
<div className="form" style={{display:this.props.status1}}>
<Close callback = {this.close} />
<h1>Edit Contacts</h1>
<Input id="full" type="text" placeholder="<NAME>" callback = {this.callback}/>
<Input id="company" type="text" placeholder="Company Name" callback = {this.callback}/>
<Input id="emailaddress" type="text" placeholder="Email" callback = {this.callback}/>
<Input id="country" type="test" placeholder="Country" callback = {this.callback}/>
<Input id="position" type="text" placeholder="Position" callback = {this.callback}/>
<Button className= {"CB1 popupBtn"} name = "Save"/>
<Button className= {"CB1 popupBtn"} name = "Cencel"/>
</div>
</div>
);
}
}
export default Edit;<file_sep>import React, { Component } from 'react';
import './Input.css';
class Input extends Component {
callback = () => this.props.callback;
render() {
return (
<div className="w3-rest">
<label className={this.props.classLabel} >{this.props.text}</label>
<input value = {this.props.val} id={this.props.id} display = {this.props.display} className={this.props.class} type={this.props.type} placeholder={this.props.placeholder} required onChange = {this.props.callback}/>
</div>
);
}
}
export default Input;
<file_sep>import React, { Component } from 'react';
import Button from '../../TableComponents/Button/Button';
import Icon from '../../TableComponents/Icon/Icon';
import "./Main.css";
import { Link } from 'react-router-dom';
class MainPage extends Component {
state = {
onClick: true,
status: "none",
animation: "",
};
buttonActive = () => {
if (this.state.animation === "") {
this.setState({status: "inline-block"});
}
};
render() {
const buttons = [];
for (let i = 1; i <= 8; i++) {
if (i === 1) {
buttons.push(<Button className ="mailingList" key={i} move={`move${i}`} status = {this.state.status} name = {<Link className="mainA" to="/Mailinglist"><Icon id = {"iconColor"} className ="fa fa-envelope"/></Link>}></Button>);
}
else if (i === 5) {
buttons.push(<Button className ="contacts" key={i} move={`move${i}`} status = {this.state.status} name ={<Link className="mainA" to="/Contacts"><Icon id = {"iconColor"} className ="fa fa-users"/></Link>}></Button>);
}
else if (i < 5) {
buttons.push(<Button className ="otherBtns" key={i} move={`move${i}`} status = {this.state.status} name ={<Icon id = {"iconColor"} className ="fa fa-envelope"/>}></Button>);
}
else if (i > 5) {
buttons.push(<Button className ="otherBtns" key={i} move={`move${i}`} status = {this.state.status} name ={<Icon id = {"iconColor"} className ="fa fa-users"/>}></Button>);
}
}
return (
<div className="mainDiv">
{ buttons }
<button className="mainButton" style = {{animation: this.state.animation}} onClick={this.buttonActive}>CRM</button>
</div>
);
};
};
export default MainPage;<file_sep>import React, { Component } from 'react';
import './MailingList.css';
import '../tableContent/tableContent.css';
import { FormattedMessage } from "react-intl";
import Div from '../../Div/Div';
import Icon from '../Icon/Icon';
import Button from '../Button/Button';
import Overlay from "../Overlay/overlay";
class MailingList extends Component{
state = {
mailLists:[],
status:"none",
statusPopup:"none",
listOfContacts:"",
template: "",
emailId: "",
contactsList:"none",
listId: 0,
status3: "none",
delivery: "",
overStatus: "none",
status2: "none",
deleteId: "",
warningDisplay: "none",
warningText: "",
animation1: "none",
animation2: "none",
animation3: "none",
}
//remove from existing mail list
showDeletePopup = (e) => {
this.setState({status2: "block", deleteId: e.target.id})
}
removeFromMailList = () => {
fetch(`http://visual.istclabz.com:2112/api/emaillists/update?id=${this.state.listId}&flag=false`,{
method: 'PUT',
body: JSON.stringify([`${this.state.deleteId}`]
),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(() => this.setState({status2: "none", deleteId: ""}, () => this.getListData() ))
}
// Get List Data
getListData = () => {
fetch(`http://visual.istclabz.com:2112/api/emaillists?id=${this.state.listId}`)
.then((resp) => {return resp.json()})
.then((results) => {
this.setState({listOfContacts: results})
})
.then(() =>this.setState({contactsList: "block"}))
}
// showing list's contacts
showList = (e) => {
this.setState({listId: e.target.id},() => this.getListData() )
}
// close icon or cancel
close = () => {
if (this.state.status === "block") {
this.setState({status:"none"})
}
if (this.state.statusPopup === "block") {
this.setState({statusPopup:"none", template: "", warningDisplay: "none", warningText: "", animation1: "none", animation2: "none", animation3: "none"})
}
if (this.state.status2 === "block"){
this.setState({status2: "none", deleteId: ""})
}
}
// Send Email
popup = (e) => {
this.setState({statusPopup:"block", emailId: e.target.id})
}
//get template id during click
templateClick = (e) => {
switch (e.target.id) {
case "1":
this.setState({template: e.target.id, animation1: "glow 1.4s infinite alternate", animation2: "none", animation3: "none", warningDisplay: "none", warningText: ""})
break;
case "2":
this.setState({template: e.target.id, animation2: "glow 1.4s infinite alternate", animation1: "none", animation3: "none", warningDisplay: "none", warningText: ""})
break;
case "3":
this.setState({template: e.target.id, animation3: "glow 1.4s infinite alternate", animation1: "none", animation2: "none", warningDisplay: "none", warningText: ""})
break;
default:
break
}
}
//send email to
sendEmail = () => {
if (this.state.template) {
this.setState({statusPopup: "none", status3: "block", overStatus: "block"})
fetch(`http://visual.istclabz.com:2112/api/sendemails?template=${this.state.template}&emaillistId=${this.state.emailId}`, {
method: 'Post',
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(() => this.setState({emailId:"", template:"", delivery: <FormattedMessage id="emailSent"/>, overStatus: "none", warningDisplay: "none", warningText: "", animation1: "none", animation2: "none", animation3: "none"}))
.then(() =>{setTimeout(()=> {this.setState({delivery: "", status3: "none",})}, 2000)})
}
else this.setState({warningDisplay: "block", warningText: <FormattedMessage id="template"/>})
}
// Delete row
deleteRow = (e) => {
this.setState({listId: e.target.id,status:"block"});
}
//Delete mailing list
deleteList = () => {
fetch(`http://visual.istclabz.com:2112/api/emaillists?id=${this.state.listId}`,{
method: 'DELETE',
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(() =>this.setState({status: "none", listId:"", contactsList:"none"}))
}
// get email lists and show in page
componentDidMount(){
fetch('http://visual.istclabz.com:2112/api/emaillists')
.then((resp) => {return resp.json()})
.then((results) => {
this.setState({mailLists: results})
})
}
//refreshing after delete or add
componentDidUpdate(){
fetch('http://visual.istclabz.com:2112/api/emaillists')
.then((resp) => {return resp.json()})
.then((results) => {
this.setState({mailLists: results})
})
}
render(){
return(
<div className="mailing_list">
<div className= "mailList_section">
{this.state.mailLists.map((v,i) =>
<div key={i}>
<Div className = {"mailList_name"} name = {v.EmailListName} listId = {v.EmailListID} click = {this.showList}></Div>
<Div className = {"mailing_list_del"} click = {this.deleteRow} name = {<Icon className={"fa fa-trash" } id = {v.EmailListID}></Icon>} ></Div>
<Div className = {"mailing_list_arr"} click = {this.popup} name = {<Icon click = {this.popup} className={"fa fa-envelope-open-o"} id = {v.EmailListID}></Icon>} listId = {v.EmailListID}></Div>
</div>
)}
</div>
{/* Delete mailing list popup */}
<div className="form" style={{display:this.state.status}}>
<h3><FormattedMessage id="deleteList"/></h3>
<Button className={"CB1 popupBtn1"} click={this.deleteList} name = {<FormattedMessage id="delete"/>}/>
<Button className={"CB1 popupBtn1"} click={this.close} name = {<FormattedMessage id="cancel"/>}/>
</div>
{/* Choose template */}
<div className="popup" style={{display:this.state.statusPopup}}>
<div className="form">
<h3><FormattedMessage id="selectTemplate"/></h3>
<div className="event" style = {{animation: this.state.animation1}} onClick={this.templateClick} id = "1"><Icon click={this.templateClick} className={"fa fa-gift"} id = "1"/><span onClick={this.templateClick} id = "1"><FormattedMessage id="happyA"/></span></div>
<div className="event" style = {{animation: this.state.animation2}} onClick={this.templateClick} id = "2"><Icon click={this.templateClick} className={"fa fa-birthday-cake"} id = "2"/><span onClick={this.templateClick} id = "2"><FormattedMessage id="happyBD"/></span></div>
<div className="event" style = {{animation: this.state.animation3}} onClick={this.templateClick} id = "3"><Icon click={this.templateClick} className={"fa fa-tree"} id = "3"/><span onClick={this.templateClick} id = "3"><FormattedMessage id="marryChristmas"/></span></div>
<Div className = "warningText" display = {this.state.warningDisplay} name = {this.state.warningText}/>
<Button className={"CB1 popupBtn1"} click={this.sendEmail} name = {<FormattedMessage id="sendEmail"/>}/>
<Button className={"CB1 popupBtn1"} click={this.close} name = {<FormattedMessage id="cancel"/>}/>
</div>
</div>
<div style={{display:this.state.contactsList}} className="mailing_info">
<div className="table_box">
<div >
<div className="table_header">
<div className="header_name">{<FormattedMessage id="fullName"/>}</div>
<div className="header_name">{<FormattedMessage id="company"/>}</div>
<div className="header_name">{<FormattedMessage id="position"/>}</div>
<div className="header_name">{<FormattedMessage id="counrty"/>}</div>
<div className="header_name">{<FormattedMessage id="email"/>}</div>
<div className="header_btn1">{<FormattedMessage id="delete"/>}</div>
</div>
</div>
</div>
<div className="overflow_div">
{this.state.listOfContacts !== "" ? this.state.listOfContacts.Contacts.map((v,i) => {
return <div className="tbl_content" key={i}>
<div className="td_style_mail" style={{contenteditable:this.state.editTd}}>{v["Full Name"]}</div>
<div className="td_style_mail" style={{contenteditable:this.state.editTd}}>{v["Company Name"]}</div>
<div className="td_style_mail" style={{contenteditable:this.state.editTd}}>{v.Position}</div>
<div className="td_style_mail" style={{contenteditable:this.state.editTd}}>{v.Country}</div>
<div className="td_style_mail" style={{contenteditable:this.state.editTd}}>{v.Email}</div>
<div className="del_icon" onClick = {this.showDeletePopup}><Icon className="fa fa-trash" aria-hidden="true" id = {v.GuID} ></Icon></div>
</div>
}
): null }
</div>
</div>
{/*Loading Popup*/}
<div className="popup" style={{display:this.state.status3}}>
<Overlay status = {this.state.overStatus}/>
<h3 className = "delivery">{this.state.delivery}</h3>
</div>
{/* Delete Popup */}
<div className="popup" style={{display:this.state.status2}}>
<div className="form">
<h3>{<FormattedMessage id="deleteRow"/>}</h3>
<Button className={"CB1 popupBtn1"} click={this.removeFromMailList} name = {<FormattedMessage id="delete"/>}/>
<Button className={"CB1 popupBtn1"} click={this.close} name = {<FormattedMessage id="cancel"/>}/>
</div>
</div>
</div>
);
}
}
export default MailingList;<file_sep>import React, {Component, Fragment} from "react";
import './Icon.css'
class Icon extends Component{
render () {
return (
<Fragment>
<i className = {this.props.className} id = {this.props.id}></i>
</Fragment>
);
}
}
export default Icon;<file_sep>[LocalizedFileNames]
[email protected],0
<file_sep>import React, {Component, Fragment} from "react";
import './Div.css'
class Div extends Component{
render () {
return (
<Fragment>
<div className = {this.props.className} id = {this.props.listId} style = {this.props.style} onClick = {this.props.click} text = {this.props.text}>{this.props.name}</div>
</Fragment>
);
}
}
export default Div;<file_sep>import React, {Component} from 'react';
import './HeaderButton.css'
import SelectTemplate from '../Header/selectTemplate/selectTemplate';
import Button from '../Button/Button'
import Form from '../Forms/Form';
class HeaderButton extends Component {
state = {
status: "none"
}
addContact = ()=>{
this.setState({status: "block"})
}
callback = () => this.props.callback;
render() {
return (
<div className="btnBox">
<Form status = {this.state.status} />
<SelectTemplate/>
<Button name={"Send Email"} className= "CB1">
<i className="fa fa-envelope" aria-hidden="true"></i><br />Send Email
</Button>
<Button name={"Add to Mail List"} className= "CB1">
<i className="fa fa-folder-open" aria-hidden="true"></i>
</Button>
<Button name={"Delete Selected"} className= "CB1">
<i className="fa fa-trash-o" aria-hidden="true"></i><br />Delete Selected
</Button>
<Button name={"Add to Contact"} className= "CB1" click = {this.addContact}>
<i className="fa fa-user-plus" aria-hidden="true"></i><br />Add Contact
</Button>
<Button name={"Create Mailing List"} className= "CB1">
<i className="fa fa-list-alt" aria-hidden="true"></i><br />Create Mailing list
</Button>
<Button name={"Upload"} className= "CB1" >
<i className="fa fa-cloud-upload" aria-hidden="true"></i><br />Upload
</Button>
</div>
);
}
}
export default HeaderButton ;
|
27c173e451410d9747412a813015c3f3db61b0d0
|
[
"JavaScript",
"INI"
] | 13 |
JavaScript
|
Gayahov/CRM_System
|
88ba90745fc7fd37dfaf7987de917f55a7a91836
|
0dcb662231d781f7c30218a81c2e806e292b0112
|
refs/heads/master
|
<file_sep>/**
* physics.js
*
* @fileoverview Manages all physics related features, including forces,
* displacements, and collision detection.
* @author <NAME> <<EMAIL>>
*/
/** Velocity of airplane */
var velocity = vec3.create();
var AIRPLANE_HEIGHT = 0.0000;
/** Current thrust */
var thrust = 0;
/** Whether reverse thrust is turned on */
var reverse = false;
/** Whether airplane is on the ground (as opposed to being in the air). */
var ground = true;
/** Whether the game is stil playing (as opposed to gameover or winning). */
var playing = true;
/** Gravity */
var GRAVITY = 0.002;
/** Drag force coefficient (see getDragForce()) */
var DRAG_FORCE_COEFF = 0.0883883;
/** Drag force power (see getDragForce()) */
var DRAG_FORCE_POWER = 1.5;
/** Drag force threshold (see getDragForce()) */
var DRAG_FORCE_THRESHOLD = 0.000001;
/** Lift force coefficient (see getLiftForce()) */
var LIFT_FORCE_COEFF = 0.1;
/** Lift force multipier according to pitch keypresses. (see getLiftForce()) */
var LIFT_PITCH_COEFF = [0.4,1.0,1.6];
/** Acceleration coefficient (see getThrustForce()) */
var ACCELERATION_COEFF = 1.2e-3;
/** Roll change rate in reponse to roll keypresses. */
var ROLL_CHANGE_RATE = 2.0e-3;
/** Yaw change rate in reponse to roll keypresses. */
var YAW_CHANGE_RATE = 0.1;
/** Velocity threshold to judge whether crashing on land. */
var CRASH_ON_LAND_VELOCITY_THRESHOLD = 0.025;
/** Pitch threshold to judge whether crashing on land. */
var CRASH_ON_LAND_PITCH_THRESHOLD = degToRad(20);
/** Roll threshold to judge whether crashing on land. */
var CRASH_ON_LAND_ROLL_THRESHOLD = degToRad(20);
/** Threshold to judge whether crashing into the mountains */
var CRASH_ON_MOUNTAIN_THRESHOLD = 0.01;
/** Threshold to judge whether crashing into the walls. */
var CRASH_ON_WALL_THRESHOLD = 0.1;
/** Initialization of hysics.js */
function physicsInit(){
}
/** Update physics data.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdate(lapse){
physicsUpdatePosition(lapse);
physicsUpdateVelocity(lapse);
physicsCheckCrashes();
physicsCheckGround();
physicsUpdateRoll(lapse);
physicsUpdateLookAt();
}
/** Update airplane location based on velocity.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdatePosition(lapse){
var viewOriginChange = vec3.clone(velocity);
vec3.scale(viewOriginChange, viewOriginChange, lapse);
vec3.add(viewOrigin, viewOrigin, viewOriginChange);
}
function physicsUpdatePositions(lapse){
var viewOriginChange = vec3.clone(velocity);
console.log(velocity);
}
/** Update airplane velocity based on forces.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdateVelocity(lapse){
/** Apply lift force (along z-axis and left-right direction). */
var liftVelocityChange = vec3.create();
var liftDirection = vec3.fromValues(viewLookAt[0],viewLookAt[1],0.0);
vec3.normalize(liftDirection, liftDirection);
vec3.scale(liftDirection, liftDirection, vec3.dot(liftDirection, viewUp));
vec3.subtract(liftDirection, viewUp, liftDirection);
vec3.normalize(liftDirection, liftDirection);
vec3.scale(liftVelocityChange, liftDirection, getLiftForce()*lapse);
/** Apply thrust force (along lookAt direction). */
var thrustVelocityChange = vec3.create();
vec3.scale(thrustVelocityChange, viewLookAt, getThrustForce()*lapse);
/** Apply drag force (along negative lookAt direction). */
var dragVelocityChange = vec3.create();
vec3.scale(dragVelocityChange, viewLookAt, -getDragForce()*lapse);
/** Apply gravity (along z-axis). */
velocity[2] -= GRAVITY * lapse;
vec3.add(velocity, velocity, thrustVelocityChange);
vec3.add(velocity, velocity, liftVelocityChange);
vec3.add(velocity, velocity, dragVelocityChange);
}
/** Update lookAt direction to match velocity direction. */
function physicsUpdateLookAt(){
/** Quaternion change to apply. */
var quatChange = quat.create();
/** Velocity direction. */
var normalizedVelocity = vec3.create();
/** Update only when velocity is not zero. */
if(vec3.length(velocity) >= 0.000001){
vec3.normalize(normalizedVelocity, velocity);
/** If moving backwards, match lookAt to opposite of velocity direction. */
if(vec3.dot(viewLookAt, normalizedVelocity) < 0){
vec3.negate(normalizedVelocity, normalizedVelocity);
}
/** Apply quaternion change. */
quat.rotationTo(quatChange, viewLookAt, normalizedVelocity);
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}
/** If on the ground, eliminate roll. */
if(ground){
vec3.transformQuat(viewUp, VIEW_UP_INIT, viewQuat);
vec3.transformQuat(viewLookAt, VIEW_LOOKAT_INIT, viewQuat);
vec3.transformQuat(viewRight, VIEW_RIGHT_INIT, viewQuat);
quat.setAxisAngle(quatChange, viewLookAt, -getRoll());
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}
}
/** Check if airplane is on the ground. */
function physicsCheckGround(){
/** If was on the ground... */
if(ground){
/** If vertical velocity is positive (i.e. gravity is overcome), fly! */
if(velocity[2] > 0.0){
ground = false;
}else
/** If airplane is still on the land, clear vertical velocity and set
* airplane location right on the ground (not under the ground).
*/
if(physicsCheckAboveLand()){
velocity[2] = 0;
viewOrigin[2] = AIRPLANE_HEIGHT;
}else
{
/** If airplane is NOT on the land, fall into the ocean. */
ground = false;
}
}else{
/** If was in the air, check if airplane has landed. */
if(physicsCheckAboveLand() && viewOrigin[2] <= AIRPLANE_HEIGHT){
velocity[2] = 0;
viewOrigin[2] = AIRPLANE_HEIGHT;
ground = true;
}
}
}
/** Helper functino to check whether airplane is above the land or above the
* ocean.
*/
function physicsCheckAboveLand(){
return viewOrigin[0] >= -1.0 && viewOrigin[0] < 1.0 && viewOrigin[1] >= -1.0 && viewOrigin[1] < 1.0;
}
/** Check if gameover or winning. */
function physicsCheckCrashes(){
physicsCheckCrashOcean();
physicsCheckCrashLand();
physicsCheckCrashMountain();
physicsCheckCrashWall();
physicsCheckCrashObstacle();
physicsCheckNoFuel();
physicsCheckWin();
}
/** Check if airplane crashes into ocean. */
function physicsCheckCrashOcean(){
if(!physicsCheckAboveLand() && (viewOrigin[2] <= 0.0 || airplaneTip[2] <= 0.0)){
viewOrigin[2] = AIRPLANE_HEIGHT;
gameover("GAMEOVER! You crashed into the ocean. Press R to restart.");
}
}
/** Check if airplane crashes on land. */
function physicsCheckCrashLand(){
if(ground === false && viewOrigin[2] <= AIRPLANE_HEIGHT &&
(velocity[2] <= -CRASH_ON_LAND_VELOCITY_THRESHOLD ||
Math.abs(getRoll()) >= CRASH_ON_LAND_ROLL_THRESHOLD ||
Math.abs(getPitch()) >= CRASH_ON_LAND_PITCH_THRESHOLD ) ){
gameover("GAMEOVER! You crashed on land. Press R to restart.");
}
}
/** Check if airplane crashes into mountains. */
function physicsCheckCrashMountain(){
if(terrainReady && physicsCheckAboveLand()){
/** Distance between adjacent terrain vertices */
var stride = 2.0 / (TERRAIN_SIZE - 1);
/** Row and column index airplane is at */
var col = Math.floor((airplaneTip[0] + 1.0) / stride);
var row = Math.floor((airplaneTip[1] + 1.0) / stride);
/** X and Y distances to vertex */
var dx = (airplaneTip[0] + 1.0) / stride - col;
var dy = (airplaneTip[1] + 1.0) / stride - row;
/** Calculate the height of terrain where airplane is at. */
var gradientX;
var gradientY;
var z;
/** Check lower or upper triangle. */
if(dx + dy <= 1.0){
gradientX = terrainPositionArray[terrainIndex(row, col+1) + 2] - terrainPositionArray[terrainIndex(row, col) + 2];
gradientY = terrainPositionArray[terrainIndex(row+1, col) + 2] - terrainPositionArray[terrainIndex(row, col) + 2];
z = terrainPositionArray[terrainIndex(row, col) + 2] + dx * gradientX + dy * gradientY;
}else{
gradientX = terrainPositionArray[terrainIndex(row+1, col+1) + 2] - terrainPositionArray[terrainIndex(row+1, col) + 2];
gradientY = terrainPositionArray[terrainIndex(row+1, col+1) + 2] - terrainPositionArray[terrainIndex(row, col+1) + 2];
z = terrainPositionArray[terrainIndex(row+1, col+1) + 2] + (1.0 - dx) * gradientX + (1.0 - dy) * gradientY;
}
/** Check if airplane is below terrain. */
if(airplaneTip[2] < z - CRASH_ON_MOUNTAIN_THRESHOLD){
gameover("GAMEOVER! You crashed into the mountains. Press R to restart.");
}
}
}
/** Check if airplane tries to bypass mountains. */
function physicsCheckCrashWall(){
if(( viewOrigin[0] < -(1.0 + CRASH_ON_WALL_THRESHOLD) ||
viewOrigin[0] > 1.0 + CRASH_ON_WALL_THRESHOLD )
&& viewOrigin[1] < 0.0 && airplaneTip[1] > 0.0){
gameover("GAMEOVER! You cannot fly by the mountains. Press R to restart.");
}
}
/** Check if airplane crashes into obstacles. */
function physicsCheckCrashObstacle(){
/** Check only when obstacles are enabled. */
if(obstacleLevel !== 0){
var collision = false;
/** Iterate through all obstacles. */
for(var i = 0; i < OBSTACLE_COUNT; i++){
/** Assume obstacle is cylinder with radius r and height h. */
var r = 0.3 * OBSTACLE_SCALE[0];
var h = 1.1 * OBSTACLE_SCALE[1];
/** Location of obstacle */
var o = vec3.clone(obstacleOrigin[i]);
/** Get the two center coordinates of the two bottoms of cylinder. */
var angle = obstacleAngle[i];
var a = vec3.fromValues(o[0] - h * Math.sin(angle), o[1] + h * Math.cos(angle), o[2]);
var b = vec3.fromValues(o[0] + h * Math.sin(angle), o[1] - h * Math.cos(angle), o[2]);
/** Get coordinates of airplane tip. */
var x = vec3.clone(airplaneTip);
/** Check if x is in the cylinder. */
var ba = vec3.create();
vec3.subtract(ba, b, a);
vec3.normalize(ba, ba);
var xa = vec3.create();
vec3.subtract(xa, x, a);
var d = vec3.create();
vec3.cross(d, xa, ba);
if(vec3.dot(xa,ba) > 0 && vec3.dot(xa,ba) < h*2 && vec3.length(d) < r){
collision = true;
}
}
/** If there is collision, gameover. */
if(collision){
gameover("GAMEOVER! You crashed into another aircraft. Press R to restart.");
}
}
}
/** Check if timeout. */
function physicsCheckNoFuel(){
if(Date.now() - startTime >= TIMEOUT){
gameover("GAMEOVER! You ran out of fuel. Press R to restart.");
}
}
/** Check if wins. */
function physicsCheckWin(){
if(ground && viewOrigin[0] >= -0.003 && viewOrigin[0] <= 0.003
&& viewOrigin[1] >= 0.9 && viewOrigin[1] <= 1.0
&& getHorizontalVelocity() <= 0.002){
gameover("You WIN!!!!!!! Congratulations!");
}
}
/** Update roll or yaw in reaction to keypresses. */
function physicsUpdateRoll(lapse){
/** If in the air, modify roll. */
if(!ground){
var quatChange = quat.create();
if (currentlyPressedKeys[37] || currentlyPressedKeys[65]) {
/** Roll leftwards when Left-arrow or A is pressed. */
quat.setAxisAngle(quatChange, viewLookAt, -ROLL_CHANGE_RATE);
} else if (currentlyPressedKeys[39] || currentlyPressedKeys[68]) {
/** Roll rightwards when Right-arrow or D is pressed. */
quat.setAxisAngle(quatChange, viewLookAt, ROLL_CHANGE_RATE);
}
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}else{
/** If on the ground, modify yaw. */
if (currentlyPressedKeys[37] || currentlyPressedKeys[65]) {
/** Turn left when Left-arrow or A is pressed. */
vec3.rotateZ(velocity, velocity, vec3.create(), YAW_CHANGE_RATE*lapse);
} else if (currentlyPressedKeys[39] || currentlyPressedKeys[68]) {
/** Turn rigt when Right-arrow or D is pressed. */
vec3.rotateZ(velocity, velocity, vec3.create(), -YAW_CHANGE_RATE*lapse);
}
}
}
/** Calculate lift force.
* @return {float} liftForce
*/
function getLiftForce(){
/** Lift force = KEY_COEFF * LIFT_FORCE_COEFF * horizontal velocity */
if (currentlyPressedKeys[38] || currentlyPressedKeys[87]) {
/** More lift force when Up-arrow or W is pressed. */
return LIFT_PITCH_COEFF[2] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}else if (currentlyPressedKeys[40] || currentlyPressedKeys[83]) {
/** Less lift force when Down-arrow or S is pressed. */
return LIFT_PITCH_COEFF[0] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}else{
/** Default lift force. */
return LIFT_PITCH_COEFF[1] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}
}
/** Calculate thrust force.
* @return {float} thrustForce
*/
function getThrustForce(){
/** Thrust force = thrust * ACCELERATION_COEFF */
return thrust * ACCELERATION_COEFF;
}
function getThrustForces(){
/** Thrust force = thrust * ACCELERATION_COEFF */
console.log(thrust * ACCELERATION_COEFF);
}
/** Calculate drag force.
* @return {float} dragForce
*/
function getDragForce(){
/** Drag force = DRAG_FORCE_COEFF * (velocity)^(DRAG_FORCE_POWER) */
/** If velocity if too small, no drag force. */
if(vec3.length(velocity) > DRAG_FORCE_THRESHOLD){
return DRAG_FORCE_COEFF * Math.pow(vec3.length(velocity), DRAG_FORCE_POWER);
}else{
return 0;
}
}
function getLiftForces(){
/** Lift force = KEY_COEFF * LIFT_FORCE_COEFF * horizontal velocity */
if (currentlyPressedKeys[38] || currentlyPressedKeys[87]) {
/** More lift force when Up-arrow or W is pressed. */
console.log(LIFT_PITCH_COEFF[2] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}else if (currentlyPressedKeys[40] || currentlyPressedKeys[83]) {
/** Less lift force when Down-arrow or S is pressed. */
console.log(LIFT_PITCH_COEFF[0] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}else{
/** Default lift force. */
console.log(LIFT_PITCH_COEFF[1] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}
}
/** Check if airplane crashes into obstacles. */
function physicsCheckCrashObstacles(){
if(ground === false && viewOrigin[2] <= AIRPLANE_HEIGHT){
console.log("Stopped");
}
}
function getDragForces(){
/** Drag force = DRAG_FORCE_COEFF * (velocity)^(DRAG_FORCE_POWER) */
/** If velocity if too small, no drag force. */
if(vec3.length(velocity) > DRAG_FORCE_THRESHOLD){
return DRAG_FORCE_COEFF * Math.pow(vec3.length(velocity), DRAG_FORCE_POWER);
}else{
return 0;
}
}
function initPerformanceTab(mainViewer) {
const COLOR_PALETTE = [];
for (let i = 8; i > 0; i--) {
COLOR_PALETTE.push({
r: Math.floor(Math.random() * 255),
g: Math.floor(Math.random() * 255),
b: Math.floor(Math.random() * 255)
});
}
const temperatures = new Float32Array(1500);
const ALERTS_STORAGE_KEY = 'alert-config';
const alerts = JSON.parse(localStorage.getItem(ALERTS_STORAGE_KEY) || '{}');
const needle = document.getElementById('gauge-needle');
var dbid = 10; // random number to start with
/*
alerts = {
<partId>: {
temperature: {
max: <number>
}
}
};
*/
function updateTemperatures(chart) {
//update part bar chart
// chart.data.datasets[0].data = [12, 19, 3, 5, 2, 3].map(i => Math.floor(Math.random() * 100))
/*
// Generate new temperatures for each partId from 1 to 1500
for (let i = 0, len = temperatures.length; i < len; i++) {
temperatures[i] = 90.0 + Math.random() * 20.0;
}
// Trigger alerts if any part temperature exceed preconfigured limit
Object.keys(alerts).forEach(function(partId) {
const alert = alerts[partId];
const temp = temperatures[partId];
if (alert && alert.temperature && temp > alert.temperature.max) {
// console.log(`Part ${partId} temperature ${temp} exceeded limit ${alert.temperature.max}!`);
mainViewer.setThemingColor(partId, new THREE.Vector4(1.0, 0.0, 0.0, 0.99));
setTimeout(function() {
// TODO: revert to original theming color if there was one
mainViewer.setThemingColor(partId, new THREE.Vector4(1.0, 0.0, 0.0, 0.0));
}, 500);
}
});
*/
// update temperature gauge
needle.setAttribute('transform', `rotate(${dbid+Math.floor(Math.random() * 10)}, 100, 100)`);
}
function createEngineSpeedChart() {
const ctx = document.getElementById('engine-speed-chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Speed [rpm]',
borderColor: 'rgba(255, 196, 0, 1.0)',
backgroundColor: 'rgba(255, 196, 0, 0.5)',
data: []
}]
},
options: {
scales: {
xAxes: [{ type: 'realtime', realtime: { delay: 2000 } }],
yAxes: [{ ticks: { beginAtZero: true } }]
}
}
});
return chart;
}
function createHeightChart() {
const ctx = document.getElementById('height').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Km/hr [m]',
borderColor: 'rgba(255, 196, 0, 1.0)',
backgroundColor: 'rgba(255, 196, 0, 0.5)',
data: []
}]
},
options: {
scales: {
xAxes: [{ type: 'realtime', realtime: { delay: 2000 } }],
yAxes: [{ ticks: { beginAtZero: true } }]
}
}
});
return chart;
}
function createEngineVibrationsChart() {
const ctx = document.getElementById('engine-vibrations-chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Min [mm/s]',
borderColor: 'rgba(255, 192, 0, 1.0)',
backgroundColor: 'rgba(255, 192, 0, 0.5)',
data: []
},{
label: 'Avg [mm/s]',
borderColor: 'rgba(192, 128, 0, 1.0)',
backgroundColor: 'rgba(192, 128, 0, 0.5)',
data: []
},{
label: 'Max [mm/s]',
borderColor: 'rgba(128, 64, 0, 1.0)',
backgroundColor: 'rgba(128, 64, 0, 0.5)',
data: []
}]
},
options: {
scales: {
xAxes: [{ type: 'realtime', realtime: { delay: 2000 } }],
yAxes: [{ ticks: { beginAtZero: true } }]
}
}
});
return chart;
}
function createPartTemperaturesChart() {
const ctx = document.getElementById('part-temperatures-chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [{
label: 'Avg. Temp.',
data: [12, 19, 3, 5, 2, 3].map(i => Math.floor(Math.random() * 100)),
backgroundColor: [
'rgba(192, 128, 0, 0.5)',
'rgba(192, 128, 0, 0.5)',
'rgba(192, 128, 0, 0.5)',
'rgba(192, 128, 0, 0.5)',
'rgba(192, 128, 0, 0.5)',
'rgba(192, 128, 0, 0.5)'
],
borderColor: [
'rgba(192, 128, 0, 1.0)',
'rgba(192, 128, 0, 1.0)',
'rgba(192, 128, 0, 1.0)',
'rgba(192, 128, 0, 1.0)',
'rgba(192, 128, 0, 1.0)',
'rgba(192, 128, 0, 1.0)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
return chart;
}
function refreshEngineSpeed(chart) {
chart.data.datasets[0].data.push({
x: Date.now(),
y: 9750.0 + Math.random() * 500.0
});
}
function refreshHeight(chart) {
chart.data.datasets[0].data.push({
x: Date.now(),
y: asdf()
});
}
function refreshEngineVibrations(chart) {
console.log("minVibration"+getLiftForces() * 1000);
const date = Date.now();
const minVibration = 2.0 + getLiftForces() * 5000;
const maxVibration = minVibration + getLiftForces() * 5000;
console.log("minVibration"+minVibration);
console.log("minVibration"+maxVibration);
chart.data.datasets[0].data.push({ x: date, y: minVibration });
chart.data.datasets[1].data.push({ x: date, y: 0.5 * (minVibration + maxVibration) });
chart.data.datasets[2].data.push({ x: date, y: maxVibration });
}
function updateTemperatureAlertForm(partIds) {
$form = $('#temperature-alert-form');
if (!partIds || partIds.length !== 1) {
$form.fadeOut();
} else {
$('#temperature-alert-part').val(partIds[0]);
const config = alerts[partIds[0]];
if (config && config.temperature && config.temperature.max) {
$('#temperature-alert-max').val(config.temperature.max);
} else {
$('#temperature-alert-max').val('');
}
$form.fadeIn();
}
}
const engineSpeedChart = createEngineSpeedChart();
const heightChart = createHeightChart();
const engineVibrationsChart = createEngineVibrationsChart();
const partTemperaturesChart = createPartTemperaturesChart();
const $partCurrentTemperature = $('#part-current-temperature');
const $partTemperatureChart = $('#part-temperatures-chart');
const $partSelectionAlert = $('#performance-part div.alert');
mainViewer.addEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, function(ev) {
const ids = mainViewer.getSelection();
if (ids.length === 1) {
dbid = ids[0];
// Generate a set of random temperatures (between 95.0 and 105.0) with dbId as seed
let rng = new RandomNumberGenerator(dbid);
let temperatures = [];
for (let i = 0; i < 6; i++) {
temperatures.push(95.0 + rng.nextFloat() * 10.0);
}
partTemperaturesChart.data.datasets[0].data = temperatures;
partTemperaturesChart.update();
$partCurrentTemperature.show();
$partTemperatureChart.show();
$partSelectionAlert.hide();
} else {
$partCurrentTemperature.hide();
$partTemperatureChart.hide();
$partSelectionAlert.show();
}
});
$partCurrentTemperature.hide();
$partTemperatureChart.hide();
$partSelectionAlert.show();
$('#temperature-alert-form button.btn-primary').on('click', function(ev) {
const partId = parseInt($('#temperature-alert-part').val());
const tempMax = parseFloat($('#temperature-alert-max').val());
alerts[partId] = alerts[partId] || {};
alerts[partId].temperature = alerts[partId].temperature || {};
alerts[partId].temperature.max = tempMax;
window.localStorage.setItem(ALERTS_STORAGE_KEY, JSON.stringify(alerts));
updateTemperatureAlertForm([partId]);
ev.preventDefault();
});
$('#temperature-alert-form button.btn-secondary').on('click', function(ev) {
const partId = $('#temperature-alert-part').val();
delete alerts[partId];
window.localStorage.setItem(ALERTS_STORAGE_KEY, JSON.stringify(alerts));
updateTemperatureAlertForm([partId]);
ev.preventDefault();
});
setInterval(function() {
updateTemperatures();
refreshEngineSpeed(engineSpeedChart);
refreshHeight(heightChart);
refreshEngineVibrations(engineVibrationsChart);
}, 1000);
updateTemperatureAlertForm();
}
function getHorizontalVelocity(){
console.log("vel"+velocity);
return Math.sqrt(velocity[0] * velocity[0] + velocity[1] * velocity[1]);
}
function asdf() {
/** Set values of interfaces. */
var velocity = getIfVelocityOppositeToLookat() ? -getHorizontalVelocity() : getHorizontalVelocity();
interfaces.velocity.set( velocity );
values.velocity.nodeValue = (velocity*10000).toFixed(2) + " knots";
interfaces.fuel.set( 1.0 - ( Date.now() - startTime ) / TIMEOUT );
values.fuel.nodeValue = ((1.0 - ( Date.now() - startTime ) / TIMEOUT)*100).toFixed(2) + "%";
interfaces.roll.set( getRoll() );
values.roll.nodeValue = (getRoll()>=0?"+":"") + radToDeg(getRoll()).toFixed(2) + " deg";
interfaces.pitch.set( getPitch() );
values.pitch.nodeValue = (getPitch()>=0?"+":"") + radToDeg(getPitch()).toFixed(2) + " deg";
interfaces.height.set( viewOrigin[2] );
values.height.nodeValue = (viewOrigin[2]*10000).toFixed(2);
return values.height.nodeValue;
/** Increment/decrement thrust if necessary. */
if(currentlyPressedKeys[88] || currentlyPressedKeys[76]){
/** If X or L is pressed. */
interfaces.thrust.set( parseFloat(interfaces.thrust.get()) + 5 );
}else if(currentlyPressedKeys[90] || currentlyPressedKeys[75]){
/** If Z or K is pressed. */
interfaces.thrust.set( parseFloat(interfaces.thrust.get()) - 5 );
}
/** Calculate and update thrust based on slider value. */
thrust = parseFloat(interfaces.thrust.get()) / 1000 * (reverse ? (getIfVelocityOppositeToLookat() ? -0.2 : -1.6) : 1.0);
values.thrust.nodeValue = (thrust>=0?"+":"-") + (parseFloat(interfaces.thrust.get())/10.0).toFixed(1) + "%";
/** Update compass' location and direction. */
interfaces.orientation.style.transform = "rotate(" + radToDeg( getOrientation() ) + "deg)";
interfaces.orientation.style.left = ((viewOrigin[0]+1.0)/2.0*200-12) + "px";
interfaces.orientation.style.top = ((1.0-viewOrigin[1])/2.0*200-12) + "px";
/** Update obstacles' locations and directions. */
for(var i = 0; i < OBSTACLE_COUNT; i++){
airplaneIcons[i].style.transform = "rotate(" + (-radToDeg( obstacleAngle[i] )) + "deg)";
airplaneIcons[i].style.left = ((obstacleOrigin[i][0]+1.0)/2.0*200-8) + "px";
airplaneIcons[i].style.top = ((1.0-obstacleOrigin[i][1])/2.0*200-8) + "px";
}
}<file_sep>
setInterval(getCookie,2000);
function getCookie() {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape('start') + '=([^;]*)'));
if(match ? match[1] : null){
document.getElementById('sidebar').style.display = "block";
document.getElementById('content').style.display = "none";
}
console.log(match ? match[1] : null);
}
setInterval(getCookies,2000);
function getCookies() {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };
var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape('stop') + '=([^;]*)'));
if(match ? match[1] : null){
document.getElementById('sidebar').style.display = "none";
document.getElementById('content-after').style.display = "block";
}
console.log(match ? match[1] : null);
}<file_sep>
/** Currently pressed keys. True if pressed, otherwise not pressed. */
var currentlyPressedKeys = {};
/** Hold interface elements. */
var interfaces = {};
/** Hold text nodes of interface elements. */
var values = {};
/** Hold elements of airplane icons. */
var airplaneIcons = [];
/** Hold the text node of message board. */
var msgDOM;
/** Time limit of each game in ms. */
var TIMEOUT = 900 * 1000;
/** Initialize interfaces. */
function interfaceInit(){
/** Attach key event listeners. */
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
/* Initialize gauges. */
interfaces.velocity = new Gauge( document.getElementById("velocityGaugeCanvas") ).setOptions({ limitMax: 'true' });
interfaces.velocity.maxValue = 0.04;
interfaces.velocity.animationSpeed = 1;
interfaces.velocity.set(0);
values.velocity = document.getElementById("velocityGaugeValue").firstChild;
interfaces.fuel = new Gauge( document.getElementById("fuelGaugeCanvas") ).setOptions({ limitMax: 'true' });
interfaces.fuel.maxValue = 1;
interfaces.fuel.animationSpeed = 1;
interfaces.fuel.set(1);
values.fuel = document.getElementById("fuelGaugeValue").firstChild;
/** Initialize compass. */
interfaces.orientation = document.getElementById("orientationCompass")
/** Initialize sliders. */
interfaces.roll = noUiSlider.create(document.getElementById("rollSlider"),
{ start: [0],
range:
{ 'min': [ -Math.PI / 2 ],
'max': [ Math.PI / 2 ]
},
connect: [true, false],
animate: false
});
values.roll = document.getElementById("rollSliderValue").firstChild;
interfaces.pitch = noUiSlider.create(document.getElementById("pitchSlider"),
{ start: [0],
range:
{ 'min': [ -Math.PI / 6 ],
'max': [ Math.PI / 6 ]
},
connect: [true, false],
orientation: "vertical",
direction: 'rtl',
animate: false
});
values.pitch = document.getElementById("pitchSliderValue").firstChild;
interfaces.height = noUiSlider.create(document.getElementById("heightSlider"),
{ start: [0],
range:
{ 'min': [ 0.0 ],
'max': [ 1.0 ]
},
connect: [true, false],
orientation: "vertical",
direction: 'rtl',
animate: false
});
console.log(`interfaces.height:${interfaces.height}`);
values.height = document.getElementById("heightSliderValue").firstChild;
interfaces.thrust = noUiSlider.create(document.getElementById("thrustSlider"),
{ start: [0],
range:
{ 'min': [ 0 ],
'max': [ 1000 ]
},
step: 1,
connect: [true, false],
orientation: "vertical",
direction: 'rtl',
animate: false
});
values.thrust = document.getElementById("thrustSliderValue").firstChild;
/** Create airplane icons for obstacles. */
for(var i = 0; i < OBSTACLE_COUNT; i++){
var newDOM = document.createElement("img");
newDOM.src = "https://maxcdn.icons8.com/office/PNG/16/Transport/airport-16.png";
newDOM.width = 16;
newDOM.style.position = "absolute";
newDOM.style.zIndex = 10;
newDOM.style.visibility = "hidden";
document.getElementById("positionDOM").appendChild(newDOM);
airplaneIcons.push(newDOM);
}
}
/**
* Handle key presses.
* @param {event object} event
*/
function handleKeyDown(event) {
currentlyPressedKeys[event.keyCode] = true;
/** Toggle thrust if C or J is pressed. */
if(event.keyCode == 67 || event.keyCode == 74){
reverse = !reverse;
var button = document.getElementById("reverseButton");
button.style.borderStyle = (button.style.borderStyle!=='inset' ? 'inset' : 'outset');
}
}
/**
* Handle key releases.
* @param {event object} event
*/
function handleKeyUp(event) {
currentlyPressedKeys[event.keyCode] = false;
}
/** Update the interface. */
function interfaceUpdate() {
/** Set values of interfaces. */
var velocity = getIfVelocityOppositeToLookat() ? -getHorizontalVelocity() : getHorizontalVelocity();
interfaces.velocity.set( velocity );
values.velocity.nodeValue = (velocity*10000).toFixed(2) + " knots";
interfaces.fuel.set( 1.0 - ( Date.now() - startTime ) / TIMEOUT );
values.fuel.nodeValue = ((1.0 - ( Date.now() - startTime ) / TIMEOUT)*100).toFixed(2) + "%";
interfaces.roll.set( getRoll() );
values.roll.nodeValue = (getRoll()>=0?"+":"") + radToDeg(getRoll()).toFixed(2) + " deg";
interfaces.pitch.set( getPitch() );
values.pitch.nodeValue = (getPitch()>=0?"+":"") + radToDeg(getPitch()).toFixed(2) + " deg";
interfaces.height.set( viewOrigin[2] );
values.height.nodeValue = (viewOrigin[2]*10000).toFixed(2) + " feet";
console.log(`interfaces.heights:${values.height.nodeValue}`);
/** Increment/decrement thrust if necessary. */
if(currentlyPressedKeys[88] || currentlyPressedKeys[76]){
/** If X or L is pressed. */
interfaces.thrust.set( parseFloat(interfaces.thrust.get()) + 5 );
}else if(currentlyPressedKeys[90] || currentlyPressedKeys[75]){
/** If Z or K is pressed. */
interfaces.thrust.set( parseFloat(interfaces.thrust.get()) - 5 );
}
/** Calculate and update thrust based on slider value. */
thrust = parseFloat(interfaces.thrust.get()) / 1000 * (reverse ? (getIfVelocityOppositeToLookat() ? -0.2 : -1.6) : 1.0);
values.thrust.nodeValue = (thrust>=0?"+":"-") + (parseFloat(interfaces.thrust.get())/10.0).toFixed(1) + "%";
/** Update compass' location and direction. */
interfaces.orientation.style.transform = "rotate(" + radToDeg( getOrientation() ) + "deg)";
interfaces.orientation.style.left = ((viewOrigin[0]+1.0)/2.0*200-12) + "px";
interfaces.orientation.style.top = ((1.0-viewOrigin[1])/2.0*200-12) + "px";
/** Update obstacles' locations and directions. */
for(var i = 0; i < OBSTACLE_COUNT; i++){
airplaneIcons[i].style.transform = "rotate(" + (-radToDeg( obstacleAngle[i] )) + "deg)";
airplaneIcons[i].style.left = ((obstacleOrigin[i][0]+1.0)/2.0*200-8) + "px";
airplaneIcons[i].style.top = ((1.0-obstacleOrigin[i][1])/2.0*200-8) + "px";
}
}
/** Show messgae on message board.
* @param {string} text
* @param {function|null} callback callback function after the text is shown.
*/
function msg(text, callback){
msgDOM.nodeValue = text;
if(callback){
setTimeout(callback,0);
}
}
/** Set obstacle level.
* @param {int} level none=0, static=1, moving=2
*/
function setObstacleLevel(level){
obstacleLevel = level;
/** Update visibility of airplane icons. */
if(level === 0){
for(var i = 0; i < OBSTACLE_COUNT; i++){
airplaneIcons[i].style.visibility = "hidden";
}
}else{
for(var i = 0; i < OBSTACLE_COUNT; i++){
airplaneIcons[i].style.visibility = "visible";
}
}
}<file_sep>
/** Identification prefix for terrain shader. */
var TERRAIN_PREFIX = "terrain";
/** GL buffers for terrain. */
var terrainPositionBuffer;
var terrainIndexBuffer;
var terrainColorBuffer;
var terrainNormalBuffer;
/** Data array for terrain. */
var terrainPositionArray;
var terrainIndexArray;
var terrainColorArray;
var terrainNormalArray;
/** Shader program for terrain. */
var terrainShaderProgram;
/** Variable locations in shader program. */
var terrainLocations = {};
/** Whether terrain is ready. (Terrain is generated asynchronously.) */
var terrainReady = false;
/** Detail level of terrain. */
var TERRAIN_DETAIL_LEVEL = 8;
/** Number of vertices on each side of terrain. */
var TERRAIN_SIZE = Math.pow(2, TERRAIN_DETAIL_LEVEL) + 1;
/** Random generator parameters. See terrainRandomFunction(). */
var TERRAIN_RANDOM_INITIAL = 0.75;
var TERRAIN_RANDOM_DECAY = 0.6;
/** Initialize terrain's shader programs and variable locations. */
function terrainShaderInit(){
terrainShaderProgram = shaderPrograms[TERRAIN_PREFIX];
/** Attributes */
terrainLocations["aVertexPosition"] = gl.getAttribLocation(terrainShaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(terrainLocations["aVertexPosition"]);
terrainLocations["aVertexColor"] = gl.getAttribLocation(terrainShaderProgram, "aVertexColor");
gl.enableVertexAttribArray(terrainLocations["aVertexColor"]);
terrainLocations["aVertexNormal"] = gl.getAttribLocation(terrainShaderProgram, "aVertexNormal");
gl.enableVertexAttribArray(terrainLocations["aVertexNormal"]);
/** Uniforms */
terrainLocations["uPMatrix"] = gl.getUniformLocation(terrainShaderProgram, "uPMatrix");
terrainLocations["uMVMatrix"] = gl.getUniformLocation(terrainShaderProgram, "uMVMatrix");
terrainLocations["uViewOrigin"] = gl.getUniformLocation(terrainShaderProgram, "uViewOrigin");
terrainLocations["uLightDirection"] = gl.getUniformLocation(terrainShaderProgram, "uLightDirection");
terrainLocations["uAmbientLight"] = gl.getUniformLocation(terrainShaderProgram, "uAmbientLight");
terrainLocations["uDiffuseLight"] = gl.getUniformLocation(terrainShaderProgram, "uDiffuseLight");
terrainLocations["uSpecularLight"] = gl.getUniformLocation(terrainShaderProgram, "uSpecularLight");
}
/** Initialize airplane's buffer. */
function terrainBufferInit(){
terrainPositionBuffer = gl.createBuffer();
terrainPositionBuffer.itemSize = 3;
terrainPositionBuffer.numOfItems = TERRAIN_SIZE * TERRAIN_SIZE;
terrainIndexBuffer = gl.createBuffer();
terrainIndexBuffer.itemSize = 1;
terrainIndexBuffer.numOfItems = 3 * 2 * (TERRAIN_SIZE - 1) * (TERRAIN_SIZE - 1);
terrainColorBuffer = gl.createBuffer();
terrainColorBuffer.itemSize = 3;
terrainColorBuffer.numOfItems = TERRAIN_SIZE * TERRAIN_SIZE;
terrainNormalBuffer = gl.createBuffer();
terrainNormalBuffer.itemSize = 3;
terrainNormalBuffer.numOfItems = TERRAIN_SIZE * TERRAIN_SIZE;
}
/** Terrain draw call */
function terrainDraw(){
if(terrainReady){
/** Setup variables. */
gl.useProgram(terrainShaderProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, terrainPositionBuffer);
gl.vertexAttribPointer(terrainLocations["aVertexPosition"], terrainPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, terrainIndexBuffer);
gl.bindBuffer(gl.ARRAY_BUFFER, terrainColorBuffer);
gl.vertexAttribPointer(terrainLocations["aVertexColor"], terrainColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, terrainNormalBuffer);
gl.vertexAttribPointer(terrainLocations["aVertexNormal"], terrainNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.uniformMatrix4fv(terrainLocations["uPMatrix"], false, pMatrix);
gl.uniformMatrix4fv(terrainLocations["uMVMatrix"], false, mvMatrix);
gl.uniform3fv(terrainLocations["uViewOrigin"], viewOrigin);
gl.uniform3fv(terrainLocations["uLightDirection"], LIGHT_DIRECTION);
gl.uniform3fv(terrainLocations["uAmbientLight"], AMBIENT_LIGHT);
gl.uniform3fv(terrainLocations["uDiffuseLight"], DIFFUSE_LIGHT);
gl.uniform3fv(terrainLocations["uSpecularLight"], SPECULAR_LIGHT);
/** Draw! */
gl.drawElements(gl.TRIANGLES, terrainIndexBuffer.numOfItems, gl.UNSIGNED_INT, 0);
}
}
/**
* Terrain animate call
*
* @param {float} lapse timelapse since last frame in sec
*/
function terrainAnimate(lapse){
}
/** Initialization of terrain.js */
function terrainInit(){
/** Register shaders, draw calls, animate calls. */
var prefix = "terrain";
shaderPrefix.push(prefix);
shaderInit[prefix] = terrainShaderInit;
bufferInit[prefix] = terrainBufferInit;
drawFunctions[prefix] = terrainDraw;
animateFunctions[prefix] = terrainAnimate;
/** Initialize arrays. */
terrainPositionArray = new Float32Array(3 * TERRAIN_SIZE * TERRAIN_SIZE);
terrainIndexArray = new Int32Array(3 * 2 * (TERRAIN_SIZE - 1) * (TERRAIN_SIZE - 1));
terrainColorArray = new Float32Array(3 * TERRAIN_SIZE * TERRAIN_SIZE);
terrainNormalArray = new Float32Array(3 * TERRAIN_SIZE * TERRAIN_SIZE);
/** Start asynchronous terrain generation.
* Terrain is generated asynchronously such that the user would not feel that
* the browser freezes.
* The functions are called on after another in the following order:
* <ul>
* <li>terrainGenerateTerrain()</li>
* <li>terrainGenerateTerrainInterator()</li>
* <li>terrainAddField()</li>
* <li>terrainGenerateIndex()</li>
* <li>terrainGenerateNormal()</li>
* <li>terrainGenerateColor()</li>
* <li>terrainBindBuffer()</li>
* </ul>
*/
terrainGenerateTerrain();
}
/** Prepare for terrain generation. */
function terrainGenerateTerrain(){
/** Set X and Y coordinates. */
for(var row = 0; row < TERRAIN_SIZE; row++){
for(var col = 0; col < TERRAIN_SIZE; col++){
terrainPositionArray[terrainIndex(row, col) + 0] = -1.0 + 2.0 / (TERRAIN_SIZE - 1) * col;
terrainPositionArray[terrainIndex(row, col) + 1] = -1.0 + 2.0 / (TERRAIN_SIZE - 1) * row;
}
}
/** Specify the first 9 heights. */
terrainPositionArray[terrainIndex(0 , 0 ) + 2] = 0.1;
terrainPositionArray[terrainIndex(0 , (TERRAIN_SIZE - 1) / 2) + 2] = -0.3;
terrainPositionArray[terrainIndex(0 , (TERRAIN_SIZE - 1) ) + 2] = 0.1;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) / 2, 0 ) + 2] = 0.6;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) / 2, (TERRAIN_SIZE - 1) / 2) + 2] = 0.8;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) / 2, (TERRAIN_SIZE - 1) ) + 2] = 0.6;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) , 0 ) + 2] = 0.1;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) , (TERRAIN_SIZE - 1) / 2) + 2] = -0.3;
terrainPositionArray[terrainIndex((TERRAIN_SIZE - 1) , (TERRAIN_SIZE - 1) ) + 2] = 0.1;
/** Asynchronously call the terrain generation iterator. */
msg("Generating terrain vertices..... 0%",
function(){
terrainGenerateTerrainInterator( TERRAIN_DETAIL_LEVEL, TERRAIN_DETAIL_LEVEL - 1, terrainRandomFunction)});
}
/**
* An interation of diamond-square algorithm.
*
* This function automatically calls the next iteration.
*
* @param {int} toplevel
* @param {int} currentLevel
* @param {function} randFunction
*/
function terrainGenerateTerrainInterator(topLevel, currentLevel, randFunction){
/** Check if the end of interation. */
if(currentLevel > 0){
/** Stride width at current level. */
var stride = Math.pow(2,currentLevel);
/** Number of strides at current level. */
var times = Math.pow(2,topLevel - currentLevel);
/** Diamond step */
for(var strideRow = 0; strideRow < times; strideRow++){
for(var strideCol = 0; strideCol < times; strideCol++){
var row = strideRow * stride;
var col = strideCol * stride;
var corners = [ terrainPositionArray[terrainIndex(row , col ) + 2],
terrainPositionArray[terrainIndex(row , col + stride) + 2],
terrainPositionArray[terrainIndex(row + stride, col + stride) + 2],
terrainPositionArray[terrainIndex(row + stride, col ) + 2]];
/** Assign value with average of four corners plus rand. */
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2] =
(corners[0] + corners[1] + corners[2] + corners[3]) / 4
+ terrainRandomFunction(topLevel, currentLevel);
}
}
/** Square step */
for(var strideRow = 0; strideRow < times; strideRow++){
for(var strideCol = 0; strideCol < times; strideCol++){
var row = strideRow * stride;
var col = strideCol * stride;
var corners;
/** Assign height to bottom vertex. */
if(strideRow == 0){
corners = [ terrainPositionArray[terrainIndex(row , col ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row , col + stride ) + 2]];
terrainPositionArray[terrainIndex(row, col + stride / 2) + 2] =
(corners[0] + corners[1] + corners[2]) / 3
+ terrainRandomFunction(topLevel, currentLevel);
}
/** Assign height to left vertex. */
if(strideCol == 0){
corners = [ terrainPositionArray[terrainIndex(row , col ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row + stride , col ) + 2]];
terrainPositionArray[terrainIndex(row + stride / 2, col) + 2] =
(corners[0] + corners[1] + corners[2]) / 3
+ terrainRandomFunction(topLevel, currentLevel);
}
/** Assign height to top vertex. */
if(strideRow == times - 1){
corners = [ terrainPositionArray[terrainIndex(row + stride , col ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row + stride , col + stride ) + 2]];
terrainPositionArray[terrainIndex(row + stride, col + stride / 2) + 2] =
(corners[0] + corners[1] + corners[2]) / 3
+ terrainRandomFunction(topLevel, currentLevel);
}else{
corners = [ terrainPositionArray[terrainIndex(row + stride , col ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row + stride , col + stride ) + 2],
terrainPositionArray[terrainIndex(row + stride/2*3, col + stride / 2) + 2]];
terrainPositionArray[terrainIndex(row + stride, col + stride / 2) + 2] =
(corners[0] + corners[1] + corners[2] + corners[3]) / 4
+ terrainRandomFunction(topLevel, currentLevel);
}
/** Assign height to right vertex. */
if(strideCol == times - 1){
corners = [ terrainPositionArray[terrainIndex(row , col + stride ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row + stride , col + stride ) + 2]];
terrainPositionArray[terrainIndex(row + stride / 2, col + stride) + 2] =
(corners[0] + corners[1] + corners[2]) / 3
+ terrainRandomFunction(topLevel, currentLevel);
}else{
corners = [ terrainPositionArray[terrainIndex(row , col + stride ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride / 2) + 2],
terrainPositionArray[terrainIndex(row + stride , col + stride ) + 2],
terrainPositionArray[terrainIndex(row + stride / 2, col + stride/2*3) + 2]];
terrainPositionArray[terrainIndex(row + stride / 2, col + stride) + 2] =
(corners[0] + corners[1] + corners[2] + corners[3]) / 4
+ terrainRandomFunction(topLevel, currentLevel);
}
}
}
/** Asynchronously call next iteration. */
msg("Generating terrain vertices..... " + ((topLevel - currentLevel) / topLevel * 100).toFixed(0) + "%",
function(){
terrainGenerateTerrainInterator(topLevel, currentLevel - 1, randFunction)});
}else{
/** Asynchronously call terrainAddField(). */
msg("Generating terrain fields..... 100%",
function(){
terrainAddField();});
}
}
/** Random number generator with decay along levels.
* @param {int} topLevel
* @param {int} currentLevel
*/
function terrainRandomFunction(topLevel, currentLevel){
/** rand is uniform distibution within
* +- 0.5 * TERRAIN_RANDOM_INITIAL * (TERRAIN_RANDOM_DECAY)^(topLevel - currentLevel)
*/
return (Math.random() - 0.5) * TERRAIN_RANDOM_INITIAL * Math.pow(TERRAIN_RANDOM_DECAY, topLevel - currentLevel);
}
/** Generate flat regions. */
function terrainAddField(){
for(var row = 0; row < TERRAIN_SIZE; row++){
for(var col = 0; col < TERRAIN_SIZE; col++){
var x = terrainPositionArray[terrainIndex(row,col) + 0];
var y = terrainPositionArray[terrainIndex(row,col) + 1];
var z = terrainPositionArray[terrainIndex(row,col) + 2];
if(z < 0.0){
/** If original height is negative. */
terrainPositionArray[terrainIndex(row,col) + 2] = 0.0;
}else if(x <= 0.004 && x >= -0.004 && ((y >= -1.0 && y <= -0.9)||(y >= 0.9 && y <= 1.0))){
/** If location is in runways. */
terrainPositionArray[terrainIndex(row,col) + 2] = 0.0;
}else if(row === 0 || col === 0 || row === TERRAIN_SIZE-1 || col === TERRAIN_SIZE-1){
/** Generate cliffs for the outer vertices. */
terrainPositionArray[terrainIndex(row,col) + 2] = 0.0;
}
}
}
/** Asynchronously call terrainGenerateIndex(). */
msg("Generating terrain indices..... 100%",
function(){
terrainGenerateIndex();});
}
/** Generate indices. */
function terrainGenerateIndex(){
var idx = 0;
for(var row = 0; row < TERRAIN_SIZE - 1; row++){
for(var col = 0; col < TERRAIN_SIZE - 1; col++){
/** Lower triangle */
terrainIndexArray[idx + 0] = row * TERRAIN_SIZE + col;
terrainIndexArray[idx + 1] = row * TERRAIN_SIZE + col + 1;
terrainIndexArray[idx + 2] = (row + 1) * TERRAIN_SIZE + col;
/** Upper triangle */
terrainIndexArray[idx + 3] = row * TERRAIN_SIZE + col + 1;
terrainIndexArray[idx + 4] = (row + 1) * TERRAIN_SIZE + col + 1;
terrainIndexArray[idx + 5] = (row + 1) * TERRAIN_SIZE + col;
idx = idx + 6;
}
}
/** Asynchronously call terrainGenerateNormal(). */
msg("Generating terrain indices.....",
function(){
terrainGenerateNormal();});
}
/** Generate normals. */
function terrainGenerateNormal(){
for(var row = 0; row < TERRAIN_SIZE; row++){
for(var col = 0; col < TERRAIN_SIZE; col++){
/** Normal of a vertex is calculated by averaging the normals of the six
* triangles connected to the vertex.
*/
var count = 0;
var sum = vec3.create();
var self = vec3.fromValues( terrainPositionArray[terrainIndex(row, col) + 0],
terrainPositionArray[terrainIndex(row, col) + 1],
terrainPositionArray[terrainIndex(row, col) + 2]);
/** Add normal of bottom left triangle. */
if(row > 0 && col > 0){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row + 0, col - 1) + 0],
terrainPositionArray[terrainIndex(row + 0, col - 1) + 1],
terrainPositionArray[terrainIndex(row + 0, col - 1) + 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row - 1, col + 0) + 0],
terrainPositionArray[terrainIndex(row - 1, col + 0) + 1],
terrainPositionArray[terrainIndex(row - 1, col + 0) + 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
/** Add normals of the two bottom right triangles. */
if(row > 0 && col < TERRAIN_SIZE - 1){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row - 1, col + 0) + 0],
terrainPositionArray[terrainIndex(row - 1, col + 0) + 1],
terrainPositionArray[terrainIndex(row - 1, col + 0) + 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row - 1, col + 1) + 0],
terrainPositionArray[terrainIndex(row - 1, col + 1) + 1],
terrainPositionArray[terrainIndex(row - 1, col + 1) + 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
if(row > 0 && col < TERRAIN_SIZE - 1){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row - 1, col + 1) + 0],
terrainPositionArray[terrainIndex(row - 1, col + 1) + 1],
terrainPositionArray[terrainIndex(row - 1, col + 1) + 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row + 0, col + 1)+ 0],
terrainPositionArray[terrainIndex(row + 0, col + 1)+ 1],
terrainPositionArray[terrainIndex(row + 0, col + 1)+ 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
/** Add normal of top left triangle. */
if(row < TERRAIN_SIZE - 1 && col < TERRAIN_SIZE - 1){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row + 0, col + 1)+ 0],
terrainPositionArray[terrainIndex(row + 0, col + 1)+ 1],
terrainPositionArray[terrainIndex(row + 0, col + 1)+ 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row + 1, col + 0)+ 0],
terrainPositionArray[terrainIndex(row + 1, col + 0)+ 1],
terrainPositionArray[terrainIndex(row + 1, col + 0)+ 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
/** Add normals of the two top left triangles. */
if(row < TERRAIN_SIZE - 1 && col > 0){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row + 1, col + 0)+ 0],
terrainPositionArray[terrainIndex(row + 1, col + 0)+ 1],
terrainPositionArray[terrainIndex(row + 1, col + 0)+ 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row + 1, col - 1) + 0],
terrainPositionArray[terrainIndex(row + 1, col - 1) + 1],
terrainPositionArray[terrainIndex(row + 1, col - 1) + 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
if(row < TERRAIN_SIZE - 1 && col > 0){
var first = vec3.fromValues(terrainPositionArray[terrainIndex(row + 1, col - 1) + 0],
terrainPositionArray[terrainIndex(row + 1, col - 1) + 1],
terrainPositionArray[terrainIndex(row + 1, col - 1) + 2]);
var second = vec3.fromValues(terrainPositionArray[terrainIndex(row + 0, col - 1) + 0],
terrainPositionArray[terrainIndex(row + 0, col - 1) + 1],
terrainPositionArray[terrainIndex(row + 0, col - 1) + 2]);
var normal = vec3.create();
vec3.subtract(first, self, first);
vec3.subtract(second, self, second);
vec3.cross(normal, first, second);
vec3.normalize(normal, normal);
vec3.add(sum, sum, normal);
count++;
}
/** Take average. */
vec3.scale(sum, sum, 1 / count);
terrainNormalArray[terrainIndex(row, col) + 0] = sum[0];
terrainNormalArray[terrainIndex(row, col) + 1] = sum[1];
terrainNormalArray[terrainIndex(row, col) + 2] = sum[2];
}
}
/** Asynchronously call terrainGenerateColor(). */
msg("Generating terrain colors.....",
function(){
terrainGenerateColor();});
}
/** Generate colors. */
function terrainGenerateColor(){
for(var row = 0; row < TERRAIN_SIZE; row++){
for(var col = 0; col < TERRAIN_SIZE; col++){
/** Get height of the vertex. */
var height = terrainPositionArray[terrainIndex(row, col) + 2];
/** Colors from high to low: White -> Dark green -> Bright green */
if(height > 0.6){
terrainColorArray[terrainIndex(row, col) + 0] = 1.4;
terrainColorArray[terrainIndex(row, col) + 1] = 1.4;
terrainColorArray[terrainIndex(row, col) + 2] = 1.4;
}else{
terrainColorArray[terrainIndex(row, col) + 0] = 0.0;
terrainColorArray[terrainIndex(row, col) + 1] = 1.2-height/0.6*0.9;
terrainColorArray[terrainIndex(row, col) + 2] = 0.0;
}
}
}
/** Asynchronously call terrainBindBuffer(). */
msg("Binding terrain buffers.....",
function(){
terrainBindBuffer();});
}
/** Bind terrain buffers. */
function terrainBindBuffer(){
gl.bindBuffer(gl.ARRAY_BUFFER, terrainPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, terrainPositionArray, gl.STATIC_DRAW);
gl.vertexAttribPointer(terrainLocations["aVertexPosition"], terrainPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, terrainIndexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, terrainIndexArray, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, terrainColorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, terrainColorArray, gl.STATIC_DRAW);
gl.vertexAttribPointer(terrainLocations["aVertexColor"], terrainColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, terrainNormalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, terrainNormalArray, gl.STATIC_DRAW);
gl.vertexAttribPointer(terrainLocations["aVertexNormal"], terrainNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);
/** Finally, the terrain is ready! */
terrainReady = true;
msg("Initialization done! Start having fun!");
}
/** Helper function to get index of a vertex.
* @param {int} row
* @param {int} col
*/
function terrainIndex(row, col){
return (row * TERRAIN_SIZE + col) * 3;
}
<file_sep>/**
* view.js
*
* @fileoverview Manages all vision features, including viewing parameters
* (eye coordinates, lookAt vector, up vector, view quaternion, pitch, roll,
* yaw, viewing matrices) and lighting parameters.
* @author <NAME> <<EMAIL>>
*/
/** Initial eye height */
var AIRPLANE_HEIGHT = 0.0006;
/** Initial eye coordinates */
var viewOrigin = vec3.fromValues(0.0,-0.9,AIRPLANE_HEIGHT);
/** Coordinates of the tip of airplane */
var airplaneTip = vec3.clone(viewOrigin);
/** Up vector */
var viewUp = vec3.create();
/** LookAt vector */
var viewLookAt = vec3.create();
/** LookAt center */
var viewCenter = vec3.create();
/** Right vector */
var viewRight = vec3.create();
/** Viewing quaternion */
var viewQuat = quat.create();
/** Viewing matrix */
var mvMatrix = mat4.create();
/** Perspective projection matrix */
var pMatrix = mat4.create();
/** Unit vectors along each axis */
var X_AXIS = vec3.fromValues(1.0,0.0,0.0);
var Y_AXIS = vec3.fromValues(0.0,1.0,0.0);
var Z_AXIS = vec3.fromValues(0.0,0.0,1.0);
/** Initial viewing directions */
var VIEW_UP_INIT = vec3.fromValues(0.0,0.0,1.0);
var VIEW_LOOKAT_INIT = vec3.fromValues(0.0,-1.0,0.0);
var VIEW_RIGHT_INIT = vec3.fromValues(-1.0,0.0,0.0);
/** Field of view */
var VIEWPORT = 85;
/** Lighting parameters */
/** Parallel light source */
var LIGHT_DIRECTION = vec3.fromValues(Math.sin(degToRad(30))*Math.cos(degToRad(30)),
Math.sin(degToRad(30))*Math.sin(degToRad(30)),
Math.cos(degToRad(30)));
/** White lights for ambient and diffuse parts. */
var AMBIENT_LIGHT = vec3.fromValues(0.3, 0.3, 0.3);
var DIFFUSE_LIGHT = vec3.fromValues(0.6, 0.6, 0.6);
/** Specular light is soft warm sunlight (RGB = 253,184,19). */
var SPECULAR_LIGHT = vec3.fromValues(0.55*253/255, 0.55*184/255, 0.55*19/255);
/** Initialization of view.js */
function viewInit(){
/** Generate perpective projection matrix. */
mat4.perspective(pMatrix, degToRad(VIEWPORT), gl.viewportWidth / gl.viewportHeight, 0.0001, 10.0);
}
/** Update viewing vectors and matrices. */
function viewUpdateMatrix(){
/** Update up, lookAt, and right vector based on current quat. */
vec3.transformQuat(viewUp, VIEW_UP_INIT, viewQuat);
vec3.transformQuat(viewLookAt, VIEW_LOOKAT_INIT, viewQuat);
vec3.transformQuat(viewRight, VIEW_RIGHT_INIT, viewQuat);
/** Update viewing matrix */
vec3.add(viewCenter, viewOrigin, viewLookAt);
mat4.lookAt(mvMatrix, viewOrigin, viewCenter, viewUp);
/** Update airplane tip. */
var offsetFront = vec3.create();
var offsetUp = vec3.create();
vec3.scale(offsetFront, viewLookAt, AIRPLANE_TIP_FRONT);
vec3.scale(offsetUp, viewUp, AIRPLANE_TIP_UP);
vec3.add(airplaneTip, viewOrigin, offsetFront);
vec3.add(airplaneTip, airplaneTip, offsetUp);
}
/** Calculate current roll.
* @return {float} roll in rad
*/
function getRoll(){
return vec3.angle(viewRight, Z_AXIS) - Math.PI / 2;
}
/** Calculate current pitch.
* @return {float} pitch in rad
*/
function getPitch(){
return Math.PI / 2 - vec3.angle(viewLookAt, Z_AXIS);
}
/** Calculate current yaw.
* @return {float} yaw in rad
*/
function getYaw(){
return angleNormalize(getOrientation() - getVelocityOrientation());
}
/** Calculate current lookAt orientation (with +y-axis being 0 and +x-axis being PI/2).
* @return {float} looatAtOrientation in rad
*/
function getOrientation(){
var orientation = vec3.fromValues(viewLookAt[0],viewLookAt[1],0);
return angleNormalize(viewLookAt[0] < 0 ? -vec3.angle(orientation, Y_AXIS) : vec3.angle(orientation, Y_AXIS));
}
/** Calculate current velocity orientation (with +y-axis being 0 and +x-axis being PI/2).
* @return {float} velocityOrientation in rad
*/
function getVelocityOrientation(){
var orientation = vec3.fromValues(velocity[0],velocity[1],0);
return angleNormalize(velocity[0] < 0 ? -vec3.angle(orientation, Y_AXIS) : vec3.angle(orientation, Y_AXIS));
}
/** Check if velocity is in opposite direction to lookAt. (Basically, whether
* airplane is going backwards.)
* @return {boolean}
*/
function getIfVelocityOppositeToLookat(){
var yaw = getYaw();
return yaw > degToRad(90) || yaw < degToRad(-90);
}
/** Calculate horizontal velocity.
* @return {float} horizontalVelocity
*/
function getHorizontalVelocity(){
return Math.sqrt(velocity[0] * velocity[0] + velocity[1] * velocity[1]);
}
/** Helper function to make sure an angle falls within -PI to PI.
* @param {float} angle in rad
* @return {float} angle in rad
*/
function angleNormalize(angle){
if(angle > degToRad(180)){
angle -= Math.PI * 2;
}else if(angle <= degToRad(-180)){
angle += Math.PI * 2;
}
return angle;
}
<file_sep>
/** Velocity of airplane */
var velocity = vec3.create();
/** Current thrust */
var thrust = 0;
/** Whether reverse thrust is turned on */
var reverse = false;
/** Whether airplane is on the ground (as opposed to being in the air). */
var ground = true;
/** Whether the game is stil playing (as opposed to gameover or winning). */
var playing = true;
/** Gravity */
var GRAVITY = 0.002;
/** Drag force coefficient (see getDragForce()) */
var DRAG_FORCE_COEFF = 0.0883883;
/** Drag force power (see getDragForce()) */
var DRAG_FORCE_POWER = 1.5;
/** Drag force threshold (see getDragForce()) */
var DRAG_FORCE_THRESHOLD = 0.000001;
/** Lift force coefficient (see getLiftForce()) */
var LIFT_FORCE_COEFF = 0.1;
/** Lift force multipier according to pitch keypresses. (see getLiftForce()) */
var LIFT_PITCH_COEFF = [0.4,1.0,1.6];
/** Acceleration coefficient (see getThrustForce()) */
var ACCELERATION_COEFF = 1.2e-3;
/** Roll change rate in reponse to roll keypresses. */
var ROLL_CHANGE_RATE = 2.0e-3;
/** Yaw change rate in reponse to roll keypresses. */
var YAW_CHANGE_RATE = 0.1;
/** Velocity threshold to judge whether crashing on land. */
var CRASH_ON_LAND_VELOCITY_THRESHOLD = 0.025;
/** Pitch threshold to judge whether crashing on land. */
var CRASH_ON_LAND_PITCH_THRESHOLD = degToRad(20);
/** Roll threshold to judge whether crashing on land. */
var CRASH_ON_LAND_ROLL_THRESHOLD = degToRad(20);
/** Threshold to judge whether crashing into the mountains */
var CRASH_ON_MOUNTAIN_THRESHOLD = 0.01;
/** Threshold to judge whether crashing into the walls. */
var CRASH_ON_WALL_THRESHOLD = 0.1;
/** Initialization of hysics.js */
function physicsInit(){
}
/** Update physics data.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdate(lapse){
physicsUpdatePosition(lapse);
physicsUpdateVelocity(lapse);
physicsCheckCrashes();
physicsCheckGround();
physicsUpdateRoll(lapse);
physicsUpdateLookAt();
}
/** Update airplane location based on velocity.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdatePosition(lapse){
var viewOriginChange = vec3.clone(velocity);
vec3.scale(viewOriginChange, viewOriginChange, lapse);
vec3.add(viewOrigin, viewOrigin, viewOriginChange);
}
function physicsUpdatePositions(lapse){
var viewOriginChange = vec3.clone(velocity);
console.log(velocity);
}
/** Update airplane velocity based on forces.
* @param {float} lapse timelapse since last frame in sec
*/
function physicsUpdateVelocity(lapse){
/** Apply lift force (along z-axis and left-right direction). */
var liftVelocityChange = vec3.create();
var liftDirection = vec3.fromValues(viewLookAt[0],viewLookAt[1],0.0);
vec3.normalize(liftDirection, liftDirection);
vec3.scale(liftDirection, liftDirection, vec3.dot(liftDirection, viewUp));
vec3.subtract(liftDirection, viewUp, liftDirection);
vec3.normalize(liftDirection, liftDirection);
vec3.scale(liftVelocityChange, liftDirection, getLiftForce()*lapse);
/** Apply thrust force (along lookAt direction). */
var thrustVelocityChange = vec3.create();
vec3.scale(thrustVelocityChange, viewLookAt, getThrustForce()*lapse);
/** Apply drag force (along negative lookAt direction). */
var dragVelocityChange = vec3.create();
vec3.scale(dragVelocityChange, viewLookAt, -getDragForce()*lapse);
/** Apply gravity (along z-axis). */
velocity[2] -= GRAVITY * lapse;
vec3.add(velocity, velocity, thrustVelocityChange);
vec3.add(velocity, velocity, liftVelocityChange);
vec3.add(velocity, velocity, dragVelocityChange);
}
/** Update lookAt direction to match velocity direction. */
function physicsUpdateLookAt(){
/** Quaternion change to apply. */
var quatChange = quat.create();
/** Velocity direction. */
var normalizedVelocity = vec3.create();
/** Update only when velocity is not zero. */
if(vec3.length(velocity) >= 0.000001){
vec3.normalize(normalizedVelocity, velocity);
/** If moving backwards, match lookAt to opposite of velocity direction. */
if(vec3.dot(viewLookAt, normalizedVelocity) < 0){
vec3.negate(normalizedVelocity, normalizedVelocity);
}
/** Apply quaternion change. */
quat.rotationTo(quatChange, viewLookAt, normalizedVelocity);
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}
/** If on the ground, eliminate roll. */
if(ground){
vec3.transformQuat(viewUp, VIEW_UP_INIT, viewQuat);
vec3.transformQuat(viewLookAt, VIEW_LOOKAT_INIT, viewQuat);
vec3.transformQuat(viewRight, VIEW_RIGHT_INIT, viewQuat);
quat.setAxisAngle(quatChange, viewLookAt, -getRoll());
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}
}
/** Check if airplane is on the ground. */
function physicsCheckGround(){
/** If was on the ground... */
if(ground){
/** If vertical velocity is positive (i.e. gravity is overcome), fly! */
if(velocity[2] > 0.0){
ground = false;
}else
/** If airplane is still on the land, clear vertical velocity and set
* airplane location right on the ground (not under the ground).
*/
if(physicsCheckAboveLand()){
velocity[2] = 0;
viewOrigin[2] = AIRPLANE_HEIGHT;
}else
{
/** If airplane is NOT on the land, fall into the ocean. */
ground = false;
}
}else{
/** If was in the air, check if airplane has landed. */
if(physicsCheckAboveLand() && viewOrigin[2] <= AIRPLANE_HEIGHT){
velocity[2] = 0;
viewOrigin[2] = AIRPLANE_HEIGHT;
ground = true;
}
}
}
/** Helper functino to check whether airplane is above the land or above the
* ocean.
*/
function physicsCheckAboveLand(){
return viewOrigin[0] >= -1.0 && viewOrigin[0] < 1.0 && viewOrigin[1] >= -1.0 && viewOrigin[1] < 1.0;
}
/** Check if gameover or winning. */
function physicsCheckCrashes(){
physicsCheckCrashOcean();
physicsCheckCrashLand();
physicsCheckCrashMountain();
physicsCheckCrashWall();
physicsCheckCrashObstacle();
physicsCheckNoFuel();
physicsCheckWin();
}
/** Check if airplane crashes into ocean. */
function physicsCheckCrashOcean(){
if(!physicsCheckAboveLand() && (viewOrigin[2] <= 0.0 || airplaneTip[2] <= 0.0)){
viewOrigin[2] = AIRPLANE_HEIGHT;
gameover("GAMEOVER! You crashed into the ocean. Press R to restart.");
}
}
/** Check if airplane crashes on land. */
function physicsCheckCrashLand(){
if(ground === false && viewOrigin[2] <= AIRPLANE_HEIGHT &&
(velocity[2] <= -CRASH_ON_LAND_VELOCITY_THRESHOLD ||
Math.abs(getRoll()) >= CRASH_ON_LAND_ROLL_THRESHOLD ||
Math.abs(getPitch()) >= CRASH_ON_LAND_PITCH_THRESHOLD ) ){
gameover("GAMEOVER! You crashed on land. Press R to restart.");
}
}
/** Check if airplane crashes into mountains. */
function physicsCheckCrashMountain(){
if(terrainReady && physicsCheckAboveLand()){
/** Distance between adjacent terrain vertices */
var stride = 2.0 / (TERRAIN_SIZE - 1);
/** Row and column index airplane is at */
var col = Math.floor((airplaneTip[0] + 1.0) / stride);
var row = Math.floor((airplaneTip[1] + 1.0) / stride);
/** X and Y distances to vertex */
var dx = (airplaneTip[0] + 1.0) / stride - col;
var dy = (airplaneTip[1] + 1.0) / stride - row;
/** Calculate the height of terrain where airplane is at. */
var gradientX;
var gradientY;
var z;
/** Check lower or upper triangle. */
if(dx + dy <= 1.0){
gradientX = terrainPositionArray[terrainIndex(row, col+1) + 2] - terrainPositionArray[terrainIndex(row, col) + 2];
gradientY = terrainPositionArray[terrainIndex(row+1, col) + 2] - terrainPositionArray[terrainIndex(row, col) + 2];
z = terrainPositionArray[terrainIndex(row, col) + 2] + dx * gradientX + dy * gradientY;
}else{
gradientX = terrainPositionArray[terrainIndex(row+1, col+1) + 2] - terrainPositionArray[terrainIndex(row+1, col) + 2];
gradientY = terrainPositionArray[terrainIndex(row+1, col+1) + 2] - terrainPositionArray[terrainIndex(row, col+1) + 2];
z = terrainPositionArray[terrainIndex(row+1, col+1) + 2] + (1.0 - dx) * gradientX + (1.0 - dy) * gradientY;
}
/** Check if airplane is below terrain. */
if(airplaneTip[2] < z - CRASH_ON_MOUNTAIN_THRESHOLD){
gameover("GAMEOVER! You crashed into the mountains. Press R to restart.");
}
}
}
/** Check if airplane tries to bypass mountains. */
function physicsCheckCrashWall(){
if(( viewOrigin[0] < -(1.0 + CRASH_ON_WALL_THRESHOLD) ||
viewOrigin[0] > 1.0 + CRASH_ON_WALL_THRESHOLD )
&& viewOrigin[1] < 0.0 && airplaneTip[1] > 0.0){
gameover("GAMEOVER! You cannot fly by the mountains. Press R to restart.");
}
}
/** Check if airplane crashes into obstacles. */
function physicsCheckCrashObstacle(){
/** Check only when obstacles are enabled. */
if(obstacleLevel !== 0){
var collision = false;
/** Iterate through all obstacles. */
for(var i = 0; i < OBSTACLE_COUNT; i++){
/** Assume obstacle is cylinder with radius r and height h. */
var r = 0.3 * OBSTACLE_SCALE[0];
var h = 1.1 * OBSTACLE_SCALE[1];
/** Location of obstacle */
var o = vec3.clone(obstacleOrigin[i]);
/** Get the two center coordinates of the two bottoms of cylinder. */
var angle = obstacleAngle[i];
var a = vec3.fromValues(o[0] - h * Math.sin(angle), o[1] + h * Math.cos(angle), o[2]);
var b = vec3.fromValues(o[0] + h * Math.sin(angle), o[1] - h * Math.cos(angle), o[2]);
/** Get coordinates of airplane tip. */
var x = vec3.clone(airplaneTip);
/** Check if x is in the cylinder. */
var ba = vec3.create();
vec3.subtract(ba, b, a);
vec3.normalize(ba, ba);
var xa = vec3.create();
vec3.subtract(xa, x, a);
var d = vec3.create();
vec3.cross(d, xa, ba);
if(vec3.dot(xa,ba) > 0 && vec3.dot(xa,ba) < h*2 && vec3.length(d) < r){
collision = true;
}
}
/** If there is collision, gameover. */
if(collision){
gameover("GAMEOVER! You crashed into another aircraft. Press R to restart.");
}
}
}
/** Check if timeout. */
function physicsCheckNoFuel(){
if(Date.now() - startTime >= TIMEOUT){
gameover("GAMEOVER! You ran out of fuel. Press R to restart.");
}
}
/** Check if wins. */
function physicsCheckWin(){
if(ground && viewOrigin[0] >= -0.003 && viewOrigin[0] <= 0.003
&& viewOrigin[1] >= 0.9 && viewOrigin[1] <= 1.0
&& getHorizontalVelocity() <= 0.002){
gameover("You WIN!!!!!!! Congratulations!");
}
}
/** Update roll or yaw in reaction to keypresses. */
function physicsUpdateRoll(lapse){
/** If in the air, modify roll. */
if(!ground){
var quatChange = quat.create();
if (currentlyPressedKeys[37] || currentlyPressedKeys[65]) {
/** Roll leftwards when Left-arrow or A is pressed. */
quat.setAxisAngle(quatChange, viewLookAt, -ROLL_CHANGE_RATE);
} else if (currentlyPressedKeys[39] || currentlyPressedKeys[68]) {
/** Roll rightwards when Right-arrow or D is pressed. */
quat.setAxisAngle(quatChange, viewLookAt, ROLL_CHANGE_RATE);
}
quat.multiply(viewQuat, quatChange, viewQuat);
quat.normalize(viewQuat, viewQuat);
}else{
/** If on the ground, modify yaw. */
if (currentlyPressedKeys[37] || currentlyPressedKeys[65]) {
/** Turn left when Left-arrow or A is pressed. */
vec3.rotateZ(velocity, velocity, vec3.create(), YAW_CHANGE_RATE*lapse);
} else if (currentlyPressedKeys[39] || currentlyPressedKeys[68]) {
/** Turn rigt when Right-arrow or D is pressed. */
vec3.rotateZ(velocity, velocity, vec3.create(), -YAW_CHANGE_RATE*lapse);
}
}
}
/** Calculate lift force.
* @return {float} liftForce
*/
function getLiftForce(){
/** Lift force = KEY_COEFF * LIFT_FORCE_COEFF * horizontal velocity */
if (currentlyPressedKeys[38] || currentlyPressedKeys[87]) {
/** More lift force when Up-arrow or W is pressed. */
return LIFT_PITCH_COEFF[2] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}else if (currentlyPressedKeys[40] || currentlyPressedKeys[83]) {
/** Less lift force when Down-arrow or S is pressed. */
return LIFT_PITCH_COEFF[0] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}else{
/** Default lift force. */
return LIFT_PITCH_COEFF[1] * LIFT_FORCE_COEFF * getHorizontalVelocity();
}
}
/** Calculate thrust force.
* @return {float} thrustForce
*/
function getThrustForce(){
/** Thrust force = thrust * ACCELERATION_COEFF */
return thrust * ACCELERATION_COEFF;
}
function getThrustForces(){
/** Thrust force = thrust * ACCELERATION_COEFF */
console.log(thrust * ACCELERATION_COEFF);
}
/** Calculate drag force.
* @return {float} dragForce
*/
function getDragForce(){
/** Drag force = DRAG_FORCE_COEFF * (velocity)^(DRAG_FORCE_POWER) */
/** If velocity if too small, no drag force. */
if(vec3.length(velocity) > DRAG_FORCE_THRESHOLD){
return DRAG_FORCE_COEFF * Math.pow(vec3.length(velocity), DRAG_FORCE_POWER);
}else{
return 0;
}
}
function getLiftForces(){
/** Lift force = KEY_COEFF * LIFT_FORCE_COEFF * horizontal velocity */
if (currentlyPressedKeys[38] || currentlyPressedKeys[87]) {
/** More lift force when Up-arrow or W is pressed. */
console.log(LIFT_PITCH_COEFF[2] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}else if (currentlyPressedKeys[40] || currentlyPressedKeys[83]) {
/** Less lift force when Down-arrow or S is pressed. */
console.log(LIFT_PITCH_COEFF[0] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}else{
/** Default lift force. */
console.log(LIFT_PITCH_COEFF[1] * LIFT_FORCE_COEFF * getHorizontalVelocity());
}
}
/** Check if airplane crashes into obstacles. */
function physicsCheckCrashObstacles(){
if(ground === false && viewOrigin[2] <= AIRPLANE_HEIGHT){
console.log("Stopped");
}
}
function getDragForces(){
/** Drag force = DRAG_FORCE_COEFF * (velocity)^(DRAG_FORCE_POWER) */
/** If velocity if too small, no drag force. */
if(vec3.length(velocity) > DRAG_FORCE_THRESHOLD){
return DRAG_FORCE_COEFF * Math.pow(vec3.length(velocity), DRAG_FORCE_POWER);
}else{
return 0;
}
}
|
b2b2fb2b3aef1f62cce4260e1c77523ae9d4a707
|
[
"JavaScript"
] | 6 |
JavaScript
|
saikiran402/collins
|
835bfbbbe13aeed542c8085b173eb9b3b6c46ee6
|
f605653d26a4d86b9ab3ca942442d51665060fd2
|
refs/heads/master
|
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idPlanEst = $_POST['inputIdPlanEst'];
$name = $_POST['inputName'];
$grade = $_POST['inputGrado'];
$cad = '';
$ban = false;
$sqlInsertMat = "INSERT INTO $tMats "
. "(nombre, nivel_grado_id, plan_estudio_id) "
. "VALUES ('$name', '$grade', '$idPlanEst' ) ";
if ($con->query($sqlInsertMat) === TRUE) {
$ban = true;
$cad .= 'Materia añadida con éxito.';
} else {
$ban = false;
$cad .= 'Error al añadir materia al plan de estudios.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$mats = array();
$msgErr = '';
$ban = false;
$idGrupo = $_POST['idGrupo'];
//Obtenemos el plan de estudios y el nivel
$sqlGetPlanNiv = "SELECT nivel_grado_id, plan_estudios_id FROM $tGInfo WHERE id = '$idGrupo' ";
$resGetPlanNiv = $con->query($sqlGetPlanNiv);
$rowGetPlanNiv = $resGetPlanNiv->fetch_assoc();
$idPlanEst = $rowGetPlanNiv['plan_estudios_id'];
$idNivel = $rowGetPlanNiv['nivel_grado_id'];
//Obtenemos las materias de ese plan de estudios y nivel al que pertenece el grupo
$sqlGetMatsPlanNiv = "SELECT $tMats.id as idMat, $tMats.nombre as nameMat "
. " FROM $tMats "
. " WHERE $tMats.plan_estudio_id = '$idPlanEst' AND $tMats.nivel_grado_id = '$idNivel' ";
$resGetMatPlanNiv = $con->query($sqlGetMatsPlanNiv);
if ($resGetMatPlanNiv->num_rows > 0) {
while ($rowGetMatPlanNiv = $resGetMatPlanNiv->fetch_assoc()) {
$id = $rowGetMatPlanNiv['idMat'];
$nameMat = $rowGetMatPlanNiv['nameMat'];
$mats[] = array('id' => $id, 'nombre' => $nameMat);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen materias en este plan de estudio, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $mats, "sql" => $sqlGetMatsPlanNiv));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr, "sql" => $sqlGetMatsPlanNiv));
}
?><file_sep><?php
date_default_timezone_set('America/Mexico_City');
$host="localhost";
$user="root";
$pass="";
$db="eva_pec2";
$con=mysqli_connect($host, $user, $pass, $db);
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
//echo 'Hola';
//Tablas Usuarios
$tUsers = "usuarios";
$tUPerfil = "perfiles"; //[Director, Administrativo, Profesor, Alumno, Tutor]
$tEdos = "estados"; //[Activo, Desactivo]
$tInfo = "usuarios_informacion";
$tGrade = "banco_niveles_grados";
$tMats = "banco_materias";
$tPerInfo = "periodo_info";
$tPerFecha = "periodo_fecha";
$tGInfo = "grupos_info";
$tTurn = "banco_nivel_turnos";
$tPlanEst = "planes_estudios";
$tGMatProf = "grupos_mat_prof";
$tGAlum = "grupos_alumnos";
$tGMatAlum = "grupos_mat_alum";
// $tPerMatProm = "";
$tRubInfo = "rubrica_info";
$tRubInfoCalif = "rubrica_info_calif";
$tRubDetCalif = "rubrica_detalles_calif";
// $tPerRubCalif = "";
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['inputIdGrupo'];
$idGMatProf = $_POST['inputIdGMatProf'];
$idMat = $_POST['inputMat'];
$idProf = $_POST['inputProf'];
$cad = '';
$ban = false;
$sqlUpdMatProf = "UPDATE $tGMatProf SET banco_materia_id = '$idMat', "
. "user_profesor_id = '$idProf' WHERE id = '$idGMatProf' ";
if ($con->query($sqlUpdMatProf) === TRUE) {
$ban = true;
$cad .= 'Materia actualizada con éxito.';
} else {
$ban = false;
$cad .= 'Error al actualizar materia al grupo.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad, "sql"=>$sqlUpdMatProf));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 3) {
$idUser = $_SESSION['userId'];
$idGMatProf = $_GET['idGMatProf'];
$idGrupo = $_GET['idGrupo'];
$idPeriodo = $_GET['idPeriodo'];
$idPeriodoFecha = $_GET['idPeriodoFecha'];
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<form id="formCalifRub" name="formCalifRub">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-4">
<input type="hidden" id="inputIdRubrica" name="inputIdRubrica" >
<label for="inputRubricas">Selecciona la rubrica a Modificar:</label>
<select class="form-control" id="inputRubricas" name="inputRubricas"></select>
</div>
<div class="col-xs-offset-4 col-xs-4">
<button type="submit" id="guardar_datos" class="btn btn-info">Modificar</button>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Alumnos a evaluar</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</form>
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
$.ajax({
type: "POST",
data: {idPeriodoFecha: <?=$idPeriodoFecha;?>, idGMatProf: <?=$idGMatProf; ?>},
url: "../controllers/get_rubricas_info.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$(".content-header #inputRubricas").html("<option></option>");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$(".content-header #inputRubricas").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
}else{
$(".content-header #inputRubricas").html("<option>"+msg.msgErr+"</option>");
}
}
});
$(".content-wrapper").on('change', '#inputRubricas', function(){
var idRubrica = $(this).val();
console.log(idRubrica);
$("#inputIdRubrica").val(idRubrica);
$("#data thead").html("");
$("#data tbody").html("");
//Si salio correcto cargamos los alumnos y las rubricas
$.ajax({
type: "POST",
data: {idGrupo: <?= $idGrupo; ?>, idRubricaInfo: idRubrica},
url: "../controllers/get_calif_alumnos_rubricas.php",
success: function(msg2){
console.log(msg2);
msg2 = jQuery.parseJSON(msg2);
if(msg2.error == 0){
//Añadimos cabecerás
var newRowTH = '<tr><th>Nombre</th>';
var cantRub = 0;
$.each(msg2.rubricas, function(i, item){
newRowTH += '<th>' + msg2.rubricas[i].nombreRub + ' <br>('
+ msg2.rubricas[i].fechaRub + ')</th>';
cantRub++;
});
newRowTH += '</tr>';
$(newRowTH).appendTo("#data thead");
//Añadimos alumnos y sus calificaciones
var newRowTB = '';
$.each(msg2.students, function(j, item){
newRowTB += '<tr>'
newRowTB += '<td>' + msg2.students[j].nameStudent + '</td>';
$.each(msg2.calRubricas, function(k, item){
//newRowTB += '<td>'+msg2.students[j].cals[k].califRub+'</td>';
newRowTB += '<td><input type="hidden" name="inputIdDetCalif[]" id="inputIdDetCalif" value="'+msg2.students[j].cals[k].idDetCalif+'">'
+'<input type="number" class="form-control" id="inputCalif" name="inputCalif[]" value="'+msg2.students[j].cals[k].califRub+'" min="0" max="10"></td>';
})
newRowTB += '</tr>';
});
$(newRowTB).appendTo("#data tbody");
}else{
var newRow = '<tr><td colspan="3">' + msg2.msgErr + '</td></tr>';
$("#data thead").html(newRow);
}
}
});
});
//Actualizar rubrica
$('#formCalifRub').validate({
rules: {
'inputCalif[]': {required: true, range: [0, 10], digits: true}
},
messages: {
'inputCalif[]': {
required: "Calificación del alumno obligatoria",
range: "Solo números entre 0 y 10",
digits: "Solo se permiten números enteros."
}
},
tooltip_options:{
'inputCalif[]': {trigger: "focus", placement: "bottom"}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_rubrica_det_calif.php",
data: $('form#formCalifRub').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('.divError').css({color: "#77DD77"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('.divError').css({color: "#FF0000"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
$('.divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al actualizar calificaciones.");
}
});
}
}); // end añadir rubrica
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html><file_sep><?php
//MODIFICAR
include('../config/conexion.php');
include('../config/variables.php');
$students = array();
$rubricas = array();
$userProfId = $_POST['inputUserId'];
$idPeriodoFecha = $_POST['inputPeriodoFecha'];
$idGrupoMatProf = $_POST['inputGMatProf'];
$idGrupo = $_POST['inputIdGrupo'];
$countRubs = count($_POST['inputIdRubInfo']);
$cad = '';
$ban = false;
for($i = 0; $i < $countRubs; $i++) {
$idRubInfo = $_POST['inputIdRubInfo'][$i];
$porcRub = $_POST['porcRub'][$i];
$sqlUpdateRubInfo = "UPDATE $tRubInfo SET porcentaje = '$porcRub', estado_id = '2' WHERE id = '$idRubInfo' ";
if ($con->query($sqlUpdateRubInfo) === TRUE) {
$ban = true;
$cad .= 'Rubrica ' . $idRubInfo . ', actualizada con éxito.';
} else {
$cad .= 'Error al actualizar porcentajes <br>' . $con->error;
$ban = false;
break;
}
}
//Obtenemos alumnos del grupo
$sqlGetStudents = "SELECT $tUsers.id as idStudent, $tUsers.nombre as nameStudent "
. "FROM $tGAlum "
. "INNER JOIN $tUsers ON $tUsers.id = $tGAlum.user_alumno_id "
. "WHERE $tGAlum.grupo_info_id = '$idGrupo' ORDER BY nameStudent ";
//Obtenemos las rubricas y porcentajes
$sqlGetRubricas = "SELECT $tRubInfo.id as idRub, $tRubInfo.nombre as nombre, $tRubInfo.porcentaje as porcRub "
. "FROM $tRubInfo "
. "WHERE $tRubInfo.estado_id = '2' AND $tRubInfo.grupo_mat_prof_id = '$idGrupoMatProf' "
. "AND $tRubInfo.periodo_fecha_id = '$idPeriodoFecha' ";
$resGetRubricas = $con->query($sqlGetRubricas);
if ($resGetRubricas->num_rows > 0) {
while ($rowGetRubricas = $resGetRubricas->fetch_assoc()) {
$idRub = $rowGetRubricas['idRub'];
$nombreRub = $rowGetRubricas['nombre'];
$porcRub = $rowGetRubricas['porcRub'];
$rubricas[] = array('idRub' => $idRub, 'nombreRub' => $nombreRub, 'porcRub' => $porcRub);
}
}else{
$ban = false;
$msgErr .= 'No existen calificaciones en ésta rubrica, aún.<br>' . $con->error;
}
$cadDR = '';
$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$promGral = 0;
$idStudent = $rowGetStudents['idStudent'];
$calRubricas = array();
foreach($rubricas as $key => $value){
$idRubInfo = $value['idRub'];
$porcentaje = $value['porcRub'];
$calif = 0;
$promCalif = 0;
$porcCalif = 0;
//Obtenemos rubricas_info_calif y luego rubricas_detalles_calif
$sqlGetRubInfoCalif = "SELECT id, nombre FROM $tRubInfoCalif WHERE rubrica_info_id = '$idRubInfo' ";
$resGetRubInfoCalif= $con->query($sqlGetRubInfoCalif);
if($resGetRubInfoCalif->num_rows > 0){
while($rowGetRubInfoCalif = $resGetRubInfoCalif->fetch_assoc()){
$idRubInfoCalif = $rowGetRubInfoCalif['id'];
$sqlGetCalifRub = "SELECT $tRubDetCalif.id as idDetCalif, $tRubDetCalif.calificacion as califRub "
. "FROM $tRubDetCalif "
. "WHERE $tRubDetCalif.rubrica_info_calif_id = '$idRubInfoCalif' "
. "AND $tRubDetCalif.user_alumno_id = '$idStudent' ";
$resGetCalifRub = $con->query($sqlGetCalifRub);
if($resGetCalifRub->num_rows > 0){
while($rowGetCalifRubricas = $resGetCalifRub->fetch_assoc()){
$idDetCalif = $rowGetCalifRubricas['idDetCalif'];
$califRub = $rowGetCalifRubricas['califRub'];
$calif += $califRub;
}
}else{
$msgErr .= 'No existen calificaciones de ésta rubrica, aún.<br>' . $con->error;
}
}
$promCalif = $calif / $resGetRubInfoCalif->num_rows;
$porcCalif = $promCalif * ($porcentaje * 0.01);
$promGral += $porcCalif;
//$cadDR .= 'ID: '.$idStudent.': , IDRUB: '.$idRubInfo.', SUMCALIF: '.$calif.', PROMCALIF: '.$promCalif.', %:'.$porcCalif;
}else{
$msgErr .= 'No existen actividades en ésta rubrica, aún.<br>' . $con->error;
}
//$calRubricas[] = array('idRub' => $idRubInfo, 'porcentaje'=>$porcentaje, 'promCalif' => $promCalif, 'porcCalif' => $porcCalif);
// FIXME:
// $sqlInsertPerRubCalif = "INSERT INTO $tPerRubCalif (rubrica_info_id, user_alumno_id, calificacion) "
// . "VALUES ('$idRubInfo', '$idStudent', '$promCalif')";
// if($con->query($sqlInsertPerRubCalif) === TRUE){
// continue;
// }else{
// $ban = false;
// $msgErr .= 'Error al añadir calificacion del alumno.<br>'.$con->error;
// break;
// }
}
//$students[] = array('idStudent' => $idStudent, 'cals' => $calRubricas);
$sqlInsertPerMatProm = "INSERT INTO $tPerMatProm (periodo_fecha_id, user_alumno_id, grupo_mat_prof_id, promedio) "
. "VALUES ('$idPeriodoFecha', '$idStudent', '$idGrupoMatProf', '$promGral')";
if($con->query($sqlInsertPerMatProm) === TRUE){
continue;
}else{
$ban = false;
$msgErr .= 'Error al añadir el promedio.<br>'.$con->error;
break;
}
}
}else {
$ban = false;
$msgErr .= 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$students = array();
$rubricas = array();
$msgErr = '';
$ban = true;
$idGrupo = $_POST['idGrupo'];
$idGrupoMatProf = $_POST['idGrupoMtProf'];
$idPeriodoFecha = $_POST['periodoFecha'];
//Obtenemos alumnos del grupo
$sqlGetStudents = "SELECT $tUsers.id as idStudent, $tUsers.nombre as nameStudent "
. "FROM $tGAlum "
. "INNER JOIN $tUsers ON $tUsers.id = $tGAlum.user_alumno_id "
. "WHERE $tGAlum.grupo_info_id = '$idGrupo' ORDER BY nameStudent ";
//Obtenemos las rubricas y porcentajes
$sqlGetRubricas = "SELECT $tRubInfo.id as idRub, $tRubInfo.nombre as nombre, $tRubInfo.porcentaje as porcRub "
. "FROM $tRubInfo "
. "WHERE $tRubInfo.estado_id = '2' AND $tRubInfo.grupo_mat_prof_id = '$idGrupoMatProf' "
. "AND $tRubInfo.periodo_fecha_id = '$idPeriodoFecha' ";
$resGetRubricas = $con->query($sqlGetRubricas);
if ($resGetRubricas->num_rows > 0) {
while ($rowGetRubricas = $resGetRubricas->fetch_assoc()) {
$idRub = $rowGetRubricas['idRub'];
$nombreRub = $rowGetRubricas['nombre'];
$porcRub = $rowGetRubricas['porcRub'];
$rubricas[] = array('idRub' => $idRub, 'nombreRub' => $nombreRub, 'porcRub' => $porcRub);
}
}else{
$ban = false;
$msgErr .= 'No existen calificaciones en ésta rubrica, aún.<br>' . $con->error;
}
$cadDR = '';
$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$idStudent = $rowGetStudents['idStudent'];
$name = $rowGetStudents['nameStudent'];
$calRubricas = array();
foreach($rubricas as $key => $value){
//$idRubArr = $value['idRub'];
$idRubInfo = $value['idRub'];
$porcentaje = $value['porcRub'];
$calif = 0;
$promCalif = 0;
$porcCalif = 0;
//Obtenemos rubricas_info_calif y luego rubricas_detalles_calif
$sqlGetRubInfoCalif = "SELECT id, nombre FROM $tRubInfoCalif WHERE rubrica_info_id = '$idRubInfo' ";
$resGetRubInfoCalif= $con->query($sqlGetRubInfoCalif);
if($resGetRubInfoCalif->num_rows > 0){
while($rowGetRubInfoCalif = $resGetRubInfoCalif->fetch_assoc()){
$idRubInfoCalif = $rowGetRubInfoCalif['id'];
$sqlGetCalifRub = "SELECT $tRubDetCalif.id as idDetCalif, $tRubDetCalif.calificacion as califRub "
. "FROM $tRubDetCalif "
. "WHERE $tRubDetCalif.rubrica_info_calif_id = '$idRubInfoCalif' "
. "AND $tRubDetCalif.user_alumno_id = '$idStudent' ";
$resGetCalifRub = $con->query($sqlGetCalifRub);
if($resGetCalifRub->num_rows > 0){
while($rowGetCalifRubricas = $resGetCalifRub->fetch_assoc()){
$idDetCalif = $rowGetCalifRubricas['idDetCalif'];
$califRub = $rowGetCalifRubricas['califRub'];
$calif += $califRub;
//$calRubricas[] = array('idDetCalif' => $idDetCalif, 'califRub' => $califRub);
}
}else{
//$ban = false;
$msgErr .= 'No existen calificaciones de ésta rubrica, aún.<br>' . $con->error;
//break;
}
}
$promCalif = $calif / $resGetRubInfoCalif->num_rows;
$porcCalif = $promCalif * ($porcentaje * 0.01);
//$cadDR .= 'ID: '.$idStudent.': , IDRUB: '.$idRubInfo.', SUMCALIF: '.$calif.', PROMCALIF: '.$promCalif.', %:'.$porcCalif;
}else{
//$ban = false;
$msgErr .= 'No existen actividades en ésta rubrica, aún.<br>' . $con->error;
}
$calRubricas[] = array('idRub' => $idRubInfo, 'porcentaje'=>$porcentaje, 'promCalif' => $promCalif, 'porcCalif' => $porcCalif);
}
$students[] = array('idStudent' => $idStudent, 'nameStudent' => $name, 'cals' => $calRubricas);
}
}else {
$ban = false;
$msgErr .= 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "students" => $students, "rubricas" => $rubricas, "calRubricas" => $calRubricas,
"sql" => $sqlGetStudents, "sql2"=>$sqlGetRubricas, "sql3"=>$cadDR));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr,
"sql" => $sqlGetStudents, "sql2"=>$sqlGetRubricas, "sql3"=>$cadDR));
}
?><file_sep><?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>AdminLTE 2 | Log in</title>
<!-- Favicon -->
<link rel="shortcut icon" href="../dist/img/logo.jpg">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="../components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="../components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="../components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="../dist/css/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="index.php"><b>EVA</b>Rubricas</a>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Inicia sesión</p>
<p class="bg-danger" id="msgErr"></p>
<form method="post" id="formLogin">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Correo Electrónico" id="inputUser" name="inputUser">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Contraseña" id="inputPass" name="inputPass">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox" name="inputCheckRecuerdame" value="yes"> Recordarme
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Iniciar</button>
</div>
<!-- /.col -->
</div>
</form>
<a href="#">Olvide mi contraseña</a><br>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 3 -->
<script src="../components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="../components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="../dist/js/icheck.min.js"></script>
<!-- validación de formularios -->
<script src="../dist/js/jquery.validate.min.js"></script>
<script src="../dist/js/additional-methods.min.js"></script>
<script src="../dist/js/jquery-validate.bootstrap-tooltip.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#formLogin").validate({
rules: {
inputUser: {required: true},
inputPass: {required: true}
},
messages: {
inputUser: "Usuario obligatorio",
inputPass: "<PASSWORD>"
},
tooltip_options: {
inputUser: {trigger: "focus", placement: "right"},
inputPass: {trigger: "focus", placement: "right"}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/login_user.php",
data: $("form#formLogin").serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
var idPerfil = parseInt(msg.perfil);
switch(idPerfil){
case 1:
location.href = "index_director.php";
break;
case 2:
location.href = "index_administrativo.php";
break;
case 3:
location.href = "index_profesor.php";
break;
case 5:
location.href = "index_tutor.php";
break;
default:
location.href = "login.php";
}
}else{
$("#msgErr").html(msg.msgErr);
$("#msgErr").delay(5000).hide(600);
}
},
error: function(){
var err = "Error al iniciar sesión.";
$("#msgErr").html(err);
$("#msgErr").delay(5000).hide(600);
}
})
}
})
});
</script>
</body>
</html>
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$name = $_POST['inputName'];
$num = $_POST['inputNum'];
$cad = '';
$ban = false;
$sqlInsertUser = "INSERT INTO $tPerInfo "
. "(nombre, num_periodos, estado_id, creado) "
. "VALUES ('$name', '$num', '1', '$dateNow' ) ";
if ($con->query($sqlInsertUser) === TRUE) {
$ban = true;
$cad .= 'Periodo añadido con éxito.';
} else {
$ban = false;
$cad .= 'Error al crear nuevo periodo.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$mats = array();
$msgErr = '';
$ban = false;
$idUser = $_POST['idUser'];
$sqlGetMats = "SELECT $tGMatProf.id as idGMatProf, $tMats.nombre as mat, $tGInfo.id as idGrupo, "
. "$tGInfo.nombre as grupo, $tGInfo.year as year, $tTurn.nombre as turno, "
. "$tGrade.nombre as grado, $tPlanEst.nombre as planEstudios, $tGInfo.periodo_info_id as idPeriodo "
. "FROM $tGMatProf "
. "INNER JOIN $tMats ON $tMats.id = $tGMatProf.banco_materia_id "
. "INNER JOIN $tGInfo ON $tGInfo.id = $tGMatProf.grupo_info_id "
. "INNER JOIN $tTurn ON $tTurn.id = $tGInfo.nivel_turno_id "
. "INNER JOIN $tGrade ON $tGrade.id = $tGInfo.nivel_grado_id "
. "INNER JOIN $tPlanEst ON $tPlanEst.id = $tGInfo.plan_estudios_id "
. "INNER JOIN $tPerInfo ON $tPerInfo.id = $tGInfo.periodo_info_id "
. "WHERE $tGMatProf.user_profesor_id = '$idUser' AND $tPerInfo.estado_id = '1' ";
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetMatsProf .= " AND ($tMats.nombre LIKE '%$query%' OR $tGrade.nombre LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idMat = $_POST['idMat'];
$sqlGetMatsProf .= " AND $tMats.id = '$idMat' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetMatsProf .= " ORDER BY " . $vorder;
} else {
$sqlGetMatsProf .= " ORDER BY idGMatProf ";
}
*/
$resGetMats = $con->query($sqlGetMats);
if ($resGetMats->num_rows > 0) {
while ($rowGetMats = $resGetMats->fetch_assoc()) {
$id = $rowGetMats['idGMatProf'];
$nameMat = $rowGetMats['mat'];
$idGrupo = $rowGetMats['idGrupo'];
$nameGrupo = $rowGetMats['grupo'];
$yearGrupo = $rowGetMats['year'];
$turnoGrupo = $rowGetMats['turno'];
$gradoGrupo = $rowGetMats['grado'];
$planEst = $rowGetMats['planEstudios'];
$idPeriodo = $rowGetMats['idPeriodo'];
$mats[] = array('id' => $id, 'materia' => $nameMat, 'grupo' => $nameGrupo,
'idGrupo'=>$idGrupo, 'year'=>$yearGrupo, 'turno'=>$turnoGrupo, 'grado'=>$gradoGrupo,
'planEst' => $planEst, 'idPeriodo' => $idPeriodo);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No tienes materias asignadas, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $mats, "sql" => $sqlGetMats));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$profes = array();
$msgErr = '';
$ban = false;
$sqlGetProf = "SELECT $tUsers.*, $tUsers.nombre as nameUser, $tEdos.nombre as estado FROM $tUsers INNER JOIN $tEdos ON $tEdos.id=$tUsers.estado_id WHERE perfil_id='3' ";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetProf .= " AND $tUsers.nombre LIKE '%$query%' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetProf .= " ORDER BY " . $vorder;
}
$resGetProf = $con->query($sqlGetProf);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['id'];
$name = $rowGetProf['nameUser'];
$user = $rowGetProf['user'];
$edoId = $rowGetProf['estado_id'];
$edo = $rowGetProf['estado'];
$profes[] = array('id' => $id, 'nombre' => $name, 'user' => $user, 'estado' => $edo, 'edoId' => $edoId);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen profesores aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $profes));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$students = array();
$rubricas = array();
$msgErr = '';
$ban = true;
$idGrupo = $_POST['idGrupo'];
$idRubrica = $_POST['idRubricaInfo'];
//Obtenemos alumnos
$sqlGetStudents = "SELECT $tUsers.id as idStudent, $tUsers.nombre as nameStudent "
. "FROM $tGAlum "
. "INNER JOIN $tUsers ON $tUsers.id = $tGAlum.user_alumno_id "
. "WHERE $tGAlum.grupo_info_id = '$idGrupo' ORDER BY nameStudent ";
/*$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$idStudent = $rowGetStudents['idStudent'];
$name = $rowGetStudents['nameStudent'];
$students[] = array('idStudent' => $idStudent, 'nameStudent' => $name);
}
}else {
$ban = false;
$msgErr .= 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}*/
//Obtenemos las rubricas
$sqlGetRubricas = "SELECT $tRubInfoCalif.id as idRub, $tRubInfoCalif.fecha as fechaRub, "
. "$tRubInfoCalif.nombre as nombreRub "
. "FROM $tRubInfoCalif "
. "WHERE $tRubInfoCalif.rubrica_info_id = '$idRubrica' ";
$resGetRubricas = $con->query($sqlGetRubricas);
if ($resGetRubricas->num_rows > 0) {
while ($rowGetRubricas = $resGetRubricas->fetch_assoc()) {
$idRub = $rowGetRubricas['idRub'];
$fechaRub = $rowGetRubricas['fechaRub'];
$nombreRub = $rowGetRubricas['nombreRub'];
$rubricas[] = array('idRub' => $idRub, 'fechaRub' => $fechaRub, 'nombreRub' => $nombreRub);
}
}else{
$ban = false;
$msgErr .= 'No existen calificaciones en ésta rubrica, aún.<br>' . $con->error;
}
$cadSqlRub = '';
/*
//foreach($rubricas as $key => $value){
foreach($students as $key2 => $value2){
//foreach($students as $key2 => $value2){
foreach($rubricas as $key => $value){
$idRubArr = $value['idRub'];
$idStudent = $value2['idStudent'];
$sqlGetCalifRub = "SELECT $tRubDetCalif.id as idDetCalif, $tRubDetCalif.calificacion as califRub "
. "FROM $tRubDetCalif "
. "WHERE $tRubDetCalif.user_alumno_id = '$idStudent' "
. "AND $tRubDetCalif.rubrica_info_calif_id = '$idRubArr' ";
//. "WHERE $tRubDetCalif.rubrica_info_calif_id = '$idRubArr' "
//. "AND $tRubDetCalif.user_alumno_id = '$idStudent' ";
$cadSqlRub .= $sqlGetCalifRub .';';
$resGetCalifRub = $con->query($sqlGetCalifRub);
if($resGetCalifRub->num_rows > 0){
while($rowGetCalifRubricas = $resGetCalifRub->fetch_assoc()){
$idDetCalif = $rowGetCalifRubricas['idDetCalif'];
$califRub = $rowGetCalifRubricas['califRub'];
$calRubricas[] = array('idDetCalif' => $idDetCalif, 'califRub' => $califRub);
}
}else{
$ban = false;
$msgErr .= 'No existen alumnos en éste grupo, aún.<br>' . $con->error;
break;
}
}
}
* */
$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$idStudent = $rowGetStudents['idStudent'];
$name = $rowGetStudents['nameStudent'];
$calRubricas = array();
foreach($rubricas as $key => $value){
$idRubArr = $value['idRub'];
//Obtenemos las calificaciones de los estudiantes
$sqlGetCalifRub = "SELECT $tRubDetCalif.id as idDetCalif, $tRubDetCalif.calificacion as califRub "
. "FROM $tRubDetCalif "
. "WHERE $tRubDetCalif.rubrica_info_calif_id = '$idRubArr' "
. "AND $tRubDetCalif.user_alumno_id = '$idStudent' ";
$resGetCalifRub = $con->query($sqlGetCalifRub);
if($resGetCalifRub->num_rows > 0){
while($rowGetCalifRubricas = $resGetCalifRub->fetch_assoc()){
$idDetCalif = $rowGetCalifRubricas['idDetCalif'];
$califRub = $rowGetCalifRubricas['califRub'];
$calRubricas[] = array('idDetCalif' => $idDetCalif, 'califRub' => $califRub);
}
}else{
$ban = false;
$msgErr .= 'No existen alumnos en éste grupo, aún.<br>' . $con->error;
break;
}
}
$students[] = array('idStudent' => $idStudent, 'nameStudent' => $name, 'cals' => $calRubricas);
}
}else {
$ban = false;
$msgErr .= 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "students" => $students, "rubricas" => $rubricas, "calRubricas" => $calRubricas,
"sql" => $sqlGetStudents, "sql2"=>$sqlGetRubricas, "sql3"=>$cadSqlRub));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr,
"sql" => $sqlGetStudents, "sql2"=>$sqlGetRubricas, "sql3"=>$cadSqlRub));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$countCals = count($_POST['inputCalif']);
$cad = '';
$ban = false;
for($i = 0; $i < $countCals; $i++) {
$idDetCalif = $_POST['inputIdDetCalif'][$i];
$califAlum = $_POST['inputCalif'][$i];
$sqlUpdateRubDetCalif = "UPDATE $tRubDetCalif SET calificacion = '$califAlum' WHERE id = '$idDetCalif' ";
if ($con->query($sqlUpdateRubDetCalif) === TRUE) {
$ban = true;
$cad .= 'Calificación del alumno: ' . $idDetCalif . ', actualizada con éxito.';
} else {
$cad .= 'Error al actualizar calificación del alumno: ' . $idDetCalif . '<br>' . $con->error;
$ban = false;
break;
}
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Favicon -->
<link rel="shortcut icon" href="../dist/img/logo_ico.png">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="../components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="../components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="../components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
<!-- AdminLTE Skins. Choose a skin from the css/skins -->
<link rel="stylesheet" href="../dist/css/skins/_all-skins.min.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
<?php
include('../config/variables.php');
include('../config/conexion.php');
?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME>ada (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="index2.html" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>PEC</b></span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>PEC</b></span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success">4</span>
</a>
</li>
<!-- Notifications: style can be found in dropdown.less -->
<li class="dropdown notifications-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-bell-o"></i>
<span class="label label-warning">10</span>
</a>
</li>
<!-- Tasks: style can be found in dropdown.less -->
<li class="dropdown tasks-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag-o"></i>
<span class="label label-danger">9</span>
</a>
</li>
<!-- User Account: style can be found in dropdown.less -->
<li class="dropdown user user-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="<?= $folderUpPerfil.$_SESSION['userLogo']; ?>" class="user-image" alt="User Image">
<span class="hidden-xs"><?= $_SESSION['userName']; ?></span>
</a>
<ul class="dropdown-menu">
<!-- User image -->
<li class="user-header">
<img src="<?= $folderUpPerfil.$_SESSION['userLogo']; ?>" class="img-circle" alt="User Image">
<p>
<?= $_SESSION['userName'].' - '.$_SESSION['namePerfil']; ?>
<small>Miembro desde 2017</small>
</p>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="#" class="btn btn-default btn-flat">Perfil <i class="fa fa-user" aria-hidden="true"></i></a>
</div>
<div class="pull-right">
<a href="../controllers/proc_destroy_login.php" class="btn btn-default btn-flat">Salir <i class="fa fa-sign-out" aria-hidden="true"></i></a>
</div>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu" data-widget="tree">
<li class="header">Menú</li>
<?php
include('../controllers/menu.php');
?>
<!-- <li class="treeview">
<a href="#">
<i class="fa fa-files-o"></i>
<span>Layout Options</span>
<span class="pull-right-container">
<span class="label label-primary pull-right">4</span>
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<li><a href="pages/layout/top-nav.html"><i class="fa fa-circle-o text-aqua"></i> Top Navigation</a></li>
<li><a href="pages/layout/boxed.html"><i class="fa fa-circle-o text-aqua"></i> Boxed</a></li>
<li><a href="pages/layout/fixed.html"><i class="fa fa-circle-o text-aqua"></i> Fixed</a></li>
<li><a href="pages/layout/collapsed-sidebar.html"><i class="fa fa-circle-o text-aqua"></i> Collapsed Sidebar</a></li>
</ul>
</li> -->
</ul>
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Escritorio
<small>Panel de Control</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Escritorio</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 0.0.1
</div>
<strong>Copyright © 2017 <a href="http://solucionesynegocios.com.mx">Software de México: Soluciones y Negocios S.A.S. de C.V. <img src="../dist/img/ico_nube.png" width="30px"> </a> </strong> Todos los derechos reservados.
</footer>
</div>
<!-- ./wrapper -->
<!-- jQuery 3 -->
<script src="../components/jquery/dist/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="../components/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Bootstrap 3.3.7 -->
<script src="../components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="../dist/js/adminlte.min.js"></script>
</body>
</html>
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$planes = array();
$msgErr = '';
$ban = false;
$sqlGetPlanEst = "SELECT planes_estudios.id as idPlanEst, planes_estudios.nombre as namePlanEst, planes_estudios.year as yearPlanEst "
. " FROM planes_estudios WHERE 1=1 ";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetPlanEst .= " AND (planes_estudios.nombre LIKE '%$query%' OR planes_estudios.year LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idPlanEst2 = $_POST['idPlanEst'];
$sqlGetPlanEst .= " AND planes_estudios.id = '$idPlanEst2' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetPlanEst .= " ORDER BY " . $vorder;
}
$resGetProf = $con->query($sqlGetPlanEst);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['idPlanEst'];
$name = $rowGetProf['namePlanEst'];
$year = $rowGetProf['yearPlanEst'];
$planes[] = array('id' => $id, 'nombre' => $name, 'year' => $year );
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen planes de estudio, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $planes, "sql" => $sqlGetPlanEst));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 2) {
$idUser = $_SESSION['userId'];
$idGrupo = $_GET['idGrupo'];
$idPerInfo = $_GET['idPerInfo'];
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<form id="formCalifRub" name="formCalifRub">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-4">
<input type="hidden" id="inputIdPeriodo" name="inputIdPeriodo" >
<label for="inputRubricas">Selecciona el periodo a visualizar:</label>
<select class="form-control" id="inputPeriodo" name="inputPeriodo"></select>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Alumnos</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</form>
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
//Obtenemos los periodos
$.ajax({
type: "POST",
data: {idGrupo: <?=$idGrupo; ?>, tarea: "periodo", idPeriodo: <?= $idPerInfo; ?>},
url: "../controllers/get_periodos_fechas.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$(".content-header #inputPeriodo").html("<option></option>");
if(msg.error == 0){
$(".content-header #inputPeriodo").append($('<option>', {
value: 0,
text: "TODOS"
}));
$.each(msg.dataRes, function (i, item) {
$(".content-header #inputPeriodo").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].fInicio + " a " + msg.dataRes[i].fFin
}));
});
}else{
$(".content-header #inputPeriodo").html("<option>"+msg.msgErr+"</option>");
}
}
});
$(".content-wrapper").on('change', '#inputPeriodo', function(){
var idPerFecha = $(this).val();
console.log(idPerFecha);
$("#inputIdRubrica").val(idPerFecha);
$("#data thead").html("");
$("#data tbody").html("");
if(idPerFecha == 0){
$.ajax({
type: "POST",
data: {idGrupo: <?= $idGrupo; ?>},
url: "../controllers/get_calif_alumnos_mats.php",
success: function(msg2){
console.log(msg2);
msg2 = jQuery.parseJSON(msg2);
if(msg2.error == 0){
//Añadimos cabecerás
var newRowTH = '<tr><th>Nombre</th>';
var cantMat = 0;
$.each(msg2.mats, function(i, item){
newRowTH += '<th>' + msg2.mats[i].nameMat + '</th>';
cantMat++;
});
newRowTH += '<th>Promedio</th>';
newRowTH += '</tr>';
$(newRowTH).appendTo("#data thead");
//Añadimos alumnos y sus calificaciones
var newRowTB = '';
var sumV = 0, promV = 0, cantV = 0, promHV = 0, sumHV = 0;
var matrizCal = new Array();
$.each(msg2.students, function(j, item){
var sumH =0, promH = 0, cantH = 0;
cantV++;
newRowTB += '<tr>'
newRowTB += '<td>' + msg2.students[j].nameStudent + '</td>';
$.each(msg2.mats, function(k, item){
if(j == 0) matrizCal[k] = 0;//Rellenamos primero con ceros la posición inicial
var promMat = parseFloat(msg2.students[j].cals[k].promMat);
promMat = promMat.toFixed(2);
newRowTB += '<td>' + promMat + '</td>';
sumH += parseFloat(msg2.students[j].cals[k].promMat);
cantH++;
matrizCal[k] += parseFloat(msg2.students[j].cals[k].promMat);
})
promH = sumH / cantH;
promH = promH.toFixed(2);
sumHV += parseFloat(promH);
newRowTB += '<td><b>' + promH + '</b></td>';
newRowTB += '</tr>';
});
console.log(matrizCal);
newRowTB += '<tr><td><b>Promedio por materia: </b></td>';
for(var l = 0; l < matrizCal.length; l++){
promV = matrizCal[l] / cantV;
promV = promV.toFixed(2);
newRowTB += '<td><b>' + promV + '</b></td>';
}
promHV = sumHV / cantV;
promHV = promHV.toFixed(2);
newRowTB += '<td><b>'+promHV+'</b></td></tr>';
$(newRowTB).appendTo("#data tbody");
}else{
var newRow = '<tr><td colspan="3">' + msg2.msgErr + '</td></tr>';
$("#data thead").html(newRow);
}
}
});
}else{
//Si salio correcto cargamos los alumnos y las rubricas
$.ajax({
type: "POST",
data: {idPeriodoFecha: idPerFecha, idGrupo: <?= $idGrupo; ?>},
url: "../controllers/get_calif_alumnos_mats.php",
success: function(msg2){
console.log(msg2);
msg2 = jQuery.parseJSON(msg2);
if(msg2.error == 0){
//Añadimos cabecerás
var newRowTH = '<tr><th>Nombre</th>';
var cantMat = 0;
$.each(msg2.mats, function(i, item){
newRowTH += '<th>' + msg2.mats[i].nameMat + '</th>';
cantMat++;
});
newRowTH += '<th>Promedio</th>';
newRowTH += '</tr>';
$(newRowTH).appendTo("#data thead");
//Añadimos alumnos y sus calificaciones
var newRowTB = '';
var sumV = 0, promV = 0, cantV = 0, promHV = 0, sumHV = 0;
var matrizCal = new Array();
$.each(msg2.students, function(j, item){
var sumH =0, promH = 0, cantH = 0;
cantV++;
newRowTB += '<tr>'
newRowTB += '<td>' + msg2.students[j].nameStudent + '</td>';
$.each(msg2.mats, function(k, item){
if(j == 0) matrizCal[k] = 0;//Rellenamos primero con ceros la posición inicial
//var promMat = msg2.students[j].mats[k].promMat;
//console.log(promMat);
if(msg2.students[j].cals[k].promMat == "N/D"){
newRowTB += '<td>N/D</td>';
sumH += 0;
matrizCal[k] += 0;
}else{
newRowTB += '<td>' + msg2.students[j].cals[k].promMat + '</td>';
sumH += parseFloat(msg2.students[j].cals[k].promMat);
matrizCal[k] += parseFloat(msg2.students[j].cals[k].promMat);
}
cantH++;
})
promH = sumH / cantH;
promH = promH.toFixed(2);
sumHV += parseFloat(promH);
newRowTB += '<td><b>' + promH + '</b></td>';
newRowTB += '</tr>';
});
console.log(matrizCal);
newRowTB += '<tr><td><b>Promedio por materia: </b></td>';
for(var l = 0; l < matrizCal.length; l++){
promV = matrizCal[l] / cantV;
promV = promV.toFixed(2);
newRowTB += '<td><b>' + promV + '</b></td>';
}
promHV = sumHV / cantV;
promHV = promHV.toFixed(2);
newRowTB += '<td><b>'+promHV+'</b></td></tr>';
$(newRowTB).appendTo("#data tbody");
}else{
var newRow = '<tr><td colspan="3">' + msg2.msgErr + '</td></tr>';
$("#data thead").html(newRow);
}
}
});
}
});
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idUser = $_POST['idStudent'];
$ban = false;
$msgErr = '';
$sqlDeleteStudent = "UPDATE $tUsers SET estado_id='2' WHERE id='$idUser' ";
//echo $sqlDeleteProf;
if($con->query($sqlDeleteStudent) === TRUE){
$ban = true;
}else{
$banTmp = false;
$msgErr = 'Error al dar de baja al alumno.'.$con->error;
}
if($ban){
$msgErr = 'Se elimino con éxito.';
echo json_encode(array("error"=>0, "dataRes"=>$msgErr));
}else{
echo json_encode(array("error"=>1, "dataRes"=>$msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$grupos = array();
$msgErr = '';
$ban = false;
$sqlGetGrupo = "SELECT $tGInfo.id as idGrupo, $tGInfo.nombre as grupo, $tTurn.nombre as turno, "
. "$tGrade.nombre as grado, $tGInfo.year as year, $tPlanEst.nombre as planEst, "
. "$tGInfo.periodo_info_id "
. "FROM $tGInfo "
. "INNER JOIN $tGrade ON $tGrade.id = $tGInfo.nivel_grado_id "
. "INNER JOIN $tTurn ON $tTurn.id = $tGInfo.nivel_turno_id "
. "INNER JOIN $tPlanEst ON $tPlanEst.id = $tGInfo.plan_estudios_id "
. "WHERE 1=1";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetGrupo .= " AND ($tGInfo.nombre LIKE '%$query%' OR $tGInfo.year LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idGrupo = $_POST['idGrupo'];
$sqlGetGrupo .= " AND $tGInfo.id = '$idGrupo' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetGrupo .= " ORDER BY " . $vorder;
} else {
$sqlGetGrupo .= " ORDER BY $tGInfo.nombre ";
}
$resGetGrupo = $con->query($sqlGetGrupo);
if ($resGetGrupo->num_rows > 0) {
while ($rowGetGrupo = $resGetGrupo->fetch_assoc()) {
$id = $rowGetGrupo['idGrupo'];
$grupo = $rowGetGrupo['grupo'];
$turno = $rowGetGrupo['turno'];
$grado = $rowGetGrupo['grado'];
$year = $rowGetGrupo['year'];
$planEst = $rowGetGrupo['planEst'];
$perInfoId = $rowGetGrupo['periodo_info_id'];
$grupos[] = array('id'=>$id, 'grupo' => $grupo, 'turno' => $turno,
'grado'=>$grado, 'year'=>$year, 'planEst'=>$planEst, 'perInfoId'=>$perInfoId);
$ban = true;
$msgErr = 'Grupos hallados.';
}
} else {
$ban = false;
$msgErr = 'No existen grupos aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "msgErr" => $msgErr, "dataRes" => $grupos));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr, "sql"=>$sqlGetGrupo));
}
?><file_sep><?php
if (isset($_SESSION['sessU']) AND $_SESSION['sessU'] == "true") {
$cadMenuNavbar = '';
if ($_SESSION['userPerfil'] == "1") {//Director
$cadMenuNavbar .= '<li><a href="director_planes_estudios.php"><i class="fa fa-list text-yellow"></i> <span>Planes de estudio</span></a></li>';
$cadMenuNavbar .= '<li><a href="director_ciclos.php"><i class="fa fa-clock text-yellow"></i> <span>Ciclos Escolares</span></a></li>';
$cadMenuNavbar .= '<li><a href="director_grupos.php"><i class="fa fa-list text-yellow"></i> <span>Grupos</span></a></li>';
} else if ($_SESSION['userPerfil'] == "2") {//Administrativo
$cadMenuNavbar .= '<li><a href="administrativo_grupos.php"><i class="fa fa-users text-red"></i> <span>Grupos</span></a></li>';
$cadMenuNavbar .= '<li><a href="administrativo_profesores.php"><i class="fa fa-user text-aqua"></i> <span>Profesores</span></a></li>';
$cadMenuNavbar .= '<li><a href="#"><i class="fa fa-graduation-cap text-yellow"></i> <span>Alumnos</span></a></li>';
$cadMenuNavbar .= '<li><a href="administrativo_materias.php"><i class="fa fa-book text-green"></i> <span>Materías</span></a></li>';
} else if ($_SESSION['userPerfil'] == "3") {//Profesor
$cadMenuNavbar .= '<li><a href="profesor_grupos.php"><i class="fa fa-list text-yellow"></i> <span>Grupos</span></a></li>';
} else if ($_SESSION['userPerfil'] == "4") {//Alumno
} else if ($_SESSION['userPerfil'] == "5") { //Tutor
} else if ($_SESSION['userPerfil'] == "10") { //Sysadmin
} else {
$cadMenuNavbar .= '<li>¿Cómo llegaste hasta acá?</li>';
}
echo $cadMenuNavbar;
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$mats = array();
$msgErr = '';
$ban = false;
$idGrupo = $_POST['idGrupo'];
$sqlGetMatsProf = "SELECT $tGMatProf.id as idGMatProf, $tMats.nombre as nameMat, "
. " $tUsers.nombre as nameProf "
. " FROM $tGMatProf "
. " INNER JOIN $tMats ON $tMats.id = $tGMatProf.banco_materia_id "
. " INNER JOIN $tUsers ON $tUsers.id = $tGMatProf.user_profesor_id "
. " WHERE $tGMatProf.grupo_info_id = '$idGrupo' ";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetMatsProf .= " AND ($tMats.nombre LIKE '%$query%' OR $tGrade.nombre LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idMat = $_POST['idMat'];
$sqlGetMatsProf .= " AND $tMats.id = '$idMat' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetMatsProf .= " ORDER BY " . $vorder;
} else {
$sqlGetMatsProf .= " ORDER BY idGMatProf ";
}
$resGetProf = $con->query($sqlGetMatsProf);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['idGMatProf'];
$nameMat = $rowGetProf['nameMat'];
$nameProf = $rowGetProf['nameProf'];
$mats[] = array('id' => $id, 'materia' => $nameMat, 'profesor' => $nameProf);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen materias en este grupo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $mats, "sql" => $sqlGetMatsProf));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$mats = array();
$msgErr = '';
$ban = false;
$idPlan = $_POST['idPlan'];
$sqlGetMatsPlanEst = "SELECT $tMats.id as idMat, $tMats.nombre as nameMat, "
. " $tGrade.nombre as nameGrade "
. " FROM $tMats INNER JOIN $tGrade ON $tGrade.id=$tMats.nivel_grado_id "
. " WHERE $tMats.plan_estudio_id = '$idPlan' ";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetMatsPlanEst .= " AND ($tMats.nombre LIKE '%$query%' OR $tGrade.nombre LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idMat = $_POST['idMat'];
$sqlGetMatsPlanEst .= " AND $tMats.id = '$idMat' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetMatsPlanEst .= " ORDER BY " . $vorder;
} else {
$sqlGetMatsPlanEst .= " ORDER BY nameGrade ";
}
$resGetProf = $con->query($sqlGetMatsPlanEst);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['idMat'];
$nameMat = $rowGetProf['nameMat'];
$nameGrade = $rowGetProf['nameGrade'];
$mats[] = array('id' => $id, 'nombre' => $nameMat, 'grado' => $nameGrade);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen materias en este plan de estudio, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $mats, "sql" => $sqlGetMatsPlanEst));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idPeriodo = $_POST['inputIdPeriodo'];
$idGMatProf = $_POST['inputIdGMatProf'];
$name = $_POST['inputName'];
$cad = '';
$ban = false;
$sqlInsertRubrica = "INSERT INTO $tRubInfo"
. "(nombre, grupo_mat_prof_id, periodo_fecha_id, estado_id, creado) "
. "VALUES ('$name', '$idGMatProf', '$idPeriodo', '1', '$dateNow' ) ";
if ($con->query($sqlInsertRubrica) === TRUE) {
$ban = true;
$cad .= 'Rubrica añadida con éxito.';
} else {
$ban = false;
$cad .= 'Error al crear nueva rubrica.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idMat = $_POST['inputIdMat'];
$matName = $_POST['inputName'];
$matGrado = $_POST['inputGrado'];
$cad = '';
$ban = false;
$sqlUpdateMat = "UPDATE $tMats SET nombre='$matName', nivel_grado_id='$matGrado', actualizado='$dataTimeNow' WHERE id='$idMat' ";
if($con->query($sqlUpdateMat) === TRUE){
$ban = true;
$cad .= 'Plan de estudios modificado con éxito.';
}else{
$ban = false;
$cad .= 'Error al actualizar Plan de Estudios.<br>'.$con->error;
}
//$ban = true;
if($ban){
echo json_encode(array("error"=>0, "msg"=>$cad));
}else{
echo json_encode(array("error"=>1, "msg"=>$cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$mats = array();
$msgErr = '';
$ban = false;
$sqlGetProf = "SELECT $tMats.id as idMat, $tMats.nombre as nameMat, $tGrade.nombre as nameGrade "
. "FROM $tMats "
. "INNER JOIN $tGrade ON $tGrade.id = $tMats.nivel_grado_id ";
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetProf .= " WHERE $tMats.nombre LIKE '%$query%' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetProf .= " ORDER BY " . $vorder;
}
$resGetProf = $con->query($sqlGetProf);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['idMat'];
$nameMat = $rowGetProf['nameMat'];
$nameGrade = $rowGetProf['nameGrade'];
$mats[] = array('id' => $id, 'nombre' => $nameMat, 'grado' => $nameGrade);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen materias aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $mats));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 3) {
$idUser = $_SESSION['userId'];
$idGMatProf = $_GET['idGMatProf'];
$idGrupo = $_GET['idGrupo'];
$idPeriodo = $_GET['idPeriodo'];
$nameMat = $_GET['nameMat'];
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar por nombre" id="buscar" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="load(1);"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div class="col-xs-4"></div>
<div class="col-xs-5 ">
<div class="btn-group pull-right">
</div>
</div>
</div>
<!-- modal ver rubricas -->
<div class="modal fade" id="modalViewRub" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Ver Rubricas</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<div class="row text-center buttonAddRub">
</div>
<br>
<table class="table table-striped rubricasInfo">
<thead>
<tr><th>Nombre</th><th>Actualizar</th><th>Eliminar</th></tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- ./modal-body -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
<!-- fin modal -->
<!-- modal añadir rubricas -->
<form class="form-horizontal" id="formAddRub" name="formAddRub">
<div class="modal fade" id="modalAddRub" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Añadir Rubrica</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="hidden" id="inputIdPeriodo" name="inputIdPeriodo" >
<input type="hidden" id="inputIdGMatProf" name="inputIdGMatProf" >
<div class="form-group">
<label for="inputMat" class="col-sm-3 control-label">Rubrica: </label>
<div class="col-sm-9">
<input class="form-control" id="inputName" name="inputName" required>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal actualizar rubricas -->
<form class="form-horizontal" id="formUpdRub" name="formUpdRub">
<div class="modal fade" id="modalUpdRub" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Actualizar Rubrica</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="hidden" id="inputIdRubrica" name="inputIdRubrica" >
<div class="form-group">
<label for="inputMat" class="col-sm-3 control-label">Rubrica: </label>
<div class="col-sm-9">
<input class="form-control" id="inputName" name="inputName" required>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal terminar ciclo -->
<form class="form-horizontal" id="formEndPeriod" name="formEndPeriod">
<div class="modal fade" id="modalEndPeriod" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Terminar periodo</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input id="inputUserId" name="inputUserId" >
<input id="inputPeriodoFecha" name="inputPeriodoFecha" >
<input id="inputGMatProf" name="inputGMatProf" >
<input id="inputIdGrupo" name="inputIdGrupo" >
<table class="table table-striped rubricasInfo">
<thead>
<tr><th>Nombre</th><th>%</th></tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary" disabled>Terminar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Periodos de la materia: <span class="txtTitle"><?=$nameMat;?></span></h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="grupo">Periodo</span></th>
<th><span title="grupo">Inicio</span></th>
<th><span title="grupo">Cierre</span></th>
<th><span title="grupo">Acciones</span></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
filtrar();
function filtrar() {
$(".loader").show();
$.ajax({
type: "POST",
data: {tarea: "periodo", idPeriodo: <?=$idPeriodo;?>, orderby: ordenar},
url: "../controllers/get_periodos_fechas.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td>' + (i+1) + '</td>'
+ '<td>' + msg.dataRes[i].fInicio + '</td>'
+ '<td>' + msg.dataRes[i].fFin + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li><a href="#" data-toggle="modal" data-target="#modalViewRub" id="verRubrica" data-value="'+msg.dataRes[i].id+'"><i class="fa fa-eye"></i> Ver Rubricas</a></li>'
+ '<li><a href="prof_create_rubrica.php?idGMatProf='+<?=$idGMatProf;?>
+ '&idGrupo=' + <?=$idGrupo;?> + '&idPeriodo=' + <?=$idPeriodo;?>
+ '&idPeriodoFecha=' + msg.dataRes[i].id + '"><i class="fa fa-check"></i> Evaluar Rubrica</a></li>'
+ '<li><a href="prof_update_rubrica.php?idGMatProf='+<?=$idGMatProf;?>
+ '&idGrupo=' + <?=$idGrupo;?> + '&idPeriodo=' + <?=$idPeriodo;?>
+ '&idPeriodoFecha=' + msg.dataRes[i].id + '"><i class="fa fa-edit"></i> Modificar Rubrica</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalEndPeriod" id="endRubrica" data-value="'+msg.dataRes[i].id+'"><i class="fa fa-hourglass-end"></i> Terminar periodo</a></li>'
+ '<li><a href="prof_view_rubricas_cal.php?idGMatProf='+<?=$idGMatProf;?>
+ '&idGrupo=' + <?=$idGrupo;?> + '&idPeriodo=' + <?=$idPeriodo;?>
+ '&idPeriodoFecha=' + msg.dataRes[i].id + '"><i class="fa fa-eye"></i> Ver calificaciones</a></li>'
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
$(".loader").hide();
}
//Ordenar ASC y DESC header tabla
$("#data th span").click(function () {
if ($(this).hasClass("desc")) {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("asc");
//ordenar = "&orderby="+$(this).attr("title")+" asc";
ordenar = $(this).attr("title") + " asc";
} else {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("desc");
//ordenar = "&orderby="+$(this).attr("title")+" desc";
ordenar = $(this).attr("title") + " desc";
}
filtrar();
});
//Cargar rubricas a ventana modal
$("#data").on("click", "#verRubrica", function(){
var idPeriodoFecha = $(this).data("value");
//$("#modalViewMats #addMat .buttonAddMat").data("whatever", idGrupo);
$("#modalViewRub .buttonAddRub").html('<button type="button" class="btn btn-danger" id="addRub" data-toggle="modal" data-target="#modalAddRub" data-whatever="'+idPeriodoFecha+'" >Crear Rubrica</button>');
console.log(idPeriodoFecha);
$.ajax({
type: "POST",
data: {idGMatProf: <?= $idGMatProf; ?>, idPeriodoFecha: idPeriodoFecha},
url: "../controllers/get_rubricas_info.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalViewRub .rubricasInfo tbody").html("");
if(msg.error == 0){
var newRow = '';
$.each(msg.dataRes, function(i, item){
newRow += '<tr>';
newRow += '<td>'+msg.dataRes[i].nombre+'</td>';
newRow += '<td>'
+'<button type="button" class="btn btn-primary" id="updRub" data-whatever="'+msg.dataRes[i].id+'" data-grupo="" data-toggle="modal" data-target="#modalUpdRub">'
+'Actualizar rubrica'
+'</button></td>';
newRow += '<td>'
+'<button type="button" class="btn btn-danger" id="delReb" value="'+msg.dataRes[i].id+'"><span class="glyphicon glyphicon-remove"></span></button>'
+'</td>';
newRow += '</tr>';
});
$(newRow).appendTo("#modalViewRub .rubricasInfo tbody");
}else{
var newRow = '<tr><td>'+msg.msgErr+'</td></tr>';
$(newRow).appendTo("#modalViewRub .rubricasInfo tbody");
}
}
});
});
//Añadir rubrica a periodo
$("#modalViewRub").on("click", "#addRub", function(){
var idPeriodo = $(this).data("whatever");
$("#modalAddRub .modal-body #inputIdPeriodo").val(idPeriodo);
$("#modalAddRub .modal-body #inputIdGMatProf").val(<?=$idGMatProf;?>);
console.log("hola "+idPeriodo);
});
//Actualizar rubrica
$("#modalViewRub").on("click", "#updRub", function(){
var idRubrica = $(this).data("whatever");
$("#modalUpdRub .modal-body #inputIdRubrica").val(idRubrica);
console.log("hola "+idRubrica);
$.ajax({
type: "POST",
data: {idRubrica: idRubrica},
url: "../controllers/get_rubricas_info.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
console.log(msg);
$("#modalUpdRub .modal-body #inputName").html("");
if(msg.error == 0){
$("#modalUpdRub .modal-body #inputName").val(msg.dataRes[0].nombre);
}else{
$("#modalUpdRub .modal-body #inputName").val(msg.msgErr);
}
}
});
});
//Añadir rubrica
$('#formAddRub').validate({
rules: {
inputName: {required: true},
},
messages: {
inputName: "Nombre obligatorio",
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_rubrica_info.php",
data: $('form#formAddRub').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalAddRub .divError').css({color: "#77DD77"});
$('#modalAddRub .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalAddRub .divError').css({color: "#FF0000"});
$('#modalAddRub .divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al crear rubrica.");
}
});
}
}); // end añadir rubrica
//Actualizar rubrica
$('#formUpdRub').validate({
rules: {
inputName: {required: true},
},
messages: {
inputName: "Nombre obligatorio",
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_rubrica_info.php",
data: $('form#formUpdRub').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalUpdRub .modal-header .divError').css({color: "#77DD77"});
$('#modalUpdRub .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalUpdRub .modal-header .divError').css({color: "#FF0000"});
$('#modalUpdRub .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al actualizar rubrica.");
}
});
}
}); // end añadir rubrica
//Terminar periodo
$("#data").on("click", "#endRubrica", function(){
var idPeriodoFecha = $(this).data("value");
$("#modalEndPeriod #inputUserId").val(<?= $idUser; ?>);
$("#modalEndPeriod #inputPeriodoFecha").val(idPeriodoFecha);
$("#modalEndPeriod #inputGMatProf").val(<?= $idGMatProf; ?>);
$("#modalEndPeriod #inputIdGrupo").val(<?= $idGrupo; ?>);
console.log(idPeriodoFecha);
$.ajax({
type: "POST",
data: {idGMatProf: <?= $idGMatProf; ?>, idPeriodoFecha: idPeriodoFecha},
url: "../controllers/get_rubricas_info.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalEndPeriod .rubricasInfo tbody").html("");
if(msg.error == 0){
var newRow = '';
$.each(msg.dataRes, function(i, item){
newRow += '<tr>';
newRow += '<td><input type="hidden" id="inputIdRubInfo" name="inputIdRubInfo[]" value="'+msg.dataRes[i].id+'">'+msg.dataRes[i].nombre+'</td>';
if(msg.dataRes[i].edo == 1)
newRow += '<td><input type="number" id="porcRub" name="porcRub[]" class="form-control cantPorc" value="0"></td>';
else
newRow += '<td><input type="number" id="porcRub" name="porcRub[]" class="form-control " value="'+msg.dataRes[i].porcentaje+'" readonly></td>';
newRow += '</tr>';
});
newRow += '<tr><td>Total: </td>';
if(msg.dataRes[0].edo == 1)
newRow += '<td><input type="number" disabled class="form-control" id="inputTotalRub"></td></tr>';
else
newRow += '<td><input type="number" disabled class="form-control" id="inputTotalRub" value="100.00"></td></tr>';
$(newRow).appendTo("#modalEndPeriod .rubricasInfo tbody");
}else{
var newRow = '<tr><td>'+msg.msgErr+'</td><td></td></tr>';
$(newRow).appendTo("#modalEndPeriod .rubricasInfo tbody");
}
}
});
});
$("#modalEndPeriod .rubricasInfo tbody").on("keyup change blur keypress keydown", ".cantPorc", calcPorc);
function calcPorc(){
var totalRub = 0;
$("#modalEndPeriod .rubricasInfo tbody #porcRub").each(function(){
totalRub += parseInt($(this).val());
})
totalRub = totalRub.toFixed(2);
console.log(totalRub);
$("#modalEndPeriod .rubricasInfo tbody #inputTotalRub").val(totalRub);
if(totalRub == 100.00) $("#modalEndPeriod #guardar_datos").removeAttr("disabled");
else $("#modalEndPeriod #guardar_datos").attr("disabled", true);
}
//Terminar periodo
$('#formEndPeriod').validate({
rules: {
'porcRub[]': {required: true, range: [0, 100], digits: true}
},
messages: {
'porcRub[]': {
required: "Porcentaje de la rubrica obligatorio",
range: "Solo números entre 0 y 100",
digits: "Solo se permiten números enteros."
}
},
tooltip_options:{
'porcRub[]': {trigger: "focus", placement: "bottom"}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_rubrica_info_porcentajes.php",
data: $('form#formEndPeriod').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalEndPeriod .divError').css({color: "#77DD77"});
$('#modalEndPeriod .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalEndPeriod .divError').css({color: "#FF0000"});
$('#modalEndPeriod .divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al actualizar porcentajes de las rubricas.");
}
});
}
}); // end añadir rubrica
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 3) {
$idUser = $_SESSION['userId'];
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar por nombre" id="buscar" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="load(1);"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div class="col-xs-4"></div>
<div class="col-xs-5 ">
<div class="btn-group pull-right">
</div>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Listado de Materias</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="grupo">Materia</span></th>
<th><span title="grupo">Grupo</span></th>
<th><span title="grado">Grado</span></th>
<th><span title="turno">Turno</span></th>
<th><span title="year">Año</span></th>
<th><span title="planEst">Plan de Estudios</span></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
filtrar();
function filtrar() {
$(".loader").show();
$.ajax({
type: "POST",
data: {idUser: <?= $idUser; ?>, orderby: ordenar},
url: "../controllers/get_mats_grupos_by_prof.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr class="verMat" data-href="'+msg.dataRes[i].id+'" '
+ 'data-grupo="'+msg.dataRes[i].idGrupo+'" '
+ 'data-periodo="'+msg.dataRes[i].idPeriodo+'" '
+ 'data-namemat="'+msg.dataRes[i].materia+'" >'
+ '<td>' + msg.dataRes[i].materia + '</td>'
+ '<td>' + msg.dataRes[i].grupo + '</td>'
+ '<td>' + msg.dataRes[i].grado + '</td>'
+ '<td>' + msg.dataRes[i].turno + '</td>'
+ '<td>' + msg.dataRes[i].year + '</td>'
+ '<td>' + msg.dataRes[i].planEst + '</td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
$(".loader").hide();
}
//Ordenar ASC y DESC header tabla
$("#data th span").click(function () {
if ($(this).hasClass("desc")) {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("asc");
//ordenar = "&orderby="+$(this).attr("title")+" asc";
ordenar = $(this).attr("title") + " asc";
} else {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("desc");
//ordenar = "&orderby="+$(this).attr("title")+" desc";
ordenar = $(this).attr("title") + " desc";
}
filtrar();
});
$("#data").on("click", ".verMat", function(){
var idGMatProf = $(this).data("href");
var idGrupo = $(this).data("grupo");
var idPeriodo = $(this).data("periodo");
var nameMat = $(this).data("namemat");
console.log(idGMatProf);
location.href = "profesor_view_mat.php?idGMatProf="+idGMatProf+"&idGrupo="+idGrupo+"&idPeriodo="+idPeriodo+"&nameMat="+nameMat;
});
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html>
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['inputIdGrupo'];
$name = $_POST['inputName'];
$grado = $_POST['inputGrado'];
$turno = $_POST['inputTurno'];
$planEst = $_POST['inputPE'];
$cad = '';
$ban = false;
$sqlUpdateGroup = "UPDATE $tGInfo SET nombre='$name', nivel_turno_id='$turno', "
. "nivel_grado_id='$grado', plan_estudios_id='$planEst' WHERE id='$idGrupo' ";
if ($con->query($sqlUpdateGroup) === TRUE) {
$ban = true;
$cad .= 'Grupo modificado con éxito.';
} else {
$ban = false;
$cad .= 'Error al actualizar Grupo.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idUser = $_POST['inputIdUser'];
$idInfo = $_POST['inputIdInfo'];
$name = $_POST['inputName'];
$user = $_POST['inputUser'];
$pass = $_POST['inputPass'];
// Dirección
$dir = (isset($_POST['inputDir'])) ? $_POST['inputDir'] : NULL;
// Contacto
$tel = (isset($_POST['inputTel'])) ? $_POST['inputTel'] : NULL;
$mail = (isset($_POST['inputMail'])) ? $_POST['inputMail'] : NULL;
$cad = '';
$ban = false;
$sqlUpdateInfo = "UPDATE $tInfo SET dir='$dir', tel='$tel', mail='$mail', actualizado='$dataTimeNow' WHERE id='$idInfo' ";
if($con->query($sqlUpdateInfo) === TRUE){
$sqlUpdateUser = "UPDATE $tUsers SET nombre='$name', user='$user', pass='<PASSWORD>', actualizado='$dataTimeNow' WHERE id='$idUser' ";
if($con->query($sqlUpdateUser) === TRUE){
$ban = true;
$cad .= 'Profesor modificado con éxito.';
}else{
$ban = false;
$cad .= 'Error al actualizar profesor.<br>'.$con->error;
}
}else{
$ban = false;
$cad .= 'Error al insertar información.<br>'.$con->error;
}
//$ban = true;
if($ban){
echo json_encode(array("error"=>0, "msg"=>$cad));
}else{
echo json_encode(array("error"=>1, "msg"=>$cad));
}
?><file_sep><?php
session_start();
//session_destroy();
unset ( $_SESSION['sessU'] );
unset ( $_SESSION['userId'] );
unset ( $_SESSION['userName'] );
unset ( $_SESSION['userKey'] );
unset ( $_SESSION['userLogo'] );
unset ( $_SESSION['userPerfil'] );
unset ( $_SESSION['namePerfil'] );
header('Location: ../views/login.php');
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['idGrupo'];
$nameStudent = $_POST['nameStudent'];
$cad = '';
$ban = true;
//Primero buscamos si el alumno ya existen en el grupo y si no existe lo insertamos.
$sqlGetStudent = "SELECT id, nombre FROM $tUsers WHERE nombre LIKE '%{$nameStudent}%' ";
$resGetStudent = $con->query($sqlGetStudent);
if($resGetStudent->num_rows > 0){//Si existe el alumno, ahora a buscarlo en el grupo
$rowGetStudent = $resGetStudent->fetch_assoc();
$idStudent = $rowGetStudent['id'];
$sqlGetStudentGroup = "SELECT $tGAlum.id FROM $tGAlum "
. "WHERE $tGAlum.user_alumno_id = '$idStudent' AND $tGAlum.grupo_info_id ='$idGrupo' ";
$resGetStudentGroup = $con->query($sqlGetStudentGroup);
if($resGetStudentGroup->num_rows > 0){//Si ya existe en el grupo
$cad .= 'Error: El alumno ya existe en éste grupo.<br>'.$con->error;
$ban = false;
}else{//Si es nuevo
//Insertmos Alumno en el grupo
$sqlInsertStudentGroup = "INSERT INTO $tGAlum (grupo_info_id, user_alumno_id) "
. "VALUES ('$idGrupo', '$idStudent')";
if($con->query($sqlInsertStudentGroup) === TRUE){
//Si todo correcto buscamos las materias del grupo y se las asignamos al alumno
$sqlGetMatsProfGroup = "SELECT id, banco_materia_id FROM $tGMatProf WHERE grupo_info_id = '$idGrupo' ";
$resGetMatsProfGroup = $con->query($sqlGetMatsProfGroup);
while($rowGetMatsProfGroup = $resGetMatsProfGroup->fetch_assoc()){
$idMatProf = $rowGetMatsProfGroup['id'];
$idBMat = $rowGetMatsProfGroup['banco_materia_id'];
$sqlInsertMatAlum = "INSERT INTO $tGMatAlum "
. "(grupo_mat_prof_id, user_alumno_id, creado) "
. "VALUES ('$idMatProf', '$idStudent', '$dateNow')";
if($con->query($sqlInsertMatAlum) === TRUE){
continue;
}else{
$ban = false;
$cad .= 'Error al asignar alumno a la materia.<br>'.$con->error;
break;
}
}
}else{
$ban = false;
$cad .= 'Error al insertar alumno en el grupo.<br>'.$con->query;
}
}
}else{
$cad .= 'Error: No existe éste alumno.<br>'.$con->error;
$ban = false;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msgErr" => $cad, "sql1"=>$sqlGetStudentGroup));
} else {
echo json_encode(array("error" => 1, "msgErr" => $cad, "sql2"=>$sqlGetStudentGroup));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$cad = '';
$ban = false;
$countNumFechasPer = count($_POST['inputIdFechaPeriodo']);
for($i = 0; $i < $countNumFechasPer; $i++){
$idFechaPeriodo = $_POST['inputIdFechaPeriodo'][$i];
$fechaInicio = $_POST['datePeriododBegin'][$i];
$fechaFin = $_POST['datePeriododEnd'][$i];
$sqlUpdateFechaPeriodo = "UPDATE $tPerFecha SET "
. "fecha_inicio = '$fechaInicio', fecha_fin = '$fechaFin' "
. "WHERE id = '$idFechaPeriodo' ";
if($con->query($sqlUpdateFechaPeriodo) === TRUE){
$ban = true;
continue;
}else{
$ban = false;
$cad .= 'Error al actualizar fecha del periodo.<br>'.$con->error;
break;
}
}
//$ban = true;
if ($ban) {
$cad .= 'Se actualizarón con éxito las fechas del periodo.';
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 3) {
$idUser = $_SESSION['userId'];
$idGMatProf = $_GET['idGMatProf'];
$idGrupo = $_GET['idGrupo'];
$idPeriodo = $_GET['idPeriodo'];
$idPeriodoFecha = $_GET['idPeriodoFecha'];
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<form id="formCalifRub" name="formCalifRub">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<input type="hidden" id="inputIdRubrica" name="inputIdRubrica" >
<label for="inputRubricas">Selecciona la rubrica a Evaluar:</label>
<select class="form-control" id="inputRubricas" name="inputRubricas"></select>
</div>
<div class="col-xs-5">
<label for="inputNombre">Nombre:</label>
<input class="form-control" id="inputNombre" name="inputNombre" placeholder="Nombre de la rubrica">
</div>
<div class="col-xs-3">
<label for="inputFecha">Fecha:</label>
<input type="date" class="form-control" id="inputFecha" name="inputFecha" value="<?=$dateNow; ?>">
</div>
<div class="col-xs-1">
<label>Terminar</label>
<button type="submit" id="guardar_datos" class="btn btn-info">Calificar</button>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Alumnos a evaluar</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="grupo">ID</span></th>
<th><span title="grupo">Nombre</span></th>
<th><span title="grupo">Calificación</span></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</form>
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
$.ajax({
type: "POST",
data: {idPeriodoFecha: <?=$idPeriodoFecha;?>, idGMatProf: <?=$idGMatProf; ?>},
url: "../controllers/get_rubricas_info.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$(".content-header #inputRubricas").html("<option></option>");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$(".content-header #inputRubricas").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
//Si salio correcto cargamos los alumnos
$.ajax({
type: "POST",
data: {idGrupo: <?= $idGrupo; ?>},
url: "../controllers/get_grupos_alumnos.php",
success: function(msg2){
console.log(msg2);
var msg2 = jQuery.parseJSON(msg2);
if (msg2.error == 0) {
$("#data tbody").html("");
$.each(msg2.dataRes, function (i, item){
var newRow = '<tr>'
+ '<td><input type="hidden" id="inputIdAlum" name="inputIdAlum[]" value="'+msg2.dataRes[i].idStudent+'" >'
+ msg2.dataRes[i].idStudent + '</td>'
+ '<td>' + msg2.dataRes[i].nameStudent + '</td>'
+ '<td><input type="number" id="inputCalif" name="inputCalif[]" value="10" style="display: none; " class="form-control inputCalif"></td>';
$(newRow).appendTo("#data tbody");
});
}else{
var newRow = '<tr><td colspan="3">' + msg2.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
}
});
}else{
$(".content-header #inputRubricas").html("<option>"+msg.msgErr+"</option>");
}
}
});
$(".content-wrapper").on('change', '#inputRubricas', function(){
var idRubrica = $(this).val();
console.log(idRubrica);
$("#inputIdRubrica").val(idRubrica);
$("#data tbody .inputCalif").css('display', '');
});
//Añadir rubrica
$('#formCalifRub').validate({
rules: {
inputRubricas: {required: true},
inputNombre: {required: true},
inputFecha: {required: true},
'inputCalif[]': {required: true, range: [0, 10], digits: true}
},
messages: {
inputRubricas: "Rubrica a evaluar obligatoria",
inputNombre: "Nombre de la rubrica obligatorio",
inputFecha: "Fecha de evaluación obligatoria",
'inputCalif[]': {
required: "Calificación del alumno obligatoria",
range: "Solo números entre 0 y 10",
digits: "Solo se permiten números enteros."
}
},
tooltip_options:{
inputRubricas: {trigger: "focus", placement: "bottom"},
inputNombre: {trigger: "focus", placement: "bottom"},
inputFecha: {trigger: "focus", placement: "bottom"},
'inputCalif[]': {trigger: "focus", placement: "bottom"}
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_rubrica_calif.php",
data: $('form#formCalifRub').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('.divError').css({color: "#77DD77"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('.divError').css({color: "#FF0000"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
$('.divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al calificar rubrica.");
}
});
}
}); // end añadir rubrica
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$prof = array();
$msgErr = '';
$ban = false;
$idProf = $_POST['idProf'];
$sqlGetProf = "SELECT $tUsers.*, $tInfo.* FROM $tUsers INNER JOIN $tInfo ON $tInfo.id = $tUsers.informacion_id WHERE $tUsers.perfil_id='3' AND $tUsers.id='$idProf' AND $tUsers.estado_id='1' ";
$resGetProf = $con->query($sqlGetProf);
if ($resGetProf->num_rows > 0) {
while ($rowGetProf = $resGetProf->fetch_assoc()) {
$id = $rowGetProf['id'];
$name = $rowGetProf['nombre'];
$user = $rowGetProf['user'];
$pass = $rowGetProf['pass'];
$clave = $rowGetProf['clave'];
$logo = $rowGetProf['logo'];
$idInfo = $rowGetProf['informacion_id'];
$dir = $rowGetProf['dir'];
$tel = $rowGetProf['tel'];
$mail = $rowGetProf['mail'];
$prof[] = array('id' => $id, 'nombre' => $name, 'user' => $user, 'pass' => $pass, 'clave' => $clave, 'logo' => $logo, 'idInfo' => $idInfo, 'dir' => $dir, 'tel' => $tel, 'mail' => $mail);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existe el profesor.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $prof));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$name = $_POST['inputName'];
$grado = $_POST['inputGrado'];
$turno = $_POST['inputTurno'];
$planEst = $_POST['inputPE'];
$year = 2018;
$cad = '';
$ban = false;
$sqlInsertGrupo = "INSERT INTO $tGInfo "
. "(nombre, nivel_escolar_id, nivel_turno_id, nivel_grado_id, year, plan_estudios_id, creado) "
. "VALUES ('$name', '1', '$turno', '$grado', '$year', '$planEst', '$dateNow' ) ";
if ($con->query($sqlInsertGrupo) === TRUE) {
$ban = true;
$cad .= 'Grupo añadido con éxito.';
} else {
$ban = false;
$cad .= 'Error al crear nuevo grupo.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idPlan = $_POST['inputIdPlan'];
$planName = $_POST['inputName'];
$planYear = $_POST['inputYear'];
$cad = '';
$ban = false;
$sqlUpdateUser = "UPDATE $tPlanEst SET nombre='$planName', year='$planYear' WHERE id='$idPlan' ";
if ($con->query($sqlUpdateUser) === TRUE) {
$ban = true;
$cad .= 'Plan de estudios modificado con éxito.';
} else {
$ban = false;
$cad .= 'Error al actualizar Plan de Estudios.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Escritorio
<small>Panel de Control</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Escritorio</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
</body>
</html>
<file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 3) {
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Escritorio
<small>Panel de Control</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Inicio</a></li>
<li class="active">Escritorio</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-yellow">
<div class="inner">
<h3>1</h3>
<p>Plan academico</p>
</div>
<div class="icon">
<i class="fa fa-graduation-cap"></i>
</div>
<a href="#" class="small-box-footer">Detalles <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
<div class="col-lg-3 col-xs-6">
<!-- small box -->
<div class="small-box bg-green">
<div class="inner">
<h3>1</h3>
<p>Asignaciones</p>
</div>
<div class="icon">
<i class="fa fa-calendar"></i>
</div>
<a href="#" class="small-box-footer">Detalles <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
<!-- ./col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html>
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idPlanEst = $_POST['idPlanEst'];
$idEdo = $_POST['idEdo'];
$idEdo2 = ($idEdo == 1) ? 2 : 1;
$ban = false;
$msgErr = '';
$sqlDeleteProf = "UPDATE $tPlanEst SET estado_id='$idEdo2' WHERE id='$idPlanEst' ";
//echo $sqlDeleteProf;
if($con->query($sqlDeleteProf) === TRUE){
$ban = true;
}else{
$banTmp = false;
$msgErr .= ($idEdo == 1) ? 'Error al dar de baja el plan de estudios.'.$con->error : 'Error al dar de alta el plan de estudios.'.$con->error;
}
if($ban){
$msgErr = 'Se modifico con éxito.';
echo json_encode(array("error"=>0, "dataRes"=>$msgErr));
}else{
echo json_encode(array("error"=>1, "dataRes"=>$msgErr));
}
?><file_sep><?php
date_default_timezone_set('America/Mexico_City');
$tit = "Plataforma de Evaluación Continua | P.E.C. ";
$dateNow = date("Y-m-d");
$timeNow = date("H:i");
$dataTimeNow = date("Y-m-d H:i");
$folderUpPerfil = "../uploads/perfil/";
$csvUploads = "../uploads/csv";
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['inputIdGrupo'];
$idMat = $_POST['inputMat'];
$idProf = $_POST['inputProf'];
$cad = '';
$ban = false;
$sqlInsertMatProf = "INSERT INTO $tGMatProf "
. "(banco_materia_id, user_profesor_id, grupo_info_id, creado) "
. "VALUES ('$idMat', '$idProf', '$idGrupo', '$dateNow' ) ";
if ($con->query($sqlInsertMatProf) === TRUE) {
$ban = true;
$cad .= 'Materia asignada con éxito.';
} else {
$ban = false;
$cad .= 'Error al asignar materia al grupo.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idMat = $_POST['idMat'];
$ban = false;
$msgErr = '';
$sqlDeleteMat = "DELETE FROM $tMats WHERE id='$idMat' ";
//echo $sqlDeleteProf;
if($con->query($sqlDeleteMat) === TRUE){
$ban = true;
$msgErr .= 'Se elimino con éxito.';
}else{
$banTmp = false;
$msgErr .= 'Error al eliminar materia del plan de estudios.'.$con->error;
}
if($ban){
echo json_encode(array("error"=>0, "dataRes"=>$msgErr));
}else{
echo json_encode(array("error"=>1, "dataRes"=>$msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idUser = $_POST['inputIdStudent'];
$nameUser = $_POST['inputStudent'];
$cad = '';
$ban = false;
$sqlUpdateUser = "UPDATE $tUsers SET nombre='$nameUser', actualizado='$dataTimeNow' WHERE id='$idUser' ";
if ($con->query($sqlUpdateUser) === TRUE) {
$ban = true;
$cad .= 'Alumno actualizado con éxito.';
} else {
$ban = false;
$cad .= 'Error al actualizar alumno.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msgErr" => $cad));
} else {
echo json_encode(array("error" => 1, "msgErr" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$grades = array();
$msgErr = '';
$ban = false;
$sqlGetGrade = "SELECT id, nombre FROM $tGrade ";
$resGetGrade = $con->query($sqlGetGrade);
if ($resGetGrade->num_rows > 0) {
while ($rowGetGrade = $resGetGrade->fetch_assoc()) {
$id = $rowGetGrade['id'];
$name = $rowGetGrade['nombre'];
$grades[] = array('id' => $id, 'nombre' => $name);
$ban = true;
$msgErr = 'Grado hallados.';
}
} else {
$ban = false;
$msgErr = 'No existen grados aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "msgErr" => $msgErr, "dataRes" => $grades));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['inputIdGrupo'];
$ap = $_POST['inputAP'];
$am = $_POST['inputAM'];
$name = $_POST['inputName'];
$nameAp = $ap." ".$am." ".$name;
$cad = '';
$ban = true;
//Buscamos que existan materias en el grupo
$sqlGetMatsGroup = "SELECT * FROM $tGMatProf WHERE grupo_info_id='$idGrupo' ";
$resGetMatsGroup = $con->query($sqlGetMatsGroup);
if($resGetMatsGroup->num_rows > 0){
//Obtenemos el último ID
$sqlGetMaxId = "SELECT MAX(id) as id FROM $tUsers ";
$resGetMaxId = $con->query($sqlGetMaxId);
$rowGetMaxId = $resGetMaxId->fetch_assoc();
$idMax = $rowGetMaxId['id']+1;
$user = $name{1}.$ap.$am{1}.$idMax;
//Insertamos usuario
$sqlInsertStudent = "INSERT INTO $tUsers "
. "(nombre, user, pass, perfil_id, estado_id, creado) "
. "VALUES"
. "('$nameAp', '$user', '$user', '4', '1', '$dateNow' ) ";
if($con->query($sqlInsertStudent) === TRUE){
$idStudent = $con->insert_id;
//Insertmos Alumno en el grupo
$sqlInsertStudentGroup = "INSERT INTO $tGAlum (grupo_info_id, user_alumno_id) "
. "VALUES ('$idGrupo', '$idStudent')";
if($con->query($sqlInsertStudentGroup) === TRUE){
//Si todo correcto buscamos las materias del grupo y se las asignamos al alumno
$sqlGetMatsProfGroup = "SELECT id, banco_materia_id FROM $tGMatProf WHERE grupo_info_id = '$idGrupo' ";
$resGetMatsProfGroup = $con->query($sqlGetMatsProfGroup);
while($rowGetMatsProfGroup = $resGetMatsProfGroup->fetch_assoc()){
$idMatProf = $rowGetMatsProfGroup['id'];
$idBMat = $rowGetMatsProfGroup['banco_materia_id'];
$sqlInsertMatAlum = "INSERT INTO $tGMatAlum "
. "(grupo_mat_prof_id, user_alumno_id, creado) "
. "VALUES ('$idMatProf', '$idStudent', '$dateNow')";
if($con->query($sqlInsertMatAlum) === TRUE){
continue;
}else{
$ban = false;
$cad .= 'Error al asignar alumno a la materia.<br>'.$con->error;
break;
}
}
}else{
$ban = false;
$cad .= 'Error al insertar alumno en el grupo.<br>'.$con->error;
}
}else{
$ban = false;
$cad .= 'Error al insertar alumno nuevo.<br>'.$con->error;
}
}else{
$ban = false;
$cad .= 'No puedes insertar alumnos si no hay materias creadas.';
}
//$ban = true;
if($ban){
$cad = 'Éxito, se registro el alumno nuevo.';
echo json_encode(array("error"=>'0', "msg"=>$cad, "sql"=>''));
}else{
echo json_encode(array("error"=>1, "msg"=>$cad, "sql"=>''));
}
?><file_sep><?php
include ('../config/conexion.php');
include ('../config/variables.php');
$student = array();
$query = $_REQUEST['query'];
$ban = false;
$msgErr = '';
$sqlGetStudent = "SELECT id, nombre FROM $tUsers WHERE perfil_id = '4' AND nombre LIKE '%{$query}%' ";
$resGetStudent = $con->query($sqlGetStudent);
if ($resGetStudent->num_rows > 0) {
while ($rowGetStudent = $resGetStudent->fetch_assoc()) {
$id = $rowGetStudent['id'];
$name = $rowGetStudent['nombre'];
$student[] = array('id' => $id, 'name' => $name);
//$student[] = $name;
}
$ban = true;
} else {
$ban = false;
$msgErr .= 'Error: No existe el alumno.';
}
/* if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $descuento, "sql"=>$sqlGetDesc));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr, "sql"=>$sqlGetDesc));
} */
echo json_encode($student);
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idRubrica = $_POST['inputRubricas'];
$nameRubrica = $_POST['inputNombre'];
$dateRubrica = $_POST['inputFecha'];
$countAlms = count($_POST['inputIdAlum']);
$cad = '';
$ban = false;
//Insertamos rubrica_info_calif
$sqlInsertRubInfo = "INSERT INTO $tRubInfoCalif (rubrica_info_id, fecha, nombre) "
. "VALUES ('$idRubrica', '$dateRubrica', '$nameRubrica' ) ";
if ($con->query($sqlInsertRubInfo) === TRUE) {
$cad .= 'Rubrica añadida con éxito.';
$idRubCalifInfo = $con->insert_id;
for($i = 0; $i < $countAlms; $i++){
$idAlum = $_POST['inputIdAlum'][$i];
$califAlum = $_POST['inputCalif'][$i];
$sqlInsertRubDetCalif = "INSERT INTO $tRubDetCalif (rubrica_info_calif_id, user_alumno_id, calificacion) "
. "VALUES ('$idRubCalifInfo', '$idAlum', '$califAlum' )";
if($con->query($sqlInsertRubDetCalif) === TRUE){
$ban = true;
$cad .= 'Calificación del alumno: '.$idAlum.', añadida con éxito.';
}else{
$cad .= 'Error al añadir calificación del alumno: '.$idAlum.'<br>'.$con->error;
$ban = false;
break;
}
}
} else {
$ban = false;
$cad .= 'Error al crear nueva rubrica.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idPeriodo = $_POST['inputIdPeriodo'];
$cad = '';
$ban = false;
$countNumPer = count($_POST['datePeriododBegin']);
for($i = 0; $i < $countNumPer; $i++){
$fechaInicio = $_POST['datePeriododBegin'][$i];
$fechaFin = $_POST['datePeriododEnd'][$i];
$sqlInsertFechaPeriodo = "INSERT INTO $tPerFecha (periodo_info_id, fecha_inicio, fecha_fin) "
. "VALUES ('$idPeriodo', '$fechaInicio', '$fechaFin')";
if($con->query($sqlInsertFechaPeriodo) === TRUE){
$ban = true;
continue;
}else{
$ban = false;
$cad .= 'Error al crear nueva fecha del periodo.<br>'.$con->error;
break;
}
}
//$ban = true;
if ($ban) {
$cad .= 'Se añadieron las fechas de los periodos con éxito.';
echo json_encode(array("error" => 0, "msg" => $cad));
} else {
echo json_encode(array("error" => 1, "msg" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$rubricas = array();
$msgErr = '';
$ban = false;
//$idGMatProf = $_POST['idGMatProf'];
//$idPeriodo = $_POST['idPeriodo'];
$sqlGetInfoRub = "SELECT $tRubInfo.id, $tRubInfo.nombre, $tRubInfo.porcentaje, $tRubInfo.estado_id "
. "FROM $tRubInfo WHERE 1=1 ";
$periodoFecha = (isset($_POST['idPeriodoFecha'])) ? $_POST['idPeriodoFecha'] : "";
if($periodoFecha != ''){
$idGMatProf = $_POST['idGMatProf'];
$idPeriodoFecha = $_POST['idPeriodoFecha'];
$sqlGetInfoRub .= " AND $tRubInfo.grupo_mat_prof_id = '$idGMatProf' "
. "AND $tRubInfo.periodo_fecha_id = '$idPeriodoFecha' ";
}
$idRubrica = (isset($_POST['idRubrica'])) ? $_POST['idRubrica'] : "";
if($idRubrica != ''){
$sqlGetInfoRub .= " AND $tRubInfo.id = '$idRubrica' ";
}
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetPlanEst .= " AND ($tPlanEst.nombre LIKE '%$query%' OR $tPlanEst.year LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idPlanEst2 = $_POST['idPlanEst'];
$sqlGetPlanEst .= " AND $tPlanEst.id = '$idPlanEst2' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetPlanEst .= " ORDER BY " . $vorder;
}
*/
$resGetInfoRub = $con->query($sqlGetInfoRub);
if ($resGetInfoRub->num_rows > 0) {
while ($rowGetInfoRub = $resGetInfoRub->fetch_assoc()) {
$id = $rowGetInfoRub['id'];
$name = $rowGetInfoRub['nombre'];
$porc = $rowGetInfoRub['porcentaje'];
$edo = $rowGetInfoRub['estado_id'];
$rubricas[] = array('id' => $id, 'nombre' => $name, 'porcentaje' => $porc, 'edo' => $edo );
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen rubricas en éste intervalo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $rubricas, "sql" => $sqlGetInfoRub));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$students = array();
$msgErr = '';
$ban = false;
$idGrupo = $_POST['idGrupo'];
$sqlGetStudents = "SELECT $tUsers.id as idStudent, $tUsers.nombre as nameStudent "
. "FROM $tGAlum "
// . "INNER JOIN $tGMatProf ON $tGAlum.grupo_mat_prof_id = $tGMatProf.id "
. "INNER JOIN $tUsers ON $tUsers.id = $tGAlum.user_alumno_id "
. "WHERE $tGAlum.grupo_info_id = '$idGrupo' AND $tUsers.estado_id = '1' "
. "ORDER BY nameStudent ";
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetMatsProf .= " AND ($tMats.nombre LIKE '%$query%' OR $tGrade.nombre LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idMat = $_POST['idMat'];
$sqlGetMatsProf .= " AND $tMats.id = '$idMat' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetMatsProf .= " ORDER BY " . $vorder;
} else {
$sqlGetMatsProf .= " ORDER BY idGMatProf ";
}
*/
$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$id = $rowGetStudents['idStudent'];
$name = $rowGetStudents['nameStudent'];
$students[] = array('idStudent' => $id, 'nameStudent' => $name);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $students, "sql" => $sqlGetStudents));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 1) {
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar por nombre" id="buscar" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="load(1);"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div class="col-xs-4"></div>
<div class="col-xs-5 ">
<div class="btn-group pull-right">
<a href="#" class="btn btn-default" data-toggle="modal" data-target="#modalAddGroup"><i class="fa fa-plus"></i> Nuevo</a>
</div>
</div>
</div>
<!-- modal añadir nuevo plan de estudios -->
<form class="form-horizontal" id="formAddGroup" name="formAddGroup">
<div class="modal fade" id="modalAddGroup" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Nuevo Grupo</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputPE" class="col-sm-3 control-label">Plan de Estudios</label>
<div class="col-sm-9">
<select class="form-control" id="inputPE" name="inputPE" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Nombre (Completo)</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="inputName" required>
</div>
</div>
<div class="form-group">
<label for="inputGrado" class="col-sm-3 control-label">Grado</label>
<div class="col-sm-9">
<select class="form-control" id="inputGrado" name="inputGrado" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputTurno" class="col-sm-3 control-label">Turno</label>
<div class="col-sm-9">
<select class="form-control" id="inputTurno" name="inputTurno" required>
<option value="1">Matutino</option>
<option value="2">Vespertino</option>
</select>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
<!-- modal editar plan de estudio -->
<form class="form-horizontal" id="formUpdGroup" name="formUpdGroup">
<div class="modal fade" id="modalUpdGroup" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Editar Grupo</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="hidden" id="inputIdGrupo" name="inputIdGrupo" >
<div class="form-group">
<label for="inputPE" class="col-sm-3 control-label">Plan de Estudios</label>
<div class="col-sm-9">
<select class="form-control" id="inputPE" name="inputPE" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Nombre (Completo)</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="inputName" required>
</div>
</div>
<div class="form-group">
<label for="inputGrado" class="col-sm-3 control-label">Grado</label>
<div class="col-sm-9">
<select class="form-control" id="inputGrado" name="inputGrado" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputTurno" class="col-sm-3 control-label">Turno</label>
<div class="col-sm-9">
<select class="form-control" id="inputTurno" name="inputTurno" required>
<option value="1">Matutino</option>
<option value="2">Vespertino</option>
</select>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Listado de Grupos</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="grupo">Nombre</span></th>
<th><span title="grado">Grado</span></th>
<th><span title="turno">Turno</span></th>
<th><span title="year">Año</span></th>
<th><span title="planEst">Plan de Estudios</span></th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
//Obtenemos los grados del nivel escolar del usuario
$.ajax({
type: "POST",
url: "../controllers/get_grados.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#modalAddGroup .modal-body #inputGrado").html("");
$("#modalUpdGroup .modal-body #inputGrado").html("");
$.each(msg.dataRes, function (i, item) {
$("#modalAddGroup .modal-body #inputGrado").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
$("#modalUpdGroup .modal-body #inputGrado").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
} else {
$("#modalAddGroup .modal-body #inputGrado").append($('<option>', {
value: 0,
text: "No existen grados en tu nivel Escolar"
}));
$("#modalUpdGroup .modal-body #inputGrado").append($('<option>', {
value: 0,
text: "No existen grados en tu nivel Escolar"
}));
}
}
})
//Obtenemos los planes de estudio
$.ajax({
type: "POST",
url: "../controllers/get_planes_estudio.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#modalAddGroup .modal-body #inputPE").html("");
$("#modalUpdGroup .modal-body #inputPE").html("");
$.each(msg.dataRes, function (i, item) {
$("#modalAddGroup .modal-body #inputPE").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
$("#modalUpdGroup .modal-body #inputPE").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
} else {
$("#modalAddGroup .modal-body #inputPE").append($('<option>', {
value: 0,
text: "No existen planes de estudio"
}));
$("#modalUpdGroup .modal-body #inputPE").append($('<option>', {
value: 0,
text: "No existen planes de estudio"
}));
}
}
})
filtrar();
function filtrar() {
$(".loader").show();
$.ajax({
type: "POST",
data: {orderby: ordenar},
url: "../controllers/get_grupos.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td>' + msg.dataRes[i].grupo + '</td>'
+ '<td>' + msg.dataRes[i].grado + '</td>'
+ '<td>' + msg.dataRes[i].turno + '</td>'
+ '<td>' + msg.dataRes[i].year + '</td>'
+ '<td>' + msg.dataRes[i].planEst + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li><a href="#"><i class="fa fa-eye"></i> Ver</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalUpdGroup" id="editar" data-value="' + msg.dataRes[i].id + '"><i class="fa fa-edit"></i> Editar</a></li>';
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
$(".loader").hide();
}
//Ordenar ASC y DESC header tabla
$("#data th span").click(function () {
if ($(this).hasClass("desc")) {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("asc");
//ordenar = "&orderby="+$(this).attr("title")+" asc";
ordenar = $(this).attr("title") + " asc";
} else {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("desc");
//ordenar = "&orderby="+$(this).attr("title")+" desc";
ordenar = $(this).attr("title") + " desc";
}
filtrar();
});
$("#buscar").keyup(function () {
var consulta = $(this).val();
$.ajax({
type: "POST",
data: {orderby: ordenar, query: consulta},
url: "../controllers/get_grupos.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td>' + msg.dataRes[i].grupo + '</td>'
+ '<td>' + msg.dataRes[i].grado + '</td>'
+ '<td>' + msg.dataRes[i].turno + '</td>'
+ '<td>' + msg.dataRes[i].year + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li><a href="#"><i class="fa fa-eye"></i> Ver</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalUpdPlanEst" id="editar" data-value="' + msg.dataRes[i].id + '"><i class="fa fa-edit"></i> Editar</a></li>';
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
})
$("#data").on("click", "#editar", function () {
var idGrupo = $(this).data('value');
console.log(idGrupo);
$(".loader").show();
$.ajax({
type: "POST",
url: "../controllers/get_grupos.php",
data: {ordenar: ordenar, tarea: 'editar', idGrupo: idGrupo},
success: function (msg) {
console.log(msg);
var datos = jQuery.parseJSON(msg);
$("#modalUpdGroup .modal-body #inputIdGrupo").val(datos.dataRes[0].id);
$("#modalUpdGroup .modal-body #inputName").val(datos.dataRes[0].grupo);
$(".loader").hide();
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
})
})
$(document).on("click", ".modal-body li a", function () {
tab = $(this).attr("href");
$(".modal-body .tab-content div").each(function () {
$(this).removeClass("active");
});
$(".modal-body .tab-content " + tab).addClass("active");
});
});
</script>
<script>
var form1 = $("#formAddGroup");
form1.validate({
ignore: "",
rules: {
inputPE: {required: true},
inputName: {required: true, maxlength: 9},
inputGrado: {required: true},
inputTurno: {required: true}
},
messages: {
inputPE: {
required: "Plan de Estudios obligatorio"
},
inputName: {
required: "Nombre del plan, obligatorio",
maxlength: "Máximo 9 caracteres"
},
inputGrado: {
required: "Grado obligatorio"
},
inputTurno: {
required: "Turno obligatorio"
},
},
errorPlacement: function (error, element) {
error.addClass("help-block");
element.parents(".col-sm-9").addClass("has-feedback");
if (element.prop("type") === "checkbox") {
error.insertAfter(element.parent("label"));
} else {
error.insertAfter(element);
}
if (!element.next("span")[ 0 ]) {
$("<span class='glyphicon glyphicon-remove form-control-feedback'></span>").insertAfter(element);
}
},
highlight: function (element, errorClass, validClass) {
$(element).parents(".col-sm-9").addClass("has-error").removeClass("has-success");
$(element).next("span").addClass("glyphicon-remove").removeClass("glyphicon-ok");
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".col-sm-9").addClass("has-success").removeClass("has-error");
$(element).next("span").addClass("glyphicon-ok").removeClass("glyphicon-remove");
}
});
$("#formAddGroup").submit(function (event) {
var form1 = $(this).valid();
var parametros = $(this).serialize();
if (this.hasChildNodes('.nav.nav-tabs')) {
var validator = $(this).validate();
$(this).find("input").each(function () {
if (!validator.element(this)) {
form1 = false;
$('a[href=\\#' + $(this).closest('.tab-pane:not(.active)').attr('id') + ']').tab('show');
return false;
}
});
}
if (form1) {
$(".loader").show();
$('#guardar_datos').attr("disabled", true);
$.ajax({
type: "POST",
url: "../controllers/create_grupo.php",
data: parametros,
success: function (msg) {
var datos = jQuery.parseJSON(msg);
if (datos.error == 0) {
$(".divError").removeClass("bg-danger");
$(".divError").addClass("bg-success");
$(".divError").html(datos.msg);
setTimeout(function () {
location.reload();
}, 2000);
} else {
$(".divError").removeClass("bg-success");
$(".divError").addClass("bg-danger");
$(".divError").html(datos.msg);
$(".loader").hide();
setTimeout(function () {
$(".divError").hide();
}, 3000);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
$(".divError").addClass("bg-danger");
$(".divError").html(cadErr);
setTimeout(function () {
$(".divError").hide();
}, 3000);
}
});
event.preventDefault();
}
})
</script>
<script>
var form2 = $("#formUpdGroup");
form2.validate({
ignore: "",
rules: {
inputPE: {required: true},
inputName: {required: true, maxlength: 9},
inputGrado: {required: true},
inputTurno: {required: true}
},
messages: {
inputPE: {
required: "Plan de Estudios obligatorio"
},
inputName: {
required: "Nombre del plan, obligatorio",
maxlength: "Máximo 9 caracteres"
},
inputGrado: {
required: "Grado obligatorio"
},
inputTurno: {
required: "Turno obligatorio"
},
},
errorPlacement: function (error, element) {
error.addClass("help-block");
element.parents(".col-sm-9").addClass("has-feedback");
if (element.prop("type") === "checkbox") {
error.insertAfter(element.parent("label"));
} else {
error.insertAfter(element);
}
if (!element.next("span")[ 0 ]) {
$("<span class='glyphicon glyphicon-remove form-control-feedback'></span>").insertAfter(element);
}
},
highlight: function (element, errorClass, validClass) {
$(element).parents(".col-sm-9").addClass("has-error").removeClass("has-success");
$(element).next("span").addClass("glyphicon-remove").removeClass("glyphicon-ok");
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".col-sm-9").addClass("has-success").removeClass("has-error");
$(element).next("span").addClass("glyphicon-ok").removeClass("glyphicon-remove");
}
});
$("#formUpdGroup").submit(function (event) {
var form2 = $(this).valid();
var parametros = $(this).serialize();
if (this.hasChildNodes('.nav.nav-tabs')) {
var validator = $(this).validate();
$(this).find("input").each(function () {
if (!validator.element(this)) {
form2 = false;
$('a[href=\\#' + $(this).closest('.tab-pane:not(.active)').attr('id') + ']').tab('show');
return false;
}
});
}
if (form2) {
$(".loader").show();
$('#guardar_datos').attr("disabled", true);
$.ajax({
type: "POST",
url: "../controllers/update_grupos.php",
data: parametros,
success: function (msg) {
console.log(msg);
var datos = jQuery.parseJSON(msg);
if (datos.error == 0) {
$(".loader").hide();
$(".divError").removeClass("bg-danger");
$(".divError").addClass("bg-success");
$(".divError").html(datos.msg);
setTimeout(function () {
location.reload();
}, 2000);
} else {
$(".loader").hide();
$(".divError").removeClass("bg-success");
$(".divError").addClass("bg-danger");
$(".divError").html(datos.msg);
setTimeout(function () {
$(".divError").hide();
}, 3000);
}
},
error: function (x, e) {
$(".loader").hide();
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
$(".divError").addClass("bg-danger");
$(".divError").html(cadErr);
setTimeout(function () {
$(".divError").hide();
}, 3000);
}
});
event.preventDefault();
}
})
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html>
<file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 2) {
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<div class="input-group">
<input class="typeahead form-control" name="q" type="search" autofocus autocomplete="off" id="q">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="load(1);"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div class="col-xs-4"></div>
<div class="col-xs-5 ">
<div class="btn-group pull-right">
</div>
</div>
</div>
<!-- modal ver materias -->
<div class="modal fade" id="modalViewMats" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Ver materias</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<div class="row text-center buttonAddMat">
</div>
<br>
<table class="table table-striped matsProfs">
<thead>
<tr><th>Nombre Materia</th><th>Nombre Profesor</th><th>Actualizar</th><th></th></tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- ./modal-body -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
<!-- fin modal -->
<!-- modal asignar materias -->
<form class="form-horizontal" id="formAddMatProf" name="formUpdGroup">
<div class="modal fade" id="modalAddMatProf" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Asignar materia</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdGrupo" name="inputIdGrupo" >
<div class="form-group">
<label for="inputMat" class="col-sm-3 control-label">Materia</label>
<div class="col-sm-9">
<select class="form-control" id="inputMat" name="inputMat" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputProf" class="col-sm-3 control-label">Profesor</label>
<div class="col-sm-9">
<select class="form-control" id="inputProf" name="inputProf" required> </select>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Asignar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal actualizar asignación de materias -->
<form class="form-horizontal" id="formUpdMatProf" name="formUpdGroup">
<div class="modal fade" id="modalUpdMatProf" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Actualizar materia</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdGrupo" name="inputIdGrupo" >
<input type="text" id="inputIdGMatProf" name="inputIdGMatProf" >
<div class="form-group">
<label for="inputMat" class="col-sm-3 control-label">Materia</label>
<div class="col-sm-9">
<select class="form-control" id="inputMat" name="inputMat" required> </select>
</div>
</div>
<div class="form-group">
<label for="inputProf" class="col-sm-3 control-label">Profesor</label>
<div class="col-sm-9">
<select class="form-control" id="inputProf" name="inputProf" required> </select>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal ver Alumnos/Estudiantes -->
<div class="modal fade" id="modalViewStudents" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Ver alumnos</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<div class="row text-center buttonAddStudent">
</div>
<br>
<table class="table table-striped students">
<thead>
<tr><th>No.</th><th>Nombre</th><th>Actualizar</th><th>X</th></tr>
</thead>
<tbody>
</tbody>
</table>
</div><!-- ./modal-body -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
<!-- fin modal -->
<!-- modal añadir nuevo alumno -->
<form class="form-horizontal" id="formAddStudent" name="formUpdGroup">
<div class="modal fade" id="modalAddStudent" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Añadir Alumno NUEVO</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdGrupo" name="inputIdGrupo" >
<div class="form-group">
<label for="inputAP" class="col-sm-3 control-label">Apellido Paterno</label>
<div class="col-sm-9">
<input class="form-control" id="inputAP" name="inputAP" >
</div>
</div>
<div class="form-group">
<label for="inputAM" class="col-sm-3 control-label">Apellido Materno</label>
<div class="col-sm-9">
<input class="form-control" id="inputAM" name="inputAM" >
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Nombre</label>
<div class="col-sm-9">
<input class="form-control" id="inputName" name="inputName" >
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal buscar y añadir alumno -->
<div class="modal fade" id="modalSearchStudent" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Buscar Alumno</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdGrupo" name="inputIdGrupo" >
<div class="form-group row">
<label for="inputSearchStudent" class="col-sm-2 control-label">Buscar: </label>
<div class="col-sm-9">
<input type="text" id="inputSearchStudent" name="inputSearchStudent" class="form-control searchStudent">
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="searchStudent" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
<!-- fin modal -->
<!-- modal exportar grupo -->
<form class="form-horizontal" id="formImportStudent" name="formImportStudent">
<div class="modal fade" id="modalImportStudent" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Exportar Alumnos</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdGrupo" name="inputIdGrupo" >
<div class="form-group">
<label for="inputFile" for="inputFile" class="col-sm-4 control-label">Archivo CSV
<a href="#" data-toggle="tooltip" title="Archivo Excel en formato CSV (archivo separado por comas), 3 o 4 campos: Apellido paterno, Apellido Materno, Nombre(s) y Usuario [opcional]">
<span class="glyphicon glyphicon-question-sign"></span>
</a>
<a href="../uploads/plantillaGrupo.csv" data-toggle="tooltip" title="Descargar formato">
<span class="glyphicon glyphicon-download-alt"></span>
</a>
: </label>
<div class="col-sm-8">
<input type="file" class="form-control" id="inputFile" name="inputFile" >
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Importar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
<!-- modal actualizar asignación de materias -->
<form class="form-horizontal" id="formUpdStudent" name="formUpdStudent">
<div class="modal fade" id="modalUpdStudent" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Actualizar alumno</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdStudent" name="inputIdStudent" >
<div class="form-group">
<label for="inputStudent" class="col-sm-3 control-label">Alumno: </label>
<div class="col-sm-9">
<input class="form-control" id="inputStudent" name="inputStudent" >
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form><!-- ./form -->
<!-- fin modal -->
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Listado de Grupos</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="grupo">Nombre</span></th>
<th><span title="grado">Grado</span></th>
<th><span title="turno">Turno</span></th>
<th><span title="year">Año</span></th>
<th><span title="planEst">Plan de Estudios</span></th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
filtrar();
function filtrar() {
$(".loader").show();
$.ajax({
type: "POST",
data: {orderby: ordenar},
url: "../controllers/get_grupos.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td>' + msg.dataRes[i].grupo + '</td>'
+ '<td>' + msg.dataRes[i].grado + '</td>'
+ '<td>' + msg.dataRes[i].turno + '</td>'
+ '<td>' + msg.dataRes[i].year + '</td>'
+ '<td>' + msg.dataRes[i].planEst + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li id="viewMats" value="'+msg.dataRes[i].id+'" data-toggle="modal" data-target="#modalViewMats"><a href="#" ><i class="fa fa-book "></i> Ver materias</a></li>'
+ '<li id="viewStudents" value="'+msg.dataRes[i].id+'" data-toggle="modal" data-target="#modalViewStudents" ><a href="#"><i class="fa fa-graduation-cap"></i> Ver alumnos</a></li>'
+ '<li><a href="administrativo_view_cal_group.php?idGrupo='+msg.dataRes[i].id+'&idPerInfo='+msg.dataRes[i].perInfoId+'"><i class="fa fa-eye"></i> Ver Calificaciones</a></li>'
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
$(".loader").hide();
}
//Ordenar ASC y DESC header tabla
$("#data th span").click(function () {
if ($(this).hasClass("desc")) {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("asc");
//ordenar = "&orderby="+$(this).attr("title")+" asc";
ordenar = $(this).attr("title") + " asc";
} else {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("desc");
//ordenar = "&orderby="+$(this).attr("title")+" desc";
ordenar = $(this).attr("title") + " desc";
}
filtrar();
});
//Cargar materias a ventana modal
$("#data").on("click", "#viewMats", function(){
var idGrupo = $(this).val();
//$("#modalViewMats #addMat .buttonAddMat").data("whatever", idGrupo);
$("#modalViewMats .buttonAddMat").html('<button type="button" class="btn btn-danger" id="addMat" data-toggle="modal" data-target="#modalAddMatProf" data-whatever="'+idGrupo+'" >Asignar materia</button>');
console.log(idGrupo);
$.ajax({
type: "POST",
data: {idGrupo: idGrupo},
url: "../controllers/get_grupos_mat_prof.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalViewMats .matsProfs tbody").html("");
if(msg.error == 0){
var newRow = '';
$.each(msg.dataRes, function(i, item){
newRow += '<tr>';
newRow += '<td>'+msg.dataRes[i].materia+'</td>';
newRow += '<td>'+msg.dataRes[i].profesor+'</td>';
newRow += '<td>'
+'<button type="button" class="btn btn-primary" id="updMat" data-whatever="'+msg.dataRes[i].id+'" data-grupo="'+idGrupo+'" data-toggle="modal" data-target="#modalUpdMatProf">'
+'Actualizar materia'
+'</button></td>';
newRow += '<td>'
+'<button type="button" class="btn btn-danger" id="delete" value="'+msg.dataRes[i].id+'"><span class="glyphicon glyphicon-remove"></span></button>'
+'</td>';
newRow += '</tr>';
});
$(newRow).appendTo("#modalViewMats .matsProfs tbody");
}else{
var newRow = '<tr><td>'+msg.msgErr+'</td></tr>';
$(newRow).appendTo("#modalViewMats .matsProfs tbody");
}
}
});
});
//Asignar materias
$("#modalViewMats").on("click", "#addMat", function(){
var idGrupo = $(this).data("whatever");
$("#modalAddMatProf .modal-body #inputIdGrupo").val(idGrupo);
console.log("hola "+idGrupo);
$.ajax({
type: "POST",
data: {idGrupo: idGrupo},
url: "../controllers/get_mats_plan_nivel.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$("#modalAddMatProf .modal-body #inputMat").html("");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$("#modalAddMatProf .modal-body #inputMat").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
//Llenamos profesores
$.ajax({
type: "POST",
url: "../controllers/get_profesores.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalAddMatProf .modal-body #inputProf").html("");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$("#modalAddMatProf .modal-body #inputProf").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
}else{
$("#modalAddMatProf .modal-body #inputProf").html(msg.msgErr);
}
}
})
}else{
$("#modalAddMatProf .modal-body #inputMat").html(msg.msgErr);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
});
//Actualizar materias
$("#modalViewMats").on("click", "#updMat", function(){
var idGrupo = $(this).data("grupo");
var idGMatProf = $(this).data("whatever");
$("#modalUpdMatProf .modal-body #inputIdGrupo").val(idGrupo);
$("#modalUpdMatProf .modal-body #inputIdGMatProf").val(idGMatProf);
console.log("hola "+idGrupo+"-"+idGMatProf);
$.ajax({
type: "POST",
data: {idGrupo: idGrupo},
url: "../controllers/get_mats_plan_nivel.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$("#modalUpdMatProf .modal-body #inputMat").html("");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$("#modalUpdMatProf .modal-body #inputMat").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
//Llenamos profesores
$.ajax({
type: "POST",
url: "../controllers/get_profesores.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalUpdMatProf .modal-body #inputProf").html("");
if(msg.error == 0){
$.each(msg.dataRes, function (i, item) {
$("#modalUpdMatProf .modal-body #inputProf").append($('<option>', {
value: msg.dataRes[i].id,
text: msg.dataRes[i].nombre
}));
});
}else{
$("#modalUpdMatProf .modal-body #inputProf").html(msg.msgErr);
}
}
})
}else{
$("#modalUpdMatProf .modal-body #inputMat").html(msg.msgErr);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
});
//Asignar materia y profesor
$('#formAddMatProf').validate({
rules: {
inputMat: {required: true},
inputProf: {required: true}
},
messages: {
inputMat: "Materia obligatoria",
inputProf: "Profesor que impartirá la materia, obligatorio"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_grupo_mat_prof.php",
data: $('form#formAddMatProf').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('.divError').css({color: "#77DD77"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('.divError').css({color: "#FF0000"});
$('.divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al asignar materia al grupo.");
}
});
}
}); // end añadir nuevo cargo
//Actualizar materia y profesor
$('#formUpdMatProf').validate({
rules: {
inputMat: {required: true},
inputProf: {required: true}
},
messages: {
inputMat: "Materia obligatoria",
inputProf: "Profesor que impartirá la materia, obligatorio"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_grupo_mat_prof.php",
data: $('form#formUpdMatProf').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalUpdMatProf .divError').css({color: "#77DD77"});
$('#modalUpdMatProf .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalUpdMatProf .divError').css({color: "#FF0000"});
$('#modalUpdMatProf .divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al actualizar materia al grupo.");
}
});
}
}); // end añadir nuevo cargo
//Eliminar materia
$("#modalViewMats").on("click", "#delete", function(){
var idGMatProf = $(this).val();
console.log("Hola: "+idGMatProf);
if(confirm("¿Seguro que deseas eliminar esta materia? Se borrará la materia y el profesor asignado")){
$.ajax({
method: "POST",
data: {idGMatProf: idGMatProf},
url: "../controllers/delete_grupo_mat_prof.php",
success: function(data){
console.log(data);
var msg = jQuery.parseJSON(data);
if(msg.error == 0){
setTimeout(function () {
location.reload();
}, 1500);
}else{
setTimeout(function () {
}, 1500);
}
}
})
}else{
alert("Ten cuidado.");
}
});
//Cargar Alumnos ventana Modal
$("#data").on("click", "#viewStudents", function(){
var idGrupo = $(this).val();
//$("#modalViewMats #addMat .buttonAddMat").data("whatever", idGrupo);
var buttons = '<div class="row">';
buttons += '<div class="col-sm-4"><button type="button" class="btn btn-info" id="addStudent" '
+'data-toggle="modal" data-target="#modalAddStudent" data-grupo="'+idGrupo+'" >'
+'Añadir Alumno</button></div>';
buttons += '<div class="col-sm-4"><button type="button" class="btn btn-info" id="searchStudent" '
+'data-toggle="modal" data-target="#modalSearchStudent" data-grupo="'+idGrupo+'" >'
+'Buscar y Añadir Alumno</button></div>';
buttons += '<div class="col-sm-4"><button type="button" class="btn btn-info" id="importStudent" '
+'data-toggle="modal" data-target="#modalImportStudent" data-grupo="'+idGrupo+'" >'
+'Importar Alumnos</button></div>';
buttons += '</div>';
$("#modalViewStudents .buttonAddStudent").html(buttons);
console.log(idGrupo);
$.ajax({
type: "POST",
data: {idGrupo: idGrupo},
url: "../controllers/get_grupos_alumnos.php",
success: function(msg){
var msg = jQuery.parseJSON(msg);
$("#modalViewStudents .students tbody").html("");
if(msg.error == 0){
var newRow = '';
$.each(msg.dataRes, function(i, item){
newRow += '<tr>';
newRow += '<td>'+(i+1)+'</td>';
newRow += '<td>'+msg.dataRes[i].nameStudent+'</td>';
newRow += '<td>'
+'<button type="button" class="btn btn-primary" id="updStudent" data-whatever="'+msg.dataRes[i].idStudent+'" data-toggle="modal" data-target="#modalUpdStudent">'
+'Actualizar alumno'
+'</button></td>';
newRow += '<td>'
+'<button type="button" class="btn btn-danger" id="deleteStudent" value="'+msg.dataRes[i].idStudent+'"><span class="glyphicon glyphicon-remove"></span></button>'
+'</td>';
newRow += '</tr>';
});
$(newRow).appendTo("#modalViewStudents .students tbody");
}else{
var newRow = '<tr><td>'+msg.msgErr+'</td></tr>';
$(newRow).appendTo("#modalViewStudents .students tbody");
}
}
});
});
//Añadir Alumno
$("#modalViewStudents").on("click", "#addStudent", function(){
var idGrupo = $(this).data("grupo");
$("#modalAddStudent .modal-body #inputIdGrupo").val(idGrupo);
console.log("studiante: "+idGrupo);
});
//Asignar nuevo alumno
$('#formAddStudent').validate({
rules: {
inputAP: {required: true},
inputAM: {required: true},
inputName: {required: true}
},
messages: {
inputAP: "Apellido paterno obligatoria",
inputAM: "Apellido materno obligatoria",
inputName: "Nombre obligatorio"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_student.php",
data: $('form#formAddStudent').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalAddStudent .divError').css({color: "#77DD77"});
$('#modalAddStudent .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalAddStudent .divError').css({color: "#FF0000"});
$('#modalAddStudent .divError').html(msg.msgErr);
setTimeout(function () {
$('#divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al añadir alumno.");
}
});
}
}); // end añadir nuevo cargo
//Buscar alumno async
var students = new Bloodhound({
datumTokenizer: function(datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
wildcard: '%QUERY',
url: '../controllers/search_student.php?query=%QUERY',
}
});
// Instantiate the Typeahead UI
$('#modalSearchStudent .modal-body .searchStudent').typeahead(null, {
display: 'name',
source: students,
limit: 8
});
//Buscar alumno, añadir grupo
$("#modalViewStudents").on("click", "#searchStudent", function(){
var idGrupo = $(this).data("grupo");
$("#modalSearchStudent .modal-body #inputIdGrupo").val(idGrupo);
console.log("Grupo: "+idGrupo);
});
//Añadir alumno mediante busqueda
$("#modalSearchStudent").on("click", "#searchStudent", function(){
var queryStudent = $("#modalSearchStudent #inputSearchStudent").val();
var idGrupo = $("#modalSearchStudent #inputIdGrupo").val();
console.log("Grupo:"+idGrupo+"- Student: "+queryStudent);
$.ajax({
type: "POST",
data: {idGrupo: idGrupo, nameStudent: queryStudent},
url: "../controllers/insert_alumno_busqueda.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalSearchStudent .divError').css({color: "#77DD77"});
$('#modalSearchStudent .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalSearchStudent .divError').show();
$('#modalSearchStudent .divError').css({color: "#FF0000"});
$('#modalSearchStudent .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalSearchStudent .divError').hide();
}, 1500);
}
}
});
})
//Importar alumno, añadir grupo
$("#modalViewStudents").on("click", "#importStudent", function(){
var idGrupo = $(this).data("grupo");
$("#modalImportStudent .modal-body #inputIdGrupo").val(idGrupo);
console.log("Grupo: "+idGrupo);
});
//añadir nuevo grupo
$('#formImportStudent').validate({
rules: {
inputFile: {required: true, extension: "csv"}
},
messages: {
inputFile: {
required: "Se requiere un archivo",
extension: "Solo se permite archivos *.csv (archivo separado por comas de Excel)"
}
},
tooltip_options: {
inputFile: {trigger: "focus", placement: "bottom"}
},
submitHandler: function(form){
$('#loading').show();
$.ajax({
type: "POST",
url: "../controllers/import_grupo.php",
data: new FormData($("form#formImportStudent")[0]),
//data: $('form#formAdd').serialize(),
contentType: false,
processData: false,
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalImportStudent .divError').css({color: "#77DD77"});
$('#modalImportStudent .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalImportStudent .divError').css({color: "#FF0000"});
$('#modalImportStudent .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalImportStudent .divError').hide();
}, 2500);
}
}, error: function(){
alert("Error al importar grupo");
}
});
}
}); // end añadir nuevo grupo
//Actualizar alumno
$("#modalViewStudents").on("click", "#updStudent", function(){
var idStudent = $(this).data("whatever");
$("#modalUpdStudent .modal-body #inputIdStudent").val(idStudent);
console.log("Alumno: "+idStudent);
$.ajax({
type: "POST",
data: {idStudent: idStudent},
url: "../controllers/get_alumnos.php",
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
$("#modalUpdStudent .modal-body #inputMat").html("");
if(msg.error == 0){
$("#modalUpdStudent .modal-body #inputStudent").val(msg.dataRes[0].nameStudent)
}else{
$("#modalUpdStudent .modal-body #inputStudent").html(msg.msgErr);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
});
//Actualizar alumno validación
$('#formUpdStudent').validate({
rules: {
inputStudent: {required: true}
},
messages: {
inputStudent: "Nombre del alumno obligatorio"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_alumno.php",
data: $('form#formUpdStudent').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalUpdStudent .divError').css({color: "#77DD77"});
$('#modalUpdStudent .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 2000);
}else{
$('#modalUpdStudent .divError').css({color: "#FF0000"});
$('#modalUpdStudent .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalUpdStudent .divError').hide();
}, 2000);
}
}, error: function(){
alert("Error al actualizar alumno.");
}
});
}
}); // end añadir nuevo cargo
//Eliminar alumno
$("#modalViewStudents").on("click", "#deleteStudent", function(){
var idStudent = $(this).val();
console.log("Alumno: "+idStudent);
if(confirm("¿Seguro que deseas eliminar este alumno? Se borrará de forma definida")){
$.ajax({
method: "POST",
data: {idStudent: idStudent},
url: "../controllers/delete_alumno.php",
success: function(data){
console.log(data);
var msg = jQuery.parseJSON(data);
if(msg.error == 0){
setTimeout(function () {
location.reload();
}, 1500);
}else{
setTimeout(function () {
}, 1500);
}
}
})
}else{
alert("Ten cuidado.");
}
});
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html>
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$periodos = array();
$msgErr = '';
$ban = false;
$sqlGetPeriodos = "SELECT $tPerFecha.id as idPerFecha, "
. "$tPerFecha.fecha_inicio as fInicio, $tPerFecha.fecha_fin as fFin "
. "FROM $tPerFecha "
. "WHERE 1=1 ";
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea == 'periodo') {
$idPeriodo = $_POST['idPeriodo'];
$sqlGetPeriodos .= " AND $tPerFecha.periodo_info_id = '$idPeriodo' ";
}
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetPlanEst .= " AND ($tPlanEst.nombre LIKE '%$query%' OR $tPlanEst.year LIKE '%$query%' ) ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetPlanEst .= " ORDER BY " . $vorder;
}
*/
$resGetPeriodos = $con->query($sqlGetPeriodos);
if ($resGetPeriodos->num_rows > 0) {
while ($rowGetPeriodos = $resGetPeriodos->fetch_assoc()) {
$id = $rowGetPeriodos['idPerFecha'];
$fInicio = $rowGetPeriodos['fInicio'];
$fFin = $rowGetPeriodos['fFin'];
$periodos[] = array('id' => $id, 'fInicio' => $fInicio, 'fFin' => $fFin );
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen periodos creados.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $periodos, "sql" => $sqlGetPeriodos));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr, "sql" => $sqlGetPeriodos));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGMatProf = $_POST['idGMatProf'];
$ban = false;
$msgErr = '';
$sqlDeleteMat = "DELETE FROM $tGMatProf WHERE id='$idGMatProf' ";
if ($con->query($sqlDeleteMat) === TRUE) {
$ban = true;
$msgErr .= 'Se elimino con éxito.';
} else {
$banTmp = false;
$msgErr .= 'Error al eliminar materia del grupo.' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $msgErr));
} else {
echo json_encode(array("error" => 1, "dataRes" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idProf = $_POST['idProf'];
$idEdo = $_POST['idEdo'];
$idEdo2 = ($idEdo == 1) ? 2 : 1;
$ban = false;
$msgErr = '';
$sqlDeleteProf = "UPDATE $tUsers SET estado_id='$idEdo2' WHERE id='$idProf' ";
//echo $sqlDeleteProf;
if($con->query($sqlDeleteProf) === TRUE){
$ban = true;
}else{
$banTmp = false;
$msgErr .= ($idEdo == 1) ? 'Error al dar de baja al profesor.'.$con->error : 'Error al dar de alta al profesor.'.$con->error;
}
if($ban){
$msgErr = 'Se modifico con éxito.';
echo json_encode(array("error"=>0, "dataRes"=>$msgErr));
}else{
echo json_encode(array("error"=>1, "dataRes"=>$msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idRubrica = $_POST['inputIdRubrica'];
$name = $_POST['inputName'];
$cad = '';
$ban = false;
$sqlUpdateGroup = "UPDATE $tRubInfo SET nombre='$name' WHERE id='$idRubrica' ";
if ($con->query($sqlUpdateGroup) === TRUE) {
$ban = true;
$cad .= 'Rubrica modificada con éxito.';
} else {
$ban = false;
$cad .= 'Error al actualizar Rubrica.<br>' . $con->error;
}
//$ban = true;
if ($ban) {
echo json_encode(array("error" => 0, "msgErr" => $cad));
} else {
echo json_encode(array("error" => 1, "msgErr" => $cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$name = $_POST['inputName'];
$user = $_POST['inputUser'];
$pass = $_POST['inputPass'];
// Dirección
$dir = (isset($_POST['inputDir'])) ? $_POST['inputDir'] : NULL;
// Contacto
$tel = (isset($_POST['inputTel'])) ? $_POST['inputTel'] : NULL;
$mail = (isset($_POST['inputMail'])) ? $_POST['inputMail'] : NULL;
$cad = '';
$ban = false;
$sqlInsertInfo = "INSERT INTO $tInfo "
. "(dir, tel, mail, creado) "
. "VALUES"
. "('$dir', '$tel', '$mail', '$dateNow') ";
if($con->query($sqlInsertInfo) === TRUE){
$idInfo = $con->insert_id;
$sqlInsertUser = "INSERT INTO $tUsers "
."(nombre, user, pass, clave, informacion_id, perfil_id, estado_id, creado) "
. "VALUES ('$name', '$user', '$pass', '$user', '$idInfo', '3', '1', '$dateNow' ) ";
if($con->query($sqlInsertUser) === TRUE){
$ban = true;
$cad .= 'Profesor añadido con éxito.';
}else{
$ban = false;
$cad .= 'Error al crear nueva profesor.<br>'.$con->error;
}
}else{
$ban = false;
$cad .= 'Error al insertar información.<br>'.$con->error;
}
//$ban = true;
if($ban){
echo json_encode(array("error"=>'0', "msg"=>$cad));
}else{
echo json_encode(array("error"=>1, "msg"=>$cad));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$fechasPeriodo = array();
$msgErr = '';
$ban = false;
$idPeriodo = $_POST['idPeriodo'];
$sqlGetFechasPeriodo = "SELECT $tPerFecha.id, "
. "$tPerFecha.fecha_inicio as fechaInicio, $tPerFecha.fecha_fin as fechaFin "
. " FROM $tPerFecha WHERE $tPerFecha.periodo_info_id = '$idPeriodo' ";
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetPlanEst .= " AND ($tPlanEst.nombre LIKE '%$query%' OR $tPlanEst.year LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idPlanEst2 = $_POST['idPlanEst'];
$sqlGetPlanEst .= " AND $tPlanEst.id = '$idPlanEst2' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetPlanEst .= " ORDER BY " . $vorder;
}
*/
$resGetFechasPeriodos = $con->query($sqlGetFechasPeriodo);
if ($resGetFechasPeriodos->num_rows > 0) {
while ($rowGetPeriodos = $resGetFechasPeriodos->fetch_assoc()) {
$id = $rowGetPeriodos['id'];
$fechaInicio = $rowGetPeriodos['fechaInicio'];
$fechaFin = $rowGetPeriodos['fechaFin'];
$fechasPeriodo[] = array('id' => $id, 'fechaInicio' => $fechaInicio, 'fechaFin' => $fechaFin);
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen fechas en éste periodo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $fechasPeriodo, "sql" => $sqlGetFechasPeriodo));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$idGrupo = $_POST['inputIdGrupo']; //idGrupo
$file = $_FILES['inputFile']['name'];
$msgErr = '';
$cad = '';
$ban = true;
$arrIdMatsIns = array();
//Asignamos nombre al archivo subido, con fecha
$extFile = explode(".", $_FILES['inputFile']['name']);
$nameFile = 'grupo_' . $dateNow . "." . $extFile[1];
//Procesamos Excel
$destinoCsv = $csvUploads . '/' . $nameFile;
$csv = @move_uploaded_file($_FILES["inputFile"]["tmp_name"], $destinoCsv);
$sustituye = array("\r\n", "\n\r", "\n", "\r");
// Validamos archivo CSV (estructura)
if ($csv) {
$csvFile = file($destinoCsv);
$i = 0;
foreach ($csvFile as $linea_num => $linea) {
$i++;
if ($i == 1)
continue;
$linea = utf8_encode($linea);
$datos = explode(",", $linea);
$contador = count($datos);
//Número de campos menor
if ($contador < 3) {
$msgErr .= 'Tu archivo tiene menos columnas de las requeridas.' . $i;
$ban = false;
break;
}
//Se excede el número de campos
if ($contador > 4) {
$msgErr .= 'Tu archivo tiene más columnas de las requeridas.' . $i;
$ban = false;
break;
}
//Buscamos los usuarios, si no existe alguno mandamos mensaje de error
$usuario = trim(str_replace($sustituye, "", $datos[3]));
if ($usuario != "") {
$sqlSearchUser = "SELECT id FROM $tUsers WHERE user='$usuario' ";
$resSearchUser = $con->query($sqlSearchUser);
if ($resSearchUser->num_rows < 1) {
$msgErr .= 'El usuario: ' . $usuario . ', no existe.' . $i;
$ban = false;
break;
}
}
//Validamos solo letras en los campos
if (!preg_match('/^[a-zA-Z ]+$/', $datos[0]) || !preg_match('/^[a-zA-Z ]+$/', $datos[1]) || !preg_match('/^[a-zA-Z ]+$/', $datos[2])) {
$msgErr .= 'Los nombres y apellidos solo pueden contener letras (sin acentos), registro: ' . $i . '--' . $datos[0] . $datos[1] . $datos[2];
$ban = false;
break;
}
}
} else {
$msgErr .= "Error al subir el archivo CSV.";
$ban = false;
}
if ($ban) {
//Recorremos Excel para insertar alumnos
$csvFile = file($destinoCsv);
$j = 0;
foreach ($csvFile as $linea_num => $linea) {
$j++;
if ($j == 1)
continue;
$linea = utf8_encode($linea);
$datos = explode(",", $linea);
$usuario = str_replace($sustituye, "", $datos[3]);
if ($usuario != "") { //si hay algo en el campo de usuario
/* $sqlSearchUser = "SELECT id FROM $tAlum WHERE user='$usuario' ";
$resSearchUser = $con->query($sqlSearchUser);
$rowGetUser = $resSearchUser->fetch_assoc();
$idAlumno = $rowGetUser['id'];
$sqlInsertAlumnoGrupo = "INSERT INTO $tGrupoAlums (grupo_id, alumno_id, creado) "
. "VALUES ('$idGrupo', '$idAlumno','$dateNow')";
if($con->query($sqlInsertAlumnoGrupo) === TRUE){
$countArrIdMats = count($arrIdMatsIns);
for($k = 0; $k < $countArrIdMats; $k++){
$idMatProf = $arrIdMatsIns[$k];
$sqlInsertMatAlum = "INSERT INTO $tGMatAlums "
. "(grupo_materia_profesor_id, usuario_alumno_id, creado) "
. "VALUES ('$idMatProf', '$idAlumno', '$dateNow')";
if($con->query($sqlInsertMatAlum) === TRUE){
continue;
}else{
$ban = false;
$msgErr .= 'Error al insertar Materia del Alumno.'.$j.'.'.$con->error;
break;
}
}//end for countArrMatsIns
}else{
$msgErr .= 'Error al insertar grupo alumno.'.$j.'.'.$con->error;
$ban = false;
break;
}
*/
}//end if usuario != null
else {//Si es usuario nuevo
//Obtenemos el último ID
$sqlGetMaxId = "SELECT MAX(id) as id FROM $tUsers ";
$resGetMaxId = $con->query($sqlGetMaxId);
$rowGetMaxId = $resGetMaxId->fetch_assoc();
$idMax = $rowGetMaxId['id'] + 1;
//Obtenemos el usuario generado
$apTmp = str_replace(' ', '', $datos[0]);
$user = strtolower($datos[2]{0}) . strtolower($apTmp) . strtolower($datos[1]{0}) . $idMax;
$name = $datos[0].' '.$datos[1].' '.$datos[2];
//Insertamos usuario
$sqlInsertStudent = "INSERT INTO $tUsers "
. "(nombre, user, perfil_id, estado_id, creado) "
. "VALUES"
. "('$name', '$user', '4', '1', '$dateNow' ) ";
if ($con->query($sqlInsertStudent) === TRUE) {
$idStudent = $con->insert_id;
//Insertmos Alumno en el grupo
$sqlInsertStudentGroup = "INSERT INTO $tGAlum (grupo_info_id, user_alumno_id) "
. "VALUES ('$idGrupo', '$idStudent')";
if ($con->query($sqlInsertStudentGroup) === TRUE) {
//Si todo correcto buscamos las materias del grupo y se las asignamos al alumno
$sqlGetMatsProfGroup = "SELECT id, banco_materia_id FROM $tGMatProf WHERE grupo_info_id = '$idGrupo' ";
$resGetMatsProfGroup = $con->query($sqlGetMatsProfGroup);
while ($rowGetMatsProfGroup = $resGetMatsProfGroup->fetch_assoc()) {
$idMatProf = $rowGetMatsProfGroup['id'];
$idBMat = $rowGetMatsProfGroup['banco_materia_id'];
$sqlInsertMatAlum = "INSERT INTO $tGMatAlum "
. "(grupo_mat_prof_id, user_alumno_id, creado) "
. "VALUES ('$idMatProf', '$idStudent', '$dateNow')";
if ($con->query($sqlInsertMatAlum) === TRUE) {
continue;
} else {
$ban = false;
$cad .= 'Error al asignar alumno a la materia.<br>' . $con->error;
break;
}
}
} else {
$ban = false;
$cad .= 'Error al insertar alumno en el grupo.<br>' . $con->query;
}
} else {
$ban = false;
$cad .= 'Error al insertar alumno nuevo.<br>' . $con->error;
}
}//end else usuario existe o no
}//end foreach csvFile
} else {
$msgErr .= "Hubo un error al validar CSV.";
$ban = false;
}
if ($ban) {
$cad .= 'Grupo importado con éxito';
echo json_encode(array("error" => 0, "msgErr" => $cad));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
//Función para generar password usuario
// http://www.leonpurpura.com/tutoriales/generar-claves-aleatorias.html
function generar_clave($longitud) {
$cadena = "[^A-Z0-9]";
return substr(eregi_replace($cadena, "", md5(rand())) .
eregi_replace($cadena, "", md5(rand())) .
eregi_replace($cadena, "", md5(rand())), 0, $longitud);
}
?><file_sep><?php
session_start();
include ('../config/conexion.php');
$user = $_POST['inputUser'];
$pass = $_POST['inputPass'];
$cadErr = '';
$ban = false;
$perfil = 0;
$sqlGetUser = "SELECT $tUsers.id as id, $tUsers.nombre as name, "
. "$tUsers.clave as clave, $tUsers.logo, $tUsers.perfil_id, $tUPerfil.nombre as perfil_name "
//. "$tEsc.nivel_escolar_id as nivEscId, $tUsers.escuela_id as idEsc "
. "FROM $tUsers "
. "INNER JOIN $tUPerfil ON $tUPerfil.id=$tUsers.perfil_id "
//. "INNER JOIN $tEsc ON $tEsc.id = $tUsers.escuela_id "
. "WHERE BINARY $tUsers.user='$user' AND BINARY $tUsers.pass='$<PASSWORD>' AND $tUsers.estado_id='1' ";
$resGetUser = $con->query($sqlGetUser);
if ($resGetUser->num_rows > 0) {
if (array_key_exists('inputCheckRecuerdame', $_POST)) {
// Crear un nuevo cookie de sesion, que expira a los 30 días
ini_set('session.cookie_lifetime', 60 * 60 * 24 * 30);
session_regenerate_id(TRUE);
}
$rowGetUser = $resGetUser->fetch_assoc();
$_SESSION['sessU'] = true;
$_SESSION['userId'] = $rowGetUser['id'];
$_SESSION['userName'] = $rowGetUser['name'];
$_SESSION['userKey'] = $rowGetUser['clave'];
$_SESSION['userLogo'] = $rowGetUser['logo'];
//$_SESSION['idEsc'] = $rowGetUser['idEsc'];
//$_SESSION['nivEscId'] = $rowGetUser['nivEscId'];
$_SESSION['userPerfil'] = $rowGetUser['perfil_id'];
$perfil = $rowGetUser['perfil_id'];
$_SESSION['namePerfil'] = $rowGetUser['perfil_name'];
$ban = true;
} else {
$_SESSION['sessU'] = false;
$cadErr = "Usuario incorrecto";
$ban = false;
}
if ($ban) {
echo json_encode(array("error" => 0, "perfil" => $perfil));
} else {
echo json_encode(array("error" => 1, "msgErr" => $cadErr, "sql" => $sqlGetUser));
}
?><file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$students = array();
$mats = array();
$msgErr = '';
$ban = true;
$idPerFecha = (isset($_POST['idPeriodoFecha'])) ? $_POST['idPeriodoFecha'] : "";
$idGrupo = $_POST['idGrupo'];
$cadSqlRub = '';
//Obtenemos alumnos
$sqlGetStudents = "SELECT $tUsers.id as idStudent, $tUsers.nombre as nameStudent "
. "FROM $tGAlum "
. "INNER JOIN $tUsers ON $tUsers.id = $tGAlum.user_alumno_id "
. "WHERE $tGAlum.grupo_info_id = '$idGrupo' ORDER BY nameStudent ";
//Obtenemos nombre de las materias del grupo
/*$sqlGetMats = "SELECT $tMats.nombre as nameMat, $tMats.id as idMat "
. "FROM $tPerMatProm "
. "INNER JOIN $tGMatProf ON $tGMatProf.id = $tPerMatProm.grupo_mat_prof_id "
. "INNER JOIN $tMats ON $tMats.id = $tGMatProf.banco_materia_id "
. "WHERE $tGMatProf.grupo_info_id = '$idGrupo' AND $tPerMatProm.periodo_fecha_id = '$idPerFecha' ";*/
/*$sqlGetMats = "SELECT $tMats.id as idMat, $tMats.nombre as nameMat "
. "FROM $tGMatProf "
. "INNER JOIN $tMats ON $tMats.id = $tGMatProf.banco_materia_id "
. "INNER JOIN $tPerMatProm ON $tPerMatProm.grupo_mat_prof_id = $tGMatProf.id "
. "WHERE $tPerMatProm.periodo_fecha_id = '$idPerFecha' AND $tGMatProf.grupo_info_id = '$idGrupo' ";*/
$sqlGetMats = "SELECT $tMats.id as idMat, $tMats.nombre as nameMat "
. "FROM $tMats "
. "INNER JOIN $tGMatProf ON $tGMatProf.banco_materia_id = $tMats.id "
. "WHERE $tGMatProf.grupo_info_id = '$idGrupo' ";
$resGetMats = $con->query($sqlGetMats);
if ($resGetMats->num_rows > 0) {
while ($rowGetMats = $resGetMats->fetch_assoc()) {
$idMat = $rowGetMats['idMat'];
$nameMat = $rowGetMats['nameMat'];
$mats[] = array('idMat' => $idMat, 'nameMat' => $nameMat);
}
}else{
$ban = false;
$msgErr .= 'No existen materias en éste grupo, aún.<br>' . $con->error;
}
$resGetStudents = $con->query($sqlGetStudents);
if ($resGetStudents->num_rows > 0) {
while ($rowGetStudents = $resGetStudents->fetch_assoc()) {
$idStudent = $rowGetStudents['idStudent'];
$name = $rowGetStudents['nameStudent'];
$calMats = array();
foreach($mats as $key => $value){
$idMat = $value['idMat'];
if($idPerFecha != ""){
$sqlGetProms = "SELECT $tPerMatProm.id as idPermatProm, $tPerMatProm.promedio as promMat "
. "FROM $tPerMatProm "
. "INNER JOIN $tGMatProf ON $tGMatProf.id = $tPerMatProm.grupo_mat_prof_id "
. "WHERE $tGMatProf.grupo_info_id = '$idGrupo' "
. "AND $tPerMatProm.user_alumno_id = '$idStudent' "
. "AND $tPerMatProm.periodo_fecha_id = '$idPerFecha' "
. "AND $tGMatProf.banco_materia_id = '$idMat' ";
}else{
$sqlGetProms = "SELECT $tPerMatProm.id as idPermatProm, AVG($tPerMatProm.promedio) as promMat "
. "FROM $tPerMatProm "
. "INNER JOIN $tGMatProf ON $tGMatProf.id = $tPerMatProm.grupo_mat_prof_id "
. "WHERE $tGMatProf.grupo_info_id = '$idGrupo' "
. "AND $tPerMatProm.user_alumno_id = '$idStudent' "
. "AND $tGMatProf.banco_materia_id = '$idMat' ";
}
$resGetProms = $con->query($sqlGetProms);
if($resGetProms->num_rows > 0){
while($rowGetProms = $resGetProms->fetch_assoc()){
$idPermatProm = $rowGetProms['idPermatProm'];
//if($idPerFecha == "") $promMat = $rowGetProms['promMat'] / ($resGetProms->num_rows+1);
//else $promMat = $rowGetProms['promMat'];
$promMat = $rowGetProms['promMat'];
$calMats[] = array('idPerMatProm' => $idPermatProm, 'promMat' => $promMat, "numRows" => $resGetProms->num_rows);
}
}else{
//$ban = false;
$msgErr .= 'No existen calificaciones de ésta materia, aún.<br>' . $con->error;
$calMats[] = array('idPerMatProm' => '0', 'promMat' => 'N/D');
//break;
}
}
$students[] = array('idStudent' => $idStudent, 'nameStudent' => $name, 'cals' => $calMats);
}
}else {
$ban = false;
$msgErr .= 'No existen alumnos en este grupo, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "students" => $students, "mats" => $mats, "sql1"=>$sqlGetMats));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr, "sql3"=>$sqlGetMats));
}
?><file_sep><?php require('header.php'); ?>
<title><?= $tit; ?></title>
<meta name="author" content="<NAME> (GianBros)" />
<meta name="description" content="Descripción de la página" />
<meta name="keywords" content="etiqueta1, etiqueta2, etiqueta3" />
</head>
<body class="hold-transition skin-blue sidebar-mini">
<?php require('navbar.php'); ?>
<?php
if (isset($_SESSION['sessU']) AND $_SESSION['userPerfil'] == 1) {
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="row">
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar por nombre" id="buscar" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="load(1);"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div class="col-xs-4"></div>
<div class="col-xs-5 ">
<div class="btn-group pull-right">
<a href="#" class="btn btn-default" data-toggle="modal" data-target="#modalAddPeriodo"><i class="fa fa-plus"></i> Nuevo</a>
<!-- <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Mostrar <span class="caret"></span>
</button> -->
</div>
</div>
</div>
<!-- modal añadir nuevo periodo -->
<form class="form-horizontal" id="formAddPeriodo" name="formAddPeriodo">
<div class="modal fade" id="modalAddPeriodo" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Nuevo Periodo</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Nombre (Completo)</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="inputName" required>
</div>
</div>
<div class="form-group">
<label for="inputNum" class="col-sm-3 control-label">Número de Periodos</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="inputNum" name="inputNum" value="3" max="10" required>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
<!-- modal añadir fechas periodo -->
<form class="form-horizontal" id="formAddDatePeriodo" name="formAddDatePeriodo">
<div class="modal fade" id="modalAddDatePeriodo" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Nuevas fechas para el periodo</h4>
<p class="divError"></p>
<input type="text" class="form-control" id="inputIdPeriodo" name="inputIdPeriodo" >
</div>
<div class="modal-body">
<div class="contenido2"></div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Añadir</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
<!-- modal editar fechas periodo -->
<form class="form-horizontal" id="formUpdDatePeriodo" name="formUpdDatePeriodo">
<div class="modal fade" id="modalUpdDatePeriodo" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Editar fechas para el periodo</h4>
<p class="divError"></p>
<input type="text" class="form-control" id="inputIdPeriodo" name="inputIdPeriodo" >
</div>
<div class="modal-body"> </div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
<!-- modal ver fechas periodo -->
<form class="form-horizontal" id="formViewDatePeriodo" name="formViewDatePeriodo">
<div class="modal fade" id="modalViewDatePeriodo" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Ver fechas para el periodo</h4>
<p class="divError"></p>
</div>
<div class="modal-body"> </div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
<!-- modal editar plan de estudio -->
<form class="form-horizontal" id="formUpdPlanEst" name="formUpdPlanEst">
<div class="modal fade" id="modalUpdPlanEst" tabindex="-1" role="dialog" aria-labellebdy="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Editar Plan de Estudios</h4>
<p class="divError"></p>
</div>
<div class="modal-body">
<input type="text" id="inputIdPlan" name="inputIdPlan" >
<div class="form-group">
<label for="inputName" class="col-sm-3 control-label">Nombre (Completo)</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="inputName" required>
</div>
</div>
<div class="form-group">
<label for="inputYear" class="col-sm-3 control-label">Año</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="inputYear" name="inputYear" value="2018" max="2018" required>
</div>
</div>
</div><!-- ./modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar_datos" class="btn btn-primary">Actualizar</button>
</div><!-- ./modal-footer -->
</div><!-- ./modal-content -->
</div><!-- ./modal-dialog -->
</div><!-- ./modal fade -->
</form>
<!-- fin modal -->
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Listado de Ciclos Escolares</h3>
<div class="divError"></div>
</div>
<div class="box-body">
<div class="table table-condensed table-hover table-striped">
<table class="table table-striped table-bordered" id="data">
<thead>
<tr>
<th><span title="">Nombre</span></th>
<th><span title="">Número de periodos</span></th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- ./table -->
</div><!-- ./box-body -->
</div><!-- ./box -->
</div><!-- ./col-sm-12 -->
</div><!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<!-- scripts acá -->
<script>
$(".loader").hide();
var ordenar = '';
$(document).ready(function () {
filtrar();
function filtrar() {
$(".loader").show();
$.ajax({
type: "POST",
data: {orderby: ordenar},
url: "../controllers/get_periodos.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td>' + msg.dataRes[i].nombre + '</td>'
+ '<td>' + msg.dataRes[i].numero + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li><a href="#" data-toggle="modal" data-target="#modalAddDatePeriodo" id="addDatePeriodo" data-periodo="' + msg.dataRes[i].id + '" data-num="'+msg.dataRes[i].numero+'" ><i class="far fa-calendar-plus"></i> Asignar fechas</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalUpdDatePeriodo" id="updDatePeriodo" data-periodo="' + msg.dataRes[i].id + '"><i class="far fa-calendar-alt"></i> Modificar fechas</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalViewDatePeriodo" id="viewDatePeriodo" data-periodo="' + msg.dataRes[i].id + '"><i class="far fa-eye"></i> Ver</a></li>'
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
$(".loader").hide();
}
//Ordenar ASC y DESC header tabla
$("#data th span").click(function () {
if ($(this).hasClass("desc")) {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("asc");
//ordenar = "&orderby="+$(this).attr("title")+" asc";
ordenar = $(this).attr("title") + " asc";
} else {
$("#data th span").removeClass("desc").removeClass("asc");
$(this).addClass("desc");
//ordenar = "&orderby="+$(this).attr("title")+" desc";
ordenar = $(this).attr("title") + " desc";
}
filtrar();
});
$("#buscar").keyup(function () {
var consulta = $(this).val();
$.ajax({
type: "POST",
data: {orderby: ordenar, query: consulta},
url: "../controllers/get_planes_estudio.php",
success: function (msg) {
console.log(msg);
var msg = jQuery.parseJSON(msg);
if (msg.error == 0) {
$("#data tbody").html("");
$.each(msg.dataRes, function (i, item) {
var newRow = '<tr>'
+ '<td><a href="director_plan_estudio.php?action=viewDetails&route=viewDirection&pln=17' + msg.dataRes[i].id + '&id=256&idUser=512">' + msg.dataRes[i].nombre + '</a></td>'
+ '<td>' + msg.dataRes[i].year + '</td>'
+ '<td><div class="btn-group pull-right dropdown">'
+ '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >Acciones <span class="fa fa-caret-down"></span></button>'
+ '<ul class="dropdown-menu">'
+ '<li><a href="director_plan_estudio.php?action=viewDetails&route=viewDirection&pln=17' + msg.dataRes[i].id + '&id=256&idUser=512"><i class="fa fa-eye"></i> Ver</a></li>'
+ '<li><a href="#" data-toggle="modal" data-target="#modalUpdPlanEst" id="editar" data-value="' + msg.dataRes[i].id + '"><i class="fa fa-edit"></i> Editar</a></li>';
+ '</ul></div></td>'
+ '</tr>';
$(newRow).appendTo("#data tbody");
})
} else {
var newRow = '<tr><td colspan="3">' + msg.msgErr + '</td></tr>';
$("#data tbody").html(newRow);
}
},
error: function (x, e) {
var cadErr = '';
if (x.status == 0) {
cadErr = '¡Estas desconectado!\n Por favor checa tu conexión a Internet.';
} else if (x.status == 404) {
cadErr = 'Página no encontrada.';
} else if (x.status == 500) {
cadErr = 'Error interno del servidor.';
} else if (e == 'parsererror') {
cadErr = 'Error.\nFalló la respuesta JSON.';
} else if (e == 'timeout') {
cadErr = 'Tiempo de respuesta excedido.';
} else {
cadErr = 'Error desconocido.\n' + x.responseText;
}
alert(cadErr);
}
});
})
$("#data").on("click", "#updDatePeriodo", function(){
var idPeriodo = $(this).data('periodo');
$("#modalUpdDatePeriodo .modal-header #inputIdPeriodo").val(idPeriodo);
console.log(idPeriodo);
$.ajax({
type: "POST",
url: "../controllers/get_fechas_periodo.php",
data: {idPeriodo: idPeriodo},
success: function(msg){
console.log(msg);
var datos = jQuery.parseJSON(msg);
if (datos.error == 0) {
$("#modalUpdDatePeriodo .modal-body").html("");
var cadInputFecha = '';
$.each(datos.dataRes, function (i, item) {
cadInputFecha += '<div class="row">'
+ '<div class="col-sm-2">'
+ '<input type="text" id="inputIdFechaPeriodo" name="inputIdFechaPeriodo[]" value="'+datos.dataRes[i].id+'">'
+ '<label class="control-label">Fecha de Inicio ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control datePeriododBegin" id="datePeriododBegin" name="datePeriododBegin[]" required value="'+datos.dataRes[i].fechaInicio+'">'
+ '</div>'
+ '<div class="col-sm-2">'
+ '<label class="control-label">Fecha de Fin ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control" id="datePeriododEnd" name="datePeriododEnd[]" required value="'+datos.dataRes[i].fechaFin+'">'
+ '</div>'
+ '</div>';
});
$("#modalUpdDatePeriodo .modal-body").html(cadInputFecha);
}else{
$("#modalUpdDatePeriodo .modal-body").html(datos.msgErr);
}
}
})
})
$("#data").on("click", "#viewDatePeriodo", function(){
var idPeriodo = $(this).data('periodo');
//$("#modalUpdDatePeriodo .modal-header #inputIdPeriodo").val(idPeriodo);
console.log(idPeriodo);
$.ajax({
type: "POST",
url: "../controllers/get_fechas_periodo.php",
data: {idPeriodo: idPeriodo},
success: function(msg){
console.log(msg);
var datos = jQuery.parseJSON(msg);
if (datos.error == 0) {
$("#modalViewDatePeriodo .modal-body").html("");
var cadInputFecha = '';
$.each(datos.dataRes, function (i, item) {
cadInputFecha += '<div class="row">'
+ '<div class="col-sm-2">'
+ '<label class="control-label">Fecha de Inicio ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control datePeriododBegin" id="datePeriododBegin" name="datePeriododBegin[]" readonly value="'+datos.dataRes[i].fechaInicio+'">'
+ '</div>'
+ '<div class="col-sm-2">'
+ '<label class="control-label">Fecha de Fin ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control" id="datePeriododEnd" name="datePeriododEnd[]" readonly value="'+datos.dataRes[i].fechaFin+'">'
+ '</div>'
+ '</div>';
});
$("#modalViewDatePeriodo .modal-body").html(cadInputFecha);
}else{
$("#modalViewDatePeriodo .modal-body").html(datos.msgErr);
}
}
})
})
$(document).on("click", ".modal-body li a", function () {
tab = $(this).attr("href");
$(".modal-body .tab-content div").each(function () {
$(this).removeClass("active");
});
$(".modal-body .tab-content " + tab).addClass("active");
});
//Crear nuevo periodo
$('#formAddPeriodo').validate({
rules: {
inputName: {required: true},
inputNum: {required: true}
},
messages: {
inputName: "Nombre del periodo a crear, obligatorio",
inputNum: "Número de periodos internos, obligatorios, mínimo 1."
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_periodo.php",
data: $('form#formAddPeriodo').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalAddPeriodo .modal-header .divError').css({color: "#77DD77"});
$('#modalAddPeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalAddPeriodo .modal-header .divError').css({color: "#FF0000"});
$('#modalAddPeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalAddPeriodo .modal-header .divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al crear periodo nuevo.");
}
});
}
}); // end añadir nuevo cargo
//Crear nuevas fechas para el periodo
$('#formAddDatePeriodo').validate({
debug:false,
rules: {
'datePeriododBegin[]': {required: true},
'datePeriododEnd[]': {required: true}
},
messages: {
'datePeriododBegin[]': "Fecha de inicio obligatoria",
'datePeriododEnd[]': "Fecha de finalización obligatoria"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/create_fechas_periodo.php",
data: $('form#formAddDatePeriodo').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalAddDatePeriodo .modal-header .divError').css({color: "#77DD77"});
$('#modalAddDatePeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalAddDatePeriodo .modal-header .divError').css({color: "#FF0000"});
$('#modalAddDatePeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalAddDatePeriodo .modal-header .divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al crear fechas del periodo.");
}
});
}
}); // end añadir nuevo cargo
//Crear nuevas fechas para el periodo
$('#formUpdDatePeriodo').validate({
debug:false,
rules: {
'datePeriododBegin[]': {required: true},
'datePeriododEnd[]': {required: true}
},
messages: {
'datePeriododBegin[]': "Fecha de inicio obligatoria",
'datePeriododEnd[]': "Fecha de finalización obligatoria"
},
submitHandler: function(form){
$.ajax({
type: "POST",
url: "../controllers/update_fechas_periodo.php",
data: $('form#formUpdDatePeriodo').serialize(),
success: function(msg){
console.log(msg);
var msg = jQuery.parseJSON(msg);
if(msg.error == 0){
$('#modalUpdDatePeriodo .modal-header .divError').css({color: "#77DD77"});
$('#modalUpdDatePeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
location.reload();
}, 1500);
}else{
$('#modalUpdDatePeriodo .modal-header .divError').css({color: "#FF0000"});
$('#modalUpdDatePeriodo .modal-header .divError').html(msg.msgErr);
setTimeout(function () {
$('#modalUpdDatePeriodo .modal-header .divError').hide();
}, 1500);
}
}, error: function(){
alert("Error al actualizar fechas del periodo.");
}
});
}
}); // end añadir nuevo cargo
//Obtener ID Periodo
$("#data tbody").on("click", "#addDatePeriodo", function(){
var idPeriodo = $(this).data("periodo");
var numPeriodo = $(this).data("num");
$("#modalAddDatePeriodo .modal-header #inputIdPeriodo").val(idPeriodo);
console.log("Periodo: "+idPeriodo+", Núm: "+numPeriodo);
$("#modalAddDatePeriodo .modal-body .contenido2").html("");
var cadInputFecha = '';
for(var i=0; i<numPeriodo; i++){
cadInputFecha += '<div class="row">'
+ '<div class="col-sm-2">'
+ '<label class="control-label">Fecha de Inicio ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control datePeriododBegin" id="datePeriododBegin" name="datePeriododBegin[]" required>'
+ '</div>'
+ '<div class="col-sm-2">'
+ '<label class="control-label">Fecha de Fin ' +(i+1)+ '</label>'
+ '</div>'
+ '<div class="col-sm-4">'
+ '<input type="date" class="form-control" id="datePeriododEnd" name="datePeriododEnd[]" required>'
+ '</div>'
+ '</div>';
}
console.log(cadInputFecha);
$("#modalAddDatePeriodo .modal-body .contenido2").html(cadInputFecha);
});
});
</script>
<?php
} else {
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Error 401
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="error-page">
<h2 class="headline text-yellow"> 401</h2>
<div class="error-content">
<h3><i class="fa fa-warning text-yellow"></i> Oops! No tienes autorización para visualizar ésta página.</h3>
<p>
<a href="login.php">Inicia sesión</a> para poder visualizar el contenido, lamentamos las molestias.
</p>
</div>
<!-- /.error-content -->
</div>
<!-- /.error-page -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<?php require('footer.php'); ?>
<script>
$(".loader").hide();
</script>
<?php
}
?>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 14-03-2021 a las 17:31:45
-- Versión del servidor: 10.1.30-MariaDB
-- Versión de PHP: 7.2.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `eva_pec2`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `banco_materias`
--
CREATE TABLE `banco_materias` (
`id` int(11) NOT NULL,
`nombre` varchar(100) NOT NULL,
`plan_estudio_id` int(11) NOT NULL,
`nivel_grado_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `banco_materias`
--
INSERT INTO `banco_materias` (`id`, `nombre`, `plan_estudio_id`, `nivel_grado_id`) VALUES
(1, 'Mat 1', 1, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `banco_niveles_escolares`
--
CREATE TABLE `banco_niveles_escolares` (
`id` int(11) NOT NULL,
`nombre` varchar(20) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `banco_niveles_escolares`
--
INSERT INTO `banco_niveles_escolares` (`id`, `nombre`, `creado`) VALUES
(1, 'Primaria', '2020-07-26'),
(2, 'Secundaria', '2020-07-26'),
(3, 'Medio superior', '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `banco_niveles_grados`
--
CREATE TABLE `banco_niveles_grados` (
`id` int(11) NOT NULL,
`nombre` varchar(10) NOT NULL,
`nivel_escolar_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `banco_niveles_grados`
--
INSERT INTO `banco_niveles_grados` (`id`, `nombre`, `nivel_escolar_id`) VALUES
(1, '1', 2),
(2, '2', 2),
(3, '3', 2);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `banco_nivel_turnos`
--
CREATE TABLE `banco_nivel_turnos` (
`id` int(11) NOT NULL,
`nombre` varchar(20) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `banco_nivel_turnos`
--
INSERT INTO `banco_nivel_turnos` (`id`, `nombre`, `creado`) VALUES
(1, 'Matutino', '2020-07-26'),
(2, 'Vespertino', '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `estados`
--
CREATE TABLE `estados` (
`id` int(11) NOT NULL,
`nombre` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `estados`
--
INSERT INTO `estados` (`id`, `nombre`) VALUES
(1, 'Activo'),
(2, 'Desactivo');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupos_alumnos`
--
CREATE TABLE `grupos_alumnos` (
`id` int(11) NOT NULL,
`grupo_info_id` int(11) NOT NULL,
`user_alumno_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `grupos_alumnos`
--
INSERT INTO `grupos_alumnos` (`id`, `grupo_info_id`, `user_alumno_id`) VALUES
(1, 1, 7),
(2, 1, 10),
(3, 1, 6),
(4, 1, 11),
(5, 1, 12),
(6, 1, 13);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupos_info`
--
CREATE TABLE `grupos_info` (
`id` int(11) NOT NULL,
`nombre` varchar(20) NOT NULL,
`nivel_escolar_id` int(11) NOT NULL,
`nivel_turno_id` int(11) NOT NULL,
`nivel_grado_id` int(11) NOT NULL,
`periodo_info_id` int(11) NOT NULL,
`plan_estudios_id` int(11) NOT NULL,
`year` int(11) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `grupos_info`
--
INSERT INTO `grupos_info` (`id`, `nombre`, `nivel_escolar_id`, `nivel_turno_id`, `nivel_grado_id`, `periodo_info_id`, `plan_estudios_id`, `year`, `creado`) VALUES
(1, 'Grupo1', 1, 1, 1, 1, 1, 0, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupos_mat_alum`
--
CREATE TABLE `grupos_mat_alum` (
`id` int(11) NOT NULL,
`grupo_mat_prof_id` int(11) NOT NULL,
`user_alumno_id` int(11) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `grupos_mat_alum`
--
INSERT INTO `grupos_mat_alum` (`id`, `grupo_mat_prof_id`, `user_alumno_id`, `creado`) VALUES
(1, 1, 10, '2020-07-26'),
(2, 1, 6, '2020-07-26'),
(3, 1, 11, '2020-07-26'),
(4, 1, 12, '2020-07-26'),
(5, 1, 13, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `grupos_mat_prof`
--
CREATE TABLE `grupos_mat_prof` (
`id` int(11) NOT NULL,
`banco_materia_id` int(11) NOT NULL,
`user_profesor_id` int(11) NOT NULL,
`grupo_info_id` int(11) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `grupos_mat_prof`
--
INSERT INTO `grupos_mat_prof` (`id`, `banco_materia_id`, `user_profesor_id`, `grupo_info_id`, `creado`) VALUES
(1, 1, 3, 1, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `perfiles`
--
CREATE TABLE `perfiles` (
`id` int(11) NOT NULL,
`nombre` varchar(30) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `perfiles`
--
INSERT INTO `perfiles` (`id`, `nombre`, `creado`) VALUES
(1, 'Director', '2017-11-10'),
(2, 'Administrativo', '2017-11-10'),
(3, 'Profesor', '2017-11-10'),
(4, 'Alumno', '2017-11-10'),
(5, 'Tutor', '2017-11-10');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `periodo_fecha`
--
CREATE TABLE `periodo_fecha` (
`id` int(11) NOT NULL,
`periodo_info_id` int(11) NOT NULL,
`fecha_inicio` date NOT NULL,
`fecha_fin` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `periodo_fecha`
--
INSERT INTO `periodo_fecha` (`id`, `periodo_info_id`, `fecha_inicio`, `fecha_fin`) VALUES
(1, 1, '2020-07-01', '2020-07-04'),
(2, 1, '2020-07-05', '2020-07-11'),
(3, 1, '2020-07-12', '2020-07-18');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `periodo_info`
--
CREATE TABLE `periodo_info` (
`id` int(11) NOT NULL,
`nombre` varchar(50) NOT NULL,
`num_periodos` int(11) NOT NULL,
`estado_id` int(11) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `periodo_info`
--
INSERT INTO `periodo_info` (`id`, `nombre`, `num_periodos`, `estado_id`, `creado`) VALUES
(1, 'Periodo 1', 3, 1, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `planes_estudios`
--
CREATE TABLE `planes_estudios` (
`id` int(11) NOT NULL,
`nombre` varchar(50) NOT NULL,
`year` int(11) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `planes_estudios`
--
INSERT INTO `planes_estudios` (`id`, `nombre`, `year`, `creado`) VALUES
(1, 'Test', 2018, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `rubrica_detalles_calif`
--
CREATE TABLE `rubrica_detalles_calif` (
`id` int(11) NOT NULL,
`rubrica_info_calif_id` int(11) NOT NULL,
`user_alumno_id` int(11) NOT NULL,
`calificacion` int(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `rubrica_detalles_calif`
--
INSERT INTO `rubrica_detalles_calif` (`id`, `rubrica_info_calif_id`, `user_alumno_id`, `calificacion`) VALUES
(1, 1, 6, 8),
(2, 1, 7, 10),
(3, 1, 10, 10),
(4, 1, 11, 10),
(5, 1, 12, 8),
(6, 1, 13, 8),
(7, 2, 6, 10),
(8, 2, 7, 8),
(9, 2, 10, 10),
(10, 2, 11, 8),
(11, 2, 12, 10),
(12, 2, 13, 10),
(13, 3, 6, 10),
(14, 3, 7, 10),
(15, 3, 10, 8),
(16, 3, 11, 10),
(17, 3, 12, 10),
(18, 3, 13, 10),
(19, 4, 6, 10),
(20, 4, 7, 9),
(21, 4, 10, 8),
(22, 4, 11, 8),
(23, 4, 12, 9),
(24, 4, 13, 10),
(25, 5, 6, 0),
(26, 5, 7, 10),
(27, 5, 10, 10),
(28, 5, 11, 10),
(29, 5, 12, 10),
(30, 5, 13, 0),
(31, 6, 6, 10),
(32, 6, 7, 10),
(33, 6, 10, 0),
(34, 6, 11, 0),
(35, 6, 12, 10),
(36, 6, 13, 10),
(37, 7, 6, 5),
(38, 7, 7, 6),
(39, 7, 10, 7),
(40, 7, 11, 7),
(41, 7, 12, 6),
(42, 7, 13, 5),
(43, 8, 6, 9),
(44, 8, 7, 8),
(45, 8, 10, 9),
(46, 8, 11, 10),
(47, 8, 12, 9),
(48, 8, 13, 8),
(49, 9, 6, 5),
(50, 9, 7, 5),
(51, 9, 10, 6),
(52, 9, 11, 7),
(53, 9, 12, 6),
(54, 9, 13, 7);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `rubrica_info`
--
CREATE TABLE `rubrica_info` (
`id` int(11) NOT NULL,
`nombre` varchar(50) NOT NULL,
`grupo_mat_prof_id` int(11) NOT NULL,
`periodo_fecha_id` int(11) NOT NULL,
`estado_id` int(11) NOT NULL,
`porcentaje` int(3) NOT NULL,
`creado` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `rubrica_info`
--
INSERT INTO `rubrica_info` (`id`, `nombre`, `grupo_mat_prof_id`, `periodo_fecha_id`, `estado_id`, `porcentaje`, `creado`) VALUES
(1, 'Asistencia', 1, 1, 2, 50, '2020-07-26'),
(2, 'Tareas', 1, 1, 2, 20, '2020-07-26'),
(3, 'Examen', 1, 1, 2, 30, '2020-07-26'),
(4, 'Asistencias', 1, 2, 2, 10, '2020-07-26'),
(5, 'Tareas', 1, 2, 2, 30, '2020-07-26'),
(6, 'Examen', 1, 2, 2, 60, '2020-07-26');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `rubrica_info_calif`
--
CREATE TABLE `rubrica_info_calif` (
`id` int(11) NOT NULL,
`rubrica_info_id` int(11) NOT NULL,
`fecha` date NOT NULL,
`nombre` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `rubrica_info_calif`
--
INSERT INTO `rubrica_info_calif` (`id`, `rubrica_info_id`, `fecha`, `nombre`) VALUES
(1, 1, '2020-07-26', 'Lista'),
(2, 1, '2020-07-27', 'Lista2'),
(3, 1, '2020-07-28', 'Lista3'),
(4, 4, '2020-07-27', 'Lista'),
(5, 4, '2020-07-28', 'Lista2'),
(6, 4, '2020-07-29', 'Lista3'),
(7, 5, '2020-07-26', 'Tarea 1'),
(8, 5, '2020-07-31', 'Tarea2'),
(9, 6, '2020-08-01', 'Exa');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE `usuarios` (
`id` int(11) NOT NULL,
`nombre` varchar(150) NOT NULL,
`user` varchar(20) NOT NULL,
`pass` varchar(20) NOT NULL,
`clave` varchar(20) NOT NULL,
`logo` varchar(25) DEFAULT NULL,
`informacion_id` int(11) DEFAULT NULL,
`perfil_id` int(11) NOT NULL,
`estado_id` int(11) NOT NULL,
`creado` date NOT NULL,
`actualizado` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuarios`
--
INSERT INTO `usuarios` (`id`, `nombre`, `user`, `pass`, `clave`, `logo`, `informacion_id`, `perfil_id`, `estado_id`, `creado`, `actualizado`) VALUES
(6, 'AP1 AM1 Name1', 'aAP1M5', 'aAP1M5', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(7, 'AP2 AM2 Name2UPD', 'aAP2M7', 'aAP2M7', '', NULL, NULL, 4, 1, '2020-07-26', '2020-07-26 20:55:00'),
(8, 'AP2 AM2 Name2', 'aAP2M8', 'aAP2M8', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(9, 'AP2 AM2 Name2', 'aAP2M9', 'aAP2M9', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(10, 'AP3 AM3 Name3', 'aAP3M10', 'aAP3M10', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(13, '<NAME>', 'asarmientoh13', '', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(1, '<NAME>', 'GianBros', '123', 'gianbros', 'gianbros.png', 1, 1, 1, '2017-11-10', NULL),
(12, '<NAME>', 'ilimav12', '', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(11, '<NAME>', 'mbrionest11', '', '', NULL, NULL, 4, 1, '2020-07-26', NULL),
(2, 'Test Profesor 1', 'prof1', 'prof1', 'prof1', NULL, 2, 2, 1, '2017-11-18', '2017-11-20 14:44:00'),
(3, 'Test profesor 2', 'prof2', 'prof2', 'prof2', NULL, 3, 3, 1, '2017-11-19', NULL),
(4, 'Test profesor 3', 'prof3', 'prof3', 'prof3', NULL, 4, 3, 1, '2017-11-19', NULL);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios_informacion`
--
CREATE TABLE `usuarios_informacion` (
`id` int(11) NOT NULL,
`dir` varchar(150) DEFAULT NULL,
`tel` varchar(10) DEFAULT NULL,
`mail` varchar(50) DEFAULT NULL,
`creado` date NOT NULL,
`actualizado` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuarios_informacion`
--
INSERT INTO `usuarios_informacion` (`id`, `dir`, `tel`, `mail`, `creado`, `actualizado`) VALUES
(1, 'Av. Revolucion No. 168, Acxotla del Río, Totolac, Tlaxcala.', '2461231894', '<EMAIL>', '2017-11-10', NULL),
(2, '', '1515151515', '', '2017-11-18', '2017-11-20 14:44:00'),
(3, '', '0987654321', '', '2017-11-19', NULL),
(4, '', '', '<EMAIL>', '2017-11-19', NULL);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `banco_materias`
--
ALTER TABLE `banco_materias`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `banco_niveles_escolares`
--
ALTER TABLE `banco_niveles_escolares`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `banco_niveles_grados`
--
ALTER TABLE `banco_niveles_grados`
ADD PRIMARY KEY (`id`),
ADD KEY `nivel_escolar_id` (`nivel_escolar_id`);
--
-- Indices de la tabla `banco_nivel_turnos`
--
ALTER TABLE `banco_nivel_turnos`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `estados`
--
ALTER TABLE `estados`
ADD KEY `id` (`id`);
--
-- Indices de la tabla `grupos_alumnos`
--
ALTER TABLE `grupos_alumnos`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `grupos_info`
--
ALTER TABLE `grupos_info`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `grupos_mat_alum`
--
ALTER TABLE `grupos_mat_alum`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `grupos_mat_prof`
--
ALTER TABLE `grupos_mat_prof`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `perfiles`
--
ALTER TABLE `perfiles`
ADD KEY `id` (`id`);
--
-- Indices de la tabla `periodo_fecha`
--
ALTER TABLE `periodo_fecha`
ADD PRIMARY KEY (`id`),
ADD KEY `periodo_info_id` (`periodo_info_id`);
--
-- Indices de la tabla `periodo_info`
--
ALTER TABLE `periodo_info`
ADD PRIMARY KEY (`id`),
ADD KEY `estado_id` (`estado_id`);
--
-- Indices de la tabla `planes_estudios`
--
ALTER TABLE `planes_estudios`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `rubrica_detalles_calif`
--
ALTER TABLE `rubrica_detalles_calif`
ADD PRIMARY KEY (`id`),
ADD KEY `rubrica_info_calif_id` (`rubrica_info_calif_id`,`user_alumno_id`),
ADD KEY `user_alumno_id` (`user_alumno_id`);
--
-- Indices de la tabla `rubrica_info`
--
ALTER TABLE `rubrica_info`
ADD PRIMARY KEY (`id`),
ADD KEY `grupo_mat_prof_id` (`grupo_mat_prof_id`,`periodo_fecha_id`,`estado_id`),
ADD KEY `periodo_fecha_id` (`periodo_fecha_id`),
ADD KEY `estado_id` (`estado_id`);
--
-- Indices de la tabla `rubrica_info_calif`
--
ALTER TABLE `rubrica_info_calif`
ADD PRIMARY KEY (`id`),
ADD KEY `rubrica_info_id` (`rubrica_info_id`);
--
-- Indices de la tabla `usuarios`
--
ALTER TABLE `usuarios`
ADD UNIQUE KEY `user` (`user`),
ADD KEY `id` (`id`),
ADD KEY `informacion_id` (`informacion_id`,`perfil_id`,`estado_id`),
ADD KEY `perfil_id` (`perfil_id`),
ADD KEY `estado_id` (`estado_id`);
--
-- Indices de la tabla `usuarios_informacion`
--
ALTER TABLE `usuarios_informacion`
ADD KEY `id` (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `banco_materias`
--
ALTER TABLE `banco_materias`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `banco_niveles_escolares`
--
ALTER TABLE `banco_niveles_escolares`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `banco_niveles_grados`
--
ALTER TABLE `banco_niveles_grados`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `banco_nivel_turnos`
--
ALTER TABLE `banco_nivel_turnos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT de la tabla `estados`
--
ALTER TABLE `estados`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT de la tabla `grupos_alumnos`
--
ALTER TABLE `grupos_alumnos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT de la tabla `grupos_info`
--
ALTER TABLE `grupos_info`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `grupos_mat_alum`
--
ALTER TABLE `grupos_mat_alum`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `grupos_mat_prof`
--
ALTER TABLE `grupos_mat_prof`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `perfiles`
--
ALTER TABLE `perfiles`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `periodo_fecha`
--
ALTER TABLE `periodo_fecha`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT de la tabla `periodo_info`
--
ALTER TABLE `periodo_info`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `planes_estudios`
--
ALTER TABLE `planes_estudios`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT de la tabla `rubrica_detalles_calif`
--
ALTER TABLE `rubrica_detalles_calif`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=55;
--
-- AUTO_INCREMENT de la tabla `rubrica_info`
--
ALTER TABLE `rubrica_info`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT de la tabla `rubrica_info_calif`
--
ALTER TABLE `rubrica_info_calif`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT de la tabla `usuarios`
--
ALTER TABLE `usuarios`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT de la tabla `usuarios_informacion`
--
ALTER TABLE `usuarios_informacion`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `banco_niveles_grados`
--
ALTER TABLE `banco_niveles_grados`
ADD CONSTRAINT `banco_niveles_grados_ibfk_1` FOREIGN KEY (`nivel_escolar_id`) REFERENCES `banco_niveles_escolares` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `periodo_fecha`
--
ALTER TABLE `periodo_fecha`
ADD CONSTRAINT `periodo_fecha_ibfk_1` FOREIGN KEY (`periodo_info_id`) REFERENCES `periodo_info` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `periodo_info`
--
ALTER TABLE `periodo_info`
ADD CONSTRAINT `periodo_info_ibfk_1` FOREIGN KEY (`estado_id`) REFERENCES `estados` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `rubrica_detalles_calif`
--
ALTER TABLE `rubrica_detalles_calif`
ADD CONSTRAINT `rubrica_detalles_calif_ibfk_1` FOREIGN KEY (`rubrica_info_calif_id`) REFERENCES `rubrica_info_calif` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `rubrica_detalles_calif_ibfk_2` FOREIGN KEY (`user_alumno_id`) REFERENCES `usuarios` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `rubrica_info`
--
ALTER TABLE `rubrica_info`
ADD CONSTRAINT `rubrica_info_ibfk_1` FOREIGN KEY (`grupo_mat_prof_id`) REFERENCES `grupos_mat_prof` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `rubrica_info_ibfk_2` FOREIGN KEY (`periodo_fecha_id`) REFERENCES `periodo_fecha` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `rubrica_info_ibfk_3` FOREIGN KEY (`estado_id`) REFERENCES `estados` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `rubrica_info_calif`
--
ALTER TABLE `rubrica_info_calif`
ADD CONSTRAINT `rubrica_info_calif_ibfk_1` FOREIGN KEY (`rubrica_info_id`) REFERENCES `rubrica_info` (`id`) ON UPDATE CASCADE;
--
-- Filtros para la tabla `usuarios`
--
ALTER TABLE `usuarios`
ADD CONSTRAINT `usuarios_ibfk_1` FOREIGN KEY (`informacion_id`) REFERENCES `usuarios_informacion` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `usuarios_ibfk_2` FOREIGN KEY (`perfil_id`) REFERENCES `perfiles` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `usuarios_ibfk_3` FOREIGN KEY (`estado_id`) REFERENCES `estados` (`id`) ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
include('../config/conexion.php');
include('../config/variables.php');
$periodos = array();
$msgErr = '';
$ban = false;
$sqlGetPeriodos = "SELECT $tPerInfo.id as idPeriodo, $tPerInfo.nombre as namePeriodo, "
. "$tPerInfo.estado_id as edoPeriodo, $tPerInfo.num_periodos as numPeriodos "
. " FROM $tPerInfo WHERE 1=1 ";
/*
$query = (isset($_POST['query'])) ? $_POST['query'] : "";
if ($query != '') {
$sqlGetPlanEst .= " AND ($tPlanEst.nombre LIKE '%$query%' OR $tPlanEst.year LIKE '%$query%' ) ";
}
$tarea = (isset($_POST['tarea'])) ? $_POST['tarea'] : "";
if ($tarea != '') {
$idPlanEst2 = $_POST['idPlanEst'];
$sqlGetPlanEst .= " AND $tPlanEst.id = '$idPlanEst2' ";
}
//Ordenar ASC y DESC
$vorder = (isset($_POST['orderby'])) ? $_POST['orderby'] : "";
if ($vorder != '') {
$sqlGetPlanEst .= " ORDER BY " . $vorder;
}
*/
$resGetPeriodos = $con->query($sqlGetPeriodos);
if ($resGetPeriodos->num_rows > 0) {
while ($rowGetPeriodos = $resGetPeriodos->fetch_assoc()) {
$id = $rowGetPeriodos['idPeriodo'];
$name = $rowGetPeriodos['namePeriodo'];
$edo = $rowGetPeriodos['edoPeriodo'];
$num = $rowGetPeriodos['numPeriodos'];
$periodos[] = array('id' => $id, 'nombre' => $name, 'estado' => $edo, 'numero'=>$num );
$ban = true;
}
} else {
$ban = false;
$msgErr = 'No existen periodos, aún.<br>' . $con->error;
}
if ($ban) {
echo json_encode(array("error" => 0, "dataRes" => $periodos, "sql" => $sqlGetPeriodos));
} else {
echo json_encode(array("error" => 1, "msgErr" => $msgErr));
}
?>
|
c89f694c3b6b92cadea5332ffd6fc5602281ac83
|
[
"SQL",
"PHP"
] | 63 |
PHP
|
SdMSyN/eva_pec
|
19c28ddde9f3877e343391d3a0c9c0c5e801a714
|
93c490c9d4e0ef55f8fcc0e5f6b2d2787d72a7b2
|
refs/heads/master
|
<repo_name>kyskar/pcomp<file_sep>/component_tests/joystickServo/joystickServo.ino
#include <Servo.h>
const int Spin = 6; // switch input
const int Xpin = A0; // X input
const int Ypin = A1; // Y input
//const int Mpin = 3; // servo motor output
Servo myservo;
void setup() {
pinMode(Xpin, INPUT);
pinMode(Ypin, INPUT);
pinMode(Spin, INPUT_PULLUP);
// pinMode(Mpin, OUTPUT);
myservo.attach(3);
myservo.write(90);
digitalWrite(Spin, HIGH);
Serial.begin(9600);
}
void loop() {
int Xposition = 0;
int Yposition = 0;
int Sstate = 0;
int Xmap = 0;
int Ymap = 0;
int currentServo = 90;
Xposition = analogRead(Xpin);
Yposition = analogRead(Ypin);
Sstate = digitalRead(Spin);
Xmap = map(Xposition,0,1022,0,180);
Ymap = map(Yposition,0,1022,0,180);
currentServo = myservo.read();
Serial.println(currentServo);
if(Xmap != 90){
myservo.write(Xmap);
}
else{
if(currentServo >= 88 ){
myservo.write(currentServo-1);
}
if(currentServo <= 82){
myservo.write(currentServo+1);
}
}
delay(100);
}
<file_sep>/project_related/distance_measure_main.ino
#include "SevSeg.h"
SevSeg sevseg;
const int trigPin = 9;
const int echoPin = 8;
long duration;
int distance;
const int analogInPin = A1;
int sensorValue = 0;
int state = 4;
void setup(){
pinMode(A5,INPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Serial.begin(9600);
byte numDigits = 4;
byte digitPins[] = {10, 11, 12, 13};
byte segmentPins[] = {1, 2, 3, 5, 6, 0, 7, 4};
bool resistorsOnSegments = true;
bool updateWithDelaysIn = true;
byte hardwareConfig = COMMON_CATHODE;
sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
sevseg.setBrightness(90);
}
void loop(){
readSwitch();
if (state == 0) {
digitalWrite(trigPin, LOW); // clear trigger
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // send wave
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration *0.034/2;
sevseg.setNumber(distance);
state = 4; // STOPS CONSTANT READSWITCH ISSUE
delay(40);
}
// if (state == 1) {
//
// }
sevseg.refreshDisplay();
}
void readSwitch () {
sensorValue = analogRead(analogInPin);
if (sensorValue < 800 && sensorValue > 750) {
state = 0;
delay(100);
}
if (sensorValue < 749 && sensorValue > 650) {
state = 1;
delay(100);
}
if (sensorValue < 649 && sensorValue > 425) {
state = 2;
delay(100);
}
if (sensorValue < 425 && sensorValue >= 0) {
state = 3;
delay(100);
}
delay(1);
}
<file_sep>/project_related/sevseg_test.ino
#include "SevSeg.h"
SevSeg sevseg;
const int trigPin = 1;
const int echoPin = 0;
long duration;
int distance;
int switchState = 0;
void setup(){
pinMode(A5,INPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Serial.begin(9600);
byte numDigits = 4;
byte digitPins[] = {10, 11, 12, 13};
byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};
bool resistorsOnSegments = true;
bool updateWithDelaysIn = true;
byte hardwareConfig = COMMON_CATHODE;
sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
sevseg.setBrightness(90);
}
void loop(){
switchState = digitalRead(A5);
if (switchState == HIGH) {
digitalWrite(trigPin, LOW); // clear trigger
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // send wave
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration *0.034/2;
// Serial.println(duration);
// Serial.println(distance);
sevseg.setNumber(distance);
delay(300);
}
sevseg.refreshDisplay();
}
<file_sep>/project_related/ultrasonic_test.ino
const int trigPin = 9;
const int echoPin = 10;
//const int greenPin = 3;
//const int yellowPin = 5;
//const int redPin = 6;
int limit1 = 12;
int limit2 = 5;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// pinMode(greenPin, OUTPUT);
// pinMode(yellowPin, OUTPUT);
// pinMode(redPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW); // clear trigger
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // send wave
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration *0.034/2;
// Serial.println(duration);
Serial.println(distance);
// digitalWrite(redPin, LOW);
// digitalWrite(yellowPin, LOW);
// digitalWrite(greenPin, LOW);
//
// if (distance <= limit1){
// digitalWrite(redPin, LOW);
// digitalWrite(greenPin, HIGH);
// digitalWrite(yellowPin, HIGH);
// }
// if (distance >= limit1 and distance <= limit2) {
// digitalWrite(yellowPin, LOW);
// digitalWrite(greenPin, HIGH);
// digitalWrite(redPin, HIGH);
// }
// if (distance >= limit2) {
// digitalWrite(greenPin, LOW);
// digitalWrite(yellowPin, HIGH);
// digitalWrite(redPin, HIGH);
// }
}
|
f03315cc822cde70790ca753533c42fd28d4a14a
|
[
"C++"
] | 4 |
C++
|
kyskar/pcomp
|
e7f5291d1eb9abfbb0dcb5c541a8602bc75f8ee1
|
8c448cd2d002234d3d21028a1c1740294c309b20
|
refs/heads/master
|
<repo_name>sppteam/iOS<file_sep>/iOS/spp.en.js
/*!
* SPP English Localization
* Created By Eugene 19/11/2015 Globalize 0.x
* Modified By Eugene 14/09/2016 Globalize 1.x
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(function (require, exports, module) {
factory(require("../message"))
})
}
else {
factory(DevExpress.localization.message)
}
}(this, function (message) {
message.load({
en: {
Back: "Back",
Cancel: "Cancel",
Clear: "Clear",
Done: "Done",
Loading: "Loading...",
No: "No",
OK: "OK",
Search: "Search",
Select: "Select...",
Yes: "Yes",
"dxCalendar-ariaWidgetName": "Calendar",
"dxCalendar-todayButtonText": "Today",
"dxCollectionWidget-noDataText": "NA",
"dxColorView-ariaAlpha": "Transparency",
"dxColorView-ariaBlue": "Blue",
"dxColorView-ariaGreen": "Green",
"dxColorView-ariaHex": "Color code",
"dxColorView-ariaRed": "Red",
"dxDataGrid-applyFilterText": "Apply filter",
"dxDataGrid-ariaCollapse": "Collapse",
"dxDataGrid-ariaColumn": "Column",
"dxDataGrid-ariaDataGrid": "Data grid",
"dxDataGrid-ariaExpand": "Expand",
"dxDataGrid-ariaFilterCell": "Filter cell",
"dxDataGrid-ariaSearchInGrid": "Search in data grid",
"dxDataGrid-ariaSelectAll": "Select all",
"dxDataGrid-ariaSelectRow": "Select row",
"dxDataGrid-ariaValue": "Value",
"dxDataGrid-columnChooserEmptyText": "Drag a column here to hide it",
"dxDataGrid-columnChooserTitle": "Column Chooser",
"dxDataGrid-columnFixingFix": "Fix",
"dxDataGrid-columnFixingLeftPosition": "To the left",
"dxDataGrid-columnFixingRightPosition": "To the right",
"dxDataGrid-columnFixingUnfix": "Unfix",
"dxDataGrid-editingAddRow": "Add a row",
"dxDataGrid-editingCancelAllChanges": "Discard changes",
"dxDataGrid-editingCancelRowChanges": "Cancel",
"dxDataGrid-editingConfirmDeleteMessage": "Are you sure you want to delete this record?",
"dxDataGrid-editingConfirmDeleteTitle": "",
"dxDataGrid-editingDeleteRow": "Delete",
"dxDataGrid-editingEditRow": "Edit",
"dxDataGrid-editingSaveAllChanges": "Save changes",
"dxDataGrid-editingSaveRowChanges": "Save",
"dxDataGrid-editingUndeleteRow": "Undelete",
"dxDataGrid-excelFormat": "Excel file",
"dxDataGrid-exportTo": "Export to",
"dxDataGrid-exportToExcel": "Export to Excel file",
"dxDataGrid-falseText": "false",
"dxDataGrid-filterRowOperationContains": "Contains",
"dxDataGrid-filterRowOperationEndsWith": "Ends with",
"dxDataGrid-filterRowOperationEquals": "Equals",
"dxDataGrid-filterRowOperationGreater": "Greater than",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Greater than or equal to",
"dxDataGrid-filterRowOperationLess": "Less than",
"dxDataGrid-filterRowOperationLessOrEquals": "Less than or equal to",
"dxDataGrid-filterRowOperationNotContains": "Does not contain",
"dxDataGrid-filterRowOperationNotEquals": "Does not equal",
"dxDataGrid-filterRowOperationStartsWith": "Starts with",
"dxDataGrid-filterRowResetOperationText": "Reset",
"dxDataGrid-filterRowShowAllText": "(All)",
"dxDataGrid-groupContinuedMessage": "Continued from the previous page",
"dxDataGrid-groupContinuesMessage": "Continues on the next page",
"dxDataGrid-groupPanelEmptyText": "Drag a column header here to group by that column",
"dxDataGrid-headerFilterCancel": "Cancel",
"dxDataGrid-headerFilterEmptyValue": "(Blanks)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-noDataText": "No data",
"dxDataGrid-searchPanelPlaceholder": "Search...",
"dxDataGrid-selectedRows": "Selected rows",
"dxDataGrid-sortingAscendingText": "Sort Ascending",
"dxDataGrid-sortingClearText": "Clear Sorting",
"dxDataGrid-sortingDescendingText": "Sort Descending",
"dxDataGrid-summaryAvg": "Avg: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Avg of {1} is {0}",
"dxDataGrid-summaryCount": "Count: {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Max of {1} is {0}",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Min of {1} is {0}",
"dxDataGrid-summarySum": "Sum: {0}",
"dxDataGrid-summarySumOtherColumn": "Sum of {1} is {0}",
"dxDataGrid-trueText": "true",
"dxDataGrid-validationCancelChanges": "Cancel changes",
"dxDateBox-simulatedDataPickerTitleDate": "Select date",
"dxDateBox-simulatedDataPickerTitleDateTime": "Select date and time",
"dxDateBox-simulatedDataPickerTitleTime": "Select time",
"dxDateBox-validation-datetime": "Value must be a date or time",
"dxFileSaver-fileExported": "File exported",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-bytes": "bytes",
"dxFileUploader-dropFile": "or Drop file here",
"dxFileUploader-kb": "kb",
"dxFileUploader-readyToUpload": "Ready to upload",
"dxFileUploader-selectFile": "Select file",
"dxFileUploader-upload": "Upload",
"dxFileUploader-uploadFailedMessage": "Upload failed",
"dxFileUploader-uploaded": "Uploaded",
"dxList-nextButtonText": "More",
"dxList-pageLoadingText": "Loading...",
"dxList-pulledDownText": "Release to refresh...",
"dxList-pullingDownText": "Pull down to refresh...",
"dxList-refreshingText": "Refreshing...",
"dxList-selectAll": "Select All",
"dxListEditDecorator-delete": "Delete/Reject",
"dxListEditDecorator-more": "More",
"dxLookup-searchPlaceholder": "Minimum character number: {0}",
"dxPager-infoText": "Page {0} of {1}",
"dxPivotGrid-allFields": "All Fields",
"dxPivotGrid-collapseAll": "Collapse All",
"dxPivotGrid-columnFields": "Column Fields",
"dxPivotGrid-dataFields": "Data Fields",
"dxPivotGrid-expandAll": "Expand All",
"dxPivotGrid-fieldChooserTitle": "Field Chooser",
"dxPivotGrid-filterFields": "Filter Fields",
"dxPivotGrid-grandTotal": "Grand Total",
"dxPivotGrid-removeAllSorting": "Remove All Sorting",
"dxPivotGrid-rowFields": "Row Fields",
"dxPivotGrid-showFieldChooser": "Show Field Chooser",
"dxPivotGrid-sortColumnBySummary": "Sort '{0}' by This Column",
"dxPivotGrid-sortRowBySummary": "Sort '{0}' by This Row",
"dxPivotGrid-total": "{0} Total",
"dxRangeSlider-ariaFrom": "From {0}",
"dxRangeSlider-ariaTill": "Till {0}",
"dxScheduler-allDay": "All day",
"dxScheduler-editorLabelDescription": "Description",
"dxScheduler-editorLabelEndDate": "End Date",
"dxScheduler-editorLabelRecurrence": "Repeat",
"dxScheduler-editorLabelStartDate": "Start Date",
"dxScheduler-editorLabelTitle": "Subject",
"dxScheduler-openAppointment": "Open appointment",
"dxScheduler-recurrenceAfter": "After",
"dxScheduler-recurrenceDaily": "Daily",
"dxScheduler-recurrenceEnd": "End repeat",
"dxScheduler-recurrenceEvery": "Every",
"dxScheduler-recurrenceMonthly": "Monthly",
"dxScheduler-recurrenceNever": "Never",
"dxScheduler-recurrenceOn": "On",
"dxScheduler-recurrenceRepeatCount": "occurrence(s)",
"dxScheduler-recurrenceRepeatDaily": "day(s)",
"dxScheduler-recurrenceRepeatMonthly": "month(s)",
"dxScheduler-recurrenceRepeatOnDate": "on date",
"dxScheduler-recurrenceRepeatWeekly": "week(s)",
"dxScheduler-recurrenceRepeatYearly": "year(s)",
"dxScheduler-recurrenceWeekly": "Weekly",
"dxScheduler-recurrenceYearly": "Yearly",
"dxScheduler-switcherDay": "Day",
"dxScheduler-switcherMonth": "Month",
"dxScheduler-switcherWeek": "Week",
"dxScheduler-switcherWorkWeek": "Work week",
"dxScrollView-pulledDownText": "Release to refresh...",
"dxScrollView-pullingDownText": "Pull down to refresh...",
"dxScrollView-reachBottomText": "Loading...",
"dxScrollView-refreshingText": "Refreshing...",
"dxSwitch-offText": "OFF",
"dxSwitch-onText": "ON",
"validation-compare": "Values do not match",
"validation-compare-formatted": "{0} does not match",
"validation-custom": "Value is invalid",
"validation-custom-formatted": "{0} is invalid",
"validation-email": "Email is invalid",
"validation-email-formatted": "{0} is invalid",
"validation-mask": "Value is invalid",
"validation-numeric": "Value must be a number",
"validation-numeric-formatted": "{0} must be a number",
"validation-pattern": "Value does not match pattern",
"validation-pattern-formatted": "{0} does not match pattern",
"validation-range": "Value is out of range",
"validation-range-formatted": "{0} is out of range",
"validation-required": "Required",
"validation-required-formatted": "{0} is required",
"validation-stringLength": "The length of the value is not correct",
"validation-stringLength-formatted": "The length of {0} is not correct",
//Menu
"Home": "Home",
"My-Task": "My Task",
"Business-Intelligence": "Business Intelligence",
"Business-Planning": "Business Planning",
"Project-Management": "Project Management",
"Quote": "Quote",
"Finance": "Finance",
"Basic-Data-(TBD)": "Basic Data (TBD)",
"E-Contract-Management": "E - Contract Management",
"System-Admin": "System Admin",
"Market,-Competitor,-Customer": "Market, Competitor, Customer",
"CRM": "CRM",
"Customer-Map": "Customer Map",
//Menu (sub) Title
"Major-Account-Report": "Major Account Report",
"Quotation-Tasks": "Quotation Tasks",
"BI-Reports": "BI Reports",
"Capability": "Capability",
"Capacity": "Capacity",
"NPI-Dashboard": "NPI Dashboard",
"System-Setting": "System Setting",
"Approval": "Approval",
//Menu (sub) Item
"User-Maintenance": "User Maintenance",
"Function-Maintenance": "Function Maintenance",
"Role-Maintenance": "Role Maintenance",
"Plant-Maintenance": "Plant Maintenance",
"Organization-Maintenance": "Organization Maintenance",
"BU-Master-Maintenance": "BU Master Maintenance",
"BU-Detail-Maintenance": "BU Detail Maintenance",
"Organization-BOM-Maintenance": "Organization BOM Maintenance",
"Role-Function-Setting": "Role Function Setting",
"User-Role-Setting": "User Role Setting",
"User-Organization-Setting": "User Organization Setting",
"User-Plant-Setting": "User Plant Setting",
"User-BU-Setting": "User BU Setting",
"Competitor-Capability-Matrix": "Competitor Capability Matrix",
"Customer-Needs-Capability-Matrix": "Customer Needs Capability Matrix",
"Products-Tear-Down-Analysis": "Products Tear Down Analysis",
"R&D-Reference": "R&D Reference",
"Competitor-&-Customer": "Competitor & Customer",
"Customer-Share-Of-Wallet": "Customer Share Of Wallet",
"Consumer-Electronics-Reports": "Consumer Electronics Reports",
"Capacity-Update": "Capacity Update",
"Capacity-Report": "Capacity Report",
"Site-Profile": "Site Profile",
"Machine-Utilization-Report": "Machine Utilization Report",
"Project-Initiative-Consolidate-Report": "Project Initiative Consolidate Report",
"Quotation-Tasks": "Quotation Tasks",
//User Define Keyword
"login": "Login",
"logout": "Logout",
"logout_now": "Logout Now",
"username": "Username",
"password": "<PASSWORD>",
"ntid": "NTID",
"please_scan_touchid": "Please Scan Touch ID",
"success_verify_fingerprint": "Verification Successful",
"fail_verify_fingerprint": "Verification Failed",
"choose_language": "Choose Language",
"language_change_reload_page": "Changing language required to restart the app",
"confirm_change": "Confirm Restart?",
"language": "Language",
//Login
"invalid_username_password": "<PASSWORD>/Password",
"menu_signin": "Sign in to start your session",
//Company
"company": "Company",
"ticker": "Ticker",
"legal_name": "Name",
"stock_exchange": "Stock Exchange",
"sic": "SIC",
"long_description": "Description",
"ceo": "CEO",
"company_url": "URL",
"business_address": "Address",
"business_phone_no": "Phone",
"cik": "CIK",
"hq_state": "HQ State",
"hq_country": "HQ Country",
"inc_state": "INC State",
"inc_country": "INC Country",
"employees": "Employees",
"sector": "Sector",
"industry_category": "Category",
"industry_group": "Group",
"please_select_company": "Please Select Company",
"social_media": "Social Media",
"social_feed": "Social Feed",
//Setting
"setting": "Setting",
"touchid": "Touch ID",
"on": "On",
"off": "Off",
"no_internet_connection": "No Internet Connection",
"check_vpn_connection": "Please check VPN is turn on",
"unauthorized": "Unauthorized",
"na": "No Information",
"close": "Close",
//Capacity
"sqft": "Sqft",
"sqft_available": "Sqft Avail",
"floor_space": "Floor Space",
"mfg_space": "MFG Space",
"surplus_mfg_space": "Surplus MFG Space",
"site": "Site",
"site_profile": "Site Profile",
"Taichung": "Taichung",
"Changhua": "Changhua",
"Suzhou": "Suzhou",
"Yantai": "Yantai",
"Tianjin": "Tianjin",
"Wuxi": "Wuxi",
"Chengdu": "Chengdu",
"Huangpu": "HuangPu",
"Shenzhen": "Shenzhen",
"Penang": "Penang",
"business": "Business",
"key_capabilities": "Key Capabilities",
"Tianjin Plastic": "Tianjin Plastic",
"Tianjin Metal": "Tianjin Metal",
"Penang Plastic": "Penang Plastic",
"Penang FATP": "Penang FATP",
"Shenzhen Plastic": "Shenzhen Plastic",
"Shenzhen FATP": "Shenzhen FATP",
"Taichung Plastic": "Taichung Plastic",
"Taichung FATP": "Taichung FATP",
"Taichung Metal": "Taichung Metal",
"Chengdu Automation": "Chengdu Automation",
"Chengdu FATP": "Chengdu FATP",
"Chengdu Metal": "Chengdu Metal",
"Suzhou SND": "Suzhou SND",
"Suzhou Metal": "Suzhou Metal",
"Suzhou SIP": "Suzhou SIP",
"Suzhou Lounan": "Suzhou Lounan",
"Wuxi Plastic": "Wuxi Plastic",
"Wuxi Metal": "Wuxi Metal",
"Wuxi FATP": "Wuxi FATP",
"Wuxi Automation": "Wuxi Automation",
"Yantai Plastic": "Yantai Plastic",
//Product - Added By Eugene 2015/11/30
"product_detail": "Product Detail",
"product": "Product",
"products_tear_down_analysis": "Products Tear Down Analysis",
"apple": "Apple",
"microsoft": "Microsoft",
"htc": "HTC",
"samsung": "Samsung",
"blackberry": "BlackBerry",
"sony": "Sony",
"lenovo": "Lenovo",
"nokia": "Nokia",
"motorola": "Motorola",
"oppo": "Oppo",
"xiaomi": "Xiaomi",
"smartphones": "Smartphone",
"tablets": "Tablet",
"phablets": "Phablet",
"customer": "Customer",
"type": "Type",
"photo": "Photo",
"operating_system": "OS",
"display": "Display",
"battery": "Battery",
"camera": "Camera",
"connectivity_and_sensors": "Connectivity & Sensors",
"nand": "NAND",
"sdram": "SDRAM",
"feature": "Features",
"cost": "Cost",
"processor": "Processor",
"bb+xcr": "BB + XCR",
"remarks": "Remarks",
"teardown_date": "Teardown Date",
"display_touchscreen_glass": "Display, Touchscreen, Glass",
"connectivity": "Connectivity",
"memory_nand": "Memory NAND",
"power_mgmt_audio": "Power Management Audio",
"non_electronic": "Non Electronic",
"other_mechanics_pcba": "Other Mechanics PCBA",
"supporting_materials": "Supporting Materials",
"manufacturing_cost": "Manufacturing Cost",
"total": "Total",
"selling_price": "Selling Price",
"margin": "Margin",
"stock": "Stock",
"stock_current_month": "Stock (Current Month)",
"income": "Income",
"income_current_year": "Income (Year 2016)",
//Company FY Report
"totalrevenue": "Total Revenue",
"operatingrevenue": "Operating Revenue",
"operatingcostofrevenue": "Operating Cost Of Revenue",
"totalcostofrevenue": "Total Cost Of Revenue",
"totalgrossprofit": "Total Gross Profit",
"sgaexpense": "SGA Expense",
"rdexpense": "RD Expense",
"totaloperatingexpenses": "Total Operating Expenses",
"totaloperatingincome": "Total Operating Income",
"otherincome": "Other Income / (Expense), net",
"totalotherincome": "Total Other Income / (Expense), net",
"totalpretaxincome": "Total Pre-Tax Income",
"incometaxexpense": "Income Tax Expense",
"netincomecontinuing": "Net Income / (Loss) Continuing Operations",
"netincome": "Consolidated Net Income / (Loss)",
"netincometocommon": "Net Income / (Loss) Attributable to Common Shareholders",
"weightedavebasicsharesos": "Weighted Average Basic Shares Outstanding",
"netincomecontinuing": "Net Income / (Loss) Continuing Operations",
"basiceps": "Basic Earnings per Share",
"weightedavedilutedsharesos": "Weighted Average Diluted Shares Outstanding",
"dilutedeps": "Diluted Earnings per Share",
"weightedavebasicdilutedsharesos": "Weighted Average Basic & Diluted Shares Outstanding",
"basicdilutedeps": "Basic & Diluted Earnings per Share",
"cashdividendspershare": "Cash Dividends to Common per Share",
"impairmentexpense": "Impairment Charge",
//Quote Approval
"quote_tasks": "Quotation Tasks",
"status": "Status",
"review": "Open",
"review_comments": "Review Comments",
"approve": "Approved",
"reject": "Rejected",
"project": "Project",
"customer": "Customer",
"parts": "Parts",
"category": "Category",
"approve_confirmation": "Approve Confirmation",
"reject_confirmation": "Reject Confirmation",
"confirm_approve": "Confirm Approve",
"confirm_reject": "Confirm Reject",
"quote_date": "Date",
"approval_details": "Approval Details",
"quote_detail": "Quote Details",
"quotation_no": "Quotation No",
"your_quotation": "Your Quotation",
"has_been_approved": "Has Been Approved.",
"has_been_rejected": "Has Been Rejected.",
"reject_reason": "Reject Reason",
"attachment": "Attachment",
"please_enter_reject_reason": "Please Enter Reject Reason.",
"enter_ntid_and_password": "<PASSWORD> & <PASSWORD>",
//Capacity Report
"capacity_report": "Capacity Report",
"plant_type": "Plant Type",
"site_name": "Site Name",
"quarter": "Quarter",
}
})
}));
//Globalize.addCultureInfo("en", {
// messages: {
// //System Default
// Back: "Back",
// Cancel: "Cancel",
// Clear: "Clear",
// Done: "Done",
// Loading: "Loading...",
// No: "No",
// OK: "OK",
// Search: "Search",
// Select: "Select...",
// Yes: "Yes",
// "dxCalendar-ariaWidgetName": "Calendar",
// "dxCalendar-todayButtonText": "Today",
// "dxCollectionWidget-noDataText": "NA",
// "dxColorView-ariaAlpha": "Transparency",
// "dxColorView-ariaBlue": "Blue",
// "dxColorView-ariaGreen": "Green",
// "dxColorView-ariaHex": "Color code",
// "dxColorView-ariaRed": "Red",
// "dxDataGrid-applyFilterText": "Apply filter",
// "dxDataGrid-ariaCollapse": "Collapse",
// "dxDataGrid-ariaColumn": "Column",
// "dxDataGrid-ariaDataGrid": "Data grid",
// "dxDataGrid-ariaExpand": "Expand",
// "dxDataGrid-ariaFilterCell": "Filter cell",
// "dxDataGrid-ariaSearchInGrid": "Search in data grid",
// "dxDataGrid-ariaSelectAll": "Select all",
// "dxDataGrid-ariaSelectRow": "Select row",
// "dxDataGrid-ariaValue": "Value",
// "dxDataGrid-columnChooserEmptyText": "Drag a column here to hide it",
// "dxDataGrid-columnChooserTitle": "Column Chooser",
// "dxDataGrid-columnFixingFix": "Fix",
// "dxDataGrid-columnFixingLeftPosition": "To the left",
// "dxDataGrid-columnFixingRightPosition": "To the right",
// "dxDataGrid-columnFixingUnfix": "Unfix",
// "dxDataGrid-editingAddRow": "Add a row",
// "dxDataGrid-editingCancelAllChanges": "Discard changes",
// "dxDataGrid-editingCancelRowChanges": "Cancel",
// "dxDataGrid-editingConfirmDeleteMessage": "Are you sure you want to delete this record?",
// "dxDataGrid-editingConfirmDeleteTitle": "",
// "dxDataGrid-editingDeleteRow": "Delete",
// "dxDataGrid-editingEditRow": "Edit",
// "dxDataGrid-editingSaveAllChanges": "Save changes",
// "dxDataGrid-editingSaveRowChanges": "Save",
// "dxDataGrid-editingUndeleteRow": "Undelete",
// "dxDataGrid-excelFormat": "Excel file",
// "dxDataGrid-exportTo": "Export to",
// "dxDataGrid-exportToExcel": "Export to Excel file",
// "dxDataGrid-falseText": "false",
// "dxDataGrid-filterRowOperationContains": "Contains",
// "dxDataGrid-filterRowOperationEndsWith": "Ends with",
// "dxDataGrid-filterRowOperationEquals": "Equals",
// "dxDataGrid-filterRowOperationGreater": "Greater than",
// "dxDataGrid-filterRowOperationGreaterOrEquals": "Greater than or equal to",
// "dxDataGrid-filterRowOperationLess": "Less than",
// "dxDataGrid-filterRowOperationLessOrEquals": "Less than or equal to",
// "dxDataGrid-filterRowOperationNotContains": "Does not contain",
// "dxDataGrid-filterRowOperationNotEquals": "Does not equal",
// "dxDataGrid-filterRowOperationStartsWith": "Starts with",
// "dxDataGrid-filterRowResetOperationText": "Reset",
// "dxDataGrid-filterRowShowAllText": "(All)",
// "dxDataGrid-groupContinuedMessage": "Continued from the previous page",
// "dxDataGrid-groupContinuesMessage": "Continues on the next page",
// "dxDataGrid-groupPanelEmptyText": "Drag a column header here to group by that column",
// "dxDataGrid-headerFilterCancel": "Cancel",
// "dxDataGrid-headerFilterEmptyValue": "(Blanks)",
// "dxDataGrid-headerFilterOK": "OK",
// "dxDataGrid-noDataText": "No data",
// "dxDataGrid-searchPanelPlaceholder": "Search...",
// "dxDataGrid-selectedRows": "Selected rows",
// "dxDataGrid-sortingAscendingText": "Sort Ascending",
// "dxDataGrid-sortingClearText": "Clear Sorting",
// "dxDataGrid-sortingDescendingText": "Sort Descending",
// "dxDataGrid-summaryAvg": "Avg: {0}",
// "dxDataGrid-summaryAvgOtherColumn": "Avg of {1} is {0}",
// "dxDataGrid-summaryCount": "Count: {0}",
// "dxDataGrid-summaryMax": "Max: {0}",
// "dxDataGrid-summaryMaxOtherColumn": "Max of {1} is {0}",
// "dxDataGrid-summaryMin": "Min: {0}",
// "dxDataGrid-summaryMinOtherColumn": "Min of {1} is {0}",
// "dxDataGrid-summarySum": "Sum: {0}",
// "dxDataGrid-summarySumOtherColumn": "Sum of {1} is {0}",
// "dxDataGrid-trueText": "true",
// "dxDataGrid-validationCancelChanges": "Cancel changes",
// "dxDateBox-simulatedDataPickerTitleDate": "Select date",
// "dxDateBox-simulatedDataPickerTitleDateTime": "Select date and time",
// "dxDateBox-simulatedDataPickerTitleTime": "Select time",
// "dxDateBox-validation-datetime": "Value must be a date or time",
// "dxFileSaver-fileExported": "File exported",
// "dxFileUploader-Gb": "Gb",
// "dxFileUploader-Mb": "Mb",
// "dxFileUploader-bytes": "bytes",
// "dxFileUploader-dropFile": "or Drop file here",
// "dxFileUploader-kb": "kb",
// "dxFileUploader-readyToUpload": "Ready to upload",
// "dxFileUploader-selectFile": "Select file",
// "dxFileUploader-upload": "Upload",
// "dxFileUploader-uploadFailedMessage": "Upload failed",
// "dxFileUploader-uploaded": "Uploaded",
// "dxList-nextButtonText": "More",
// "dxList-pageLoadingText": "Loading...",
// "dxList-pulledDownText": "Release to refresh...",
// "dxList-pullingDownText": "Pull down to refresh...",
// "dxList-refreshingText": "Refreshing...",
// "dxList-selectAll": "Select All",
// "dxListEditDecorator-delete": "Delete/Reject",
// "dxListEditDecorator-more": "More",
// "dxLookup-searchPlaceholder": "Minimum character number: {0}",
// "dxPager-infoText": "Page {0} of {1}",
// "dxPivotGrid-allFields": "All Fields",
// "dxPivotGrid-collapseAll": "Collapse All",
// "dxPivotGrid-columnFields": "Column Fields",
// "dxPivotGrid-dataFields": "Data Fields",
// "dxPivotGrid-expandAll": "Expand All",
// "dxPivotGrid-fieldChooserTitle": "Field Chooser",
// "dxPivotGrid-filterFields": "Filter Fields",
// "dxPivotGrid-grandTotal": "Grand Total",
// "dxPivotGrid-removeAllSorting": "Remove All Sorting",
// "dxPivotGrid-rowFields": "Row Fields",
// "dxPivotGrid-showFieldChooser": "Show Field Chooser",
// "dxPivotGrid-sortColumnBySummary": "Sort '{0}' by This Column",
// "dxPivotGrid-sortRowBySummary": "Sort '{0}' by This Row",
// "dxPivotGrid-total": "{0} Total",
// "dxRangeSlider-ariaFrom": "From {0}",
// "dxRangeSlider-ariaTill": "Till {0}",
// "dxScheduler-allDay": "All day",
// "dxScheduler-editorLabelDescription": "Description",
// "dxScheduler-editorLabelEndDate": "End Date",
// "dxScheduler-editorLabelRecurrence": "Repeat",
// "dxScheduler-editorLabelStartDate": "Start Date",
// "dxScheduler-editorLabelTitle": "Subject",
// "dxScheduler-openAppointment": "Open appointment",
// "dxScheduler-recurrenceAfter": "After",
// "dxScheduler-recurrenceDaily": "Daily",
// "dxScheduler-recurrenceEnd": "End repeat",
// "dxScheduler-recurrenceEvery": "Every",
// "dxScheduler-recurrenceMonthly": "Monthly",
// "dxScheduler-recurrenceNever": "Never",
// "dxScheduler-recurrenceOn": "On",
// "dxScheduler-recurrenceRepeatCount": "occurrence(s)",
// "dxScheduler-recurrenceRepeatDaily": "day(s)",
// "dxScheduler-recurrenceRepeatMonthly": "month(s)",
// "dxScheduler-recurrenceRepeatOnDate": "on date",
// "dxScheduler-recurrenceRepeatWeekly": "week(s)",
// "dxScheduler-recurrenceRepeatYearly": "year(s)",
// "dxScheduler-recurrenceWeekly": "Weekly",
// "dxScheduler-recurrenceYearly": "Yearly",
// "dxScheduler-switcherDay": "Day",
// "dxScheduler-switcherMonth": "Month",
// "dxScheduler-switcherWeek": "Week",
// "dxScheduler-switcherWorkWeek": "Work week",
// "dxScrollView-pulledDownText": "Release to refresh...",
// "dxScrollView-pullingDownText": "Pull down to refresh...",
// "dxScrollView-reachBottomText": "Loading...",
// "dxScrollView-refreshingText": "Refreshing...",
// "dxSwitch-offText": "OFF",
// "dxSwitch-onText": "ON",
// "validation-compare": "Values do not match",
// "validation-compare-formatted": "{0} does not match",
// "validation-custom": "Value is invalid",
// "validation-custom-formatted": "{0} is invalid",
// "validation-email": "Email is invalid",
// "validation-email-formatted": "{0} is invalid",
// "validation-mask": "Value is invalid",
// "validation-numeric": "Value must be a number",
// "validation-numeric-formatted": "{0} must be a number",
// "validation-pattern": "Value does not match pattern",
// "validation-pattern-formatted": "{0} does not match pattern",
// "validation-range": "Value is out of range",
// "validation-range-formatted": "{0} is out of range",
// "validation-required": "Required",
// "validation-required-formatted": "{0} is required",
// "validation-stringLength": "The length of the value is not correct",
// "validation-stringLength-formatted": "The length of {0} is not correct",
// }
//});
//Globalize.addCultureInfo("en", {
// messages: {
// //Menu
// "Home": "Home",
// "My-Task": "My Task",
// "Business-Intelligence": "Business Intelligence",
// "Business-Planning": "Business Planning",
// "Project-Management": "Project Management",
// "Quote": "Quote",
// "Finance": "Finance",
// "Basic-Data-(TBD)": "Basic Data (TBD)",
// "E-Contract-Management": "E - Contract Management",
// "System-Admin": "System Admin",
// //Menu (sub) Title
// "Major-Account-Report": "Major Account Report",
// "Quotation-Tasks": "Quotation Tasks",
// "BI-Reports": "BI Reports",
// "Capability": "Capability",
// "Capacity": "Capacity",
// "NPI-Dashboard": "NPI Dashboard",
// "System-Setting": "System Setting",
// "Approval": "Approval",
// //Menu (sub) Item
// "User-Maintenance": "User Maintenance",
// "Function-Maintenance": "Function Maintenance",
// "Role-Maintenance": "Role Maintenance",
// "Plant-Maintenance": "Plant Maintenance",
// "Organization-Maintenance": "Organization Maintenance",
// "BU-Master-Maintenance": "BU Master Maintenance",
// "BU-Detail-Maintenance": "BU Detail Maintenance",
// "Organization-BOM-Maintenance": "Organization BOM Maintenance",
// "Role-Function-Setting": "Role Function Setting",
// "User-Role-Setting": "User Role Setting",
// "User-Organization-Setting": "User Organization Setting",
// "User-Plant-Setting": "User Plant Setting",
// "User-BU-Setting": "User BU Setting",
// "Competitor-Capability-Matrix": "Competitor Capability Matrix",
// "Customer-Needs-Capability-Matrix": "Customer Needs Capability Matrix",
// "Products-Tear-Down-Analysis": "Products Tear Down Analysis",
// "R&D-Reference": "R&D Reference",
// "Competitor-&-Customer": "Competitor & Customer",
// "Customer-Share-Of-Wallet": "Customer Share Of Wallet",
// "Consumer-Electronics-Reports": "Consumer Electronics Reports",
// "Capacity-Update": "Capacity Update",
// "Capacity-Report": "Capacity Report",
// "Site-Profile": "Site Profile",
// "Machine-Utilization-Report": "Machine Utilization Report",
// "Project-Initiative-Consolidate-Report": "Project Initiative Consolidate Report",
// "Quotation-Tasks": "Quotation Tasks",
// //User Define Keyword
// "login": "Login",
// "logout": "Logout",
// "logout_now": "Logout Now",
// "username": "Username",
// "password": "<PASSWORD>",
// "ntid": "NTID",
// "please_scan_touchid": "Please Scan Touch ID",
// "success_verify_fingerprint": "Verification Successful",
// "fail_verify_fingerprint": "Verification Failed",
// "choose_language" : "Choose Language",
// "language_change_reload_page":"Changing language required to restart the app",
// "confirm_change": "Confirm Restart?",
// "language": "Language",
// //Login
// "invalid_username_password": "<PASSWORD>/<PASSWORD>",
// "menu_signin": "Sign in to start your session",
// //Company
// "company": "Company",
// "ticker": "Ticker",
// "legal_name": "Name",
// "stock_exchange": "Stock Exchange",
// "sic": "SIC",
// "long_description": "Description",
// "ceo": "CEO",
// "company_url": "URL",
// "business_address": "Address",
// "business_phone_no": "Phone",
// "cik": "CIK",
// "hq_state": "HQ State",
// "hq_country": "HQ Country",
// "inc_state": "INC State",
// "inc_country": "INC Country",
// "employees": "Employees",
// "sector": "Sector",
// "industry_category": "Category",
// "industry_group": "Group",
// "please_select_company": "Please Select Company",
// "social_media": "Social Media",
// "social_feed": "Social Feed",
// //Setting
// "setting": "Setting",
// "touchid": "Touch ID",
// "on": "On",
// "off": "Off",
// "no_internet_connection": "No Internet Connection",
// "check_vpn_connection": "Please check VPN is turn on",
// "unauthorized": "Unauthorized",
// "na": "No Information",
// "close": "Close",
// //Capacity
// "sqft": "Sqft",
// "sqft_available": "Sqft Avail",
// "floor_space": "Floor Space",
// "mfg_space": "MFG Space",
// "surplus_mfg_space": "Surplus MFG Space",
// "site": "Site",
// "site_profile": "Site Profile",
// "Taichung": "Taichung",
// "Changhua": "Changhua",
// "Suzhou": "Suzhou",
// "Yantai": "Yantai",
// "Tianjin": "Tianjin",
// "Wuxi": "Wuxi",
// "Chengdu": "Chengdu",
// "Huangpu": "HuangPu",
// "Shenzhen": "Shenzhen",
// "Penang": "Penang",
// "business": "Business",
// "key_capabilities": "Key Capabilities",
// "Tianjin Plastic": "Tianjin Plastic",
// "Tianjin Metal": "Tianjin Metal",
// "Penang Plastic": "Penang Plastic",
// "Penang FATP": "Penang FATP",
// "Shenzhen Plastic": "Shenzhen Plastic",
// "Shenzhen FATP": "Shenzhen FATP",
// "Taichung Plastic": "Taichung Plastic",
// "Taichung FATP": "Taichung FATP",
// "Taichung Metal": "Taichung Metal",
// "Chengdu Automation": "Chengdu Automation",
// "Chengdu FATP": "Chengdu FATP",
// "Chengdu Metal": "Chengdu Metal",
// "Suzhou SND": "Suzhou SND",
// "Suzhou Metal": "Suzhou Metal",
// "Suzhou SIP" : "Suzhou SIP",
// "Suzhou Lounan": "Suzhou Lounan",
// "Wuxi Plastic": "Wuxi Plastic",
// "Wuxi Metal": "Wuxi Metal",
// "Wuxi FATP": "Wuxi FATP",
// "Wuxi Automation": "Wuxi Automation",
// "Yantai Plastic": "Yantai Plastic",
// //Product - Added By Eugene 2015/11/30
// "product_detail": "Product Detail",
// "product": "Product",
// "products_tear_down_analysis": "Products Tear Down Analysis",
// "apple": "Apple",
// "microsoft": "Microsoft",
// "htc": "HTC",
// "samsung": "Samsung",
// "blackberry": "BlackBerry",
// "sony": "Sony",
// "lenovo": "Lenovo",
// "nokia": "Nokia",
// "motorola": "Motorola",
// "oppo": "Oppo",
// "xiaomi": "Xiaomi",
// "smartphones": "Smartphone",
// "tablets": "Tablet",
// "phablets": "Phablet",
// "customer": "Customer",
// "type": "Type",
// "photo": "Photo",
// "operating_system": "OS",
// "display" : "Display",
// "battery": "Battery",
// "camera": "Camera",
// "connectivity_and_sensors": "Connectivity & Sensors",
// "nand": "NAND",
// "sdram": "SDRAM",
// "feature": "Features",
// "cost":"Cost",
// "processor": "Processor",
// "bb+xcr" :"BB + XCR",
// "remarks" : "Remarks",
// "teardown_date" :"Teardown Date",
// "display_touchscreen_glass": "Display, Touchscreen, Glass",
// "connectivity":"Connectivity",
// "memory_nand":"Memory NAND",
// "power_mgmt_audio": "Power Management Audio",
// "non_electronic": "Non Electronic",
// "other_mechanics_pcba": "Other Mechanics PCBA",
// "supporting_materials": "Supporting Materials",
// "manufacturing_cost": "Manufacturing Cost",
// "total": "Total",
// "selling_price" : "Selling Price",
// "margin": "Margin",
// "stock": "Stock",
// "stock_current_month": "Stock (Current Month)",
// "income": "Income",
// "income_current_year": "Income (Year 2015)",
// //Company FY Report
// "totalrevenue": "Total Revenue",
// "operatingrevenue": "Operating Revenue",
// "operatingcostofrevenue": "Operating Cost Of Revenue",
// "totalcostofrevenue": "Total Cost Of Revenue",
// "totalgrossprofit" : "Total Gross Profit",
// "sgaexpense" : "SGA Expense",
// "rdexpense" : "RD Expense",
// "totaloperatingexpenses": "Total Operating Expenses",
// "totaloperatingincome" : "Total Operating Income",
// "otherincome": "Other Income / (Expense), net",
// "totalotherincome": "Total Other Income / (Expense), net",
// "totalpretaxincome": "Total Pre-Tax Income",
// "incometaxexpense": "Income Tax Expense",
// "netincomecontinuing": "Net Income / (Loss) Continuing Operations",
// "netincome": "Consolidated Net Income / (Loss)",
// "netincometocommon": "Net Income / (Loss) Attributable to Common Shareholders",
// "weightedavebasicsharesos": "Weighted Average Basic Shares Outstanding",
// "netincomecontinuing": "Net Income / (Loss) Continuing Operations",
// "basiceps": "Basic Earnings per Share",
// "weightedavedilutedsharesos": "Weighted Average Diluted Shares Outstanding",
// "dilutedeps": "Diluted Earnings per Share",
// "weightedavebasicdilutedsharesos":"Weighted Average Basic & Diluted Shares Outstanding",
// "basicdilutedeps": "Basic & Diluted Earnings per Share",
// "cashdividendspershare": "Cash Dividends to Common per Share",
// "impairmentexpense": "Impairment Charge",
// //Quote Approval
// "quote_tasks": "Quotation Tasks",
// "status": "Status",
// "review": "Open",
// "review_comments": "Review Comments",
// "approve": "Approved",
// "reject": "Rejected",
// "project": "Project",
// "customer": "Customer",
// "parts": "Parts",
// "category": "Category",
// "approve_confirmation": "Approve Confirmation",
// "reject_confirmation": "Reject Confirmation",
// "confirm_approve": "Confirm Approve",
// "confirm_reject": "Confirm Reject",
// "quote_date": "Date",
// "approval_details": "Approval Details",
// "quote_detail": "Quote Details",
// "quotation_no": "Quotation No",
// "your_quotation": "Your Quotation",
// "has_been_approved": "Has Been Approved.",
// "has_been_rejected": "Has Been Rejected.",
// "reject_reason": "Reject Reason",
// "attachment": "Attachment",
// "please_enter_reject_reason": "Please Enter Reject Reason.",
// //Capacity Report
// "capacity_report": "Capacity Report",
// "plant_type": "Plant Type",
// "site_name": "Site Name",
// "quarter": "Quarter",
// }
//});
|
3d021983884eb6192ef25e9406c211c485e20278
|
[
"JavaScript"
] | 1 |
JavaScript
|
sppteam/iOS
|
b4ab444bea9ec6264799bd8a8c8861eaa1e27004
|
81a27730e68026246957d5931ee0950cc5a93475
|
refs/heads/master
|
<file_sep>const electron = require('electron'),
app = electron.app,
BrowserWindow = electron.BrowserWindow;
var win = null;
app.on('ready', () => {
win = new BrowserWindow({
width: 800,
height: 600,
show: false
});
win.on('closed', () => {
win = null;
});
win.loadURL('file://' + __dirname + '/html/index.html');
win.show();
});
app.on('window-all-closed', () => { app.quit(); /* ... */ });
<file_sep># PodcastProton
A Electron-Based Desktop Player
### Todo:
- Podcast-Player-Javascript so verbessern das man auch Podcasts ändern kann
### Readmap:
1. Lieblings-Podcasts
2. ...
<file_sep>var podcastplayer = (function(){
var vueel = new Vue({
el: '#pcast-player-section',
data: {
'title':"Titel...",
'author':"Autor..."
}
});
return {
vueel: vueel,
$pcastPlayerWrapper: $('#pcast-player-wrapper')
};
})();
podcastplayer.playEpisode = function(ep){
ui.startLoading();
this.ep = ep;
this.vueel.title = ep.title;
this.vueel.author = ep.author;
this.url = ep.url;
this.$pcastPlayerWrapper.html("");
fs.readFile(__dirname + '/pcast-player.html', (err, data) => {
if (err) throw err;
this.$pcastPlayerWrapper.html( data.toString() );
this.reload();
browserWindow.setTitle('PodcastProton ~ ' + ep.title);
});
};
podcastplayer.reload = function(){
var player = document.querySelector('.pcast-player');
var $player = $(player);
var audio = player.querySelector('audio');
var play = player.querySelector('.pcast-play');
var pause = player.querySelector('.pcast-pause');
var rewind = player.querySelector('.pcast-rewind');
var progress = player.querySelector('.pcast-progress');
var speed = player.querySelector('.pcast-speed');
var mute = player.querySelector('.pcast-mute');
var currentTime = player.querySelector('.pcast-currenttime');
var duration = player.querySelector('.pcast-duration');
$(audio).attr('src', this.url);
$player.find('a').attr('href', this.url);
var currentSpeedIdx = 0;
var speeds = [ 1, 1.2, 1.5, 2, 0.5, 0.8 ];
pause.style.display = 'none';
var toHHMMSS = function(totalsecs){
var sec_num = parseInt(totalsecs, 10);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours; }
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
};
audio.addEventListener('loadedmetadata', function(){
progress.setAttribute('max', Math.floor(audio.duration));
duration.textContent = toHHMMSS(audio.duration);
ui.stopLoading();
});
audio.addEventListener('timeupdate', function(){
progress.setAttribute('value', audio.currentTime);
currentTime.textContent = toHHMMSS(audio.currentTime);
});
play.addEventListener('click', function(){
this.style.display = 'none';
pause.style.display = 'inline-block';
pause.focus();
audio.play();
}, false);
pause.addEventListener('click', function(){
this.style.display = 'none';
play.style.display = 'inline-block';
play.focus();
audio.pause();
}, false);
rewind.addEventListener('click', function(){
audio.currentTime -= 30;
}, false);
progress.addEventListener('click', function(event){
audio.currentTime = Math.floor(audio.duration) * (event.offsetX / event.target.offsetWidth);
}, false);
speed.addEventListener('click', function(){
currentSpeedIdx = currentSpeedIdx + 1 < speeds.length ? currentSpeedIdx + 1 : 0;
audio.playbackRate = speeds[currentSpeedIdx];
this.textContent = speeds[currentSpeedIdx] + 'x';
return true;
}, false);
mute.addEventListener('click', function() {
if(audio.muted) {
audio.muted = false;
this.querySelector('.fa').classList.remove('fa-volume-off');
this.querySelector('.fa').classList.add('fa-volume-up');
} else {
audio.muted = true;
this.querySelector('.fa').classList.remove('fa-volume-up');
this.querySelector('.fa').classList.add('fa-volume-off');
}
}, false);
/* - - - */
this.player = player;
};
<file_sep>function startSearchFor(term){
ui.startLoading();
SearchSection.vueel.term = term;
pcm.search(term).then((pcasts) => {
var results = [];
pcasts.results.forEach((res) => {
results.push({
'author':res.artistName,
'title':res.collectionName,
'feedUrl':res.feedUrl
});
});
SearchSection.setDisplayedPodcasts(results);
ui.stopLoading();
});
}
function showEpisodesForFeedUrl(feedUrl){
ui.startLoading();
pcm.parseRSSFeed(feedUrl).then((feed) => {
SearchSection.vueel.episodes = feed;
ui.stopLoading();
});
}
var SearchSection = (function(){
var $SearchSection = $('#search-section');
var $input = $SearchSection.find('input');
$input.on('keydown', (event) => {
if (event.keyCode === 13) {
startSearchFor( $input.val() );
}
});
var vueel = new Vue({
'el': '#search-section',
'data':{
pcasts: [],
episodes: [],
term: "...",
pcastTitle: "..."
},
'methods':{
showEpisodes: function(index){
vueel.pcastTitle = vueel.pcasts[index].title;
showEpisodesForFeedUrl(vueel.pcasts[index].feedUrl);
},
playEpisode: function(index){
var ep = vueel.episodes[index];
podcastplayer.playEpisode(ep);
}
}
});
return {
vueel: vueel,
setDisplayedPodcasts: (pcasts) => {
vueel.pcasts = pcasts;
}
};
})();
|
c925a247094948120573be6a50021485bc5c2f66
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
LouKnauer/PodcastProton
|
23da375e18378215471652cf79be8cf488b23bb3
|
122cc874b40a75c64b9f0d3debb44edd42e03458
|
refs/heads/master
|
<repo_name>chrisgeary92/osx-cpfrom<file_sep>/README.md
# Copyfrom
Copyfrom is a simple bash function for OSX that attempts to copy a directory and it's sub directories into the current working directory.
## TLDR
Create a directory to store your packages under `~/Desktop/packages`, create a `demo-package` directory containing some files, then run the following from your project:
````
cpfrom demo-package
````
* * *
This was created to simplify merging common files & directories into projects. Most likely the same functionality can be achieved with `rsync` but that wouldn't have been quite as fun.
## Installation
You can copy the `cpfrom` function from [cpfrom.sh](cpfrom.sh) and add to your `.bash_profile`. If you would like tab completions, you can also copy the contents of [completions.sh](completions.sh) into your `.bash_profile`.
You will need to `source ~/.bash_profile`, or re-open your Terminal to load these changes.
## Usage
First you must define a directory to act as a package repository. For example we can store our packages inside `~/Desktop/packages`.
Packages should be self-contained within a subdirectory. Below we have a package which can be identified by the unique directory name `demo-package`.
* `~/Desktop/packages/demo-package/css/demo.css`
* `~/Desktop/packages/demo-package/css/demo-theme.css`
* `~/Desktop/packages/demo-package/src/Controllers/DemoController.php`
To merge this package into your project, you can run `cpfrom demo-project` which will attempt to copy the `demo-project` into your current working directory.
## Conflicts
Packages can only be installed if the target directory does not already contain the files you wish to install. If any of those files exist, then the file will be compared against the source using `cmp`. If the files are identical it considers it safe to overwrite, however if a difference is found it's marked as "cannot be copied", and no files will be installed.
## Disclaimer
By running this code, you're choosing to do so at your own risk. I accept no responsibility for any damages caused as a result of this software.
## License
There is no license.<file_sep>/cpfrom.sh
cpfrom() {
local src=~/Desktop/packages/$1
local blue='\033[0;34m'
local green='\033[0;32m'
local red='\033[0;31m'
local nc='\033[0m'
local cross='\xE2\x9D\x8C'
local check='\xF0\x9F\x91\x8C'
if [ ! -d $src ]; then
echo -e "${red}Failed${nc}: The [${src}] directory does not exist."
return 0
fi
local dest=$(pwd)
local can_process=1
local src_contents=$(find $src -type f -not -path '*/\.*')
local response=""
echo ""
echo -e "${nc}Src: ${blue}${src}${nc}"
echo -e "${nc}Destination: ${blue}${dest}${nc}"
for i in $src_contents; do
local corrected_path=$(echo "$i" | sed "s/${src//\//\\/}//")
if [ -f "${dest}${corrected_path}" ]; then
local can_copy=$(cmp --silent "${src}${corrected_path}" "${dest}${corrected_path}" && echo 'Y' || echo 'N')
else
local can_copy='Y'
fi
if [ 'N' == $can_copy ]; then
local can_process=0
fi
local response="${response}\nFound: $corrected_path ("$([[ 'Y' = $can_copy ]] && echo -e "${green}OK${nc}" || echo -e "${red}NO${nc}")")"
done
if [ 1 == $can_process ]; then
echo ""
for i in $src_contents; do
local corrected_path=$(echo "$i" | sed "s/${src//\//\\/}//")
ditto "${src}${corrected_path}" "${dest}${corrected_path}" > /dev/null 2>&1
if [ $? -ne 0 ]; then
echo -e "${red}Failed${nc}: $i ${cross}"
else
echo -e "${green}Copied${nc}: $i ${check}"
fi
done
echo ""
else
echo -e $response
echo ""
echo "The were problems preparing your files. Problematic files are listed above."
echo ""
fi
}
<file_sep>/completions.sh
_cpfrom_completions() {
local cur="${COMP_WORDS[COMP_CWORD]}"
COMPREPLY=($(compgen -W "$(ls ~/Desktop/packages)" -- $cur))
}
complete -o nospace -F _cpfrom_completions cpfrom
|
1f22dbf4cabfa3d1d0dd221934346171d25728ab
|
[
"Markdown",
"Shell"
] | 3 |
Markdown
|
chrisgeary92/osx-cpfrom
|
09dd3e5039c6b57e9a96834d107f484c8b390998
|
1314e2faeca24abb77eba1544500f106bdffe0b2
|
refs/heads/master
|
<file_sep>#!/usr/bin/bash
BASE=129.22
if [[ $CPUS == "" ]]; then
CPUS=8
fi
getoneip() {
IP=$(dig -x $1 @8.8.8.8 | grep arpa | grep PTR | awk '{print $5}' | grep -i edu)
if [[ $IP == "" ]]; then
return 1
fi
echo ${IP}
}
printip() {
ADDR=$(getoneip $1 || echo -n '')
if [[ $ADDR == "" ]]; then
echo -n $ADDR
else
echo ${1}: ${ADDR}
fi
}
processip1() {
printip $1 | grep tmp | awk '{print $2}' | sed 's/tmp//g' | sed 's/[.].*$//g'
}
processip2() {
out=""
for i in `processip1 $1 | fold -w2`; do
out=${out}:${i}
done
out=`echo $out | grep -E '([0-9a-fA-F]{2}:){5}[0-9a-fA-F]'`
if [[ $out == "" ]]; then
echo -n $out
else
echo $out | sed 's/^://'
fi
}
loopthroughall() {
for i in {0..255}; do
c=-1
for j in {0..255}; do
c=$((c+1))
TOTEST=${BASE}.${i}.${j}
if [[ $1 == "" ]]; then
processip2 $TOTEST &
fi
if [[ $1 == "full" ]]; then
printip $TOTEST &
fi
if [[ $c == $CPUS ]]; then
wait
c=-1
fi
done
wait
done
}
echo "Scanning ${BASE}.0.0 to ${BASE}.255.255 with max ${CPUS} threads" >&2
loopthroughall $1
<file_sep>Bastille is designed to (very inefficiently) resolve the entire CWRU IP block.
Even through multithreaded nameserver queries, this process will take several hours due to rate limiting.
By resolving every IP, we are able to find which ones are still logged in the DNS, and therefore
have MAC addresses still in the CWRU whitelist.
To obtain the MAC addresses, we simply parse the default hostname into its address.
Default hostnames are given in the form: tmp*MAC*, where *MAC* is a non-delimited hexadecimal
string of length 12.
Bastille parses these hostnames into their addresses, allowing you to spoof your own address onto the network, by squatting
on a MAC address that's on the whitelist.
How do I protect myself?
change your hostname on the CWRU ITS self-service tools, seen here:
https://its-serv2.case.edu/NetworkTools/IPDB/hostnameRequestFrame.html
This is a proof-of-concept, and still provides a traceable connection through identification of the physical faceplate interface.
<a href="https://scan.coverity.com/projects/5800">
<img alt="Coverity Scan Build Status"
src="https://scan.coverity.com/projects/5800/badge.svg"/>
</a>
|
9bf4f23f9bd07be24a87a9fa9231e1611ac798b1
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
raidancampbell/Bastille
|
e14fff6a9417ec361c572f317262aa9655eefe63
|
9dcb7129191cd237f4041ed80960d9664022d69c
|
refs/heads/master
|
<file_sep>var router = require('express').Router();
const taskController = require('../controllers/task.controller');
router.post("/", taskController.create);
router.put("/:id", taskController.update);
router.get("/show_user_tasks/:id", taskController.findAll);
router.get("/:id", taskController.findOne);
router.delete("/:id", taskController.delete);
module.exports = router;<file_sep>const express = require('express');
const dotenv = require('dotenv');
const db = require('./src/models')
const jwt = require('jsonwebtoken');
// Import routes
const userRoute = require('./src/routes/user.routes');
const loginRoute = require('./src/routes/login.routes');
const taskRoute = require('./src/routes/task.routes');
var app = express();
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
// console.log(require("crypto").randomBytes(64).toString("hex"));
//commentt
//comment ulit
dotenv.config();
db.sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully');
})
.catch((err) => {
console.error('Unable to connect to the database', err);
});
if(process.env.ALLOW_SYNC === "true"){
db.sequelize
.sync({ alter: true })
.then(() =>
console.log('Done adding/updating database based on Models')
);
}
app.use((req, res, next) => {
console.log(req.url);
console.log('Request has been sent!' + req.url);
next();
})
app.get('/', (req, res) => {
res.json({message: "Hello World!"});
});
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (token == null) return res.sendStatus(401);
// verify if token is valid
jwt.verify(token, process.env.TOKEN_SECRET, (err, user) => {
console.log(user, err);
if(err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Routes
app.use(`${process.env.API_VERSION}/login`, loginRoute);
app.use(`${process.env.API_VERSION}/user`, userRoute);
app.use(`${process.env.API_VERSION}/task`, taskRoute);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});<file_sep>// ------------------------------------------------------------------------ START OF MODEL ----------------------------------------------------------------------------------- //
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
// class Guide. Guide should be name of the file name.
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The models/index file will call this method automatically.
*/
static associate(models) {
// Default in every static associate
this.belongsTo(models.User, {
foreignKey: "created_by",
type: DataTypes.UUID
});
// Default in every static associate
this.belongsTo(models.User, {
foreignKey: "updated_by",
type: DataTypes.UUID
});
// Add your additional association here
this.hasMany(models.Task, {
foreignKey: "task_user_id",
as: "user_task",
type: DataTypes.UUID
});
// End of your additional association
}
}
// Change Guide.init to {{Filename}}.init
User.init(
{
// Default column this is a primary key
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
// Default column this is the status of the row if it is deleted or active
status: {
type: DataTypes.STRING(60),
defaultValue: "Active",
},
// Default column this is associate to user model who create the data
created_by: {
type: DataTypes.UUID,
references: {
model: User,
key: "id"
}
},
// Default column this is associate to user model who update the data
updated_by: {
type: DataTypes.UUID,
references: {
model: User,
key: "id"
}
},
// Add your additional columns here //
firstName: {
type: DataTypes.STRING,
allowNull: true,
},
lastName: {
type: DataTypes.STRING,
allowNull: true,
},
email: {
type: DataTypes.STRING,
allowNull: true,
unique: {
msg: "Email address already exist."
},
isEmail: {
msg: "Email is invalid."
},
},
password: {
type: DataTypes.STRING,
allowNull: true,
},
// End of additional columns //
},
{
sequelize,
timestamps: true,
createdAt: "created_at",
updatedAt: "updated_at",
modelName: "User", // Change model name base on file name
}
);
// Change Guide to file name first letter should be in upper case
return User;
};
// ------------------------------------------------------------------------ END OF MODEL ----------------------------------------------------------------------------------- //<file_sep>const e = require('express');
const db = require('../models');
const User = db.User;
const bcrypt = require("bcrypt");
const datatables = require("sequelize-datatables");
exports.findDataTable = (req, res) => {
// sample req
req.body = {
draw: "1",
columns: [
{
data: "full_name",
name: "",
searchable: "true",
orderable: "true",
search: {
value: "",
regex: "false",
},
},
],
order: [
{
column: "0",
dir: "asc",
},
],
start: "0",
length: "10",
search: {
value: "",
regex: "false",
},
_: "1478912938246",
};
datatables(User, req.body).then((result) => {
res.json(result);
});
};
// Create
exports.create = async (req, res) => {
req.body.full_name = "";
// req.body.created_by = req.user.id;
req.body.password = await bcrypt.hash(req.body.password, parseInt(process.env.SALT_ROUND));
console.log(req.body.password);
User.create(req.body)
.then((data) => {
User.findByPk(data.id).then((result) => {
res.send({
error: false,
data: result,
message: "User is created successfully."
});
});
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
})
});
};
// Retrive all
exports.findAll = (req, res) => {
User.findAll({ where: { status: "Active"} })
.then((data) => {
res.send({
error: false,
data: data,
message: "Retrived successfully."
});
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
})
});
};
// Find a single
exports.findOne = (req, res) => {
const id = req.params.id;
User.findByPk(id)
.then((data) => {
res.send({
error: false,
data: data,
message: "Success!"
});
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
})
})
};
// Update
exports.update = async (req, res) => {
const id = req.params.id;
req.body.full_name = "";
req.body.password = await bcrypt.hash(req.body.password, parseInt(process.env.SALT_ROUND));
User.findOne({ where: { email: req.body.email, status: "Active" }})
.then((data) => {
if(data) {
bcrypt.compare(
req.body.oldpassword,
data.password,
function (err, result) {
if(result){
User.update(req.body, {
where: {id: id},
})
.then((result) =>{
console.log(result);
if(result) {
// Success
User.findByPk(id).then((data) =>{
res.send({
error: false,
data: data,
message: [process.env.SUCCESS_UPDATE],
});
});
}
else{
// if there is an error
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
});
}
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
});
});
}
else{
res.status(500).send({
error: true,
data: [],
message: ["Invalid old password."],
});
}
}
);
}
else{
res.status(500).send({
error: true,
data: [],
message: ["Email does not exists."]
})
}
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message) || process.env.GENERAL_ERROR_MSG
});
});
};
// Delete
exports.delete = (req, res) => {
const id = req.params.id;
const body = { status: "Inactive" };
User.update(body, {
where: {id: id},
})
.then((result) =>{
console.log(result);
if(result) {
// Success
User.findByPk(id).then((data) =>{
res.send({
error: false,
data: data,
message: [process.env.SUCCESS_UPDATE],
});
});
}
else{
// if there is an error
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
});
}
})
.catch((err) => {
res.status(500).send({
error: true,
data: [],
message: err.errors.map((e) => e.message)
});
});
};
<file_sep># brs-api
<file_sep>// ------------------------------------------------------------------------ START OF MODEL ----------------------------------------------------------------------------------- //
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
// class Guide. Guide should be name of the file name.
class Guide extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The models/index file will call this method automatically.
*/
static associate(models) {
// Default in every static associate
this.belongsTo(models.User, {
foreignKey: "created_by",
type: DataTypes.UUID
});
// Default in every static associate
this.belongsTo(models.User, {
foreignKey: "updated_by",
type: DataTypes.UUID
});
// Add your additional association here
// End of your additional association
}
}
// Change Guide.init to {{Filename}}.init
Guide.init(
{
// Default column this is a primary key
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
// Default column this is the status of the row if it is deleted or active
status: {
type: DataTypes.STRING(60),
defaultValue: "Active",
},
// Default column this is associate to user model who create the data
created_by: {
type: DataTypes.UUID,
references: {
model: User,
key: "id"
}
},
// Default column this is associate to user model who update the data
updated_by: {
type: DataTypes.UUID,
references: {
model: User,
key: "id"
}
},
// Add your additional columns here //
// End of additional columns //
},
{
sequelize,
timestamps: true,
createdAt: "created_at",
updatedAt: "updated_at",
modelName: "guide", // Change model name base on file name
}
);
// Change Guide to file name first letter should be in upper case
return Guide;
};
// ------------------------------------------------------------------------ END OF MODEL ----------------------------------------------------------------------------------- //
// Default column format always place a comma in the end of properties always set allowNull to true during dev
// Just copy paste it to the additional column and modify it base on column properties on our database documentation
column_name: {
type: DataTypes.STRING,
allowNull: true,
},
// COMMONLY USED DATA TYPES
type: DataTypes.UUID, // UUID Datatypes for primary key and foreign key
type: DataTypes.STRING(255), // STRING w/ length
type: DataTypes.INTEGER, // For number
type: DataTypes.BOOLEAN, // True or False
type: DataTypes.DATE, // Date with time and timezone
type: DataTypes.DATEONLY, // Date without time
// If column has a default value
defaultValue: "Default Value"
// If record is must be unique
unique: {
msg: "Example of error message. 'Email should be unique'"
},
// Validation format
validate: {
notNull: { msg: "Column name should not be null." }, // if column cannot be null
},
validate: {
isEmail: true, // will only accept email adress format
},
// Validation properties that you can use just add it inside validate { }
isAfter: "2011-11-05", // only allow date strings after a specific date
isAlpha: true, // will only allow letters
isAlphanumeric: true, // will only allow alphanumeric characters, so "_abc" will fail
isNumeric: true, // will only allow numbers
|
b6a1ac356d18bff2d482aacf510b1dac5f685acb
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
pkylevillegas/to-do-list-api
|
603902fc0fe85798c91fcad85193c995cb2f710c
|
f56bff06817bfeea35670ff160938f891d0189f9
|
refs/heads/master
|
<repo_name>Creestoph/Blackjack<file_sep>/server/server.py
from random import shuffle
from flask import Flask, request, jsonify
cards_points = {
1: 2,
2: 3,
3: 4,
4: 5,
5: 6,
6: 7,
7: 8,
8: 9,
9: 10,
10: 10,
11: 10,
12: 10,
13: 11
}
class Card:
def __init__(self, color, rank, face_up=False):
# color - 'D' Diamonds, 'C' Clubs, 'H' Hearts, 'S' Spades
# rank - number from 1 to 13
self.color = color
self.rank = rank
self.face_up = face_up
def get_rank(self):
return self.rank
def to_dict(self):
return {"color": self.color, "rank": self.rank}
class Deck:
def __init__(self):
self.cards = []
colors = ['D', 'C', 'H', 'S']
for c in colors:
for r in range(1, 14):
self.cards.append(Card(c, r))
shuffle(self.cards)
def shuffle(self):
shuffle(self.cards)
def get_card(self):
return self.cards.pop()
class Hand:
def __init__(self, card=None):
self.playing = True
if card is None:
self.cards = []
return
if not isinstance(card, Card):
raise Exception("Variable is not Card")
self.cards = [card]
def add_card(self, card, face_up=True):
if not isinstance(card, Card):
raise Exception("Variable is not Card")
self.cards.append(Card(card.color, card.rank, face_up))
def get_card(self, deck):
if self.playing:
self.cards.append(deck.get_card())
def count_cards(self):
aces = len([x for x in self.cards if x.rank == 13])
value = sum([cards_points[x.rank] for x in self.cards])
if value <= 21 or aces == 0:
return value
while aces > 0 and value > 21:
value -= 10 # value = value - 11 (ace) + 1 (other value ace)
aces -= 1
return value
def try_split(self):
if len(self.cards) == 2 and self.cards[0].rank == self.cards[1].rank:
return self.cards.pop()
return None
def is_playing(self):
return self.playing
def to_dict(self):
return {"cards": [a.to_dict() for a in self.cards if a.face_up]}
class Table:
def __init__(self, bid):
self.winner = "" # TODO think of better solution
self.game_state = "begin_game"
self.is_first_move = True
self.client_hands = []
self.client_hands.append(Hand())
self.bid = bid
self.deck = Deck()
self.croupier_hand = Hand()
self.croupier_hand.add_card(self.deck.get_card(), False)
self.croupier_hand.add_card(self.deck.get_card())
self.add_card()
self.add_card()
self.has_split = False
self.has_double = False
self.has_insurance = False
# TODO: sprawdzic, czy to tak
# TODO: make Monika write comments in english and investigate TODO above
# self.client_card = self.croupier_hand[0].card[0]
def to_dict(self):
if self.game_state == "end_game":
return {
"header": "end_game",
"winner": self.winner,
"hands": [a.to_dict() for a in self.client_hands],
"croupier": self.croupier_hand.to_dict()
}
return {
"header": "in_game",
"insurance": self.has_insurance,
"bid": self.bid,
"hands": [a.to_dict() for a in self.client_hands],
"croupier": self.croupier_hand.to_dict()
}
def add_card(self):
for hand in self.client_hands:
if hand.playing:
hand.add_card(self.deck.get_card())
if hand.count_cards() >= 21:
hand.playing = False
end = True
for hand in self.client_hands:
if hand.playing:
end = False
break
if end:
self.end_game()
else:
self.game_state = "in_game"
def double(self):
if not self.has_double and self.game_state == "begin_game":
self.bid *= 2
self.has_double = True
self.add_card()
else:
raise Exception("Cannot double")
def split(self):
if not self.has_split and len(self.client_hands) == 1 and self.game_state == "begin_game":
t = self.client_hands[0].try_split()
if t is not None:
self.client_hands.append(Hand(t))
self.has_split = True
else:
raise Exception("Cannot split - cards are different")
else:
raise Exception("Cannot split")
# TODO check if insurance is only against Blackjack
def insure(self):
if not self.has_insurance and self.game_state == "begin_game":
if len(self.croupier_hand.cards) == 2 and \
(self.croupier_hand.cards[1].get_rank() == 10 or self.croupier_hand.cards[1].get_rank() == 11):
self.has_insurance = True
else:
raise Exception("Cannot insure")
else:
raise Exception("Cannot insure")
def pas(self, hand_number=0):
if hand_number >= len(self.client_hands):
raise Exception("Hand number out of bounds.")
if not self.client_hands[hand_number].playing:
raise Exception("Hand already passed.")
self.client_hands[hand_number].playing = False
end = True
for hand in self.client_hands:
if hand.playing:
end = False
break
if end:
self.end_game()
return 0
def end_game(self):
self.game_state = "end_game"
print("Game has ended")
player_best_hand = self.client_hands[0]
if len(self.client_hands) == 2 \
and 21 >= self.client_hands[1].count_cards() > self.client_hands[0].count_cards():
player_best_hand = self.client_hands[1]
self.croupier_hand.cards[0].face_up = True
while self.croupier_hand.count_cards() < 17:
self.croupier_hand.add_card(self.deck.get_card())
if self.croupier_hand.count_cards() > player_best_hand.count_cards() or player_best_hand.count_cards() > 21:
self.winner = "croupier"
else:
self.winner = "player"
clients = {}
actions = {
"split": Table.split,
"double": Table.double,
"insure": Table.insure,
"pas": Table.pas,
"get": Table.add_card
}
app = Flask(__name__)
# Handling requests
# Game beginning
def error(msg):
return jsonify({"header": "error", "message": msg})
last_id = -1
def get_id():
global last_id
last_id += 1
return last_id
@app.route('/begin', methods=['POST'])
def start_game():
input_json = request.get_json()
if input_json["header"] == "register":
try:
cid = get_id()
clients[cid] = Table(input_json["bid"])
return jsonify({"header": "begin_game", "id": cid, "table": clients[cid].to_dict()})
except Exception as e:
return error(str(e))
else:
return error("Invalid command")
@app.route('/game-<client_id>', methods=['POST'])
def handle_request(client_id):
input_json = request.get_json()
try:
cid = int(client_id)
actions[input_json["header"]](clients[cid])
return jsonify(clients[cid].to_dict())
except Exception as e:
return error(str(e))
if __name__ == '__main__':
app.run(host='localhost', port=5000, debug=False)
<file_sep>/client/client.py
import requests
import os
import time
server = "http://localhost:5000/"
run = True
cards_points = {
1: 2,
2: 3,
3: 4,
4: 5,
5: 6,
6: 7,
7: 8,
8: 9,
9: 10,
10: 10,
11: 10,
12: 10,
13: 11
}
def enter_game(bid):
js = requests.post(server + "begin", json={"header": "register", "bid": bid}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def split(gid):
js = requests.post(server + "game-" + str(gid), json={"header": "split"}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def double(gid):
js = requests.post(server + "game-" + str(gid), json={"header": "double"}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def pas(gid):
js = requests.post(server + "game-" + str(gid), json={"header": "pas"}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def insure(gid):
js = requests.post(server + "game-" + str(gid), json={"header": "insure"}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def get(gid):
js = requests.post(server + "game-" + str(gid), json={"header": "get"}).json()
if js["header"] == "error":
raise Exception(js["message"])
return js
def print_hand(hand):
print("(value " + str(count_cards(hand)) + "):")
for card in hand["cards"]:
print(ranks[card["rank"]] + " of " + colors[card["color"]] + " ")
def print_table(js):
print("insurance: " + str(js["insurance"]))
print("bid: " + str(js["bid"]))
hands = js["hands"]
print()
for hand in hands:
print("hand ", end="")
print_hand(hand)
print("\ncroupier ", end="")
print_hand(js["croupier"])
def print_end(js):
print("winner: " + str(js["winner"]))
hands = js["hands"]
print()
for hand in hands:
print("hand ", end="")
print_hand(hand)
print("\ncroupier ", end="")
print_hand(js["croupier"])
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
def count_cards(hand):
cards = hand["cards"]
aces = len([x for x in cards if x["rank"] == 13])
value = sum([cards_points[x["rank"]] for x in cards])
if value <= 21 or aces == 0:
return value
while aces > 0 and value > 21:
value -= 10 # value = value - 11 (ace) + 1 (other value ace)
aces -= 1
return value
ranks = {
1: "2",
2: "3",
3: "4",
4: "5",
5: "6",
6: "7",
7: "8",
8: "9",
9: "10",
10: "Jack",
11: "Queen",
12: "King",
13: "Ace"
}
colors = {
"D": "Diamonds",
"S": "Spades",
"H": "Hearts",
"C": "Clubs"
}
init_js = enter_game(10)
gid = init_js["id"]
actions = {
"split": split,
"double": double,
"pas": pas,
"insure": insure,
"hit": get
}
print("Game started (id " + str(gid) + ")")
print_table(init_js["table"])
while run:
command = input()
js = ""
cls()
if command == "quit":
break
try:
js = actions[command](gid)
if js["header"] == "in_game":
print_table(js)
elif js["header"] == "end_game":
print_end(js)
break
except Exception as e:
print("Error: " + str(e))
print_table(js)
time.sleep(3)
cls()
<file_sep>/README.md
# Blackjack
Simple client-server Blackjack game.
We used https://pl.wikipedia.org/wiki/Blackjack
##Funcionality
Client can play Blackjack with table. There is only one table for each client and one deck for each game.
##Machanics
Client posts requests to different URL and recieves PublicTable structure packed in Json as an answer.
##How to use
Run the server. Client run the application. To join to game should write join_game.You should write the number of ID. After you can write: split, pas, insure, double, hit.
**Types of requests:**
1. **Begin game**
* URL: http://[server]:[port]/begin
* Message: '[bid]'
* Result: Server generates new ID for client and creates new Table structure.
2. **Split** *(Optional, only if it's the first move)*
* URL: http://[server]:[port]/game-[client ID]
* Message:
* Result: If player has two equal cards, server splits player card set into two separate sets. From now on player has two card sets.
3. **Insure** *(Optional, only if it's the first move)*
* URL: http://[server]:[port]/game-[client ID]
* Message: 'INSURE'
* Result: If croupier has ace or 10, server marks boolean insured in Table. If croupier wins, client receives his bid back.
4. **Double** *(Optional, only if it's the first move)*
* URL: http://[server]:[port]/game-[client ID]
* Message: 'DOUBLE'
* Result: Player doubles his bid.
5. **Take**
* URL: http://[server]:[port]/game-[client ID]
* Message: 'TAKE'
* Result: Player receives new card.
6. **Pass**
* URL: http://[server]:[port]/game-[client ID]
* Message: 'PASS'
* Result: Game ends. Croupier makes his moves, and server evaluates who wins.
**Structures:**
```python
class Card:
def __init__(self, color, rank)
#color - 'D' Diamonds, 'C' Clubs, 'H' Hearts, 'S' Spades
#rank - number from 1 to 13
self.color = color
self.rank = rank
def get_rank(self):
return self.rank
```
```python
from random import shuffle
class Deck:
def __init__(self):
self.cards = [];
colors = ['D','C','H','S']
for c in colors
for r in range(1,14)
self.cards.append(Card(c,r))
def shuffle(self):
shuffle(self.cards)
def get_card(self):
return self.cards.pop()
```
```python
class Table:
def __init__(self, c, bid):
self.insurance = 0
self.state = 0
self.client_cards_1 = []
self.client_cards_2 = []
self.bid = bid
self.deck = Deck()
self.croupier_card = self.deck.get_card()
self.public_table = PublicTable(self.deck, bid)
self.add_card()
self.add_card()
self.game_state = 0
def to_json(self, bid):
d={'insurance' : 0, 'state' : 0, 'client_cards_1' : self.client_cards_1 , 'client_cards_2' : self.client_cards_2, 'bid': self.bid
'croupier_cards': self.croupier_card }
return flask.jsonify(**d)
def add_card(self):
if len(self.public_table.client_cards_2) != 0:
self.public_table.client_cards_2.append(self.deck.get_card())
self.public_table.client_cards_1.append(self.deck.get_card())
self.game_state = 1
def double(self)
if self.game_state == 0:
self.public_table.bid *= 2
self.add_card()
self.game_state = 1
def split(self)
if self.game_state == 0:
if len(self.public_table.client_cards_1) == 2 and self.public_table.client_cards_1[0].get_rank() == self.public_table.client_cards_1[1].get_rank():
self.public_table.client_cards_2.append(self.public_table.client_cards_1.pop())
def insure(self):
if self.game_state == 0:
if len(self.public_table.croupier_cards) == 1 and (self.public_table.croupier_cards[0].get_rank() == 10 or self.public_table.croupier_cards[0].get_rank() == 11):
self.public_table.insurance = True
def pass(self):
#TODO
```
```json
{
"bid": 10,
"client_cards_1": [
{
"color": "H",
"rank": 10
},
{
"color": "D",
"rank": 1
}
],
"client_cards_2": [],
"croupier_cards": [
{
"color": "S",
"rank": 10
}
],
"insurance": 0,
"state": 0
}
```
<file_sep>/DOCS.md
# Structures
## Client
Client requests may vary depending on game state
**Begin game**
```javascript
ActionBegin
{
"header": "register",
"bid": number
}
```
**In game**
```javascript
ActionInGame
{
"header": string //one of the following "split", "insure", "double", "take", "pass"
}
```
## Server
Server response may vary depending on game state
```javascript
Error
{
"header": "error",
"message": string
}
```
**Begin Game**
```javascript
ID
{
"header": "begin_game",
"id": number,
"table": TableInGame
}
```
**In Game**
```javascript
TableInGame
{
"header": "in_game",
"insurance": number,
"hands": [Hand],
"bid": number,
"croupier": Hand
}
```
**End Game**
```javascript
TableEndGame
{
"header": "end_game",
"winner": string //player or croupier
"winning_hand": Hand
}
```
## Other structures
```javascript
Hand
{
"cards": [Card]
}
```
```javascript
Card
{
"color": string, //onr of the following "Diamonds", "Hearts", "Clubs", "Spades"
"rank": number //from 1 to 13
}
```
|
c9310f6b1ee876d9a74a9bd771378c359bb3e17e
|
[
"Markdown",
"Python"
] | 4 |
Python
|
Creestoph/Blackjack
|
ede6a4fa6cfe8f249abe6aa053ff5070d6641d91
|
20912e9341452e5fdd8819aa8db5dbba0076751d
|
refs/heads/master
|
<file_sep>import React from "react";
import "./Pet.css";
import ApiService from "../../services/ApiService";
import "./Pet.css";
class Pet extends React.Component {
constructor(props) {
super(props);
this.state = {
pet: null,
adopted: false,
errorMessage: null,
};
}
handleAdoptCat = () => {
ApiService.adoptCat().then(data => {
this.setState({ adopted: true });
}).catch((resp) => {
this.setState({ errorMessage: resp.message });
});
};
handleAdoptDog = () => {
ApiService.adoptDog().then(data => {
this.setState({ adopted: true });
}).catch((resp) => {
this.setState({ errorMessage: resp.message });
});
};
renderEmptyQueue = () => {
return (
<div className="Pet">no pets</div>
);
}
renderPet = () => {
let button;
if (this.props.type === 'cat') {
button = (
<input
name="adoptCat"
type="button"
value="Adopt this cat"
className="Button"
onClick={this.handleAdoptCat}
/>
);
}
if (this.props.type === 'dog') {
button = (
<input
name="adoptDog"
type="button"
value="Adopt this dog"
className="Button"
onClick={this.handleAdoptDog}
/>
);
}
if (this.props.position > 1) {
button = (
<input
name="waiting"
type="button"
value="Waiting"
disabled
className="Button"
/>
);
}
return (
<div className="Pet">
<img
src={this.props.pet.imageURL}
alt={this.props.pet.imageDescription}
/>
<table>
<tbody>
<tr>
<th>Name</th>
<td>{this.props.pet.name}</td>
</tr>
<tr>
<th>Sex</th>
<td>{this.props.pet.sex}</td>
</tr>
<tr>
<th>Age</th>
<td>{this.props.pet.age}</td>
</tr>
<tr>
<th>Breed</th>
<td>{this.props.pet.breed}</td>
</tr>
<tr>
<th>Story</th>
<td>{this.props.pet.story}</td>
</tr>
</tbody>
</table>
<div className="ErrorMessage">{this.state.errorMessage}</div>
{ button }
</div>
);
}
renderThankYou = () => {
return (
<div className="Pet">Thank You</div>
);
}
render() {
if (this.state.adopted) {
return this.renderThankYou();
}
if (this.props.pet) {
return this.renderPet();
}
return this.renderEmptyQueue();
}
}
export default Pet;
<file_sep>import React from "react";
import ApiService from "../../services/ApiService";
class ResetRoute extends React.Component {
componentDidMount() {
ApiService.resetQueues();
}
render() {
return null;
}
}
export default ResetRoute;
|
b029fd1e1e01396d81d8625665242e0790b99e0b
|
[
"JavaScript"
] | 2 |
JavaScript
|
dc5will/DSA-Petful-Client-William
|
d63b7249f479e04689b0aaef666706298076a779
|
1d1e9d8ba569143c8507694ae6856ecdda0517a0
|
refs/heads/master
|
<repo_name>yaseenshaik/amazon-keywork-relevancy-analyzer<file_sep>/migrations/20171026183419_create-all-tables.js
exports.up = function(knex, Promise) {
return knex.schema
.createTableIfNotExists("categories", function(table) {
table.string("alias", 100).primary()
table.string("name")
table.timestamps(true, true)
})
.createTableIfNotExists("products", function(table) {
table.string("asin", 100).primary()
table.string("title")
table.text("description")
// table.text("about")
// table.integer("rank");
table.string("category_alias", 100).references("categories.alias")
table.timestamps(true, true)
})
.createTableIfNotExists("keywords", function(table) {
table.increments()
table.string("text")
table
.boolean("processed")
.defaultTo(false)
.index()
table.float("relevancy")
table.string("category_alias", 100).references("categories.alias")
// table.string("product_asin", 100).references("products.asin")
table.timestamps(true, true)
})
}
exports.down = function(knex, Promise) {
return knex.schema
.dropTable("keywords")
.dropTable("products")
.dropTable("categories")
}
<file_sep>/README.md
## Instructions
* Make sure you have mysql server started and running first.
* Copy `.env.example` to `.env` and fill the details
* Run `yarn install` to install all dependencies
* Run `yarn migrate` to create tables in the db
* Run `yarn dev` then open `localhost:3000` in the browser
## Usage & Notes
* opening `/scrape` should start scraping the best sellers in all categories.
* `/category` should give all extracted category aliases. Use this alias to perform the following operation.
* `/extract-keywords/:categoryAlias` should extract all the high density keywords
* `/assign-relevancy/:categoryAlias` should assign a relevancy score between 0-5
* `/relevant-keywords/:categoryAlias` should give all relevant keywords for a particular category<file_sep>/.env.example
MAILGUN_USERNAME='<EMAIL>'
MAILGUN_PASSWORD='<PASSWORD>'
SESSION_SECRET='<KEY>'
NODE_ENV='development'
DB_USER='root'
DB_PWD=''
DB_NAME='easysoft'
DB_HOST='127.0.0.1'
<file_sep>/models/Product.js
const db = require("../db");
require("./Category");
const Product = db.model("Product", {
tableName: "products",
category: function() {
return this.belongsTo("Category");
}
});
module.exports = Product;
<file_sep>/routes/contact.js
const express = require("express");
const contactController = require("../controllers/contact");
const router = express.Router();
module.exports = () =>
router
.get("/contact", contactController.contactGet)
.post("/contact", contactController.contactPost);
<file_sep>/controllers/scrape.js
const osmosis = require("osmosis")
const density = require("density")
const { resolve } = require("path")
const fetch = require("isomorphic-fetch")
const Product = require("../models/Product")
const Category = require("../models/Category")
const Keyword = require("../models/Keyword")
function createEntityIfNotExists(EntityClass, data, primaryKey) {
return new EntityClass({ [primaryKey]: data[primaryKey] })
.fetch()
.then(function(item) {
if (!item) {
return EntityClass.forge(data).save()
}
})
}
function getProductDetails(data) {
return {
title: data.title
? data.title
: data.title_2 ? data.title_2 : data.pageTitle.slice(12),
asin: data.asin ? data.asin : data.asin_2 ? data.asin_2 : data.asin_3,
category_alias: data.category_alias.replace("search-alias=", ""),
description:
(data.description ? sanitizeText(data.description) : "") +
" " +
(data.description_2 ? sanitizeText(data.description_2) : "") +
" " +
(data.about ? sanitizeText(data.about) : "") +
" " +
(data.features ? sanitizeText(data.features) : "") +
" " +
(data.features_2 ? sanitizeText(data.features_2) : "")
}
}
function sanitizeText(s) {
return s.replace(/[\s+\n,.!]/g, " ")
}
exports.index = function(req, res) {
var listing = []
var p
osmosis
.get("https://www.amazon.com/Best-Sellers/zgbs/ref=zg_bs_tab")
// .get(
// "https://www.amazon.com/Best-Sellers-Appliances/zgbs/appliances/ref=zg_bs_nav_0"
// )
.find("#zg_browseRoot li:nth-child(n+2) a")
.follow("@href")
.find("#zg_listTitle .category")
.set("category")
.find(".zg_page > a")
.follow("@href")
.find(".zg_itemWrapper > div > a")
.follow("@href")
.set({
rank: ".rank-number",
asin: "#ftSelectAsin@value",
asin_2: "#reviews-image-gallery-container@data-asin",
asin_3: "#frmProcessGCPCCode_Value + input[name=ASIN]@value",
category_alias: "#searchDropdownBox option[selected=selected]@value",
title: "#productTitle",
title_2: "#btAsinTitle",
pageTitle: "title",
description: "#productDescription .content",
description_2: "#mas-product-description .masrw-content-row",
// description_3: "#dpx-aplus-product-description_feature_div",
about: "#fbExpandableSection",
features: "#feature-bullets",
features_2: "#feature-bullets-btf .content"
})
.data(function(data) {
const productDetails = getProductDetails(data)
listing.push(productDetails)
createEntityIfNotExists(
Category,
{
alias: productDetails.category_alias,
name: data.category
},
"alias"
)
return createEntityIfNotExists(Product, productDetails, "asin")
})
.done(function() {
res.json(listing)
})
.log(console.log)
.error(console.log)
}
exports.scrapeCategories = function(req, res) {
var categories = []
osmosis
.get("https://www.amazon.com")
.find("#searchDropdownBox option")
.set("name")
.set("id", "@value")
.data(function(data) {
const category = new Category({
alias: data.id.replace("search-alias=", ""),
name: data.name.trim()
})
categories.push(category)
return category.save()
})
.done(function() {
res.json(categories)
})
.log(console.log)
.error(function(err) {
res.status(500).json({
error: err && err.message
})
})
}
exports.splitKeyWordsForCategory = function(req, res) {
var categoryAlias = req.params.categoryAlias
if (!categoryAlias) {
res.status(400).json({
error: "categoryAlias is required"
})
}
new Category({ alias: categoryAlias }).fetch().then(function(category) {
if (!category) {
res.status(400).json({
error: "categoryAlias is invalid"
})
}
Product.collection()
.query(function(qb) {
qb.where("category_alias", "=", categoryAlias)
})
.fetch()
.then(function(products) {
products.map(getDensity)
res.json(products)
})
})
}
function getDensity(product) {
const st = product.get("title") + " " + product.get("description")
return density(st)
.setOptions({
stopWordFile: resolve("./stopwords.json"),
maxKeywordLength: 100
})
.getDensity()
.slice(0, 10)
.filter(function(keyword) {
return keyword.count > 1
})
.map(function(data) {
const d = {
text: data.word,
// product_asin: product.attributes.asin,
category_alias: product.get("category_alias")
}
return createEntityIfNotExists(Keyword, d, "text")
})
}
exports.assignKeywordRelevancyForCategory = function(req, res) {
var categoryAlias = req.params.categoryAlias
Keyword.collection()
.query(function(qb) {
qb.where("category_alias", "=", categoryAlias).whereNot("processed", true)
})
.fetch()
.then(function(keywords) {
Promise.all(
keywords.map(function(keyword) {
getKeywordRelevancy(categoryAlias, keyword.get("text"))
return keyword.set({ processed: true }).save()
})
).then(function() {
res.json(keywords)
})
})
}
function amazonCompletion(categoryAlias, keyword) {
return fetch(
`https://completion.amazon.com/search/complete?method=completion&mkt=1&p=Gateway&b2b=0&fresh=0&sv=desktop&client=amazon-search-ui&x=String&search-alias=${categoryAlias}&q=${keyword}&cf=1&fb=1&sc=1&`
).then(function(response) {
return response.text()
})
}
function isPresent(response, keyword, topScore, categoryAlias) {
console.log(response, keyword, topScore, categoryAlias)
const completion = JSON.parse(response.match(/\[.*\]/)[0])[1]
const modifier = 1 / (completion.length - 1)
let promiseList = []
completion.forEach(function(s, i) {
if (s.match(keyword)) {
const relevancy = topScore - i * modifier
promiseList.push(
saveKeywordRelevancy({
text: s,
category_alias: categoryAlias,
relevancy: relevancy,
processed: true
})
)
}
})
return {
promise: Promise.all(promiseList),
count: promiseList.length
}
}
function saveKeywordRelevancy(key) {
return new Keyword({ category_alias: key.category_alias, text: key.text })
.fetch()
.then(function(keyword) {
if (!keyword) {
return Keyword.forge(key).save()
} else {
return keyword.set(key).save()
}
})
}
function getKeywordRelevancy(categoryAlias, keyword) {
return amazonCompletion(categoryAlias, keyword.slice(0, 1))
.then(function(response) {
let tierOneResult = isPresent(response, keyword, 5, categoryAlias)
if (tierOneResult.count > 0) {
throw new Error("Keyword Found")
} else {
return tierOneResult.promise
}
})
.then(function() {
return amazonCompletion(categoryAlias, keyword.slice(0, 2)).then(function(
response
) {
let tierTwoResult = isPresent(response, keyword, 3, categoryAlias)
if (tierTwoResult.count > 0) {
throw new Error("Keyword Found")
} else {
return tierTwoResult.promise
}
})
})
.then(function() {
return amazonCompletion(categoryAlias, keyword.slice(0, 3)).then(function(
response
) {
let tierThreeResult = isPresent(response, keyword, 1, categoryAlias)
if (tierThreeResult.count > 0) {
throw new Error("Keyword Found")
} else {
return tierThreeResult.promise
}
})
})
.catch(function(error) {
if (error.message === "Keyword Found") {
return true
} else {
console.error(error)
}
})
}
exports.getRelevantKeywordsForCategory = function(req, res) {
var categoryAlias = req.params.categoryAlias
Keyword.collection()
.query(function(qb) {
qb
.where("relevancy", "<>", "NULL")
.andWhere("category_alias", categoryAlias)
.andWhere("processed", true)
.orderBy("relevancy", "desc")
})
.fetch()
.then(function(keywords) {
res.json(keywords)
})
}
exports.getCategoryAliases = function(req, res) {
Category.collection()
.fetch()
.then(function(categories) {
res.json(categories)
})
}
<file_sep>/models/Keyword.js
const db = require("../db");
require("./Product");
const Keyword = db.model("Keyword", {
tableName: "keywords",
product: function() {
return this.belongsTo("Product");
}
});
module.exports = Keyword;
<file_sep>/routes/index.js
const express = require("express")
const HomeController = require("../controllers/home")
const OsmosisController = require("../controllers/scrape")
const contacRouter = require("./contact")
const router = express.Router()
module.exports = () =>
router
.get("/", HomeController.index)
.get("/scrape", OsmosisController.index)
.get("/scrape-categories", OsmosisController.scrapeCategories)
.get("/category", OsmosisController.getCategoryAliases)
.get(
"/extract-keywords/:categoryAlias",
OsmosisController.splitKeyWordsForCategory
)
.get(
"/assign-relevancy/:categoryAlias",
OsmosisController.assignKeywordRelevancyForCategory
)
.get(
"/relevant-keywords/:categoryAlias",
OsmosisController.getRelevantKeywordsForCategory
)
.use(contacRouter())
|
ce633fbc3c1c17e82564c461a6b3977dd520aeec
|
[
"JavaScript",
"Markdown",
"Shell"
] | 8 |
JavaScript
|
yaseenshaik/amazon-keywork-relevancy-analyzer
|
c51518825b4996dfdfb05a0e0514a65bfd3a43cc
|
e600652554d3c905f20a5f5ee8ff3767a9912eef
|
refs/heads/master
|
<repo_name>siderischristos/javascript-basics<file_sep>/05.03-ConstructorFunctions/index.js
// Constructor Function (use Pascal notation (OneTwoThreeFour))
function Circle (radius) {
this.radius = radius;
this.draw =function(){
console.log('draw');
}
}
const circle = new Circle(2);
console.log(circle);<file_sep>/03.01-If...else/index.js
let hour = 10;
if (hour>0 && hour<=24){
if (hour>=6 && hour<12)
console.log('Good morning');
else if (hour>=12 && hour<18)
console.log('Good afternoon');
else
console.log('Good evening');
} else
console.log('Invalid hour');
<file_sep>/05.09-BlogPostObject/index.js
let blogPost = {
title: 'A',
body: 'abcdefghijklmnop',
author: 'AbCd',
views: 1234,
comments: [
{author: 'EfGh', body: 'qrstuv'},
{author: 'IjKl', body: 'wxyz'}
],
isLive: true
};
console.log(blogPost);<file_sep>/04.02-MaxofTwoNumbers/index.js
function max(a,b){
if (a > b){
console.log("Max number is a " + a);
} else if (a < b){
console.log("Max number is b " + b);
} else {
console.log("The two numbers are equal");
}
}
max(3,5);
max(9,4);
max(178,178);
max(-4,-50);<file_sep>/04.10-Grade/index.js
const marks = [90, 70, 90];
calculateGrade(marks);
function calculateGrade(marks){
let sum = 0;
for (let mark of marks){
sum += mark;
}
let average = sum / marks.length;
if (average < 0 && average > 100) console.log('Error');
if (average <= 59)
console.log('Mark is F, average is ', average);
else if (average <= 69)
console.log('Mark is D, average is ', average);
else if (average <= 79)
console.log('Mark is C, average is ', average);
else if (average <= 89)
console.log('Mark is B, average is ', average);
else
console.log('Mark is A, average is ', average);
}<file_sep>/04.01-For...in/index.js
// for...in
const person = {
name: 'Christos',
age: 30
};
for (let key in person){
console.log(key, person[key]);
}
const colors =['red', 'green', 'blue'];
for (let index in colors){
console.log(index,colors[index]);
}
// for...of
// const colors =['red', 'green', 'blue'];
for (let color of colors){
console.log(color);
}<file_sep>/05.10-ConstructorFunctions/index.js
let myPost = new Post('Title', 'Body', 'me');
console.log(myPost);
function Post (title, body, author,){
this.title = title;
this.author = author;
this.body = body;
this.views = 0;
this.comments = [];
this.isLive = false;
}<file_sep>/desktop.ini
[.ShellClassInfo]
IconResource=B:\Downloads\file_javascript_128px_1173827_easyicon.net.ico,0
[ViewState]
Mode=
Vid=
FolderType=Documents
<file_sep>/05.11-PriceRangeObjects/index.js
let priceRanges = [
{ label: '$', tooltip: 'Inexpensive', minPerPerson: 5, maxPerPerson: 15 },
{ label: '$$', tooltip: 'Moderate', minPerPerson: 16, maxPerPerson: 25 },
{ label: '$$$', tooltip: 'Expensive', minPerPerson: 25, maxPerPerson: 50 }
];
let restaurants = [
{ name: 'A', averagePerPerson: 10 },
{ name: 'B', averagePerPerson: 18 },
{ name: 'C', averagePerPerson: 30 },
{ name: 'D', averagePerPerson: 13 },
{ name: 'E', averagePerPerson: 26 }
];<file_sep>/04.03-LandscapeOrPortrait/index.js
function isLandscape (width,height){
return (width>height);
}
console.log(isLandscape(10,20));<file_sep>/04.04-FizzBuzz/index.js
console.log(fizzBuzz(1));
console.log(fizzBuzz(2));
console.log(fizzBuzz(3));
console.log(fizzBuzz(4));
console.log(fizzBuzz(5));
console.log(fizzBuzz('dsf'));
console.log(fizzBuzz(15));
console.log(fizzBuzz(564));
console.log(fizzBuzz(7));
function fizzBuzz (input){
if (typeof input === 'number'){
if ((input % 3 === 0) && (input % 5 ===0)){
return 'FizzBuzz';
} else if (input % 3 === 0){
return 'Fizz';
} else if (input % 5 === 0){
return 'Buzz';
} else return input;
} else return NaN;
}<file_sep>/05.07-ExerciseFactoryAndConstructorFunction/index.js
// const address = {
// street: 'A',
// city: 'B',
// zipCode: 1234
// };
let address1 = createAddress('A', 'B', 1234);
let address2 = new Address('C', 'D', 5678);
console.log(address1);
console.log(address2);
// Factory Function
function createAddress(street, city, zipCode) {
return {
street,
city,
zipCode
};
}
// Constructor Function
function Address (street, city, zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}<file_sep>/04.07-CountTruthy/index.js
const array = [0, 2, 6 , undefined , 8];
console.log(countTruthy(array));
function countTruthy(array){
let count = 0;
for (let value of array){
if (value) count++;
}
return count;
}<file_sep>/04.11-Stars/index.js
showStars(10);
function showStars (rows){
if (typeof rows !== 'number') console.log(NaN);
let star = '*';
for (let i = 0; i < rows; i++){
console.log(star);
star += '*';
}
}
|
8947e13a25ef8e505abbaf4e4520f4386d769c0a
|
[
"JavaScript",
"INI"
] | 14 |
JavaScript
|
siderischristos/javascript-basics
|
c3ca755d36fbe8afdc9660c7454d4ba1a1027369
|
73bdd0bc33136c7c44e07b268ab1edf039ee43b1
|
refs/heads/master
|
<repo_name>uhtikiber/pnpf_uncalibrated_lib<file_sep>/tests/pnpf_benchmark.cpp
#include <Eigen/Dense>
#include <benchmark/benchmark.h>
#include <iostream>
#include "pnpf/solvers.hpp"
#include "data_generation.hpp"
using namespace pnpf;
template <class Solver> void BM_PNPf(benchmark::State &state) {
using Type = typename Solver::Scalar;
using Matrix34 = typename Solver::Matrix34;
using Matrix24 = typename Solver::Matrix24;
using Matrix33 = typename Solver::Matrix33;
using Vector3 = typename Solver::Vector3;
const int MaxSolutions = Solver::MaxSolutions;
// allocate for generated data
Matrix34 points_3d;
Matrix24 points_2d;
Type f_gen;
Matrix33 R_gen;
Vector3 C_gen;
// allocate for estimated data
int solution_num = 0;
Type f_sol_data[MaxSolutions];
Matrix33 R_sol_data[MaxSolutions];
Vector3 T_sol_data[MaxSolutions];
generateData(points_3d, points_2d, f_gen, R_gen, C_gen);
Solver solver;
for (auto _ : state) {
solver.solve(points_3d, points_2d, &solution_num, f_sol_data, R_sol_data,
T_sol_data);
}
std::cout << "Solutions: " << solution_num << std::endl;
}
BENCHMARK_TEMPLATE(BM_PNPf, P35PSolver<double>);
BENCHMARK_TEMPLATE(BM_PNPf, P35PSolver<float>);
BENCHMARK_TEMPLATE(BM_PNPf, P4PSolver<double>);
BENCHMARK_TEMPLATE(BM_PNPf, P4PSolver<float>);
<file_sep>/pnpf/include/pnpf/pnpf.h
//
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
// File: pnpf.h
//
// MATLAB Coder version : 4.3
// C/C++ source code generated on : 17-Nov-2019 18:29:06
//
#ifndef PNPF_H
#define PNPF_H
// Include Files
#include <cstddef>
#include <cstdlib>
#include "rtwtypes.h"
#include "pnpf_types.h"
// Function Declarations
extern void p35pf_double(const double X[12], const double xy[8], double e, int
*n, double f_data[], int f_size[2], double r_data[], int r_size[3], double
t_data[], int t_size[2]);
extern void p35pf_single(const float X[12], const float xy[8], float e, int *n,
float f_data[], int f_size[2], float r_data[], int r_size[3], float t_data[],
int t_size[2]);
extern void p4pf_double(const double X[12], const double xy[8], double e, int *n,
double f_data[], int f_size[2], double r_data[], int r_size[3], double t_data[],
int t_size[2]);
extern void p4pf_single(const float X[12], const float xy[8], float e, int *n,
float f_data[], int f_size[2], float r_data[], int r_size[3], float t_data[],
int t_size[2]);
extern void pnpf_initialize();
extern void pnpf_terminate();
#endif
//
// File trailer for pnpf.h
//
// [EOF]
//
<file_sep>/pnpf/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
set(SOURCE_LIB src/pnpf.cpp include/pnpf/solvers.hpp)
add_library(pnpf STATIC ${SOURCE_LIB})
target_include_directories(pnpf PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:include>)
target_link_libraries(pnpf Eigen3::Eigen)
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
find_package(Eigen3 3.3 REQUIRED CONFIG)
project(pnpf)
add_compile_options(-march=native -Wall -Wextra -Werror)
add_compile_options(
$<$<OR:$<CONFIG:RELEASE>,$<CONFIG:RELWITHDEBINFO>>:-O3>
)
if (NOT TARGET gtest_main)
add_subdirectory(googletest)
message(STATUS "Adding local google-test build")
endif()
if (NOT TARGET benchmark_main)
set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "Suppressing benchmark's tests" FORCE)
add_subdirectory(benchmark)
message(STATUS "Adding local google-benchmark build")
endif()
enable_testing()
add_subdirectory(pnpf)
add_subdirectory(tests)
<file_sep>/pnpf/include/pnpf/solvers.hpp
//
// Created by elizaveta on 28.10.2019.
//
#ifndef PNPF_SOLVERS_HPP
#define PNPF_SOLVERS_HPP
#include <Eigen/Dense>
#include <climits>
#include "pnpf/pnpf.h"
namespace pnpf {
template <typename T> struct SolverTraits {};
template <class Solver> class MatlabSolver {
public:
using Scalar = typename SolverTraits<Solver>::Scalar;
static constexpr int MaxSolutions = SolverTraits<Solver>::MaxSolutions;
static constexpr Scalar epsilon = std::numeric_limits<Scalar>::epsilon();
using Matrix34 = Eigen::Matrix<Scalar, 3, 4>;
using Matrix24 = Eigen::Matrix<Scalar, 2, 4>;
using Matrix33 = Eigen::Matrix<Scalar, 3, 3>;
using Vector3 = Eigen::Matrix<Scalar, 3, 1>;
void dataEigenToMatlab(const Matrix34 &points_3d, const Matrix24 &points_2d,
const Scalar diag) {
X = points_3d.data();
Eigen::Map<Matrix24> xy_map(xy);
xy_map = points_2d.array() * Scalar(1. / diag);
}
void dataMatlabToEigen(int *n, Scalar *fs, Matrix33 *Rs, Vector3 *Cs,
Scalar diag) {
*n = sol_num;
for (int i = 0; i < *n; ++i) {
fs[i] = f_data[i] * diag;
Cs[i] = Eigen::Map<Vector3>(t_data + 3 * i);
Rs[i] = Eigen::Map<Matrix33>(r_data + 9 * i);
}
}
void solve(const Matrix34 &points_3d, const Matrix24 &points_2d, int *n,
Scalar *fs, Matrix33 *Rs, Vector3 *Cs, Scalar diag = 1) {
dataEigenToMatlab(points_3d, points_2d, diag);
static_cast<Solver *>(this)->solveImpl();
dataMatlabToEigen(n, fs, Rs, Cs, diag);
}
protected:
const Scalar *X;
Scalar xy[8];
int sol_num;
int f_size[2], r_size[3], t_size[2];
Scalar f_data[MaxSolutions], r_data[MaxSolutions * 9],
t_data[MaxSolutions * 3];
};
template <class Scalar> class P35PSolver {};
template <typename T> struct SolverTraits<P35PSolver<T>> {
using Scalar = T;
static constexpr int MaxSolutions = 10;
};
template <> class P35PSolver<float> : public MatlabSolver<P35PSolver<float>> {
public:
void solveImpl() {
p35pf_single(X, xy, epsilon, &sol_num, f_data, f_size, r_data, r_size,
t_data, t_size);
};
};
template <> class P35PSolver<double> : public MatlabSolver<P35PSolver<double>> {
public:
void solveImpl() {
p35pf_double(X, xy, epsilon, &sol_num, f_data, f_size, r_data, r_size,
t_data, t_size);
};
};
template <class Scalar> class P4PSolver {};
template <typename T> struct SolverTraits<P4PSolver<T>> {
using Scalar = T;
static constexpr int MaxSolutions = 10;
};
template <> class P4PSolver<float> : public MatlabSolver<P4PSolver<float>> {
public:
void solveImpl() {
p4pf_single(X, xy, epsilon, &sol_num, f_data, f_size, r_data, r_size,
t_data, t_size);
};
};
template <> class P4PSolver<double> : public MatlabSolver<P4PSolver<double>> {
public:
void solveImpl() {
p4pf_double(X, xy, epsilon, &sol_num, f_data, f_size, r_data, r_size,
t_data, t_size);
};
};
} // namespace pnpf
#endif // PNPF_H
<file_sep>/tests/data_generation.hpp
#ifndef DATA_GENERATION_H
#define DATA_GENERATION_H
#include <Eigen/Dense>
#include <Eigen/LU>
#include <random>
#include <unsupported/Eigen/MatrixFunctions>
template <class Type>
Eigen::Matrix<Type, 3, 3> makeSkew(const Eigen::Matrix<Type, 3, 1> &a) {
Eigen::Matrix<Type, 3, 3> S;
S.setZero();
S(0, 1) = -a(2);
S(0, 2) = a(1);
S(1, 2) = -a(0);
S(1, 0) = a(2);
S(2, 0) = -a(1);
S(2, 1) = a(0);
return S;
}
template <class Type>
void generateData(Eigen::Matrix<Type, 3, 4> &points_3d,
Eigen::Matrix<Type, 2, 4> &points_2d, Type &f,
Eigen::Matrix<Type, 3, 3> &R, Eigen::Matrix<Type, 3, 1> &C,
Type d = 0) {
std::random_device dev;
std::mt19937_64 generator(dev()); // Mersenne Twister generator
std::uniform_real_distribution<Type> uniformDistribution(-1., 1.);
auto uniform = [&]() { return uniformDistribution(generator); };
// focal distance
f = 200 + 1800 * (uniformDistribution(generator) + 1) / 2;
// rotation
Eigen::Matrix<Type, 3, 1> rVec =
Eigen::Matrix<Type, 3, 1>::NullaryExpr(3, 1, uniform);
rVec /= 2; //???
Eigen::Matrix<Type, 3, 3> rVecSkew = makeSkew(rVec);
R = rVecSkew.exp();
// camera center
C = Eigen::Matrix<Type, 3, 1>::NullaryExpr(3, 1, uniform);
C /= 2; //???
// calibration matrix
Eigen::Matrix<Type, 3, 3> K;
K.setZero();
K(0, 0) = K(1, 1) = f;
K(2, 2) = 1;
// projection matrix
Eigen::Matrix<Type, 3, 4> P;
P.setIdentity();
P.col(3) = -C;
P = K * R * P;
// points in space
points_3d.setZero();
points_3d.row(2).setConstant(6);
Eigen::Matrix<Type, 3, 4> tmp =
Eigen::Matrix<Type, 3, 4>::NullaryExpr(3, 4, uniform);
points_3d += 2 * tmp;
for (int i = 0; i < 4; ++i) {
points_3d.col(i) = (R.transpose() * points_3d.col(i) + C).eval();
}
// image points
Eigen::Matrix<Type, 4, 4> XMHom;
XMHom << points_3d, 1, 1, 1, 1;
Eigen::Matrix<Type, 3, 4> pHom = P * XMHom;
for (int i = 0; i < 4; ++i) {
Eigen::Matrix<Type, 2, 1> dist;
if (d > 0) {
std::normal_distribution<Type> normalDistribution(0, d);
auto normal = [&]() { return normalDistribution(generator); };
dist = Eigen::Matrix<Type, 2, 1>::NullaryExpr(2, 1, normal);
} else {
dist.setZero();
}
points_2d.col(i) = pHom.col(i).hnormalized() + dist;
}
}
#endif
<file_sep>/tests/test_helper.hpp
#ifndef TEST_HELPER_HPP
#define TEST_HELPER_HPP
#include <Eigen/Dense>
#include <climits>
#include <cmath>
#include <iostream>
#include "pnpf/solvers.hpp"
#include "data_generation.hpp"
struct TestResult {
int existSolutions;
int belowThreshold;
};
template <typename Solver> TestResult runFunction(Solver &solver, int it_num) {
using Scalar = typename Solver::Scalar;
using Matrix34 = typename Solver::Matrix34;
using Matrix24 = typename Solver::Matrix24;
using Matrix33 = typename Solver::Matrix33;
using Vector3 = typename Solver::Vector3;
const int MaxSolutions = Solver::MaxSolutions;
const double f_tolerance = 0.01;
const double R_tolerance = 0.03;
const double C_tolerance = 0.1;
int succ_num = 0;
int zero_solutions_num = 0;
// allocate for generated data
Matrix34 points_3d;
Matrix24 points_2d;
Scalar f_gen;
Matrix33 R_gen;
Vector3 C_gen;
// allocate for estimated data
int solution_num = 0;
Scalar fs[MaxSolutions];
Matrix33 Rs[MaxSolutions];
Vector3 Cs[MaxSolutions];
// p4p_solver_initialize();
for (int curr_it = 0; curr_it < it_num; ++curr_it) {
generateData(points_3d, points_2d, f_gen, R_gen, C_gen);
Scalar diag =
(points_2d.rowwise().maxCoeff() - points_2d.rowwise().minCoeff())
.norm();
solver.solve(points_3d, points_2d, &solution_num, fs, Rs, Cs, diag);
// allocate for comparison
Scalar min_diff, diff_C, diff_R;
min_diff = diff_C = diff_R = std::numeric_limits<Scalar>::max();
for (int i = 0; i < solution_num; ++i) {
Scalar f = fs[i];
Vector3 C;
Matrix33 R;
C = Cs[i];
R = Rs[i];
Scalar diff = abs(f - f_gen);
Scalar diffR = (R - R_gen).norm() / 3.;
Scalar diffC = (C - C_gen).norm();
if (diff < min_diff) {
min_diff = diff;
diff_R = diffR;
diff_C = diffC;
} else if (diff == min_diff && diffR < diff_R) {
diff_R = diffR;
diff_C = diffC;
}
}
if (min_diff / abs(f_gen) < f_tolerance && diff_R < R_tolerance &&
diff_C / C_gen.norm() < C_tolerance && solution_num != 0)
succ_num++;
if (solution_num == 0)
zero_solutions_num++;
}
return {(it_num - zero_solutions_num), succ_num};
}
#endif // PNP_TEST_TEST
<file_sep>/tests/CMakeLists.txt
add_executable(pnpf_benchmark pnpf_benchmark.cpp)
target_link_libraries(pnpf_benchmark pnpf benchmark_main)
add_executable(pnpf_test pnpf_test.cpp)
target_link_libraries(pnpf_test pnpf gtest_main)
add_test(NAME pnpf COMMAND pnpf_test)
<file_sep>/tests/pnpf_test.cpp
#include "test_helper.hpp"
#include "gtest/gtest.h"
using namespace pnpf;
template <typename Solver> struct ExpectedResults {
static constexpr double solution_rate = 0.99;
static constexpr double success_rate = 0.99;
};
template <typename Solver> class PnPTest : public testing::Test {
protected:
PnPTest() {
it_num = 1e+4; // number of iterations
Solver solver;
res = runFunction(solver, it_num);
};
int it_num;
TestResult res;
using Expected = ExpectedResults<Solver>;
const double solution_rate_exp = Expected::solution_rate;
const double success_rate_exp = Expected::success_rate;
};
using testing::Types;
using SolverTypes = ::testing::Types<P35PSolver<double>, P35PSolver<float>,
P4PSolver<double>, P4PSolver<float>>;
template <> struct ExpectedResults<P35PSolver<float>> {
static constexpr double solution_rate = 0.95;
static constexpr double success_rate = 0.9;
};
template <> struct ExpectedResults<P4PSolver<float>> {
static constexpr double solution_rate = 0.85;
static constexpr double success_rate = 0.75;
};
TYPED_TEST_SUITE(PnPTest, SolverTypes);
TYPED_TEST(PnPTest, PnP) {
EXPECT_GT((double)this->res.existSolutions / this->it_num,
this->solution_rate_exp);
EXPECT_GT((double)this->res.belowThreshold / this->it_num,
this->success_rate_exp);
}
<file_sep>/README.md
Pose+focal length solvers (P3.5P & P4Pf based on 3Q3)
# Building
```bash
git submodule update --init --recursive && mkdir -p build && cd build && cmake ../ -DCMAKE_BUILD_TYPE=Release && make -j
```
# Tests & benchmarks
```bash
./build/tests/pnpf_benchmark
./build/tests/pnpf_test
```
|
7e38773cdff17dedf21277ee4439d11ee5ba7d19
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 10 |
C++
|
uhtikiber/pnpf_uncalibrated_lib
|
9c56f09ccbf9bafab4c97fc089acd7d6a87e4453
|
12d922ee10621c33a064f335f10929c137ed0842
|
refs/heads/master
|
<repo_name>sofi-g/car-app<file_sep>/src/components/Body.jsx
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const Body = () => {
const [userId, setUserId] = useState('')
const [brand, setBrand] = useState('')
const [model, setModel] = useState('')
const [color, setColor] = useState('')
const [licensePlate, setlicensePlate] = useState('')
const [carsList, setCarsList] = useState([])
const [updateStyle, setUpdateStyle] = useState(null)
useEffect(() => {
const getCars = async () => {
await axios.get('http://localhost:3001/cars')
.then(response => {
setCarsList(response.data)
}).catch(error => {
console.log(error)
})
}
getCars()
}, [setCarsList])
const getCars = async () => {
await axios.get('http://localhost:3001/cars')
.then(response => {
setCarsList(response.data)
}).catch(error => {
console.log(error)
})
}
const getData = async (id) => {
await axios.get(`http://localhost:3001/cars/${id}`)
.then(response => {
console.log(response.data)
const {brand, model, color, license_plate} = response.data
setUpdateStyle(true)
setBrand(brand)
setModel(model)
setColor(color)
setlicensePlate(license_plate)
setUserId(id)
}).catch(error => {
console.log(error)
})
}
const handleSubmit = async (event) => {
event.preventDefault()
setBrand('')
setModel('')
setColor('')
setlicensePlate('')
await axios('http://localhost:3001/cars', {
method: 'POST',
data: {
brand: brand,
model: model,
color: color,
license_plate: licensePlate
},
headers: {
'accept': 'application/json'
},
}).then(response => {
console.log(response.data)
getCars()
alert('Has registrado un automóvil con éxito')
}).catch(error => {
console.log(error)
})
}
const handleDelete = async (id) => {
await axios(`http://localhost:3001/cars/${id}`, {
method: 'DELETE',
}).then(response => {
console.log(response.data);
getCars()
}).catch(error => {
console.log(error)
})
}
const handleUpdate = async (e) => {
e.preventDefault()
setBrand('')
setModel('')
setColor('')
setlicensePlate('')
await axios(`http://localhost:3001/cars/${userId}`, {
method: 'PUT',
data: {
brand: brand,
model: model,
color: color,
license_plate: licensePlate
},
headers: {
'accept': 'application/json'
},
}).then(response => {
console.log(response.data);
setUpdateStyle(false)
getCars()
}).catch(error => {
console.log(error)
})
}
return (
<div className='app-body'>
<form className='form-group' onSubmit= { updateStyle ? handleUpdate : handleSubmit}>
<input
onChange={(e)=>{setBrand(e.target.value)}}
className='form-control mb-3'
type='text'
placeholder='Introduce la marca'
value={brand}
required
/>
<input
onChange={(e)=>{setModel(e.target.value)}}
className='form-control mb-3'
type='text'
placeholder='Introduce el modelo'
value={model}
required
/>
<input
onChange={(e)=>{setColor(e.target.value)}}
className='form-control mb-3'
type='text'
placeholder='Introduce el color'
value={color}
required
/>
<input
onChange={(e)=>{setlicensePlate(e.target.value)}}
className='form-control mb-3'
type='text'
placeholder='Introduce la patente'
value={licensePlate}
required
/>
{updateStyle ?
( <input className='btn btn-info btn-block' type='submit' value='Actualizar Auto'/>
)
:
( <input className='btn btn-info btn-block' type='submit' value='Registrar Auto'/>
)
}
</form>
<div className='col'>
<ul className='list-grow'>
{carsList.length!==0 ? (
carsList.map(item =>
<li key={item.id} className='list-group-item'>
{item.brand} | {item.model} | {item.color} | {item.license_plate}
<button className='btn btn-outline-danger float-right btn-sm'
onClick={(id)=> (handleDelete(item.id))}>
Borrar
</button>
<button className='btn btn-outline-warning float-right btn-sm'
onClick={(id)=> (getData(item.id))}>
Actualizar
</button>
</li>
)
) :
(
<span> No hay automóviles que mostrar </span>
)
}
</ul>
</div>
</div>
)
}
export default Body<file_sep>/README.md
## Getting Started with Car-App
In the project directory, you can run:
### `yarn install`
### `yarn start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
Let's run json-server in a new console, you should run:
### `json-server --watch db.json --port 3001`
|
a156a975286a93cc7e6e39a9ba218b860319d9e3
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
sofi-g/car-app
|
ec7425a3e47f511ffbc673923a4faf6bebf3a326
|
235985633dadec43b6dc8200b51c3c74de35a6ce
|
refs/heads/master
|
<repo_name>kolov/mini-node-server<file_sep>/app.js
var http = require('http')
const shell = require('shelljs')
var server = http.createServer((function (request, response) {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
response.writeHead(200,
{ "Content-Type": "text/plain" });
const { method, url } = request
console.log("method = " + method)
console.log("body = " + body)
shell.exec('/Users/assenkolov/projects/gits-sync/runme.sh')
response.end("processed\n");
});
}));
server.listen(7000);
|
6d56392900f430504babfdb15dfcad41260e14c6
|
[
"JavaScript"
] | 1 |
JavaScript
|
kolov/mini-node-server
|
2d06bb4b45ec1b18b9096cb9bc135432f9fbea7b
|
dc96d91fa9d3291e110c5ad9bd68bdb6c130962a
|
refs/heads/master
|
<repo_name>ajinkyaT/ori<file_sep>/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Amazon1Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
Item_name = scrapy.Field()
Item_href = scrapy.Field()
Model= scrapy.Field()
Brand=scrapy.Field()
Energy_Efficiency = scrapy.Field()
Capacity = scrapy.Field()
Noise_Level=scrapy.Field()
Installation_Type=scrapy.Field()
Part_Number=scrapy.Field()
Color=scrapy.Field()
Control_Console=scrapy.Field()
Voltage=scrapy.Field()
Wattage=scrapy.Field()
ASIN=scrapy.Field()
Best_Sellers_Rank_Category_home_kitchen=scrapy.Field()
Best_Sellers_Rank_Category_AC=scrapy.Field()
Offer_Price=scrapy.Field()
No_of_Reviews=scrapy.Field()
MRP=scrapy.Field()
Average_Rating=scrapy.Field()
Review_1=scrapy.Field()
Review_2=scrapy.Field()
Review_3=scrapy.Field()
Review_4=scrapy.Field()
Review_5=scrapy.Field()
Review_6=scrapy.Field()
Review_7=scrapy.Field()
Review_8=scrapy.Field()
<file_sep>/README.md
# Ori internship, Web Scraper
Web scraper ama.py is a spider and rest files are same as default files.
In amazondata.csv columns are a bit mismatched and some data is denied by server request against bot. part1-4.csv are parts of finally extracted data.
<file_sep>/ama.py
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.http.request import Request
from scrapy.conf import settings
from amazon1.items import Amazon1Item
import bs4 as bs
import lxml
class AmazonProductSpider(CrawlSpider):
name = "Amazon2"
allowed_domains = ["amazon.in"]
# Use working product URL below
start_urls = ["http://www.amazon.in/s/ref=sr_pg_2?fst=as%3Aoff&rh=n%3A976442031%2Cn%3A!976443031%2Cn%3A1380263031%2Cn%3A3474656031%2Cp_n_feature_thirteen_browse-bin%3A2753048031|2753047031&page={}&bbn=3474656031&ie=UTF8&qid=1485024415".format(x) for x in list(range(1,48,1))]
# start_urls = ["http://www.amazon.in/s/ref=sr_pg_2?fst=as%3Aoff&rh=n%3A976442031%2Cn%3A!976443031%2Cn%3A1380263031%2Cn%3A3474656031%2Cp_n_feature_thirteen_browse-bin%3A2753048031|2753047031&page=1&bbn=3474656031&ie=UTF8&qid=1485024415"]
rules = (
Rule(LxmlLinkExtractor(allow=(r'(dp)\/([A-Z])([A-Z0-9]{9})'),deny=(r'(.in)\/(dp)\/([A-Z])([A-Z0-9]{9})'), unique=True,), callback="parse_item",),
)
def parse_item(self,response):
items = Amazon1Item()
# items['Item_name'] = response.xpath('//*[@id="productTitle"]/text()').extract()
items['Item_href'] = response.url
# items['Model'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[2]/td[2]/text()').extract()
# items['Energy_Efficiency'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[3]/td[2]/text()').extract()
# items['Capacity'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[4]/td[2]/text()').extract()
# items['Noise_Level'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[5]/td[2]/text()').extract()
# items['Installation_Type'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[6]/td[2]/text()').extract()
# items['Part_Number'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[7]/td[2]/text()').extract()
# items['Color'] = response.xpath('//*[@id="prodDetails"]/div/div[1]/div/div[2]/div/div/table/tbody/tr[8]/td[2]/text()').extract()
# items['Control_Console'] = response.xpath('//*[@id="prodDetails"]/div[2]/div[1]/div/div[2]/div/div/table/tbody/tr[7]/td[2]/text()').extract()
# items['Voltage'] = response.xpath('//*[@id="prodDetails"]/div[2]/div[1]/div/div[2]/div/div/table/tbody/tr[8]/td[2]/text()').extract()
# items['Wattage'] = response.xpath('//*[@id="prodDetails"]/div[2]/div[1]/div/div[2]/div/div/table/tbody/tr[9]/td[2]/text()').extract()
# items['ASIN'] = response.xpath('//*[@id="prodDetails"]/div[2]/div[2]/div[1]/div[2]/div/div/table/tbody/tr[1]/td[2]/text()').extract()
# items['Best_Sellers_Rank_Category'] = response.xpath('//*[@id="SalesRank"]/td[2]/text()[1]').extract()
# items['Offer_Price'] = response.xpath('//*[@id="priceblock_saleprice"]/text()').extract()
# # items['MRP']=response.xpath('//*[@id="price"]/table/tbody/tr[1]/td[2]/span/text()').extract()
# items['No_of_Reviews'] = response.xpath('//*[@id="acrCustomerReviewText"]/text()').extract()
# items['Average_Rating'] = response.xpath('//*[(@id = "averageCustomerReviewRating")]/text()').extract()
soup=bs.BeautifulSoup(response.text,"lxml")
items['Item_name']=soup.title.text.encode('ascii')
try:
for string in soup.find("span",class_="a-text-strike").stripped_strings:
items['MRP']=string.encode('ascii')
except Exception: pass
try:
items['Offer_Price'] = response.xpath('//*[@id="priceblock_saleprice"]/text()').extract()[0].encode("ascii")
except Exception: pass
try:
items['Offer_Price'] = response.xpath('//*[@id="priceblock_ourprice"]/text()').extract()[0].encode("ascii")
except Exception: pass
try:
items['Offer_Price'] = response.xpath('//*[@id="priceblock_dealprice"]/text()').extract()[0].encode("ascii")
except Exception: pass
try:
items['Offer_Price'] = response.xpath('//*[@id="olp_feature_div"]/div/span/span/text()').extract()
for sting in items['Offer_Price']:items['Offer_Price']=sting.encode('ascii')
except Exception: pass
try:table1=soup.find(class_="column col1 ")
except Exception: pass
try:items['Brand'] = table1.find("td",text='Brand').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Model'] = table1.find("td",text='Model').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Energy_Efficiency'] = table1.find("td",text='Energy Efficiency').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Capacity'] = table1.find("td",text='Capacity').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Noise_Level'] =table1.find("td",text='Noise Level').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Installation_Type'] =table1.find("td",text='Installation Type').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Part_Number']= table1.find("td",text='Part Number').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Color'] = table1.find("td",text='Colour').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Control_Console'] = table1.find("td",text='Control Console').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Voltage'] = table1.find("td",text='Voltage').next_sibling.text.encode('ascii')
except Exception: pass
try:items['Wattage'] = table1.find("td",text='Wattage').next_sibling.text.encode('ascii')
except Exception: pass
try:table2=soup.find(class_="column col2 ")
except Exception: pass
try:items['ASIN'] = table2.find("td",text='ASIN').next_sibling.text.encode('ascii')
except Exception: pass
try:items['No_of_Reviews'] =table2.find(id="averageCustomerReviewCount").text.encode('ascii')
except Exception: pass
try:items['Average_Rating'] =table2.find(id="averageCustomerReviewRating").text.encode('ascii')
except Exception: pass
try:items['Best_Sellers_Rank_Category_home_kitchen']=table2.find("td",text='Best Sellers Rank').next_sibling.get_text(strip=True).split()[0].encode('ascii')
except Exception: pass
try:items['Best_Sellers_Rank_Category_AC']=table2.find("span",class_='zg_hrsr_rank').text.encode('ascii')
except Exception: pass
try:
count=0
reviews=soup.find('div',id="revMHRL")
for item in reviews.find_all('div',class_="a-section"):
if len(item["class"]) != 1:
continue;
count+=1
items['Review_{}'.format(count)]=item.get_text(strip=True).encode('ascii')
except Exception: pass
return items
|
52cd584a2e9d21501cb9d28f1ede902ec495655d
|
[
"Markdown",
"Python"
] | 3 |
Python
|
ajinkyaT/ori
|
e9fd466d951ec3696abbb535687a635f51235247
|
b3ec904da0eeab3f45942cb723d9622409535a75
|
refs/heads/master
|
<file_sep>
const fs = require('fs');
const {parse, unparse} = require('papaparse');
fs.readFile("inventory.csv",(err,inv)=>{
const invJson = parse(inv.toString());
console.log(invJson);
fs.readFile("nfs.csv",(err,nfs)=>{
const nfsJson = parse(nfs.toString());
console.log(nfsJson);
let prevName = "";
let copiesLeft = 0;
const newInv = invJson.data.map((invLine)=>{
const [number, _, name, ...rest] = invLine;
if(prevName != name){
copiesLeft = (nfsJson.data.find((line)=>line[1]==name)||[0])[0];
}
const tradeable = Math.max(number - copiesLeft,0)
copiesLeft = Math.max(copiesLeft - number,0)
prevName = name;
return [number, tradeable , name, ...rest]
})
invJson.data = newInv
fs.writeFile("invWithTrades.csv",unparse(invJson),()=>{console.log('done')});
});
});<file_sep>console.log("start")
const axios = require('axios');
const fs = require('fs');
const {parse, unparse} = require('papaparse');
jsonDecks = {
data:[],
errors:[]
}
const decks = [
'e6e6e24a-0cc1-4222-a7dc-d942e3ce78fe',
'32af5825-8477-4915-ab58-892575b5c711',
'c894513e-7826-4494-9776-08cf39019708',
'f07557e9-b925-4163-abff-0d14f000d278',
'77255518-6a2d-49e4-ad33-860b5841932f',
'2e3712e3-3215-4300-8515-4ea20a195237',
'25fa6d1b-af69-4ab0-a351-117ff9fdbfbb',
'5d417029-dbc6-45d1-9e64-fff2568f5e0e',
'c45a5c23-8aa6-44c8-8dd1-7b4fce5d7bba',
'9ef15160-b69f-409b-b5b6-41e556eef089',
'3166881c-d8bd-44e0-9a15-eaf60fcc0def',
'b8364a1a-477c-42a0-9064-b5c15ece2ef7',
'2b3d0fd5-40ed-4822-9edb-55d9d0206029',
'8b77a0a9-bc8f-483c-8aea-320ad4298624',
].map((deckGuid)=>{
return axios({
method: "get",
url: `https://api.scryfall.com/decks/${deckGuid}/export/csv`,
responseType: "blob"
}).then(function (response) {
console.log("done with " + deckGuid);
return parse(response.data);
}).catch(err=>{console.log(err)});
})
decks.forEach((deckPromise)=>{
deckPromise.then((deck)=>{
jsonDecks.data[0] = deck.data ? deck.data[0] : [];
jsonDecks.errors = jsonDecks.errors.concat(deck.errors);
jsonDecks.meta = deck.meta;
jsonDecks.data = jsonDecks.data.concat(deck.data.slice(1));
})
});
Promise.all(decks).then(()=>{
fs.writeFile("my.csv",unparse(jsonDecks),()=>{console.log('done')});
});
|
03b05bfcee49395fc210ecac78a1f398e9b82aca
|
[
"JavaScript"
] | 2 |
JavaScript
|
yoans/DeckTools
|
ddf42841011c0412979c2d6208990300b8b7e62d
|
1a0a40cba5e024f7b6bf747588c03a075c8677af
|
refs/heads/master
|
<repo_name>barthess/qtbenchmark<file_sep>/renderthread.cpp
#include <QDebug>
#include "renderthread.h"
RenderThread::RenderThread(QObject *parent) :
QThread(parent)
{
restart = false;
abort = false;
}
RenderThread::~RenderThread()
{
mutex.lock();
abort = true;
condition.wakeOne();
mutex.unlock();
wait();
}
void RenderThread::render(void){
qDebug() << "render";
}
void RenderThread::run(void){
forever {
mutex.lock();
mutex.unlock();
mutex.lock();
if (!restart)
condition.wait(&mutex);
restart = false;
mutex.unlock();
}
}
<file_sep>/README.md
qtbenchmark
===========<file_sep>/renderthread.h
#ifndef RENDERTHREAD_H
#define RENDERTHREAD_H
#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QSize>
#include <QImage>
class RenderThread : public QThread
{
Q_OBJECT
public:
explicit RenderThread(QObject *parent = 0);
~RenderThread();
void render(void);
signals:
void renderedImage(const QImage &image, double scaleFactor);
protected:
void run();
private:
QMutex mutex;
QWaitCondition condition;
bool restart;
bool abort;
};
#endif // RENDERTHREAD_H
<file_sep>/widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
connect(&thread, SIGNAL(renderedImage(QImage,double)),
this, SLOT(updatePixmap(QImage,double)));
setWindowTitle(tr("Mandelbrot"));
}
Widget::~Widget()
{
delete ui;
}
void Widget::updatePixmap(const QImage &image, double scaleFactor){
}
|
d2a602634d58701615f540514aaab337a14d7dd0
|
[
"Markdown",
"C++"
] | 4 |
C++
|
barthess/qtbenchmark
|
a816e53082667417535682c54fe8f1aeeb4de33d
|
55138d566f9313f07f4ea3df678a4c0a17710803
|
refs/heads/master
|
<repo_name>kevinkeithley/ToiletPaperMetrics<file_sep>/app.R
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application
ui <- fluidPage(
# Custom CSS Styling for font size and line height
tags$head(
tags$style(HTML("
p, #how_long, #how_many, li {
font-size: 16px;
line-height: 1.5;
}
"))
),
# Application title
titlePanel("The case of the TP hoarder"),
# Sidebar
sidebarLayout(position = "right",
sidebarPanel(
numericInput("cases",
"Number of TP cases:",
min = 1,
max = 10,
value = 4),
numericInput("rolls",
"Rolls per case:",
min = 2,
max = 40,
value = 30),
numericInput("sheets_roll",
"Sheets per roll:",
min = 300,
max = 1000,
value = 425),
hr(),
sliderInput("sheets_shit",
"Sheets per shit:",
min = 4,
max = 40,
value = 20),
sliderInput("shits",
"Shits per week (per person):",
min = 2,
max = 28,
value = 7),
hr(),
numericInput("people",
"People in household:",
min = 1,
value = 4),
sliderInput("weeks",
"Quarantine period (weeks)",
min = 1,
max = 26,
value = 8)
),
# Main Panel
mainPanel(
fluidRow(
column(12,
p("I was inspired to create this app after seeing the Facebook video of 'Dad does maths behind toilet paper panic buying'.",tags$a(href="https://www.facebook.com/news.com.au/videos/dad-does-maths-behind-toilet-paper-panic-buying/2798341280203666/","Link to video")),
p("The default values in this app roughly correlate with the Costco example in the video, but with a few more abilities. The app lets you address two related questions:"),
tags$ol(
tags$li("Given a supply of toilet paper and shitting statistics, how long will your toilet paper last?"),
tags$li("Given a supply of toilet paper, shitting statistics, and a quarantine period, how many shits can you take and not run out of toilet paper?")
),
p("Armed with your new knowledge, may you spend more time inside with your family, and less time in public stockpiling things you don't need.")
)
),
hr(),
fluidRow(
column(6,
icon("calendar", "fa-3x", lib = "font-awesome"),
h3("How long will my toilet paper last?"),
p(textOutput("how_long"))),
column(6,
icon("poop", "fa-3x", lib = "font-awesome"),
h3("How many shits can I take?"),
textOutput("how_many"))
),
hr()
)
),
fluidRow(
column(12,
tags$a(href="https://github.com/kevinkeithley/ToiletPaperMetrics", "Project files"),
" available on GitHub ",
icon("github","fa-2x",lib = "font-awesome")
)
),
fluidRow(
column(12,
"App built with ",
tags$a(href="https://shiny.rstudio.com", "Shiny"),
" from ",
tags$a(href="https://rstudio.com/", "RStudio")
)
),
fluidRow(
column(12,
"Copyright ",
icon("copyright"),
" 2020 <NAME>, MIT License"
))
)
# Define server logic
server <- function(input, output) {
# Create reactive variables for assumptions
total_sheets_react <- reactive({
(input$cases*input$rolls*input$sheets_roll)
})
# Calculate how many shits you can take for the selected quarantine period
how_many_react <- reactive({
total_sheets_react()/(input$sheets_shit*input$people*input$weeks)
})
# Calculate how long your stash of toilet paper will last
how_long_react <- reactive({
total_sheets_react()/(input$sheets_shit*input$people*input$shits)
})
# Create render functions
output$how_many <- renderText({
paste("Each person can take ",
round(how_many_react(), digits = 1),
" shit(s) per week for the course of the selected quarantine period of ",
input$weeks,
" week(s).")
})
output$how_long <- renderText({
paste("Your stash of toilet paper will last ",
round(how_long_react(), digits = 1),
" weeks.")
})
}
# Run the application
shinyApp(ui = ui, server = server)
<file_sep>/README.md
# ToiletPaperMetrics
An easy web app to help you figure out how much toilet paper you actually need to get through the Wuhan Virus pandemic
Available here: https://kevinkeithley.shinyapps.io/ToiletPaperMetrics/
|
80f8fddb136201c3036444f1e253a1152245d47b
|
[
"Markdown",
"R"
] | 2 |
R
|
kevinkeithley/ToiletPaperMetrics
|
512d7d782e20bdedc6c5ed96ce7d568681f7bb60
|
bf53203eefe7d0cd309d075b911be752f6931e5a
|
refs/heads/master
|
<file_sep>plugins {
id 'ru.d10xa.allure' version '0.5.5'
}
group 'selenium.com'
version '1.0'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'ru.d10xa.allure'
repositories {
jcenter()
}
dependencies {
compile group: 'com.codeborne', name: 'selenide', version: '4.8'
compile group: 'org.testng', name: 'testng', version: '6.11'
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.16'
annotationProcessor "org.projectlombok:lombok:1.16.16"
compile group: 'io.github.bonigarcia', name: 'webdrivermanager', version: '1.6.2'
compile group: 'ru.yandex.qatools.allure', name: 'allure-maven-plugin', version: '2.6'
testCompile group: 'io.github.bonigarcia', name: 'webdrivermanager', version: '1.6.2'
classpath "io.qameta.allure:allure-gradle:<latest>"
testCompile 'org.assertj:assertj-core:3.6.2'
}
test {
useTestNG()
outputs.upToDateWhen { false }
testLogging {
showStandardStreams = true
events "started", "passed", "skipped", "failed"
exceptionFormat = 'full'
}
}
allure {
aspectjweaver = true
testNG = true
allureVersion = "2.6"
}
<file_sep>package Entities;
public enum EditorButtons {
BOLD("#mceu_3>button"),
ITALIC("#mceu_4>button"),
REDO("#mceu_1>button"),
BULLET_LIST("#mceu_9>button"),
UNDO("#mceu_0>button");
private String editorButton;
EditorButtons(String editorButton) {
this.editorButton = editorButton;
}
public String getEditorButton() {
return editorButton;
}
}
<file_sep>rootProject.name = 'com.selenium'
<file_sep>package pages;
import Entities.EditorButtons;
import Entities.FormatStyle;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import static com.codeborne.selenide.Selenide.$;
public class EditorPage extends Page {
private SelenideElement fileBar = $("#mceu_15-open");
private SelenideElement newDocument = $("#mceu_32");
private SelenideElement editorTextLayout = $("#tinymce");
private SelenideElement defaultPureStyleOnStyleChecker = $("#mceu_29-0");
private SelenideElement boldStyle = $("#mceu_3>button");
public SelenideElement styleCheckerBar = $("#mceu_28-body");
private SelenideElement formatBar = $("#mceu_18-open");
private static String url = "/tinymce";
public EditorPage createNewDocument() {
fileBar.click();
newDocument.waitUntil(Condition.visible, 8000).click();
return this;
}
public EditorPage setFormatStyle(FormatStyle formatStyle) {
formatBar.click();
$(formatStyle.getFormatStyle()).waitUntil(Condition.visible, 8000).click();
return this;
}
public EditorPage fillTheText(String textForInput) {
editorTextLayout.setValue(textForInput);
return this;
}
public EditorPage checkDefaultStyle() {
defaultPureStyleOnStyleChecker.shouldBe(Condition.visible);
return this;
}
public EditorPage clickBarButton(EditorButtons editorButtons) {
$(editorButtons.getEditorButton()).click();
return this;
}
}
<file_sep>package Entities;
public enum FormatStyle {
BOLD("#mceu_35"),
ITALIC(".mce-ico.mce-i-italic"),
UNDERLINE("#mceu_37"),
STRIKETHROUGH("#mceu_38"),
SUPERSCRIPT("#mceu_39"),
SUBSCRIPT("#mceu_40");
private String formatStyle;
FormatStyle(String formatStyle) {
this.formatStyle = formatStyle;
}
public String getFormatStyle() {
return formatStyle;
}
}
|
97e98a14d58e3e1eb9333f37c165dd226ed188a0
|
[
"Java",
"Gradle"
] | 5 |
Gradle
|
vitaliifokine/com.selenium
|
27275424abaee9bccd2f6f09a199b7f54e79dfd7
|
c947349fed66a0ecbcbd974467531e84aa4772f8
|
refs/heads/master
|
<repo_name>dimitrinaama/Red-To-You<file_sep>/Red-To-You.py
import praw
from moviepy.editor import *
from PIL import Image, ImageFont, ImageDraw
import textwrap
import time
import shutil
import re
import glob
from random import shuffle
import threading
import json
import csv
import pandas as pd
from praw.models import Submission
from sklearn import linear_model
from mp3_tagger import MP3File, VERSION_1, VERSION_2, VERSION_BOTH
from src.formatting.time_format import *
from src.formatting.number_format import *
from src.formatting.replace_and_filter import *
"""
Word Definition
rtr Reply to a reply
threshold Factor of the minimum score criteria of a comment eg. by default, if a comment
fails to receive 30% of the score of its parent, the comment is not included
balcon Text To Speech Command Line Utility
"""
# User Input
is_classic_design = 1
is_single_threaded = 0
reddit_link = "https://www.reddit.com/r/AskReddit/comments/n1sx0h/what_are_some_luxury_items_which_you_never_knew/"
desired_length = 150
bgrd_choice = 1
custom_title = "0"
# # User Input
# is_classic_design = int(input('Mode; 0 = Redesign, 1 = Classic '))
# is_single_threaded = int(input('\nSpeed; 0 = Multithreaded, 1 = Normal '))
# reddit_link = input('\nLink; Paste your desired reddit post:\n')
# desired_length = int(input('\nTime; Enter your maximum desired video length (seconds): '))
# bgrd_choice = int(input('\nColor; Type your background color option [0 = Transparent, 1 = Default, 2 = Black]: '))
# custom_title = input('\nTitle; Type a custom title for thumbnails, to use default type 0\n')
# Reddit Setup
reddit = praw.Reddit(client_id='BHUtkEY0x4vomA', client_secret='<KEY>',
user_agent='pulling posts')
submission: Submission = reddit.submission(url=reddit_link)
number_comments = 25 # int(input('Type a Number Between 1 and 25 to represent the Number of Comments\n'))
threshold = .3 # float(input('Type a number between 0 and 1 to represent the reply threshold (.33 recommended) \n'))
MIN_SCORE = 50
DNE = None
ICON_DIR = 'Static/Icons/'
AUDIO_DIR = 'Static/Audio/'
CLIPS_DIR = 'Static/Clips'
class AbstractRedditItem:
# Imported with Pillow - Gildings
gild_w, gild_h = (20, 20)
PLATINUM = Image.open(f'{ICON_DIR}platinum.png')
PLATINUM = PLATINUM.resize((gild_w, gild_h), Image.ANTIALIAS)
GOLD = Image.open(f'{ICON_DIR}gold.png')
GOLD = GOLD.resize((gild_w, gild_h), Image.ANTIALIAS)
SILVER = Image.open(f'{ICON_DIR}silver.png')
SILVER = SILVER.resize((gild_w, gild_h), Image.ANTIALIAS)
icon_img_font = ImageFont.truetype('CustFont/verdanab.ttf', 17)
def gild_init(self):
if 'gid_1' in self.gildings:
num_silver = self.gildings['gid_1']
else:
num_silver = 0
if 'gid_2' in self.gildings:
num_gold = self.gildings['gid_2']
else:
num_gold = 0
if 'gid_3' in self.gildings:
num_platinum = self.gildings['gid_3']
else:
num_platinum = 0
icon_img = Image.new('RGBA', (200, self.gild_h), (0, 0, 0, 0)) # self.gild_h
icon_img_draw = ImageDraw.Draw(icon_img)
icon_img_height = self.gild_h
text_height = -3
small_spacing = 3
spacing = 9
current_width = 0
more_space = 0
# Draws the awards given to a specific comment
# if a given comment has more than one type of award, then we draw a count next to the award
if num_silver >= 1:
icon_img.paste(self.SILVER, (current_width, 0), self.SILVER)
current_width += self.gild_w
more_space = spacing
if num_silver >= 2:
current_width += small_spacing
icon_img_draw.text((current_width, text_height), str(num_silver), font=self.icon_img_font,
fill='#6a98af')
current_width += spacing
current_width += more_space
more_space = 0
if num_gold >= 1:
icon_img.paste(self.GOLD, (current_width, 0), self.GOLD)
current_width += self.gild_w
more_space = spacing
if num_gold >= 2:
current_width += small_spacing
icon_img_draw.text((current_width, text_height), str(num_gold), font=self.icon_img_font, fill='#6a98af')
current_width += spacing
current_width += more_space
if num_platinum >= 1:
icon_img.paste(self.PLATINUM, (current_width, 0), self.PLATINUM)
current_width += self.gild_w
if num_platinum >= 2:
current_width += small_spacing
icon_img_draw.text((current_width, text_height), str(num_platinum), font=self.icon_img_font,
fill='#6a98af')
current_width += spacing
self.icon = icon_img
def split_self(self, width):
"""
Function: split_self
Definition: Takes the string of the comment and splits the string into lines of length: width
Parameter: width
Return: List
"""
split = textwrap.wrap(self.body, width=width)
return split
def get_split_len(self, width):
"""
Function: get_split_len
Definition: returns the length of a string that was split with width: width
Parameter: width
Return: Integer
"""
split_len = textwrap.wrap(self.body, width=width)
return len(split_len)
class RedditComment(AbstractRedditItem):
def __init__(self, forrest, id, depth, parent=None):
self.include = False
self.id = id
self.author = DNE
self.score = DNE
self.time_ago = DNE
self.gildings = DNE
self.body = DNE
self.parent = parent
self.child = None
if depth > 1:
forrest.stickied = False
# If the comment has no body we do not want to use it
if hasattr(forrest, 'body'):
if not forrest.stickied:
self.author = "[deleted]"
self.body = forrest.body
self.include = True
# self.body = replace_me(forrest.body, global_replace_txt, global_replace_text_with)
self.body = re.sub(r"\[(.+)\]\(.+\)", r"\1", self.body) # Removes Links
self.score = forrest.score
self.time_ago = human_time(datetime.datetime.fromtimestamp(forrest.created))
self.gildings = forrest.gildings
self.gild_init()
if hasattr(forrest, 'author'):
self.author = forrest.author.name;
else:
print("Attribute Error: Failed to create comment; comment was likely deleted")
# We only want children that are 3 levels deep
depth += 1
if depth < 4 and (hasattr(forrest, 'replies')):
if len(forrest.replies) > 0 and hasattr(forrest.replies[0], 'body'):
self.child = RedditComment(forrest.replies[0], 0, depth, self)
class RedditSubmission(AbstractRedditItem):
def __init__(self, sub: Submission):
try:
self.author = sub.author.name
except AttributeError:
self.author = '[deleted]'
self.title = sub.title
self.body = sub.selftext
self.subreddit = sub.subreddit
self.score = sub.score
self.created = datetime.datetime.fromtimestamp(sub.created)
self.num_com = sub.num_comments
self.id = sub.id
self.children = []
for i in range(number_comments):
self.children.append(RedditComment(sub.comments[i], i, 1))
reddit_post = RedditSubmission(submission)
# Keep static, folders deleted on exit
IMG_DIR = 'Subs/Sub1/Img/'
WAV_DIR = 'Subs/Sub1/Wav/'
TXT_DIR = 'Subs/Sub1/Txt/'
VID_DIR = 'Subs/Vid/'
MUSIC_DIR = 'Static/DynamicMusic/'
# EXE Directories
BALCON_DIR = os.path.dirname(os.path.abspath("balcon.exe"))
UPLOADER_DIR = os.path.dirname(os.path.abspath('Upload/youtubeuploader_windows_amd64.exe')) + '\\'
COMMENT_CHAR_WIDTH = 175 # Width between comments
REPLY_CHAR_WIDTH = 168 # Width between replies
RTR_CHAR_WIDTH = 161 # Width between replies to replies
VID_FPS = 15 # Video frames per second
VID_NAME = str(reddit_post.id)
VID_EXTENSION = '.mp4'
VIDEO_FILENAME = VID_NAME + VID_EXTENSION
# Imported with Pillow
BACKGROUND = Image.open(f'{ICON_DIR}backgroundblack.jpg').convert('RGBA')
if is_classic_design == 0:
COMMENT_VOTE_ICON = Image.open(f'{ICON_DIR}commentupdown_2.png').convert('RGBA')
else:
COMMENT_VOTE_ICON = Image.open(f'{ICON_DIR}commentupdown.png').convert('RGBA')
COMMENT_VOTE_ICON = COMMENT_VOTE_ICON.resize((22, 56), Image.ANTIALIAS)
TITLE_VOTE_ICON = Image.open(f'{ICON_DIR}titleupdown.png').convert('RGBA')
COMMENT_VOTE_ICON = COMMENT_VOTE_ICON # Revisit Later
SUB_SCORE_ICON = Image.open(f'{ICON_DIR}sub_up_down.png').convert('RGBA')
SUB_SCORE_ICON = SUB_SCORE_ICON.resize((28, 73), Image.ANTIALIAS)
# Imported with Pillow - Thumbnail Items
ASKREDDIT_ICON = Image.open('Thumbnail/askreddit.png').resize((100, 100), Image.ANTIALIAS) # move later
UPDOWNVOTE = Image.open('Thumbnail/upvotedownvote.png').convert('RGBA')
UPDOWNVOTE = UPDOWNVOTE.resize((440, 400), Image.ANTIALIAS)
COMMENT_ICON = Image.open('Thumbnail/commenticon.png')
COMMENT_ICON = COMMENT_ICON.resize((180, 160), Image.ANTIALIAS)
if is_classic_design == 0:
TITLE_FONT_PATH = 'CustFont/noto-sans/NotoSans-Medium.ttf'
BODY_FONT_PATH = 'CustFont/noto-sans/NotoSans-Regular.ttf'
SUB_FONT_PATH = 'CustFont/IBM_TTF/IBMPlexSans-Bold.ttf'
AUTHOR_FONT_PATH = 'CustFont/IBM_TTF/IBMPlexSans-Regular.ttf'
TIME_FONT_PATH = 'CustFont/IBM_TTF/IBMPlexSans-Regular.ttf'
FOOTER_FONT_PATH = 'CustFont/IBM_TTF/IBMPlexSans-Bold.ttf'
SCORE_FONT_PATH = 'CustFont/IBM_TTF/IBMPlexSans-Regular.ttf'
# Lists all the hex code for fill
AUTHOR_HEX = '#4fbcff'
SCORE_HEX = '#818384'
TIME_HEX = '#818384'
BODY_HEX = '#d7dadc'
FOOTER_HEX = '#818384'
TITLE_HEX = '#d7dadc'
BIG_SCORE_HEX = '#818384'
TITLE_FOOTER = str(reddit_post.num_com) + ' Comments Give Award Share'
PARENT_FOOTER = 'Reply Give Award Share Report Save'
CHILD_FOOTER = PARENT_FOOTER
IMG_COLOR = '#1a1a1b'
else:
# Lists font paths
TITLE_FONT_PATH = 'CustFont/Verdana.ttf'
BODY_FONT_PATH = 'CustFont/Verdana.ttf'
SUB_FONT_PATH = 'CustFont/Verdana.ttf'
AUTHOR_FONT_PATH = 'CustFont/verdanab.ttf'
TIME_FONT_PATH = 'CustFont/verdana.ttf'
FOOTER_FONT_PATH = 'CustFont/verdanab.ttf'
SCORE_FONT_PATH = 'CustFont/verdanab.ttf'
# Lists all the hex code for fill
AUTHOR_HEX = '#6a98af'
SCORE_HEX = '#b4b4b4'
TIME_HEX = '#828282'
BODY_HEX = '#dddddd'
FOOTER_HEX = '#828282'
TITLE_HEX = '#dedede'
BIG_SCORE_HEX = '#646464'
IMG_COLOR = '#222222'
TITLE_FOOTER = str(reddit_post.num_com) + ' comments source share save hide give award report crosspost ' \
' hide all child comments'
PARENT_FOOTER = 'permalink source embed save save-RES report give award reply hide child comments'
CHILD_FOOTER = 'permalink source embed save save-RES parent report give award reply hide child comments'
# Imported with moviepy
TRANSITION = VideoFileClip(f'{CLIPS_DIR}/Transition.mp4').set_duration(.7).set_fps(VID_FPS)
OUTRO = VideoFileClip(f'{CLIPS_DIR}/Outro.mp4').set_fps(VID_FPS)
SILENCE = AudioFileClip(f'{AUDIO_DIR}Silence.wav').set_duration(.33)
def draw_outlined_text(x, y, draw, font, text, width=1, outline='black', fill='white'):
"""
Function: draw_outlined_text
Definition: This function draws text on screen by superimposing 4 lawyers of the text at an outline distance apart
then the function draws the fill text.
Parameter: x, y, draw (PIL method corresponding to a given image), text, width, outline
Return: NONE
"""
draw.text((x - width, y - width), text, font=font, fill=outline)
draw.text((x + width, y - width), text, font=font, fill=outline)
draw.text((x - width, y + width), text, font=font, fill=outline)
draw.text((x + width, y + width), text, font=font, fill=outline)
# now draw the text over it
draw.text((x, y), text, font=font, fill=fill)
def use_comment(comment):
"""
Function: use_comment
Definition: This function determines whether or not we will use a comment in our program.
we make this determination by checking if a comment was flagged with DNE upon initialisation; we also
check to see if the comment meets the minimum score criteria.
Parameter: Reddit_Item
Return: boolean
"""
if comment.include and (comment.score >= MIN_SCORE):
return True
return False
def use_reply(comment):
"""
Function: use_reply
Definition: This function determines whether or not we will use a reply in our program.
we make this determination by checking if a reply was flagged with DNE upon initialisation; we also
check to see if the comment meets the minimum score criteria.
This is determined by checking if the score multiplied by the threshold is greater than or equal to
the original comment
Parameter: Reddit_Item
Return: boolean
"""
if not use_comment(comment):
return False
if not hasattr(comment, 'child'):
return False
if comment.child is None:
return False
# Guard clauses
if (comment.child.body != DNE) and (comment.child.score >= threshold * comment.score):
return True
return False
def use_rtr(comment):
"""
Function: use_rtr
Definition: This function determines whether or not we will use a reply in our program.
First, we check if we even used a reply, then we check if a rtr was flagged with DNE upon
initialisation; we also check to see if the comment meets the minimum score criteria.
This is determined by checking if the score multiplied by the threshold is greater than or equal to
the original comment.
Parameter: Reddit_Item
Return: boolean
"""
if not use_reply(comment):
return False
if not hasattr(comment.child, 'child'):
return False
if comment.child.child is None:
return False
# Guard clauses
if (comment.child.child.body != DNE) and (comment.child.child.score >= threshold * comment.child.score):
return True
return False
def create_img(comment):
"""
Function: create_img
Definition:
Parameter: RedditItem
Return: NONE
"""
num = 0
if is_classic_design == 0:
alt_font_size = 17
redesign_footer_font = alt_font_size + 3
else:
alt_font_size = 15
redesign_footer_font = alt_font_size
# Useful Variables
line_height = 5
# Line height and indent are shifted dynamically in the program for simplicity
line_spacing = 25
medium_space = 30 # Primarily used to separate footer
large_space = 40 # Primarily used to separate comments
image_width = 1920
indent = 0
# Fonts used in this function
body_font = ImageFont.truetype(BODY_FONT_PATH, 20)
author_font = ImageFont.truetype(AUTHOR_FONT_PATH, alt_font_size)
time_font = ImageFont.truetype(TIME_FONT_PATH, alt_font_size)
footer_font = ImageFont.truetype(FOOTER_FONT_PATH, redesign_footer_font)
if use_reply(comment):
formatted_reply = comment.child.split_self(REPLY_CHAR_WIDTH)
rep_len = len(formatted_reply)
rep_height = large_space + line_spacing * rep_len + medium_space
rep_score = comment.child.score
rep_author = comment.child.author
rep_time = comment.child.time_ago
rep_gld_icon = comment.child.icon
else:
rep_height = 0
if use_rtr(comment):
formatted_rtr = comment.child.child.split_self(RTR_CHAR_WIDTH)
rtr_len = len(formatted_rtr)
rtr_height = large_space + line_spacing * rtr_len + medium_space
rtr_score = comment.child.child.score
rtr_author = comment.child.child.author
rtr_time = comment.child.child.time_ago
rtr_gld_icon = comment.child.child.icon
else:
rtr_height = 0
formatted_comment = comment.split_self(COMMENT_CHAR_WIDTH) # text values are separated into lines,
com_len = len(formatted_comment) # this gets the total number of lines
# Potential comment height; this makes and educated guess at the comments size
ptnl_com_height = line_height + line_spacing * com_len + medium_space
img_height = ptnl_com_height + rep_height + rtr_height + medium_space
img = Image.new('RGBA', (image_width, img_height), IMG_COLOR)
draw = ImageDraw.Draw(img)
author = comment.author
score = comment.score
com_time = comment.time_ago
gld_icon = comment.icon
# Gets size of several objects for later use
img_w, img_h = img.size
# Draws the header for the comment
def comment_img(fmt_com, auth, scr, tim, gld_icon):
"""
Function:
Definition:
Parameter:
Return:
"""
nonlocal line_spacing
nonlocal line_height
nonlocal indent
nonlocal num
if is_classic_design == 1:
auth = '[–] ' + auth
formatted_time = f'{tim}'
formatted_points = f' {str(abbreviate_number(scr, 10000))} points '
prev_indent = indent
indent += 40
if num > 0:
line_height += large_space
fttr = CHILD_FOOTER
else:
fttr = PARENT_FOOTER
if num == 1:
box_hex = '#121212'
else:
box_hex = '#161616'
box_outline_hex = '#333333'
arrow_indent = indent - 30 # Arrow indent refers to the vote arrow's indentation
auth_w, auth_h = author_font.getsize(auth)
scr_w, scr_h = author_font.getsize(formatted_points)
tm_w, tm_h = author_font.getsize(formatted_time)
auth_x, auth_y = (indent, line_height)
scr_x, scr_y = (auth_x + auth_w, line_height)
tm_x, tm_y = (scr_x + scr_w, line_height)
gld_x, gld_y = (tm_x + tm_w, line_height)
if is_classic_design == 1:
draw.rectangle([(prev_indent, line_height - .5*line_spacing), (1920 - 10*num, 15 + line_height + img_height - num*2)],
fill=box_hex, outline=box_outline_hex)
else:
if num > 0:
draw.line((indent - 40, img_height - 5, indent - 40, auth_y), fill='#343536', width=5)
draw.text((auth_x, auth_y), auth, font=author_font, fill=AUTHOR_HEX)
draw.text((scr_x, scr_y), formatted_points, font=author_font, fill=SCORE_HEX)
draw.text((tm_x, tm_y), formatted_time, font=time_font, fill=FOOTER_HEX)
img.paste(COMMENT_VOTE_ICON, (arrow_indent, line_height), COMMENT_VOTE_ICON)
img.paste(gld_icon, (gld_x, gld_y), gld_icon)
for line in fmt_com:
line_height += line_spacing
line_num = fmt_com.index(line)
draw.text((indent, line_height), line, font=body_font, fill=BODY_HEX)
img_path = IMG_DIR + str(comment.id) + '.' + str(num) + '.' + str(line_num) + '.png'
if line == fmt_com[-1]:
line_height += medium_space
draw.text((indent, line_height), fttr, font=footer_font, fill=FOOTER_HEX)
temp = BACKGROUND.copy()
temp.paste(img, (0, 540 - int(.5 * img_h)), img)
temp.save(img_path)
num += 1
comment_img(formatted_comment, author, score, com_time, gld_icon)
if use_reply(comment):
comment_img(formatted_reply, rep_author, rep_score, rep_time, rep_gld_icon)
if use_rtr(comment):
comment_img(formatted_rtr, rtr_author, rtr_score, rtr_time, rtr_gld_icon)
photofilepath = IMG_DIR + str(comment.id) + '.png'
# img.show()
def create_txt(comment, audio_replace):
"""
Function: create_txt
Definition: This function takes our gathered text and saves them to a file so that the text can be read by balcon
Parameter: Reddit Item
Return: NONE
"""
filename = TXT_DIR + str(comment.id) + '.0.txt'
txt_to_save = open(filename, 'w', encoding='utf-8')
txt_to_save.write(replace_me(comment.body, audio_replace[0], audio_replace[1], use_for_audio=True))
txt_to_save.close()
if use_reply(comment):
filename = TXT_DIR + str(comment.id) + '.1.txt'
txt_to_save = open(filename, 'w', encoding='utf-8') # for some reason as of 6/17/19 1:10 AM IT NEEDS ENCODING
txt_to_save.write(replace_me(comment.child.body, audio_replace[0], audio_replace[1], use_for_audio=True))
txt_to_save.close()
else:
pass
if use_rtr(comment):
filename = TXT_DIR + str(comment.id) + '.2.txt'
txt_to_save = open(filename, 'w', encoding='utf-8') # for some reason as of 6/17/19 1:10 AM IT NEEDS ENCODING
txt_to_save.write(replace_me(comment.child.child.body, audio_replace[0], audio_replace[1], use_for_audio=True))
txt_to_save.close()
else:
pass
def create_wav(comment):
"""
Function: create_wav
Definition: This function creates a command for our text to speech ulility then executes the command,
this creates a wav file
Parameter: RedditItem
Return: NONE
"""
def issue_balcon_command(num):
"""
Function: balcon
Definition: This function given a number, creates a command for our command line utiltily
Parameter: Integer
Return: NONE
"""
os.chdir(BALCON_DIR) # changes command line directory for the balcon utility
txt_file = str(comment.id) + '.%s.txt' % num
wav_file = str(comment.id) + '.%s.wav' % num
command = f'balcon -f "Subs\\Sub1\\Txt\\{txt_file}" -w "Subs\\Sub1\\Wav\\{wav_file}" -n "ScanSoft Daniel_Full_22kHz"'
os.system(command)
issue_balcon_command(0)
if use_reply(comment):
issue_balcon_command(1)
else:
pass
if use_rtr(comment):
issue_balcon_command(2)
else:
pass
def create_clip(comment):
"""
Function: create_clip
Definition: The function, given a comment, will create a clip for a given
The function gathers together the various files needed for video creation such as the image and
the audio file
Parameter: RedditItem
Return: VideoClip (moviepy defined class)
"""
split_com = ""
split_rep = ""
split_rtr = ""
if use_comment(comment):
split_com = comment.split_self(COMMENT_CHAR_WIDTH)
if use_reply(comment):
split_rep = comment.child.split_self(REPLY_CHAR_WIDTH)
if use_rtr(comment):
split_rtr = comment.child.child.split_self(RTR_CHAR_WIDTH)
# Arrays for various clips in sequence
c_clip = [] # Refers to comment clip ie. the whole this including replies/rtr
i_clip0 = []
i_clip1 = []
i_clip2 = []
a0_path = WAV_DIR + str(comment.id) + '.0.wav'
a1_path = WAV_DIR + str(comment.id) + '.1.wav'
a2_path = WAV_DIR + str(comment.id) + '.2.wav'
sum_comment_lines = sum(len(line) for line in split_com)
sum_reply_lines = sum(len(line) for line in split_rep)
sum_rtr_lines = sum(len(line) for line in split_rtr)
a_clip0 = AudioFileClip(a0_path)
a_clip0 = concatenate_audioclips([a_clip0, SILENCE])
for string in split_com:
factor = len(string) / sum_comment_lines
path = IMG_DIR + str(comment.id) + '.0' + '.%s.png' % split_com.index(string)
clip = ImageClip(path).set_duration(factor * a_clip0.duration)
i_clip0.append(clip)
# print(path)
s0 = '\ndone comment: ' + str(comment.id)
i_clip0 = concatenate_videoclips(i_clip0)
i_clip0 = i_clip0.set_audio(a_clip0)
c_clip.append(i_clip0)
if use_reply(comment):
a_clip1 = AudioFileClip(a1_path)
a_clip1 = concatenate_audioclips([a_clip1, SILENCE])
for rString in split_rep:
factor = len(rString) / sum_reply_lines
path = IMG_DIR + str(comment.id) + '.1' + '.%s.png' % split_rep.index(rString)
clip = ImageClip(path).set_duration(factor * a_clip1.duration)
i_clip1.append(clip)
# print(path)
s1 = '\n\tdone reply: ' + str(comment.id)
i_clip1 = concatenate_videoclips(i_clip1)
i_clip1 = i_clip1.set_audio(a_clip1)
c_clip.append(i_clip1)
else:
s1 = ''
pass
if use_rtr(comment):
a_clip2 = AudioFileClip(a2_path)
a_clip2 = concatenate_audioclips([a_clip2, SILENCE])
for rtrString in split_rtr:
factor = len(rtrString) / sum_rtr_lines
path = IMG_DIR + str(comment.id) + '.2' + '.%s.png' % split_rtr.index(rtrString)
clip = ImageClip(path).set_duration(factor * a_clip2.duration)
i_clip2.append(clip)
# print(path)
s2 = '\n\t\tdone rtr: ' + str(comment.id)
i_clip2 = concatenate_videoclips(i_clip2)
i_clip2 = i_clip2.set_audio(a_clip2)
c_clip.append(i_clip2)
else:
s2 = ''
pass
c_clip.append(TRANSITION)
c_clip = concatenate_videoclips(c_clip)
print(s0, end='')
print(s1, end='')
print(s2, end='')
return c_clip
def create_sub(global_replace, audio_replace):
"""
Function: create_sub
Definition: This function combines all steps previously done
The function creates an image for the submission, converts the body text of the post to audio,
then, the program creates a clip from the photo and audio
Parameter: NONE
Return: NONE
"""
size = 20
width = 180
subreddit = str(reddit_post.subreddit)
body_nolinks = re.sub(r"\[(.+)\]\(.+\)", r"\1", reddit_post.body)
body_nolinks = re.sub(r'https?:\/\/.*[\r\n]*', '', body_nolinks)
body_nolinks = replace_me(body_nolinks, global_replace[0], global_replace[1])
author_font = ImageFont.truetype(AUTHOR_FONT_PATH, 15)
score_font = ImageFont.truetype(SCORE_FONT_PATH, size - 3)
title_font = ImageFont.truetype(TITLE_FONT_PATH, size)
body_font = ImageFont.truetype(BODY_FONT_PATH, size - 2)
sub_font = ImageFont.truetype(SUB_FONT_PATH, size - 6)
footer_font = ImageFont.truetype(FOOTER_FONT_PATH, size - 6)
formatted_title = textwrap.wrap(reddit_post.title, width=width)
formatted_body = textwrap.wrap(body_nolinks, width=width + 8)
post_date_by = 'submitted ' + human_time(reddit_post.created) + ' by '
formatted_points = str(abbreviate_number(reddit_post.score)).replace('.0', '')
# Specify all variables
line_spacing = 28
more_spacing = line_spacing
small_space = 5
medium_space = 12
large_space = 35
indent_spacing = 65
line_height = 0
sub_height = (15 + line_height + len(formatted_title) * line_spacing + 2 * small_space + large_space +
len(formatted_body) * line_spacing + 2 * medium_space)
sub_img = Image.new('RGBA', (1920, sub_height), IMG_COLOR) # from #222222
sub_draw = ImageDraw.Draw(sub_img)
# Draws rectangle at current height
sub_draw.rectangle(
[(indent_spacing, line_height), (1920 - 10,
15 + line_height + len(
formatted_title) * line_spacing + 2 * small_space + large_space
+ len(formatted_body) * line_spacing + 2 * medium_space)], fill='#373737')
# Draws the score and icon
point_len = len(formatted_points.replace('.', ''))
indent = 5 * (5 - point_len)
sub_img.paste(SUB_SCORE_ICON, (15, line_height + 2), SUB_SCORE_ICON)
sub_draw.text((indent, line_height + 26), formatted_points, font=score_font, fill=BIG_SCORE_HEX)
# Writes each line in the title @
for line in formatted_title:
sub_draw.text((indent_spacing, line_height), line, font=title_font, fill=TITLE_HEX)
if line == formatted_title[-1]:
the_sizex, the_sizey = title_font.getsize(formatted_title[-1])
sub_draw.text((indent_spacing + the_sizex + 5, line_height + 5), f'(self.{str(reddit_post.subreddit)})',
font=sub_font, fill='#888888')
line_height = line_height + line_spacing
del line
# Adds spacing then writes the post date and author
line_height += small_space
sub_draw.text((indent_spacing, line_height), post_date_by, font=author_font, fill=TIME_HEX)
rrx, rry = author_font.getsize(post_date_by)
sub_draw.text((indent_spacing + rrx, line_height), ' ' + str(reddit_post.author), font=author_font, fill=AUTHOR_HEX)
line_height += small_space
temp = BACKGROUND.copy()
filename = TXT_DIR + 'title.txt'
with open(filename, 'w', encoding='utf-8') as title_txt: # for some reason as of 6/17/19 1:10 AM IT NEEDS ENCODING
title_txt.write(replace_me(reddit_post.title, audio_replace[0], audio_replace[1], use_for_audio=True))
formatted_sub = subreddit.replace('_', ' ').replace('AmItheAsshole', 'Am I The Asshole')
formatted_sub = re.sub(r"(\w)([A-Z])", r"\1 \2", formatted_sub)
formatted_sub = f'r/ {formatted_sub}'
with open(TXT_DIR + 'sub_text.txt', 'w', encoding='utf-8') as sub_txt:
sub_txt.write(formatted_sub)
os.chdir(BALCON_DIR) # changes command line directory for the balcon utility
txt_file = 'title.txt'
wav_file = 'title.wav'
balcom = f'balcon -f "Subs\\Sub1\\Txt\\{txt_file}" -w "Subs\\Sub1\\Wav\\{wav_file}" -n "ScanSoft Daniel_Full_22kHz"'
os.system(balcom)
while not os.path.isfile(WAV_DIR + 'title.wav'):
time.sleep(.12)
os.chdir(BALCON_DIR) # changes command line directory for the balcon utility
txt_file = 'sub_text.txt'
wav_file = 'sub_text.wav'
balcom = f'balcon -f "Subs\\Sub1\\Txt\\{txt_file}" -w "Subs\\Sub1\\Wav\\{wav_file}" -n "ScanSoft Daniel_Full_22kHz"'
os.system(balcom)
while not os.path.isfile(WAV_DIR + 'sub_text.wav'):
time.sleep(.12)
sub_aclip = AudioFileClip(WAV_DIR + 'sub_text.wav')
title_aclip = AudioFileClip(WAV_DIR + 'title.wav')
title_aclip = concatenate_audioclips([sub_aclip, SILENCE, title_aclip, SILENCE])
if reddit_post.body != '':
# Draws a rectangle at line spacing + large space
# large_space - small_space is used to negate the previous addition to line height
len_body = len(formatted_body)
line_height += large_space
sub_draw.rectangle([indent_spacing, line_height - medium_space, 1920 - 100, small_space + line_height +
len_body * line_spacing], fill=None, outline='#cccccc', width=1)
body_iclips = []
filename = TXT_DIR + 'body.txt'
body_txt_file = open(filename, 'w',
encoding='utf-8') # for some reason as of 6/17/19 1:10 AM IT NEEDS ENCODING
body_txt_file.write(replace_me(body_nolinks, audio_replace[0], audio_replace[1], use_for_audio=True))
body_txt_file.close()
os.chdir(BALCON_DIR) # changes command line directory for the balcon utility
txt_file = 'body.txt'
wav_file = 'body.wav'
balcom = f'balcon -f "Subs\\Sub1\\Txt\\{txt_file}" -w "Subs\\Sub1\\Wav\\{wav_file}" -n "ScanSoft Daniel_Full_22kHz"'
os.system(balcom)
while not os.path.isfile(WAV_DIR + 'body.wav'):
time.sleep(.12)
body_aclip = AudioFileClip(WAV_DIR + 'body.wav')
sum_body = sum(len(fff) for fff in formatted_body)
temp.paste(sub_img, (0, 540 - int(.5 * sub_height)), sub_img)
temp.save(IMG_DIR + 'title.png')
title_vclip = ImageClip(IMG_DIR + 'title.png').set_audio(title_aclip).set_duration(title_aclip.duration)
# Creates Text Body
for line in formatted_body:
index = formatted_body.index(line)
sub_draw.text((indent_spacing + 10, line_height), line, font=body_font, fill='#dddddd')
line_height = line_height + line_spacing
if line == formatted_body[-1]:
line_height += medium_space
sub_draw.text((indent_spacing, line_height), TITLE_FOOTER, font=footer_font, fill=FOOTER_HEX)
temp.paste(sub_img, (0, 540 - int(.5 * sub_height)), sub_img)
temp.save(IMG_DIR + f'body.{index}.png')
factor = len(line)/sum_body
# print(str(factor))
body_iclips.append(ImageClip(IMG_DIR + f'body.{index}.png').set_duration(factor * body_aclip.duration))
del line
body_iclip = concatenate_videoclips(body_iclips)
body_vclip = body_iclip.set_audio(body_aclip)
body_vclip = concatenate_videoclips([title_vclip, body_vclip, TRANSITION])
return body_vclip
else:
# Places Space Then Draws Footer
line_height += medium_space + more_spacing
sub_draw.text((indent_spacing, line_height), TITLE_FOOTER, font=footer_font, fill=FOOTER_HEX)
temp.paste(sub_img, (0, 540 - int(.5 * sub_height)), sub_img)
temp.save(IMG_DIR + 'title.png')
title_iclip = ImageClip(IMG_DIR + 'title.png').set_duration(title_aclip.duration)
title_vclip = title_iclip.set_audio(title_aclip)
title_vclip = concatenate_videoclips([title_vclip, TRANSITION])
return title_vclip
def cleanup():
"""
Function: cleanup()
Definition: This function deletes all directions involved in the creation of the video
(excluding supplementary directories that house the fonts and icons)
The function also recreates the directories, however, they will be empty
the function also contains a global variable del_vid which determines whether we delete the video
Parameter: NONE
Return: NONE
"""
global del_vid
shutil.rmtree(IMG_DIR)
print('Removed IMG')
time.sleep(.05)
os.mkdir(IMG_DIR)
print("Created IMG")
shutil.rmtree(TXT_DIR)
print('Removed TXT')
time.sleep(.05)
os.mkdir(TXT_DIR)
print('Created TXT')
shutil.rmtree(WAV_DIR)
print('Removed WAV')
time.sleep(.05)
os.mkdir(WAV_DIR)
print('Created WAV')
if os.path.isfile('Upload/Final.mp4'):
os.remove('Upload/Final.mp4')
print('Removed Vid Copy')
if os.path.isfile('Upload/thumb.png'):
os.remove('Upload/thumb.png')
print('Removed Thumb Copy')
if not os.path.isdir(VID_DIR):
os.mkdir(VID_DIR)
print("VID DNE ... Making VID")
if del_vid and os.path.isdir(VID_DIR):
shutil.rmtree(VID_DIR)
print('Removed VID')
time.sleep(.05)
os.mkdir(VID_DIR)
print("Created VID")
del_vid = False
def create_thumbnail():
"""
Function: create_thumbnail
Definition: This function uses the PIL Library to draw a easily readable thumbnail
Parameter: NONE
Return: NONE
"""
def color_options():
"""
Function: color_options
Definition: Adjust color to user input for preferred background color
Parameter: NONE
Return: NONE
"""
global bgrd_choice
if bgrd_choice == 0:
color = 0
elif bgrd_choice == 1:
color = '#222222'
elif bgrd_choice == 2:
color = 'black'
else:
print('Choice is not recognized reverting to defaults')
color = '#222222'
return color
# date = datetime.datetime.fromtimestamp(submission.created_utc)
# dif = datetime.datetime.utcnow() - date
# print(dif)
sub_time = reddit_post.created
subreddit = 'r/' + str(reddit_post.subreddit)
author = 'u/' + str(reddit_post.author)
score = int(reddit_post.score)
num_com = int(reddit_post.num_com)
title = reddit_post.title.replace('/', ' ').replace('[', '').replace(']', '')
if custom_title != '0':
title = custom_title
thumbnail = Image.new('RGBA', (1920, 1080), color_options()) # from #222222
thumb_draw = ImageDraw.Draw(thumbnail)
width = 31
formatted_title = textwrap.wrap(title, width=width)
icon_w, icon_h = ASKREDDIT_ICON.size
size = 90
sub_font = ImageFont.truetype('CustFont/NimbusSanL-Reg.ttf', 75)
author_font = ImageFont.truetype('CustFont/NimbusSanL-Bol.ttf', 45)
score_font = ImageFont.truetype('CustFont/NimbusSanL-Bol.ttf', 60)
base_height = 210
line_spacing = 90
indent_spacing = 40
point_x, point_y = -40, 720
# thumbnail.paste(COMMENT_ICON, (300, 850), COMMENT_ICON)
# thumbnail.paste(UPDOWNVOTE, (point_x, point_y), UPDOWNVOTE)
thumbnail.paste(ASKREDDIT_ICON, (40, 40), ASKREDDIT_ICON)
thumb_draw.text((icon_w + indent_spacing + 30, 120), f'submitted {human_time(sub_time)} by {author}',
font=author_font, fill='#818384')
thumb_draw.text((icon_w + indent_spacing + 30, 40), subreddit, font=sub_font)
# thumb_draw.text((90, 910), str(abbreviate_number(score)), font=score_font, fill='#FF8C60')
# thumb_draw.text((500, 900), str(abbreviate_number(num_com)) + ' Comments', font=score_font, fill='#818384')
line_height_thumb = base_height
# print(str(len(formatted_title) * (size + line_spacing)))
count_1 = 0
count_2 = 0
min_b, max_b = 1180, 1400 # From 1020, 1200
while not min_b <= len(formatted_title) * (size + line_spacing) <= max_b:
while len(formatted_title) * (size + line_spacing) >= max_b:
count_1 = count_1 + 1
size = size - 2
line_spacing = line_spacing - 2
width = width + .8
formatted_title = textwrap.wrap(title, width=width)
if count_1 >= 35:
break
while len(formatted_title) * (size + line_spacing) <= min_b:
count_2 = count_2 + 1
size = size + 2
line_spacing = line_spacing + 2
width = width - .8
formatted_title = textwrap.wrap(title, width=width)
if count_2 >= 35:
break
if count_1 >= 35:
break
if count_2 >= 35:
break
# print(str(len(formatted_title) * (size + line_spacing)))
# print(count_1, count_2)
for line in formatted_title:
body_font = ImageFont.truetype('CustFont/American_Captain.ttf', size)
draw_outlined_text(indent_spacing, line_height_thumb, thumb_draw, body_font, line, width=3)
line_height_thumb = line_height_thumb + line_spacing
# thumbnail.show()
thumbnail.save(VID_DIR + 'thumb.png')
# draw.text((indent, com_img_height - 25), footer_parent, font=author_font, fill="#828282")
# img.paste(commentUpDownIcon, (arrow_indent, 13), commentUpDownIcon)
def data_collection():
"""
Function: data_collection
Definition: Appends all function data to a csv file
Parameter: NONE
Return: NONE
"""
csv_row = [str(get_sum_chars()), str(final.duration), str(number_comments), str(threshold), str(datetime.datetime.now()),
str(reddit_link)]
with open('program_data.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(csv_row)
def dynamic_music():
"""
Function: dynamic_music
Definition: This function reads all mp3 files in the dynamic music directory and shuffles them.
The info on the shuffled list is also saved for the description.
The lower bound for the lengths of the concatenated songs will be the estimated time * 1.1.
Parameter: NONE
Return: NONE
"""
global song_sound
global sound_desc
song_sound = []
song_info = []
mp3_dir = os.path.dirname(os.path.abspath('Static/DynamicMusic/DynamicMusic.txt')) + '\\*.mp3'
music_files = glob.glob(mp3_dir)
shuffle(music_files)
dur_counter = 0
for song in music_files:
mp3 = MP3File(song)
mp3.set_version(VERSION_2)
artist = mp3.__getattribute__('artist')
title = mp3.__getattribute__('song')
index = music_files.index(song)
song_sound.append(AudioFileClip(song))
dur_counter = dur_counter + song_sound[index].duration
info = '\nSong: ' + title + \
'\nArtist: ' + artist + \
'\nTimestamp: ' + minute_format(dur_counter - song_sound[index].duration, 0) + \
'\n'
song_info.append(info)
if dur_counter > estimated_time * 1.1:
break
song_sound = concatenate_audioclips(song_sound)
song_sound = song_sound.volumex(.0875)
sound_desc = ''.join(song_info)
df = pd.read_csv('MLData.csv')
reg = linear_model.LinearRegression()
reg.fit(df[['char_len', 'num_com', 'threshold']], df.duration)
def estimate_time(char_sum):
"""
Function: estimate_time
Definition: Adds up the total number of characters in the entirity of the video and comes up with a time
estimate in seconds.
Parameter: Integer
Return: Double
"""
x = round(reg.predict([[char_sum, number_comments, threshold]])[0], 5)
return x
def video_creation(comment):
"""
Function: video_creation
Definition: Thus appends clips to the clip array, the function also makes sure the files neccesary have
already been created
Parameter: RedditItem
Return: NONE
"""
create_txt(comment, [audio_replace_txt, audio_replace_txt_with])
create_wav(comment)
create_img(comment)
# createAudioClip(comment)
sp0 = WAV_DIR + str(comment.id) + '.0.wav'
sp1 = WAV_DIR + str(comment.id) + '.1.wav'
sp2 = WAV_DIR + str(comment.id) + '.2.wav'
# print(sp0)
# print(sp1)
# print(sp2)
while not os.path.isfile(sp0):
print(sp0)
time.sleep(.3)
print("waiting for comment:" + comment.id)
if use_reply(comment):
while not os.path.isfile(sp1):
time.sleep(.3)
print("waiting for reply:" + comment.id)
else:
pass
if use_rtr(comment):
while not os.path.isfile(sp2):
time.sleep(.3)
print("waiting for comment:" + comment.id)
else:
pass
# time.sleep(3)
main_clips.append(create_clip(comment))
def metadata():
"""
Function: metadata
Definition: generates video metadata and writes it to a file
Parameter: NONE
Return: NONE
"""
str_tag = (
'reddit, best of ask reddit, reddit, ask reddit top posts, r/story, r/ askreddit, r/askreddit, story time, '
'reddify, bamboozled, brainydude, '
'reddit watchers, best posts & comments, reddit, askreddit, USER'
)
data = {
'title': reddit_post.title + ' (r/AskReddit)',
'description': f'r/{str(reddit_post.subreddit)} Videos! Welcome back to a brand new USER video!'
'\n\n Dont forget to like and subscribe'
'\n'
'\n I love to upload New daily videos to keep yall entertained'
'\n'
'\n🎧♪♫ [Track List] ♫♪🎧 '
f'\n{sound_desc}\n'
'\nOutro Template made by Grabster - Youtube.com/GrabsterTV'
'\n'
f'\nSubreddits used: r/{str(reddit_post.subreddit)}'
'\n'
'\n#reddit #askreddit #askredditscary'
'\n'
'\n--- Tags ---'
'\n' + str_tag,
'tags': [x.strip() for x in str_tag.split(',')],
'privacyStatus': 'private',
# 'embeddable': 'true',
# 'license': "creativeCommon",
# 'publicStatsViewable': 'true',
# 'publishAt': '2017-06-01T12:05:00+02:00',
# 'categoryId': '10',
# 'recordingdate': str(datetime.date),
# 'location': {
# 'latitude': 48.8584,
# 'longitude': 2.2945
}
# print(data['description'])
with open(UPLOADER_DIR + 'data.json', 'w') as f:
json.dump(data, f)
with open(VID_DIR + 'description.txt', 'w', encoding='utf-8') as desc:
desc.write(data['description'])
def upload_video(vi):
"""
** WORK IN PROGRESS **
Function: upload video
Definition: The program create a command to run the upload to youtube command line utility
Parameter: NONE
Return: NONE
"""
shutil.copy2(VID_DIR + VIDEO_FILENAME, UPLOADER_DIR)
shutil.copy2(VID_DIR + 'thumb.png', UPLOADER_DIR)
command = []
os.chdir(UPLOADER_DIR)
command.append('youtubeuploader_windows_amd64 ')
command.append('-filename ' + VID_NAME + VID_EXTENSION + ' ')
command.append('-thumbnail ' + 'thumb.png ')
command.append('-metaJSON string ' + 'data.json')
command = ''.join(command)
os.system(command)
print(command)
def get_sum_chars():
"""
Function: get_sum_chars
Definition: This function uses the currently set number of comments and threshold (indirectly) to determine the
sum of the charaters that we plan to use.
Parameter: NONE
Return: Integer
"""
char_sum = len(str(reddit_post.title)) + len(reddit_post.body)
for comment in reddit_post.children:
if comment.id+1 > number_comments:
break
char_sum = char_sum + len(comment.body)
if use_reply(comment):
char_sum += len(comment.child.body)
if use_rtr(comment):
char_sum += len(comment.child.child.body)
return char_sum
if __name__ == '__main__':
# Initialize useful lists
main_clips = []
# Replacement lists
audio_replace_txt, audio_replace_txt_with = ['’', '‘', '”', '“', '*', ';', '^', '\\', '/', '_'], \
["'", "'", '"', '"', '', '', '', '', '', ' ']
visual_replace_txt, visual_replace_text_with = [], []
global_replace_txt, global_replace_text_with = ['​'], ['']
extend_replacement_list(audio_replace_txt, audio_replace_txt_with, visual_replace_txt, visual_replace_text_with,
global_replace_txt, global_replace_text_with)
del_vid = True
cleanup()
create_thumbnail()
# This block is used for getting the video length within a certain range
estimated_time = estimate_time(get_sum_chars())
print(f'\nMaximum Video Length is: {minute_format(estimated_time)} or {str(estimated_time)}s')
if desired_length > estimated_time:
desired_length = estimated_time
print(
f'\nInput exceeds maximum time of {estimated_time}s for this reddit post, setting time to {estimated_time}')
while estimate_time(get_sum_chars()) > desired_length:
number_comments -= 1
num = estimate_time(get_sum_chars())
if estimate_time(get_sum_chars()) <= desired_length:
break
threshold += .04
num = estimate_time(get_sum_chars())
if estimate_time(get_sum_chars()) <= desired_length:
break
num = estimate_time(get_sum_chars())
if threshold > .8:
threshold = .3 # reset threshold if it gets too high
estimated_time = estimate_time(get_sum_chars())
print(f'Estimated Video Length is: {minute_format(estimated_time)} or {str(estimated_time)}s')
print(f'Number of Comments: {number_comments}')
print(f'Threshold: {threshold}')
print(f'Subreddit: {reddit_post.subreddit}')
dynamic_music()
final = [create_sub( [global_replace_txt, global_replace_text_with], [audio_replace_txt, audio_replace_txt_with] )]
# Used for multithreading purposes if the option is selected
threads = [] # 'thread' is used to keep track of all running threads so that they can be joined
if is_single_threaded == 0:
for comment in reddit_post.children:
if comment.id + 1 > number_comments:
break
job = threading.Thread(target=video_creation, args=(comment,))
threads.append(job)
threads[comment.id].start()
for comment in reddit_post.children:
if comment.id + 1 > number_comments:
break
threads[comment.id].join()
else:
for comment in reddit_post.children:
if comment.id + 1 > number_comments:
break
video_creation(comment)
# This combines all the clips created in the multithreaded workload to one video and sets the audio to the dynamic
# audio
shuffle(main_clips)
final.extend(main_clips)
final.append(OUTRO)
final = concatenate_videoclips(final)
background_music = song_sound.set_duration(final.duration)
final_audio = CompositeAudioClip([final.audio, background_music])
final = final.set_audio(final_audio)
# Used to compare the estimated video length the the actual length
percent_difference = round(100 - (abs(estimated_time / final.duration) * 100), 2)
if percent_difference > 0:
percent_difference = '+' + str(percent_difference)
else:
percent_difference = str(percent_difference)
time_difference = final.duration - estimated_time
formatted_diff = minute_format(time_difference)
if float(time_difference) > 0:
formatted_diff = '+' + formatted_diff
else:
pass
print(f'\n \nActual Video Length is: {minute_format(final.duration)} / {str(final.duration)}s. '
f'Shifted {formatted_diff} / {str(percent_difference)}% from {minute_format(estimated_time)} / '
f'{str(estimated_time)}s\n')
final.write_videofile(VID_DIR + VIDEO_FILENAME, fps=VID_FPS, threads=16, preset='ultrafast')
metadata()
# upload_video()
# Collects data to help improve the program's predictions
data_collection()
print('\n')
cleanup()
print('\nClosing in 10 seconds')
time.sleep(10)
<file_sep>/README.md
# Red to You
RedToYou is a python-based program that aims to convert reddit threads to interactive videos suitable for personal viewing or alternatively uploading to YouTube (hence the name Red(dit)ToYou(tube))
# Setup
Before running the program, it is required that the user installs python as well as pip (pythons package manager)
After installing python and pip you will need to install the following python libraries:
praw (library for interacting with reddit's API)
PIL (library for image creation)
time
datetime
shutil (for file deletion)
re
glob (to import files matching a specific pattern)
random
threading (for multi-threading)
timeit (AI is used to calculate the length of time it will take to render the video based on number gathered from this library)
json
csv (AI is fed a CSV)
pandas (used in AI)
sklearn (AI Engine)
mp3_tagger (gets information from the mp3 files in the mp3 folder)
itertools
In addition, you will need to provide your own NewError.mp4 (transiton) and outro.mp4 (video outro) in the Static folder as well as populate your own tagged music (mp3) in Static/DynamicMusic
# Using the Program
Upon launching the program, the user will be asked whether they would like to have their video created using the classic version of reddit or the redesigned version of reddit
Simply type 1 or 0 for your preferred mode
Next the user will be asked if they would like to run the program in single threaded or multithreaded mode.
It is recommended that users with ram amounts below 16GB run the program in single threaded mode to minimize the number of objects in memory
After, the user will be prompted to enter and upper bound for their desired video length (the ai will run until it finds which posts to include to get a time in the acceptable range. It is recommended that the user enter a number roughly 30 secs higher than the time they desire
The next option, backgrounds color, is only applicable to users who plan on uploading their video to the web. The prompt asks the user what color background they would like their YouTube thumbnail, to be.
Next the user is prompted for a title they would like for their thumbnail, this is only needed when the title of the post exceeds 100 characters causing the text to drop off the image

# What is Happening ?
The program first starts by gathering data from the reddit link that the user has inserted. Then the program calculates the length in time that it estimates the Text to Speech API will take to read text file based on the sklearn python prediction library. A loop is then created and is run until the program finds a satisfactory time for the program.
Once this step is done, the program creates temporary files used in the creation of the video file. The program also cleans up the previous folder in the case that the program didn’t exit successfully the first time.

After that, the user is informed what the maximum length of the video would be if the user had not limited to program to what they passed to the program.

Next the AI engine runs and calculates how long it would take the Text to speech engine to read the saved text files

Next the program show the user the estimated video length as well as how many reddit comments the video will include
>threshold : threshold multiplied by the upvote value of the parent comment gives the minimum value a reply needs to be included in the video

The program also gives the user feedback as the program progresses
* If the user uses multithreaded processes these numbers will be out of order, however, shorter comments will appear first in the video
* If the user uses single threaded, comments will match the order they appear in the thread
* In both cases, however the program scrambles the order in with the comments appear
Because video and audio as computed separatly, we can give the user that actual video length quickly, before the video begins to render, this givse the user to option to quit the program and enter an alternate value before waiting for the file to render.

After, the video is built using the images created from the PIL Library as well as the audio from the TTS library.

Then, the program finishes running

After navigating to Subs/Vid we see the following:

The video file is saved as the video’s unique identifier
# Additional Information
After the program runs, diagnostic information such as the total number of characters in the program as well as the programs duration are saved into a csv file which we feed into our learning tool, thus the program gets better and better at predicting video length over time

Because the program is built to be used by youtubers, the program also generates a description file with can the easily copied into YouTube

The program as present relies on a windows-only command line utility called Balcon meaning there is no Linux support planned.
# Roadmap
Beta version
* Support for multiple submissions
* Direct upload to youtube
* Command line arguments
* Combine RedditItem and RedditTitle User Class
* Create settup file which automatically installs required libraries
Full version
Red-To-You 1.0 - rich GUI
Red-To-You 2.0 - fully automated video upload
* The user will be able to setup the prgram to pull top posts from reddit and have the upload to youtube at set intervals throughout the day.
<file_sep>/Static/DynamicMusic/readme.txt
Add backgorund music here
|
8972d3eb79b8aa5c6a166ad1709c841318ed6c78
|
[
"Markdown",
"Python",
"Text"
] | 3 |
Python
|
dimitrinaama/Red-To-You
|
bb74c2043d1f2b9eb2fcc95eaa9ef2d435882e6c
|
9de70d89a6fad4139c8266428899ad5290c4a618
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// homework2
//
// Created by user160572 on 10/31/19.
// Copyright © 2019 user160572. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
count = UserDefaults.standard.integer(forKey: "count")
label.text = "Score: \(count), click one more!"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func button(_ sender: Any) {
count = count + 1
label.text = "Score: \(count), click one more!"
UserDefaults.standard.set(count, forKey: "count")
}
@IBAction func reset(_ sender: Any) {
count = 0
UserDefaults.standard.removeObject(forKey: "count")
label.text = "Score: \(count), click one more!"
}
}
|
490086b5982ea87639090e777b97d67c267a2bbf
|
[
"Swift"
] | 1 |
Swift
|
emuuul/homework
|
7a284a017f72c23357b86ce66dac42d2c48e4bcd
|
86618bbb483f456cda7e7bbc4fbe95f4694a3b6e
|
refs/heads/master
|
<repo_name>sheronov/TestComposerPackage<file_sep>/src/WebRush/Status.php
<?php
namespace WebRush;
class Status
{
private const SUCCESS_CODE = 200;
public static function getStatus(): string
{
return 'All services are work normally.';
}
public static function getStatusCode(): int
{
return self::SUCCESS_CODE;
}
}
|
c698841ed945d386593b04a33a649647a8b297a6
|
[
"PHP"
] | 1 |
PHP
|
sheronov/TestComposerPackage
|
5a6e13495d735cf70c1fe764390e7e8c98274552
|
9d2845811650ff7fe9b720b0640e20bac36a681b
|
refs/heads/master
|
<repo_name>dpgc11/DsAndAKt<file_sep>/src/sort/InsertionSort.kt
package sort
class InsertionSort {
companion object {
fun printArray(arr: IntArray) {
for (i in 0 until arr.size) {
print("${arr[i]}\t")
}
println()
}
}
fun sort(arr: IntArray) {
for (i in 1 until arr.size) {
val key = arr[i]
var j = i - 1
/*
Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position
*/
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]
j -= 1
}
arr[j + 1] = key
}
}
}
fun main() {
val arr = intArrayOf(12, 11, 13, 5, 6)
val ob = InsertionSort()
ob.sort(arr)
InsertionSort.printArray(arr)
}
<file_sep>/src/programs/array/ClosestPair.kt
package programs.array
import kotlin.math.abs
// This class will store the result
data class Pair(var i: Int, var j: Int)
// ar1[0..m-1] and ar2[0..n-1] are two given sorted
// arrays/ and x is given number. This function prints
// the pair from both arrays such that the sum of the
// pair is closest to x.
// Brute Force Approach
fun printClosest(ar1: IntArray, ar2: IntArray, m: Int, n: Int, x: Int) {
// init the result
val pair = Pair(ar1[0], ar2[0])
var difference = Int.MAX_VALUE
for (i in 0 until ar1.size) {
for (j in 0 until ar2.size) {
val tempDifference = abs(x - (ar1[i] + ar2[j]))
println("Temp difference between ${ar1[i]} and ${ar2[j]} is $tempDifference")
if (tempDifference < difference) {
pair.i = ar1[i]
pair.j = ar2[j]
difference = tempDifference
}
}
}
// Print the result
println("The closest pair are: ${pair.i} and ${pair.j}")
}
fun main(args: Array<String>) {
val ar1 = intArrayOf(1, 4, 5, 7)
val ar2 = intArrayOf(10, 20, 30, 40)
val m = ar1.size
val n = ar2.size
val x = 38
printClosest(ar1, ar2, m, n, x)
}<file_sep>/src/programs/array/ReverseArray.kt
package programs.array
import java.util.*
// Complete the reverseArray function below.
fun reverseArray(a: Array<Int>): Array<Int> {
val result = Array<Int>(a.size) { 0 }
var initialFlag = 0
for (i in a.size - 1 downTo 0) {
result[initialFlag] = a[i]
initialFlag += 1
}
return result
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val arrCount = scan.nextLine().trim().toInt()
val arr = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
val res = reverseArray(arr)
println(res.joinToString(" "))
}
<file_sep>/src/sort/BubbleSort.kt
package sort
fun bubbleSort(arr: IntArray) {
var temp: Int
val n = arr.size
var swapped: Boolean
for (i in 0 until n - 1) {
swapped = false
for (j in 0 until n - i - 1) {
if (arr.get(j) > arr.get(j + 1)) { // swap arr[j] and arr[j+1]
temp = arr.get(j)
arr.set(j, arr.get(j + 1))
arr.set(j + 1, temp)
swapped = true
}
}
// If no two elements were
// swapped by inner loop, then break
if (swapped == false) break
}
}
/* Prints the array */
fun printArray(arr: IntArray) {
for (i in 0 until arr.size) {
print("${arr.get(i)} \t")
}
println()
}
fun main() {
val arr: IntArray = intArrayOf(64, 34, 25, 12, 22, 11, 90)
println("Initial array")
printArray(arr)
bubbleSort(arr)
println("Sorted array")
printArray(arr)
}
<file_sep>/src/programs/linkedList/GetNodeValue.kt
package programs.linkedList
import java.util.*
// Complete the getNode function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* data: Int
* next: SinglyLinkedListNode
* }
*
*/
fun getNode(_llist: SinglyLinkedListNode?, positionFromTail: Int): Int {
var result = -1
var llist = _llist
/**
* 2 pointer method START
*/
var main_ptr: SinglyLinkedListNode? = _llist
var ref_ptr: SinglyLinkedListNode? = _llist
var count = 0
if (_llist != null) {
while (count <= positionFromTail) {
// if (ref_ptr == null) {
// return
// }
ref_ptr = ref_ptr?.next
count++
}
while (ref_ptr != null) {
main_ptr = main_ptr!!.next
ref_ptr = ref_ptr.next
}
if (main_ptr != null)
result = main_ptr.data
}
/**
* END
*/
/**
* Length of LL start
*/
// // 0 1 2 3 4 indexes
// // 5 4 3 2 1 values
// // size - (positionFromTail + 1) from the start will give the item at positionFromTail when size is known
// // 5 - (3 + 1) = 1
// var count = 0
// // find the size of the LL
// while (llist != null) {
// llist = llist.next
// count++
// }
// llist = _llist
// // deduce the positionFromStart using the formula
// val positionFromStart = count - (positionFromTail + 1)
// println("positionFromStart: $positionFromStart")
// // get the value at positionFromStart
// for (i in 0 until positionFromStart) {
// llist = llist?.next
// }
// // assign the value to result
// if (llist != null) {
// result = llist.data
// }
/**
* END
*/
return result
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val tests = scan.nextLine().trim().toInt()
for (testsItr in 1..tests) {
val llistCount = scan.nextLine().trim().toInt()
val llist = SinglyLinkedList()
for (i in 0 until llistCount) {
val llist_item = scan.nextLine().trim().toInt()
llist.insertNode(llist_item)
}
val position = scan.nextLine().trim().toInt()
val result = getNode(llist.head, position)
println(result)
}
}<file_sep>/src/programs/array/SubarraySum.kt
package programs.array
/*
Returns true if there is a subarray of arr[] with a sum equal to
'sum' otherwise returns false. Also, prints the result
*/
fun subarraySumBruteForce(arr: IntArray, n: Int, sum: Int): Boolean {
var result = false
var currentSum = -1
// Pick a starting point
for (i in 0 until n) {
currentSum = arr[i]
// try all subarrays starting with 'i'
for (j in i + 1..n) {
if (currentSum == sum) {
val p = j - 1
println("Sum found between indexes $i and $p")
result = true
return result
}
if (currentSum > sum || j == n) {
break
}
currentSum = currentSum + arr[j]
}
}
println("No subarray found")
return result
}
/*
Returns true if there is a subarray of arr[] with a sum equal to
'sum' otherwise returns false. Also, prints the result
*/
fun subarraySumEfficient(arr: IntArray, n: Int, sum: Int): Boolean {
var result = false
var currentSum = arr[0]
var start = 0
// Pick a starting point
for (i in 1..n) {
// if currentSum exceeds the sum, then remove the starting elements
while (currentSum > sum && start < i - 1) {
currentSum -= arr[start]
start++
}
// if currentSum becomes equal to sum, then return true
if (currentSum == sum) {
val p = i - 1
println("Sum found between indexes $start and $p")
result = true
return result
}
// add this element to currentSum
if (i < n) {
currentSum += arr[i]
}
}
println("No subarray found")
return result
}
fun main() {
val arr = intArrayOf(15, 2, 4, 8, 9, 5, 10, 23)
val n = arr.size
val sum = 23
subarraySumEfficient(arr, n, sum)
}
<file_sep>/src/sort/SelectionSort.kt
package sort
class SelectionSort {
fun sort(arr: IntArray) {
val n = arr.size
// One by one move boundary of unsorted subarray
for (i in 0 until n - 1) {
// Find the minimum element in unsorted array
var minIdx = i
for (j in i + 1 until n) {
if (arr[j] < arr[minIdx]) {
minIdx = j
}
}
// Swap the found minimum element with the first element
val temp = arr[minIdx]
arr[minIdx] = arr[i]
arr[i] = temp
}
}
}
fun main() {
val ob = SelectionSort()
val arr = intArrayOf(64, 25, 12, 22, 11)
ob.sort(arr)
println("Sorted array")
printArray(arr)
}
<file_sep>/src/programs/array/PushZero.kt
package programs.array
class PushZero {
companion object {
// function which pushes all zeroes to end of an array
fun pushZeroesToEnd(arr: IntArray, n: Int) {
// count of non-zero elements
var count = 0
// Traverse the array. IF element encountered is
// non-zero, then replace the element at index 'count'
// with this element
for (i in 0 until n) {
if (arr[i] != 0) {
// here count in incremented
arr[count++] = arr[i]
}
}
// Now all non-zero elements have been shifted to
// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while (count < n) {
arr[count++] = 0
}
}
}
}
fun main() {
val arr = intArrayOf(1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9)
val n = arr.size
PushZero.pushZeroesToEnd(arr, n)
println("Array after pushing zeroes to the back: ")
for (i in 0 until n) {
print("${arr[i]}\t")
}
}<file_sep>/src/programs/array/DynamicArray.kt
package programs.array
/*
* Complete the 'dynamicArray' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER n
* 2. 2D_INTEGER_ARRAY queries
*/
fun dynamicArray(n: Int, queries: Array<Array<Int>>): Array<Int> {
// Write your code here
// init values
var lastAnswer = 0
val queryMap = emptyMap<Int, List<Int>>().toMutableMap()
var result = emptyArray<Int>().toMutableList()
for (i in 0 until n) {
queryMap[i] = emptyList<Int>().toMutableList()
}
// queryMap.forEach { (key, value) -> println("$key = $value") }
// loop through the queries
for (query in queries) {
// println("query type ${query[0]}")
// check for the query type in the zeroth element of the query
when (query[0]) {
// query type 1
1 -> {
val seq = getSequence(query, lastAnswer, n)
// println("query type 1: seq: $seq")
val temp = queryMap.get(seq)!!.toMutableList()
// println("seq size before adding '${query[2]}' is ${temp.size}")
temp.add(query[2])
// println("seq size after adding ${temp.size}")
queryMap.put(seq, temp)
// for (j in temp) {
// print("$j ")
// }
// queryMap.forEach { (key, value) -> println("$key = $value") }
}
// query type 2
2 -> {
val seq = getSequence(query, lastAnswer, n)
// println("query type 2: seq: $seq")
val temp = queryMap[seq]!!
val index = query[2] % temp.size
lastAnswer = temp[index]
result.add(lastAnswer)
}
}
}
return result.toTypedArray()
}
/**
* Returns the sequence number
*/
private fun getSequence(query: Array<Int>, lastAnswer: Int, n: Int) =
(query[1] xor lastAnswer) % n
fun main(args: Array<String>) {
val first_multiple_input = readLine()!!.trimEnd().split(" ")
val n = first_multiple_input[0].toInt()
val q = first_multiple_input[1].toInt()
val queries = Array<Array<Int>>(q, { Array<Int>(3, { 0 }) })
for (i in 0 until q) {
queries[i] = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray()
}
val result = dynamicArray(n, queries)
println(result.joinToString("\n"))
}<file_sep>/src/programs/string/ReverseWords.kt
package programs.string
fun main() {
val s = "i like this program very much".split(" ")
var ans = ""
for (i in s.size - 1 downTo 0) {
ans += s[i] + " "
}
println("Reversed String: ")
println(ans.substring(0, ans.length - 1))
}<file_sep>/src/programs/linkedList/LinkedList.kt
package programs.linkedList
class Node(value: Int) {
var value: Int = value
var next: Node? = null
var previous: Node? = null
}
class LinkedList {
var head: Node? = null
// reverse the linked list
fun reverse(_n: Node): Node {
var node: Node = _n
var prev: Node? = null
var current: Node = node
var next: Node?
while (current != null) {
next = current.next
print("while loop next ${next!!.value}")
current.next = prev!!
prev = current
current = next
}
node = prev!!
return node
}
// prints content of double linked list
fun printList(n: Node?) {
var node = n
while (node != null) {
print("${node.value} -> ")
node = node.next
}
print("NULL")
println()
}
}
fun main() {
val list = LinkedList()
list.head = Node(85)
list.head!!.next = Node(15)
list.head!!.next!!.next = Node(4)
list.head!!.next!!.next!!.next = Node(20)
println("Given Linked list")
list.printList(list.head)
list.head = list.reverse(list.head!!)
println()
println("Reversed Linked list")
list.printList(list.head)
}<file_sep>/src/programs/linkedList/SortedInsert.kt
package programs.linkedList
import java.util.*
class DoublyLinkedListNode(nodeData: Int) {
var data: Int
var next: DoublyLinkedListNode?
var prev: DoublyLinkedListNode?
init {
data = nodeData
next = null
prev = null
}
}
class DoublyLinkedList {
var head: DoublyLinkedListNode?
var tail: DoublyLinkedListNode?
init {
head = null
tail = null
}
fun insertNode(nodeData: Int) {
var node = DoublyLinkedListNode(nodeData)
if (head == null) {
head = node
} else {
tail?.next = node
node.prev = tail
}
tail = node
}
}
fun printDoublyLinkedList(head: DoublyLinkedListNode?, sep: String) {
var node = head
while (node != null) {
print(node.data)
node = node.next
if (node != null) {
print(sep)
}
}
}
// Complete the sortedInsert function below.
/*
* For your reference:
*
* DoublyLinkedListNode {
* data: Int
* next: DoublyLinkedListNode
* prev: DoublyLinkedListNode
* }
*
*/
fun sortedInsert(llist: DoublyLinkedListNode?, data: Int): DoublyLinkedListNode? {
var node = DoublyLinkedListNode(data)
// 1 2 3
// data = 4
if (llist != null) {
var head = llist
var temp = llist
var prev: DoublyLinkedListNode? = null
var next: DoublyLinkedListNode? = null
while (temp != null) {
prev = temp.prev
next = temp.next
// println("temp: ${temp?.data}\tprev: ${prev?.data}\tnext: ${next?.data}")
if (node.data <= temp.data) {
node.next = temp
if (prev != null) {
prev.next = node
} else {
temp.prev = node
}
node.prev = prev
break
}
if (next != null) {
temp = next
} else {
if (temp != null) {
temp.next = node
}
node.prev = temp
break
}
}
// println("outside while temp: ${temp?.data}\tprev: ${prev?.data}\tnext: ${next?.data}")
if (node.data > head.data)
node = head
}
return node
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
val llistCount = scan.nextLine().trim().toInt()
val llist = DoublyLinkedList()
for (i in 0 until llistCount) {
val llist_item = scan.nextLine().trim().toInt()
llist.insertNode(llist_item)
}
val data = scan.nextLine().trim().toInt()
val llist1 = sortedInsert(llist.head, data)
printDoublyLinkedList(llist1, " ")
}
}
<file_sep>/src/ds/StackAsArray.kt
package ds
class StackAsArray {
companion object {
const val MAX = 1000
}
var top: Int
var arr = IntArray(MAX)
fun isEmpty(): Boolean {
return top < 0
}
fun push(x: Int): Boolean {
if (top >= MAX - 1) {
println("Stack Overflow")
return false
} else {
arr.set(++top, x)
println("$x pushed into stack")
return true
}
}
fun pop(): Int {
if (top < 0) {
println("Stack Underflow")
return 0
} else {
val x = arr.get(top--)
return x
}
}
fun peek(): Int {
if (top < 0) {
println("Stack Underflow")
return 0
} else {
val x = arr.get(top)
return x
}
}
init {
top = -1
}
}
fun main() {
val s = StackAsArray()
s.push(10)
s.push(20)
s.push(30)
println("${s.pop()} Popped from stack")
}<file_sep>/src/programs/linkedList/Reverse.kt
package programs.linkedList
import java.util.*
// Complete the reverse function below.
/*
* For your reference:
*
* DoublyLinkedListNode {
* data: Int
* next: DoublyLinkedListNode
* prev: DoublyLinkedListNode
* }
*
*/
fun reverse(_llist: DoublyLinkedListNode?): DoublyLinkedListNode? {
// print("original: ")
// printDoublyLinkedList(_llist, " ")
var next: DoublyLinkedListNode? = null
var prev: DoublyLinkedListNode? = null
var current: DoublyLinkedListNode? = null
var llist = _llist
// 1 <-> 2 <-> 3 <-> 4 -> NULL
// 4 <-> 3 <-> 2 <-> 1 -> NULL
while (llist != null) {
current = llist
next = current.next
prev = current.prev
// println("prev: ${prev?.data}\tcurrent: ${current.data}\tnext: ${next?.data}")
// current.next = prev
// current.prev = next
llist = llist.next
current.next = prev
current.prev = next
}
// println()
// println("after while llist:${llist?.data}\tprev: ${prev?.data}\tcurrent: ${current?.data}\tnext: ${next?.data}")
// print("current: ")
// printDoublyLinkedList(current, " ")
// println()
//
// println()
return current
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
val llistCount = scan.nextLine().trim().toInt()
val llist = DoublyLinkedList()
for (i in 0 until llistCount) {
val llist_item = scan.nextLine().trim().toInt()
llist.insertNode(llist_item)
}
val llist1 = reverse(llist.head)
printDoublyLinkedList(llist1, " ")
// println()
}
}
<file_sep>/src/programs/array/MergeTwoSorted.kt
package programs.array
// Merge Sort (also read: Two Pointer Technique)
class MergeTwoSorted {
companion object {
// Merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
fun mergeArrays(arr1: IntArray, arr2: IntArray, n1: Int,
n2: Int, arr3: IntArray) {
var i = 0
var j = 0
var k = 0
// Traverse both array
while (i < n1 && j < n2) {
// Check if current element of first
// array is smaller than current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] < arr2[j]) arr3[k++] = arr1[i++] else arr3[k++] = arr2[j++]
}
// Store remaining elements of first array
while (i < n1) arr3[k++] = arr1[i++]
// Store remaining elements of second array
while (j < n2) arr3[k++] = arr2[j++]
}
}
}
fun main() {
val arr1: IntArray = intArrayOf(1, 2, 3, 5, 7)
val n1 = arr1.size
val arr2 = intArrayOf(2, 4, 6, 8)
val n2 = arr2.size
val arr3 = IntArray(n1 + n2)
MergeTwoSorted.mergeArrays(arr1, arr2, n1, n2, arr3)
println("Array after merging")
for (i in 0 until (n1 + n2)) {
print("${arr3[i]}\t")
}
}<file_sep>/src/search/BinarySearch.kt
package search
fun main() {
val arr = intArrayOf(2, 3, 4, 10, 40)
val x = 10
val result: Int = binarySearch(arr, x)
if (result == -1) println("Element not present") else println("Element found at "
+ "index " + result)
}
fun binarySearch(arr: IntArray, x: Int): Int {
var result = -1
var left = 0
var right = arr.size - 1
while (left <= right) {
var mid = left + (right - 1) / 2
// Check if x is +nt at mid
if (arr.get(mid) == x) {
return mid
}
// if x is greater, ignore left half
if (arr.get(mid) < x) {
left = mid + 1
}
// If x is smaller, ignore right half
else
right = mid - 1
}
// if we reach here, then element was not +nt
return result
}<file_sep>/src/programs/array/LeftRotation.kt
package programs.array
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val nd = scan.nextLine().split(" ")
val n = nd[0].trim().toInt()
val d = nd[1].trim().toInt()
val a = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
leftRotate(a, d)
}
fun leftRotate(_a: Array<Int>, d: Int) {
val a = _a.toMutableList()
val iterations = d % a.size
val tempArray1 = a.subList(iterations, a.size)
val tempArray = a.subList(0, iterations)
tempArray1.addAll(tempArray)
print(tempArray1.joinToString(" "))
}
<file_sep>/src/programs/linkedList/RemoveDuplicates.kt
package programs.linkedList
import java.util.*
// Complete the removeDuplicates function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* data: Int
* next: SinglyLinkedListNode
* }
*
*/
fun removeDuplicates(head: SinglyLinkedListNode?): SinglyLinkedListNode? {
if (head == null) return null
var nextItem: SinglyLinkedListNode? = head.next
while (nextItem != null && head.data === nextItem.data) {
nextItem = nextItem.next
}
head.next = removeDuplicates(nextItem)
return head
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val t = scan.nextLine().trim().toInt()
for (tItr in 1..t) {
val llistCount = scan.nextLine().trim().toInt()
val llist = SinglyLinkedList()
for (i in 0 until llistCount) {
val llist_item = scan.nextLine().trim().toInt()
llist.insertNode(llist_item)
}
val llist1 = removeDuplicates(llist.head)
printSinglyLinkedList(llist1, " ")
}
}
<file_sep>/src/programs/linkedList/ReversePrint.kt
package programs.linkedList
import java.util.*
class SinglyLinkedListNode(nodeData: Int) {
var data: Int = nodeData
var next: SinglyLinkedListNode? = null
}
class SinglyLinkedList {
var head: SinglyLinkedListNode?
var tail: SinglyLinkedListNode?
init {
head = null
tail = null
}
fun insertNode(nodeData: Int) {
val node = SinglyLinkedListNode(nodeData)
if (head == null) {
head = node
} else {
tail?.next = node
}
tail = node
}
}
fun printSinglyLinkedList(head: SinglyLinkedListNode?, sep: String) {
var node = head
while (node != null) {
print(node.data)
node = node.next
if (node != null) {
print(sep)
}
}
}
// Complete the reversePrint function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* data: Int
* next: SinglyLinkedListNode
* }
*
*/
fun reversePrint(_llist: SinglyLinkedListNode?) {
val llist = _llist
var current = llist
var prev: SinglyLinkedListNode? = null
var next: SinglyLinkedListNode? = null
while (current != null) {
next = current.next
current.next = prev
prev = current
current = next
}
while (prev != null) {
println("${prev.data}")
prev = prev.next
}
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val tests = scan.nextLine().trim().toInt()
for (testsItr in 1..tests) {
val llistCount = scan.nextLine().trim().toInt()
val llist = SinglyLinkedList()
for (i in 0 until llistCount) {
val llist_item = scan.nextLine().trim().toInt()
llist.insertNode(llist_item)
}
reversePrint(llist.head)
}
}
|
dbc1575fd5548c6eb3b0c2821f87e5a91af43b26
|
[
"Kotlin"
] | 19 |
Kotlin
|
dpgc11/DsAndAKt
|
b107084190e1cb56b74707375ee4a3707f2b46d0
|
ef65da9aa000ca0cd8c46506af9cc6f1b33e1279
|
refs/heads/master
|
<file_sep>require_relative './artist.rb'
class Song
attr_accessor :name, :artist, :genre
@@all = []
def initialize (name)
@name = name
self.save
end
def save
Song.all << self
end
def self.all
@@all
end
def self.new_by_filename(filename)
filename_info = filename.split(" - ")
int_song = Song.new(filename_info[1])
int_song.artist = Artist.find_or_create_by_name(filename_info[0])
filename_info[2].slice!(".mp3")
int_song.genre = filename_info[2]
return int_song
end
def artist_name= (name)
self.artist = Artist.find_or_create_by_name(name)
end
end<file_sep>require_relative './song.rb'
require_relative './artist.rb'
class MP3Importer
attr_accessor :path
def initialize (filepath)
@path = filepath
end
def files
files_standard_format = []
files_arr = Dir.glob(File.join(self.path, '*.mp3'))
files_arr.each do |file|
files_standard_format << File.basename(file)
end
return files_standard_format
end
def import
self.files.each do |file|
Song.new_by_filename(file)
end
end
end<file_sep>require_relative './song.rb'
class Artist
attr_accessor :name
@@all = []
def initialize (name)
@name = name
self.save
end
def self.all
@@all
end
def save
Artist.all << self
end
def songs
Song.all.select do |int_song|
int_song.artist == self
end
end
def add_song (song)
song.artist = self
end
def self.find_or_create_by_name(name)
result = Artist.all.find do |int_artist|
int_artist.name == name
end
if result == nil
new_int = Artist.new(name)
return new_int
else
return result
end
end
def print_songs
self.songs.each {|int_song| puts int_song.name}
end
# def self.am_i_there?(int_artist)
# Artist.all.include?(int_artist)
# end
end
|
ab28ff11e76aee9e698744e4d3ab2c7f6acd3e81
|
[
"Ruby"
] | 3 |
Ruby
|
KaladaJumbo/ruby-oo-object-relationships-collaborating-objects-lab
|
86463c5052fd37833f1cb1e3c3007ae73a509fba
|
d697f374fd207d2cf4a1c96a90cd44f36743d92d
|
refs/heads/master
|
<repo_name>juancampa/membrane-agent-ticker<file_sep>/src/index.js
import { root, sheet, currencies } from './schema';
export const init = () => {
return setTimer('onTimer', 0.1, 10);
}
const SYMBOLS = [ 'BTC', 'ETH', 'XRP', 'MIOTA', 'XMN', 'LTC', 'XLM', 'VTC' ];
// Called every time the timer fires
export async function onTimer() {
const coins = await currencies.items().query('{ symbol name priceUsd marketCapUsd volumeUsd24h percentChange7d rank }');
// Filter and coerce to string
const rows = coins
.filter((c) => SYMBOLS.includes(c.symbol))
.map((c) => Object.values(c).map(String));
// Header
const date = new Date().toGMTString();
await sheet.setCells({ startCell: 'A1', values: [
['Updated ' + date],
]});
// Data
await sheet.setCells({ startCell: 'A4', values: rows });
}
<file_sep>/info.js
const { dependencies, endpoints, environment, imports, schema } = program;
program.name = 'ticker';
// Imports
imports
.add('coinmarketcap')
.add('googlesheets')
// Dependencies
dependencies
.add('currencies', 'coinmarketcap:CurrencyCollection', 'Currencies to keep an eye on')
.add('sheet', 'googlesheets:Sheet', 'The sheet to put the data on')
schema.type('Root')
|
020cb6f916de4b3428dc3968708956c0c41c1cbf
|
[
"JavaScript"
] | 2 |
JavaScript
|
juancampa/membrane-agent-ticker
|
e51e83e174fb2e47238a71fba1114607d301e3bd
|
a07198590ec3f669262a5853b03eb72719c85cb3
|
refs/heads/master
|
<file_sep>import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
class JSacad {
@Test
void test() {
Sacad plataforma = new Sacad();
Contato contatoEscola = new Contato("São José dos Campos", "1225646845");
Disciplina informaticaBasica = new Disciplina("Informatica Basica", "Textyo longo", 25);
Curso informatica = new Curso(2.5f);
informatica.addDisciplina(informaticaBasica);
Curso eletronica = new Curso(2.5f);
eletronica.addDisciplina(informaticaBasica);
Escola novaEscola = new Escola(4151654, "ETEP", "Técnico", contatoEscola);
novaEscola.adicionarCurso(informatica);
novaEscola.adicionarCurso(eletronica);
plataforma.cadastrarEscola(novaEscola);
}
}
<file_sep>import java.util.LinkedList;
import java.util.List;
public class Professor {
private String matricula, nome, cpf, email, data_nasc, telefone;
public Professor(String matricula, String nome, String cpf, String email, String data_nasc, String telefone){
// TODO: CONSTRUTOR
}
}
<file_sep>import java.util.LinkedList;
import java.util.List;
public class Sacad {
public List<Escola> escolas = new LinkedList<Escola>();
public void cadastrarEscola(Escola novaEscola){
escolas.add(novaEscola);
}
}
|
5b3e0b12aed9fcb36190f1c11e9bb24a1b4e59e3
|
[
"Java"
] | 3 |
Java
|
leonardormlins/classesDiagram
|
4c921c326f2e3d625f86b79d164b5db24e4e2084
|
8908da5152c8df480a7be7b50173f6a259ed3bb7
|
refs/heads/master
|
<file_sep>makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL
setMatrix <- function(matrix = matrix()){
x <<- matrix
}
getMatrix <- function() x
setInverse <- function(inverseMatrix = matrix()){
inverse <<- inverseMatrix
}
getInverse <- function() inverse
list(get = getMatrix, set = setMatrix, getI = getInverse, setI = setInverse)
}
|
1cecd7397d947dc7eae7dfa7fe395ab7948a8069
|
[
"R"
] | 1 |
R
|
gburgess7/ProgrammingAssignment2
|
a2d6e192df5e086b72b86f74343e8c93951fd8be
|
d461d3b82a815926922db7747bcbe8abc43b3ccc
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
form={
email:"",
password:""
}
constructor() { }
ngOnInit(): void {}
login(){
this.form.email=(String)($('#floatingInput').val());
this.form.password=(String)($('#floatingPassword').val());
const url="http://localhost:5000/login";
fetch(url,{
method:'post',
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify(this.form)
}).then((res)=>res.json())
.then((res)=>{
console.log(res)
alert(res.message);
})
.catch((e)=>{
alert("login failed");
})
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
form={
name:"",
email:"",
mobile:"",
password:"",
confirmpassword:""
}
constructor() { }
ngOnInit(): void {
}
Register(){
this.form.name=(String)($('#name').val());
this.form.email=(String)($('#floatingInput').val());
this.form.mobile=(String)($('#mobile').val());
this.form.password=(String)($('#password').val());
this.form.confirmpassword=(String)($('#cpassword').val());
// alert(this.form.email);
const url="http://localhost:5000/register";
fetch(url,{
method:'post',
headers: {
'Content-Type': 'application/json',
},
body:JSON.stringify(this.form)
}).then((res)=>res.json())
.then((res)=>{
alert(res.message);
})
.catch((e)=>{
alert(e);
// console.log("error",e);
})
}
}
|
0e9ae69507da9512c3437bccca46caaab336a2f4
|
[
"TypeScript"
] | 2 |
TypeScript
|
ksakshi2723/wk24
|
23c5695d16d9f9368bfdb69038d4d34e0d7815fd
|
ad38483d2ba7a649e037ac247ef4fc2e55194b40
|
refs/heads/master
|
<file_sep>import {
GraphQLEnumType,
} from 'graphql';
const MakeEnumType = new GraphQLEnumType({
name: 'MakeEnum',
values: {
AUDI: {
value: 0,
},
BMW: {
value: 1,
},
MERCEDES: {
value: 2,
},
VW: {
value: 3
},
SKODA: {
value: 4
}
},
});
export default MakeEnumType<file_sep>import {
GraphQLEnumType,
} from 'graphql';
const FuelEnumType = new GraphQLEnumType({
name: 'FuelEnum',
values: {
PETROL: {
value: 0,
},
DEISEL: {
value: 1,
},
ELECTRIC: {
value: 2,
},
LPG: {
value: 3,
},
HYBRID: {
value: 4,
},
},
});
export default FuelEnumType;<file_sep>import * as mod from "./../../lambda/handler";
import * as jestPlugin from "serverless-jest-plugin";
const lambdaWrapper = jestPlugin.lambdaWrapper;
const wrapped = lambdaWrapper.wrap(mod, { handler: "queryVehicles" });
describe("λ Function - queryVehicles", () => {
// beforeAll((done) => {
// //lambdaWrapper.init(liveFunction); // Run the deployed lambda
// done();
// });
it("Invoke / Initiate function test", () => {
return wrapped.run({}).then((response) => {
expect(response).not.toBe(null);
expect(response).toHaveProperty("statusCode");
expect(response).toHaveProperty("body");
expect(response.statusCode).toBe(200);
});
});
});
<file_sep>'use strict';
import {dynamodb} from "../dynamodb";
import * as uuid from "uuid";
export const updateVehicle = (data) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Item: {
make: data.make,
model: data.model,
transmission : data.transmission,
mileage: data.mileage,
fuel_type: data.fuel_type,
vehicle_type: data.vehicle_type,
vehicle_color: data.vehicle_color,
id: data.id,
created_at: data.created_at,
updated_at: Date.now()
}
};
return dynamodb.put(params).promise()
.then(result => params.Item);
};
<file_sep>'use strict';
import {dynamodb} from "../dynamodb";
export const viewVehicle = (id) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: { id }
};
return dynamodb.get(params).promise()
.then(r => r.Item);
};
<file_sep>import {
GraphQLEnumType,
} from 'graphql';
const ColorTypeEnum = new GraphQLEnumType({
name: 'ColorEnum',
values: {
BLACK: {
value: 0,
},
WHITE: {
value: 1,
},
RED: {
value: 2,
},
YELLOW: {
value: 3
},
SILVER: {
value: 4
}
},
});
export default ColorTypeEnum<file_sep>'use strict';
import {dynamodb} from "../dynamodb";
export const listVehicles = () => dynamodb.scan({ TableName: process.env.DYNAMODB_TABLE }).promise()
.then(r => r.Items);
<file_sep>'use strict';
import { graphql } from 'graphql';
import {schema} from "../schema";
export const queryVehicles = (event, context, callback) => {
graphql(schema, event.body)
.then(result => callback(null, {statusCode: 200, body: JSON.stringify(result)}))
.catch(callback);
};
<file_sep>'use strict';
import {dynamodb} from "../dynamodb";
export const removeVehicle = (id) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: { id }
};
return dynamodb.delete(params).promise().then(res => {
return Object.keys(res).length === 0;
})
};
<file_sep>{
"name": "aws-node-graphql-api-with-dynamodb-typescript-and-offline",
"version": "1.0.0",
"description": "Serverless Lambda with DynamoDB, typescript, graphQL and offline support",
"repository": "",
"author": "<NAME>",
"license": "MIT",
"scripts": {
"test-lambda": "serverless invoke test --stage default -f queryVehicles",
"start": "sls offline start",
"test": "jest --config=jest.config.test.js",
"compile": "tsc"
},
"dependencies": {
"@shelf/jest-dynamodb": "^1.8.1",
"aws-lambda": "^0.1.2",
"graphql-yoga": "^1.18.3",
"node": "^12.3.1",
"serverless-jest-plugin": "^0.3.0",
"uuid": "^3.3.2"
},
"devDependencies": {
"@babel/core": "^7.14.6",
"@babel/preset-env": "^7.14.7",
"@babel/preset-typescript": "^7.14.5",
"@types/aws-lambda": "8.10.1",
"@types/jest": "^26.0.23",
"@types/node": "^8.0.57",
"@types/uuid": "^3.4.4",
"aws-sdk": "^2.625.0",
"babel-jest": "^27.0.5",
"babel-loader": "^8.1.0",
"cache-loader": "^4.1.0",
"fork-ts-checker-webpack-plugin": "^5.0.12",
"jest": "^26.0.0",
"serverless": "^1.77.1",
"serverless-bundle": "3.2.1",
"serverless-dynamodb-local": "^0.2.39",
"serverless-offline": "^6.5.0",
"serverless-webpack": "^5.1.1",
"source-map-support": "^0.5.6",
"ts-loader": "^4.2.0",
"typescript": "^3.9.7",
"webpack": "^4.5.0",
"webpack-node-externals": "^2.5.0"
}
}
<file_sep>'use strict';
import {createVehicle} from "./resolvers/create";
import {viewVehicle} from "./resolvers/view";
import {listVehicles} from "./resolvers/list";
import {removeVehicle} from "./resolvers/remove";
import {updateVehicle} from "./resolvers/update";
import TransmissionEnum from "./types/transmission.type";
import FuelEnumType from "./types/fuel.type";
import VehicleEnumType from "./types/vehicle.type";
import {
GraphQLBoolean,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
} from 'graphql';
const vehicleType = new GraphQLObjectType({
name: 'Vehicles',
fields: {
id: {type: new GraphQLNonNull(GraphQLString)},
make: {type: new GraphQLNonNull(GraphQLString)},
model: {type: new GraphQLNonNull(GraphQLString)},
transmission: {type: new GraphQLNonNull(TransmissionEnum)},
mileage: {type: new GraphQLNonNull(GraphQLInt)},
fuel_type: {type: new GraphQLNonNull(FuelEnumType)},
vehicle_type: {type: new GraphQLNonNull(VehicleEnumType)},
vehicle_color: {type: new GraphQLNonNull(GraphQLString)},
}
});
export const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
listVehicles: {
type: new GraphQLList(vehicleType),
resolve: (parent, args) => listVehicles()
},
viewVehicle: {
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
type: vehicleType,
resolve: (parent, args) => viewVehicle(args.id)
}
}
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
createVehicle: {
args: {
make: {type: new GraphQLNonNull(GraphQLString)},
model: {type: new GraphQLNonNull(GraphQLString)},
transmission : {type: new GraphQLNonNull(TransmissionEnum)},
mileage: {type: new GraphQLNonNull(GraphQLInt)},
fuel_type: {type: new GraphQLNonNull(FuelEnumType)},
vehicle_type: {type: new GraphQLNonNull(VehicleEnumType)},
vehicle_color: {type: new GraphQLNonNull(GraphQLString)},
},
type: vehicleType,
resolve: (parent, args) => createVehicle(args)
},
updateVehicle: {
args: {
id: {type: new GraphQLNonNull(GraphQLString)},
make: {type: new GraphQLNonNull(GraphQLString)},
model: {type: new GraphQLNonNull(GraphQLString)},
transmission : {type: new GraphQLNonNull(TransmissionEnum)},
mileage: {type: new GraphQLNonNull(GraphQLInt)},
fuel_type: {type: new GraphQLNonNull(FuelEnumType)},
vehicle_type: {type: new GraphQLNonNull(VehicleEnumType)},
vehicle_color: {type: new GraphQLNonNull(GraphQLString)}
},
type: vehicleType,
resolve: (parent, args) => updateVehicle(args)
},
removeVehicle: {
args: {
id: {type: new GraphQLNonNull(GraphQLString)}
},
type: GraphQLBoolean,
resolve: (parent, args) => removeVehicle(args.id)
},
}
})
});
<file_sep>import {
GraphQLEnumType,
} from 'graphql';
const TransmissionEnumType = new GraphQLEnumType({
name: 'TransmissionEnum',
values: {
MANUAL_GEARBOX: {
value: 0,
},
SEMI_AUTOMATIC: {
value: 1,
},
AUTOMATIC_TRANSMISSION: {
value: 2,
},
},
});
export default TransmissionEnumType<file_sep>## Setup
```bash
OS
install docker v.3.1.1
install node v12+
npm install - g serverless
npm install -g typescript
inside the project
npm install
cd ./dynamodb && docker-compose up -d
serverless offline start
serverless dynamodb migrate (this imports schema)
```
## Run service offline
```bash
serverless offline start
```
## Usage
You can create, retrieve, update, or delete vehicles with the following commands:
### Create a Vehicle
```bash
curl -X POST -H "Content-Type:application/graphql" -d "mutation {createVehicle(make: \"VW\", model: \"Golf\", transmission: MANUAL_GEARBOX, mileage: 10000, fuel_type: PETROL, vehicle_type: SUV, vehicle_color: \"BLACK\") { id make model transmission mileage fuel_type vehicle_type vehicle_color }}" "http://localhost:3000/dev/vehicles"
```
Example Result:
```bash
{"data":{"createVehicle":{"id":"de741d00-d810-11eb-9ced-f5458d80f4f6","make":"VW","model":"Golf","transmission":"MANUAL_GEARBOX","mileage":10000,"fuel_type":"PETROL","vehicle_type":"SUV","vehicle_color":"BLACK"}}}%
```
### List all Vehicles
```bash
curl -X POST -H "Content-Type:application/graphql" -d "query { listVehicles { id make model transmission mileage fuel_type vehicle_type vehicle_color } }" "http://localhost:3000/dev/vehicles"
```
Example output:
```bash
{"data":{"listVehicles":[{"id":"2a342640-d80c-11eb-b8d2-153cb284dce0","make":"VW","model":"Touareg","transmission":"MANUAL_GEARBOX","mileage":10000,"fuel_type":"PETROL","vehicle_type":"SUV","vehicle_color":"BLACK"},
{"id":"de741d00-d810-11eb-9ced-f5458d80f4f6","make":"VW","model":"Golf","transmission":"MANUAL_GEARBOX","mileage":10000,"fuel_type":"PETROL","vehicle_type":"SUV","vehicle_color":"BLACK"}]}}%
```
### Get one Vehicle
```bash
# Replace the <id> part with a real id from your todos table
curl -X POST -H "Content-Type:application/graphql" -d "query {viewVehicle(id: \"<id>\") { id make model transmission mileage fuel_type vehicle_type vehicle_color }}" "http://localhost:3000/dev/vehicles"
```
Example Result:
```bash
{"data":{"viewVehicle":{"id":"de741d00-d810-11eb-9ced-f5458d80f4f6","make":"VW","model":"Golf","transmission":"MANUAL_GEARBOX","mileage":10000,"fuel_type":"PETROL","vehicle_type":"SUV","vehicle_color":"BLACK"}}}%
```
### Update a Vehicle
```bash
# Replace the <id> part with a real id from your vehicles table
curl -X POST -H "Content-Type:application/graphql" -d "mutation {updateVehicle(id: \"<id>\", make: \"VW\", model: \"Touareg\", transmission: MANUAL_GEARBOX, mileage: 10000, fuel_type: PETROL, vehicle_type: SUV, vehicle_color: \"BLACK\") { id make model transmission mileage fuel_type vehicle_type vehicle_color }}" "http://localhost:3000/dev/vehicles"
```
Example Result:
```bash
{"data":{"updateVehicle":{"id":"2a342640-d80c-11eb-b8d2-153cb284dce0","make":"VW","model":"Touareg","transmission":"MANUAL_GEARBOX","mileage":10000,"fuel_type":"PETROL","vehicle_type":"SUV","vehicle_color":
"BLACK"}}}
```
### Delete a Vehicle
```bash
# Replace the <id> part with a real id from your vehicles table
curl -X POST -H "Content-Type:application/graphql" -d "mutation {removeVehicle(id: \"<id>\")}" "http://localhost:3000/dev/vehicles"
```
Example Result:
```bash
{"data":{"removeVehicle":true}}
```
<file_sep>import {
GraphQLEnumType,
} from 'graphql';
const VehicleEnumType = new GraphQLEnumType({
name: 'VehicleType',
values: {
CABRIOLET: {
value: 0,
},
COUPE: {
value: 1,
},
ESTATE: {
value: 2,
},
SUV: {
value: 3
},
SALOON: {
value: 4
},
VAN: {
value: 5
},
SMALL: {
value: 6
},
OTHER: {
value: 7
}
},
});
export default VehicleEnumType;<file_sep>import * as uuid from "uuid";
import {dynamodb} from "../../../dynamodb";
const { DocumentClient } = require('aws-sdk/clients/dynamodb');
const isTest = process.env.JEST_WORKER_ID;
const config = {
convertEmptyValues: true,
...(isTest && {
endpoint: 'localhost:8000',
sslEnabled: false,
region: 'local-env',
}),
};
const ddb = new DocumentClient(config);
describe('method', () => {
it('should insert vehicle into table', async (done) => {
const id = uuid.v1();
const vehicle = {
id,
make: "Audi",
model: "A4",
transmission: "MANUAL_GEARBOX",
mileage: 10000,
fuel_type: "PETROL",
vehicle_type: "SUV",
vehicle_color: "BLACK",
created_at: Date.now(),
updated_at: null
};
await ddb
.put({TableName: 'vehicles', Item: vehicle})
.promise()
done();
const {Item} = await ddb.get({TableName: 'vehicles', Key: {id}}).promise();
expect(Item).toEqual(vehicle);
});
})
|
7a2126cfd0b8599744890a1a5fa76bdb50622e10
|
[
"Markdown",
"JSON",
"TypeScript"
] | 15 |
TypeScript
|
minchom/instamotion
|
269ea54661e8a36bc8016b7ad41a0da2df08684a
|
cc53a34c7a68c7b3f6d81d37f6e3ab1cc0a78cdd
|
refs/heads/master
|
<file_sep>import React from "react";
import firebase from "../../firebase";
import MessagesHeader from "./MessagesHeader";
import MessageForm from "./MessageForm";
import Message from "./Message";
import { setUserPosts } from "../../store/actions";
import { connect } from "react-redux";
import { Segment, Comment } from "semantic-ui-react";
class Messages extends React.Component {
state = {
messages: [],
numUniqueUsers: "",
searchTerm: "",
searchLoading: false,
searchResults: [],
privateChannel: this.props.isPrivate,
privateMessagesRef: firebase.database().ref("privateMessages"),
usersRef: firebase.database().ref("users"),
isChannelStarred: false,
listeners: [],
};
componentDidMount() {
const { currentChannel, currentUser } = this.props;
const { listeners } = this.state;
if (!currentUser || !currentChannel) return;
this.removeListeners(listeners);
this.addListeners(currentChannel.id);
this.addUserStarredListener(currentChannel.id, currentUser.uid);
}
componentWillUnmount() {
this.removeListeners(this.state.listeners);
}
removeListeners = (listeners) => {
this.state.listeners.forEach((listener) => {
listener.ref.child(listener.id).off(listener.event);
});
};
addToListeners = (id, ref, event) => {
const index = this.state.listeners.findIndex(
(listener) =>
listener.id === id && listener.ref === ref && listener.event === event
);
if (index === -1) {
const listener = {
id,
ref,
event,
};
this.setState({ listeners: [...this.state.listeners, listener] });
}
};
addListeners = (channelId) => {
this.addMessageListener(channelId);
};
addUserStarredListener = (channelId, userId) => {
this.state.usersRef
.child(`${userId}/starred`)
.once("value")
.then((data) => {
if (data.val() !== null) {
const channelIds = Object.keys(data.val());
const prevStarred = channelIds.includes(channelId);
this.setState({ isChannelStarred: prevStarred });
}
});
};
addMessageListener = (id) => {
const { messagesRef } = this.props;
let loadedMessages = [];
const ref = this.getMessagesRef();
ref.child(id).on("child_added", (snap) => {
loadedMessages.push(snap.val());
this.setState({ messages: [...loadedMessages] });
this.countUniqueUsers(loadedMessages);
this.countUserPosts(loadedMessages);
});
this.addToListeners(id, ref, "child_added");
};
countUniqueUsers = (messages) => {
const numUniqueUsers = messages.reduce((accumulator, currentMessage) => {
const {
user: { id },
} = currentMessage;
if (!accumulator.includes(id)) accumulator.push(id);
return accumulator;
}, []).length;
const displayString =
numUniqueUsers > 1 ? `${numUniqueUsers} users` : `${numUniqueUsers} user`;
this.setState({ numUniqueUsers: displayString });
};
countUserPosts = (messages) => {
let userPosts = messages.reduce((accumulator, { user }) => {
if (user.name in accumulator) {
accumulator[user.name].count += 1;
} else {
accumulator[user.name] = {
avatar: user.avatar,
count: 1,
};
}
return accumulator;
}, {});
this.props.setUserPosts(userPosts);
};
displayMessages = (messages) => {
const { currentUser } = this.props;
if (!messages || !messages.length) return null;
return messages.map((message) => (
<Message key={message.timestamp} user={currentUser} message={message} />
));
};
displayChannelName = (channel) =>
channel ? `${this.state.privateChannel ? "@" : "#"}${channel.name}` : "";
handleSearchChange = (event) => {
this.setState(
{
searchTerm: event.target.value,
searchLoading: true,
},
() => {
this.handleSearchMessages();
}
);
};
handleSearchMessages = () => {
const { searchTerm, messages } = this.state;
const channelMessages = [...messages];
const regex = new RegExp(searchTerm, "gi");
const searchResults = channelMessages.filter(
(message) =>
(message.content && message.content.match(regex)) ||
message.user.name.match(regex)
);
this.setState({
searchResults,
});
setTimeout(() => this.setState({ searchLoading: false }), 1000);
};
getMessagesRef = () => {
const { messagesRef } = this.props;
const { privateMessagesRef, privateChannel } = this.state;
if (privateChannel) return privateMessagesRef;
return messagesRef;
};
handleStar = () => {
this.setState(
(prevState) => ({
isChannelStarred: !prevState.isChannelStarred,
}),
() => this.starChannel()
);
};
starChannel = () => {
if (this.state.isChannelStarred) {
this.state.usersRef
.child(`${this.props.currentUser.uid}/starred`)
.update({
[this.props.currentChannel.id]: {
name: this.props.currentChannel.name,
details: this.props.currentChannel.details,
createdBy: {
name: this.props.currentChannel.createdBy.name,
avatar: this.props.currentChannel.createdBy.avatar,
},
},
});
} else {
this.state.usersRef
.child(`${this.props.currentUser.uid}/starred`)
.child(this.props.currentChannel.id)
.remove((err) => console.log(err));
}
};
render() {
const { currentChannel, currentUser, messagesRef } = this.props;
const {
numUniqueUsers,
messages,
searchResults,
searchTerm,
searchLoading,
privateChannel,
isChannelStarred,
} = this.state;
return (
<React.Fragment>
<MessagesHeader
channelName={this.displayChannelName(currentChannel)}
users={numUniqueUsers}
handleSearchChange={this.handleSearchChange}
searchLoading={searchLoading}
privateChannel={privateChannel}
handleStar={this.handleStar}
isChannelStarred={isChannelStarred}
/>
<Segment>
<Comment.Group className="messages">
{searchTerm
? this.displayMessages(searchResults)
: this.displayMessages(messages)}
</Comment.Group>
</Segment>
<MessageForm
currentChannel={currentChannel}
currentUser={currentUser}
messagesRef={messagesRef}
privateChannel={privateChannel}
getMessagesRef={this.getMessagesRef}
/>
</React.Fragment>
);
}
}
export default connect(null, { setUserPosts })(Messages);
<file_sep>import React from "react";
import { Grid } from "semantic-ui-react";
import "./App.css";
import { connect } from "react-redux";
import firebase from "../../firebase";
import ColorPanel from "../color-panel/ColorPanel";
import SidePanel from "../side-panel/SidePanel";
import Messages from "../messages/Messages";
import MetaPanel from "../meta-panel/MetaPanel";
import Spinner from "../../Spinner";
import { setCurrentChannel } from "../../store/actions";
class App extends React.Component {
state = {
messagesRef: firebase.database().ref("messages"),
};
handleChannelChange = (channel) => {
const { setCurrentChannel } = this.props;
setCurrentChannel(channel);
};
render() {
const { messagesRef } = this.state;
const {
currentChannel,
isPrivate,
currentUser,
userPosts,
primaryColor,
secondaryColor,
} = this.props;
return (
<Grid
columns="equal"
className="app"
style={{ backgroundColor: secondaryColor }}
>
<ColorPanel
key={currentUser && currentUser.name}
currentUser={currentUser}
/>
<SidePanel
onChannelChange={this.handleChannelChange}
currentChannel={currentChannel}
currentUser={currentUser}
primaryColor={primaryColor}
/>
<Grid.Column
style={{
width: "auto",
display: "flex",
flexDirection: "column",
height: "100vh",
}}
>
{currentChannel && messagesRef ? (
<Messages
key={currentChannel && currentChannel.id}
currentUser={currentUser}
currentChannel={currentChannel}
messagesRef={messagesRef}
isPrivate={isPrivate}
/>
) : (
<Spinner />
)}
</Grid.Column>
<Grid.Column>
<MetaPanel
key={currentChannel && currentChannel.name}
isPrivate={isPrivate}
currentChannel={currentChannel}
userPosts={userPosts}
/>
</Grid.Column>
</Grid>
);
}
}
const mapStateToProps = ({ channel, user: { currentUser }, colors }) => ({
currentChannel: channel.currentChannel,
isPrivate: channel.isPrivate,
userPosts: channel.userPosts,
currentUser,
primaryColor: colors.primaryColor,
secondaryColor: colors.secondaryColor,
});
export default connect(mapStateToProps, { setCurrentChannel })(App);
<file_sep>import * as actionTypes from "./types";
// USERS
export const setUser = (user) => ({
type: actionTypes.SET_USER,
payload: user,
});
export const clearUser = () => ({
type: actionTypes.CLEAR_USER,
});
// CHANNELS
export const setCurrentChannel = (channel) => ({
type: actionTypes.SET_CURRENT_CHANNEL,
payload: channel,
});
export const setPrivateChannel = (isPrivate) => ({
type: actionTypes.SET_PRIVATE_CHANNEL,
payload: isPrivate,
});
export const setUserPosts = (posts) => ({
type: actionTypes.SET_USER_POSTS,
payload: posts,
});
// COLORS
export const setColors = (primaryColor, secondaryColor) => ({
type: actionTypes.SET_COLORS,
payload: {
primaryColor,
secondaryColor,
},
});
<file_sep>import { combineReducers } from "redux";
import userReducer from "./user-reducer";
import channelReducer from "./channel-reducer";
import colorsReducer from "./colors-reducer";
const rootReducer = combineReducers({
user: userReducer,
channel: channelReducer,
colors: colorsReducer,
});
export default rootReducer;
<file_sep>import firebase from "firebase";
import "firebase/auth";
import "firebase/database";
import "firebase/storage";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "slack-clone-db90b.firebaseapp.com",
databaseURL: "https://slack-clone-db90b.firebaseio.com",
projectId: "slack-clone-db90b",
storageBucket: "slack-clone-db90b.appspot.com",
messagingSenderId: "709963579195",
appId: "1:709963579195:web:eb1d2fad0d459a4444411e",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase;
<file_sep># Slack clone
## Stack: React, Firebase, Redux, SemanticUI
|
0f03adb6f870bf28d51e6689c98b87f615416434
|
[
"JavaScript",
"Markdown"
] | 6 |
JavaScript
|
Vincent-Vais/Slack-clone
|
1e8ab3806c39614751d8ebd63884b7c8f21a85fb
|
5eff55951b7bef2d19b5bbee64a880530a4989a6
|
refs/heads/main
|
<repo_name>NUCG1GB/Magnetic-dipole-field-calculations-in-parallel<file_sep>/dipole_field_parallel.cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include <mpi.h>
#include <iomanip>
double avg_1D(std::vector<double> &array)
{
double sum=0;
int count=0;
for (int i =0; i<array.size();i++)
{
if (array[i]!=0)
{
sum = sum + array[i];
}
else
{
count++;
}
}
return(sum/(array.size()-count)); //only average over dipoles inside ellipsoid
}
//each call of this function returns the x,y,z component of the total B
//field for a single point within the ellipsoid
double* getB(double m[],int nx,int nxny,int i,double k, double l,int N,int x,int y,int z)
{
int j;//tracks the array position of the dipole acting on dipole i
int x2,y2,z2; //coordinates of acting dipole
int dx,dy,dz;
double mag,rdotm,r_mag_cubed,k_div_r_mag_cubed;
double r_hat[3] ={0};//stores unit vector from j to i
double* out = new double[3];//stores cumulative bx,by,bz values acting on i
z= i/(nxny);//calculates x,y,z coordinates starting from (0,0,0) of each dipole i
y=(i-nxny*z)/nx;
x=i%nx;
out[0]=0;
out[1]=0;
out[2]=0;
for (j=0;j<N;j++)
{
if (i!=j)//to filter out particles from acting on themselves
{
z2= j/(nxny);//x,y,z coordinates of each dipole j
y2=(j-nxny*z2)/nx;
x2=j%nx;
dx=x2-x;
dy=y2-y;
dz=z2-z;
mag = sqrt((dx)*(dx)+(dy)*(dy)+(dz)*(dz)); //magnitude of r
r_mag_cubed = (mag*l)*(mag*l)*(mag*l);
k_div_r_mag_cubed=k/r_mag_cubed;
r_hat[0] = (dx)/mag;//calculate and normalise r
r_hat[1] = (dy)/mag;
r_hat[2] = (dz)/mag;
rdotm = (r_hat[0]*m[0]+r_hat[1]*m[1]+r_hat[2]*m[2]);
//calculate contribution to B at i due to j
out[0] = out[0]+k_div_r_mag_cubed*((3*r_hat[0]*rdotm-m[0]));
out[1] = out[1]+k_div_r_mag_cubed*((3*r_hat[1]*rdotm-m[1]));
out[2] = out[2]+k_div_r_mag_cubed*((3*r_hat[2]*rdotm-m[2]));
}
}
return(out);
}
bool inside_ellipsoid(float x,float y,float z,float rx,float ry,float rz)
{
//returns true/false depending on if a particles coordinates are within the ellipsoid
bool in = (((x-rx)*(x-rx))/(rx*rx)+((y-ry)*(y-ry))/(ry*ry)+((z-rz)*(z-rz))/(rz*rz))<=1.00;
return in;
}
void print_xyplane(std::vector<double> const &Bx,int nx,int ny,int layer)
{
//for a chosen z layer, prints a x-y grid of Bx/By/Bz values
for (int i =0;i<ny;i++)
{
//the outer loop iterates over each row, the inner loop iterates from the start of that
//row on the specified layer and the end of that row,ie over each column
for (int j =layer*nx*ny+i*nx;j<layer*nx*ny+i*nx+nx;j++)
{
std::cout<<Bx[j]<<" ";
}
std::cout<<std::endl;
}
}
void print_zyplane(std::vector<double> const &Bx,int nz,int ny,int nx,int layer)
{
//for a chosen z layer, prints a z-y grid of Bx/By/Bz values
for (int i =0;i<ny;i++)
{
//takes significantly longer to print due to non contiguous memory access
for (int j =layer+i*ny;j<layer+nx*ny*nz+i*ny;j+=nx*ny)
{
std::cout<<Bx[j]<<" ";
}
std::cout<<std::endl;
}
}
void errcheck (int ierror, const char* msg) //checks for MPI errors and returns the name of the function causing the error
{
if (ierror != MPI_SUCCESS)
{
printf("Error in %s! \n",msg);
}
}
int main (int argc, char *argv[])
{
////////////////////////////////////////MPI Initiation//////////////////////////////////////////////
int ierror = 0;
ierror = MPI_Init(&argc, &argv); errcheck(ierror, "MPI_Init");
double start_time = MPI_Wtime();
int rank,num_processors;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_processors);
///////////////////////////////Simulation user input variables//////////////////////////////////////
double u = 9.274009e-24; //magnetic dipole moment=bohr magneton
float rx=10e-9; //x,y,z radius of ellipsoid, minimum value for rx,ry,rz is 0.6e-9
float ry=10e-9;
float rz =20e-9;
const double l=3e-10; //lattice seperation
double m[3] = {1,0,0}; //magnetic moment direction
///////////////////////////////////////Simulation setup/////////////////////////////////////////////
double k = u * 1e-7;
int nx=2*rx/l; //lattice dimensions
int ny=2*ry/l;
int nz=2*rz/l;
int N=nx*ny*nz;
int nxny = nx*ny;
int z,y,x;
std::vector<int> proc_start_pos((num_processors+1),0); //This stores the dipole that each processor starts working on
//The following structure is responsible for load balancing of the processors by dividing the dipoles between processors so that each has the same amount of dipoles that actualy contribute to the magnetic field.
//Done in serial due to low computation requirements
if (rank ==0)
{
int inside_count=0;
int inside_total=0;
for (int i =0;i<N;i++) //This loop adds up the total dipoles inside the ellopse and stores it as inside_total
{
z= i/(nx*ny); //calculates the 3D coordinates of each particle
y=(i-nx*ny*z)/nx;
x=i%nx;
if (inside_ellipsoid(x,y,z,((float)(nx)-1)/2,((float)(ny)-1)/2,((float)(nz)-1)/2) ==1)
inside_count++; //checks if point x,y,z is inside ellipsoid
}
inside_total=inside_count;
inside_count =0;
int proc_start_pos_count=0;
//This loop assigns each processor its starting dipole by counting through all points in the lattice and adding 1 to inside_count if the particle is inside the ellipsoid. Every time inside_count reaches a multiple of inside_total/num_processors, the current i is saved to the proc_start_pos array. This results in each processor being assigned the same amount of dipoles inside the ellipsoid but the processors which compute the dipoles near the poles of the ellipsoid will iterate over more dipoles, but most will be outside the ellipsoid and so no calculation is required.
for (int i =0;i<N;i++)
{
z= i/(nx*ny);
y=(i-nx*ny*z)/nx;
x=i%nx;
if (inside_ellipsoid(x,y,z,((float)(nx)-1)/2,((float)(ny)-1)/2,((float)(nz)-1)/2) ==1)
inside_count++;
if (inside_count==(inside_total/num_processors))
{
proc_start_pos[proc_start_pos_count+1]=i;
proc_start_pos_count++;
inside_count=0;
}
}
std::cout<<"N is "<<N<<" and nx,ny,nz are "<<nx<<","<<ny<<","<<nz<<std::endl;
std::cout<<"Total non 0 dipoles "<<inside_total<<std::endl;
proc_start_pos[num_processors]=N;
}
//Sends each processor the array of starting positions, they only need a single start position (their own) but it is easier to do it this way and the memory requirement is insignificant. This is a synchronous communication
ierror = MPI_Bcast(&proc_start_pos[0],num_processors+1,MPI_INT,0,MPI_COMM_WORLD);
proc_start_pos[num_processors+1]=N; errcheck(ierror, "MPI_Bcast");
for (int i =0; i<num_processors;i++)
{
if(i==rank)
{
std::cout<<"My rank is "<<rank<<" and my starting dipole is "<<proc_start_pos[rank]<<std::endl;
}
}
///////////////////////////////////////////Simulation////////////////////////////////////////
int N_proc=N/num_processors;
double B_self[3]={0,0,0};//stores the self generated magnetic field in each axis
std::vector<double> Bx(N,0);//stores x,y,z component of the magnetic field respectively
std::vector<double> By(N,0);
std::vector<double> Bz(N,0);
double* ptr;//A temporary pointer which stores the output of the result of getB
B_self[0] = (k*8*M_PI)/(3*(l*l*l))*m[0];//calculate B due to self
B_self[1] = (k*8*M_PI)/(3*(l*l*l))*m[1];
B_self[2] = (k*8*M_PI)/(3*(l*l*l))*m[2];
//The following structure loops through all dipoles assigned to a processor, for each dipole within the ellipsoid it calls the getB function which calculates the magnetic field due to the interaction of all N dipoles. It then combines the total magnetic field at each dipole
for (int i=proc_start_pos[rank];i<proc_start_pos[rank+1];i++)
{
z= i/(nx*ny);
y=(i-nx*ny*z)/nx;
x=i%nx;
if (inside_ellipsoid(x,y,z,((float)(nx)-1)/2,((float)(ny)-1)/2,((float)(nz)-1)/2) ==1)//only calculates B for dipoles within ellipsoid
{
ptr=getB(m,nx,nxny,i,k,l,N,x,y,z);
Bx[i]=ptr[0] + B_self[0];//combines interacting and self generated fields
By[i]=ptr[1] + B_self[1];
Bz[i]=ptr[2] + B_self[2];
}
}
////////////////////////////////////Vector reduction and deallocation///////////////////////////////
std::vector<double> fBx(N,0); //stores the final magnetic field after reduction from all procs
std::vector<double> fBy(N,0);
std::vector<double> fBz(N,0);
//sums the value of B at each position over all processors, for each dipole only the output from 1 processor will be non zero
ierror = MPI_Reduce(&Bx[0], &fBx[0], N, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); errcheck(ierror, "MPI_Reduce");
MPI_Reduce(&By[0], &fBy[0], N, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&Bz[0], &fBz[0], N, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
//deallocates Bx,By,Bz on all processors
std::vector<double>().swap(Bx);
std::vector<double>().swap(By);
std::vector<double>().swap(Bz);
////////////////////////////////Final parameter calculation and data output/////////////////////////
double D[3] ={0,0,0}; //demagnetizing factors
double B_avg[3]={0,0,0}; //Average magnetic fields
if (rank==0)
{
//find average B in each axis
B_avg[0] = avg_1D(fBx);
B_avg[1] = avg_1D(fBy);
B_avg[2] = avg_1D(fBz);
//calculate demganetizing factor in each axis
D[0] = 1-(B_avg[0]*(l*l*l))/(k*4*M_PI);
D[1] = 1-(B_avg[1]*(l*l*l))/(k*4*M_PI);
D[2] = 1-(B_avg[2]*(l*l*l))/(k*4*M_PI);
std::cout<<std::setprecision(30);
std::cout<<"Average Bx,By,Bz is:("<<B_avg[0]<<","<<B_avg[1]<<","<<B_avg[2]<<")"<<std::endl;
std::cout<<"Average Dx,Dy,Dz is:("<<D[0]<<","<<D[1]<<","<<D[2]<<")"<<std::endl;
std::cout<<std::setprecision(6);
for (int i = 0;i<nz;i++)
{
if (i==nz/2)//remove this to print all layers
{
print_xyplane(fBx,nx,ny,i);//replacing fBx with fBy/fBz prints corresponding component of the field
}
}
for (int i = 0;i<nx;i++)
{
//print_zyplane(fBx,nz,ny,nx,i);
}
}
double end_time = MPI_Wtime(); //timer
std::cout << "Run time: " << end_time -start_time << " seconds" <<std::endl;
ierror = MPI_Finalize(); errcheck(ierror, "MPI_Finalize");
}
<file_sep>/README.md
# Magnetic-dipole-field-calculations-in-parallel
Calculations of the magnetic field and the demagnetizing factor generated by a lattice of magnetic dipoles. Written in C++ with a serial implementation and a parallel implementation using MPI.
<file_sep>/dipole_field_serial.cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
#include <iomanip>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
double avg_1D(std::vector<double> &array)
{
double sum=0;
int count=0;
for (int i =0; i<array.size();i++)
{
if (array[i]!=0)
{
sum = sum + array[i];
}
else
{
count++;
}
}
return(sum/(array.size()-count));
}
//each call of this function returns the x,y,z component of the total B
//field for a single point within the ellipsoid
double* getB(double m[],int nx,int nxny,int i,double k, double l,int N,int x,int y,int z)
{
int j;//tracks the array position of the dipole acting on dipole i
int x2,y2,z2; //coordinates of acting dipole
int dx,dy,dz;
double mag,rdotm,r_mag_cubed,k_div_r_mag_cubed;
double r_hat[3] ={0};//stores unit vector from j to i
double* out = new double[3];//stores cumulative bx,by,bz values acting on i
z= i/(nxny);//calculates x,y,z coordinates starting from (0,0,0) of each dipole i
y=(i-nxny*z)/nx;
x=i%nx;
out[0]=0;
out[1]=0;
out[2]=0;
for (j=0;j<N;j++)
{
if (i!=j)//to filter out particles from acting on themselves
{
z2= j/(nxny);//x,y,z coordinates of each dipole j
y2=(j-nxny*z2)/nx;
x2=j%nx;
dx=x2-x;
dy=y2-y;
dz=z2-z;
mag = sqrt((dx)*(dx)+(dy)*(dy)+(dz)*(dz)); //magnitude of r
r_mag_cubed = (mag*l)*(mag*l)*(mag*l);
k_div_r_mag_cubed=k/r_mag_cubed;
r_hat[0] = (dx)/mag;//calculate and normalise r
r_hat[1] = (dy)/mag;
r_hat[2] = (dz)/mag;
rdotm = (r_hat[0]*m[0]+r_hat[1]*m[1]+r_hat[2]*m[2]);
//calculate contribution to B at i due to j
out[0] = out[0]+k_div_r_mag_cubed*((3*r_hat[0]*rdotm-m[0]));
out[1] = out[1]+k_div_r_mag_cubed*((3*r_hat[1]*rdotm-m[1]));
out[2] = out[2]+k_div_r_mag_cubed*((3*r_hat[2]*rdotm-m[2]));
}
}
return(out);
}
bool inside_ellipsoid(float x,float y,float z,float rx,float ry,float rz)
{
//returns true/false depending on if a particles coordinates are within the ellipsoid
bool in = (((x-rx)*(x-rx))/(rx*rx)+((y-ry)*(y-ry))/(ry*ry)+((z-rz)*(z-rz))/(rz*rz))<=1.00;
return in;
}
void print_xyplane(std::vector<double> const &Bx,int nx,int ny,int layer)
{
//for a chosen z layer, prints a x-y grid of Bx/By/Bz values
for (int i =0;i<ny;i++)
{
//the outer loop iterates over each row, the inner loop iterates from the start of that
//row on the specified layer and the end of that row,ie over each column
for (int j =layer*nx*ny+i*nx;j<layer*nx*ny+i*nx+nx;j++)
{
std::cout<<Bx[j]<<" ";
}
std::cout<<std::endl;
}
}
void print_zyplane(std::vector<double> const &Bx,int nz,int ny,int nx,int layer)
{
//for a chosen z layer, prints a z-y grid of Bx/By/Bz values
for (int i =0;i<ny;i++)
{
//takes significantly longer to print due to non contiguous memory access
for (int j =layer+i*ny;j<layer+nx*ny*nz+i*ny;j+=nx*ny)
{
std::cout<<Bx[j]<<" ";
}
std::cout<<std::endl;
}
}
int main (int argc, char *argv[])
{
auto t1 = Clock::now(); //timer
///////////////////////////////Simulation user input variables//////////////////////////////////////
double u = 9.274009e-24; //magnetic dipole moment=bohr magneton
float rx= 10e-9; //x,y,z radius of ellipsoid
float ry= 10e-9;
float rz= 20e-9;
const double l=3e-10; //lattice seperation
double m[3] = {1,0,0}; //magnetic moment direction
///////////////////////////////////////Simulation setup/////////////////////////////////////////////
double k = u * 1e-7;
int nx=2*rx/l; //lattice dimensions
int ny=2*ry/l;
int nz=2*rz/l;
int N=nx*ny*nz;
int nxny = nx*ny;
int z,y,x;
///////////////////////////////////////////Simulation////////////////////////////////////////
double B_self[3]={0,0,0};//stores the self generated magnetic field in each axis
std::vector<double> Bx(N,0);//stores x,y,z component of the magnetic field respectively
std::vector<double> By(N,0);
std::vector<double> Bz(N,0);
double* ptr;//A temporary pointer which stores the output of the result of getB
B_self[0] = (k*8*M_PI)/(3*(l*l*l))*m[0];//calculate B due to self
B_self[1] = (k*8*M_PI)/(3*(l*l*l))*m[1];
B_self[2] = (k*8*M_PI)/(3*(l*l*l))*m[2];
//The following structure loops through all dipoles, for each dipole within the ellipsoid it calls the getB function which calculates the magnetic field due to the interaction of all N dipoles. It then combines the self generated and interaction magnetic fields
for (int i=0;i<N;i++)
{
z= i/(nx*ny);
y=(i-nx*ny*z)/nx;
x=i%nx;
if (inside_ellipsoid(x,y,z,((float)(nx)-1)/2,((float)(ny)-1)/2,((float)(nz)-1)/2) ==1)//only calculates B for dipoles within ellipsoid
{
ptr=getB(m,nx,nxny,i,k,l,N,x,y,z);
Bx[i]=ptr[0] + B_self[0];//combines interacting and self generated fields
By[i]=ptr[1] + B_self[1];
Bz[i]=ptr[2] + B_self[2];
}
}
////////////////////////////////Final parameter calculation and data output/////////////////////////
double D[3] ={0,0,0}; //demagnetizing factors
double B_avg[3]={0,0,0}; //Average magnetic fields
//find average B in each axis
B_avg[0] = avg_1D(Bx);
B_avg[1] = avg_1D(By);
B_avg[2] = avg_1D(Bz);
//calculate demganetizing factor in each axis
D[0] = 1-(B_avg[0]*(l*l*l))/(k*4*M_PI);
D[1] = 1-(B_avg[1]*(l*l*l))/(k*4*M_PI);
D[2] = 1-(B_avg[2]*(l*l*l))/(k*4*M_PI);
std::cout<<std::setprecision(30);
std::cout<<"Average Bx,By,Bz is:("<<B_avg[0]<<","<<B_avg[1]<<","<<B_avg[2]<<")"<<std::endl;
std::cout<<"Average Dx,Dy,Dz is:("<<D[0]<<","<<D[1]<<","<<D[2]<<")"<<std::endl;
std::cout<<std::setprecision(6);
for (int i = 0;i<nz;i++)
{
if (i==nz/2)//remove this to print all layers
{
print_xyplane(Bx,nx,ny,i);//replacing fBx with fBy/fBz prints corresponding component of the field
}
}
for (int i = 0;i<nx;i++)
{
//print_zyplane(Bx,nz,ny,nx,i);
}
auto t2 = Clock::now();
double timetaken =(std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count())*1e-9;
std::cout <<"Time taken: "<<timetaken<<" seconds"<<std::endl;
}
|
0a1a445da102bbbcb0eebd7b534e806b3c73e2bb
|
[
"Markdown",
"C++"
] | 3 |
C++
|
NUCG1GB/Magnetic-dipole-field-calculations-in-parallel
|
1c0cb3f3f4d66a308617e2da4d419de906eaa9d1
|
84dab0f06d3b4cabd1fc17ce6e008861cd850c6e
|
refs/heads/master
|
<file_sep>## Put comments here that give an overall description of what your
## functions do
## makeCacheMatrix allows the caching of the matrix and its inversion through the variables x and i that lives only within the enclosing environment
## cacheSolve is the actual matrix inversion function but it firsts checks if it has been cached before solving
## Write a short comment describing this function
## function that returns a list of functions, acts similiarily to objects in OOP
## functions include:
## set() stores a matrix
## get() retrieves the matrix
## setinverse() stores the inverted matrix
## getinverse() retrieves the inverted matrix
makeCacheMatrix <- function(x = matrix()) {
i <- NULL
set <- function(y) {
x <<- y
i <<- NULL
}
get <- function() x
setinverse <- function(inverse) i <<- inverse
getinverse <- function() i
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Write a short comment describing this function
## function that attempts to retrieve the cached inverted matrix, if not found, compute the inverted matrix via solve()
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
i <- x$getinverse()
if(!is.null(i)) {
print("getting cached data")
return(i)
}
data <- x$get()
i <- solve(data, ...)
x$setinverse(i)
i
}
|
81b66d6668aafe8e88f6b7db0c11f673cad5b299
|
[
"R"
] | 1 |
R
|
ajchang84/ProgrammingAssignment2
|
77e17a46c5cd3381823329daf69818b33420d8ab
|
f888a07312fe8009e33250c4d88b4266832a5c03
|
refs/heads/master
|
<repo_name>Tatharo/Maes<file_sep>/README.md
# Maes
Start up
<file_sep>/src/com/tatharo/crm/persistence/repository/GenericRepository.java
package com.tatharo.crm.persistence.repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class GenericRepository<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(GenericRepository.class);
private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("Maes");
public T merge(T entity) {
EntityManager em = this.getEntityManager();
T mergedEntity = null;
try {
em.getTransaction().begin();
mergedEntity = em.merge(entity);
em.getTransaction().commit();
} catch (Exception e) {
LOGGER.error("Unable to update Entity " + entity.getClass().toString(), e);
try {
em.getTransaction().rollback();
} catch (Exception ex) {
LOGGER.error("exception", ex);
}
}
return mergedEntity;
}
public void remove(T entity) {
EntityManager em = this.getEntityManager();
try {
em.getTransaction().begin();
em.remove(entity);
em.getTransaction().commit();
} catch (Exception e) {
em.getTransaction().rollback();
LOGGER.error("Unable to update Entity " + entity.getClass().toString(), e);
}
}
// TODO Entity manager per logged in user/session
protected EntityManager getEntityManager() {
EntityManager em = factory.createEntityManager();
return em;
}
}
<file_sep>/src/com/tatharo/crm/service/UserService.java
package com.tatharo.crm.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.tatharo.crm.persistence.model.User;
import com.tatharo.crm.persistence.repository.UserRepository;
@Path("/user")
public class UserService {
@GET
@Path("/dummy")
@Produces(MediaType.TEXT_PLAIN)
public String dummy() {
new UserRepository().merge(new User("Hashtag"));
return "Received";
}
}
|
a5f5a4f10244461264899bf75c00d3c22634c998
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
Tatharo/Maes
|
8c12f3fd4ef5af82fed39dd7c7c8b214042e565e
|
7754881c53c34a48f9725610947748e0f811e660
|
refs/heads/main
|
<repo_name>leomesssssssi/Li-jia-ming<file_sep>/clf.py
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from sklearn.decomposition import PCA
import numpy as np
import re
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.naive_bayes import GaussianNB
from mlxtend.classifier import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import Perceptron
from sklearn import tree
from sklearn.neural_network import MLPClassifier
from sklearn import neighbors
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from sklearn.ensemble import AdaBoostClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import BaggingClassifier
def load_data(input_file_name_in):
input_file = open(input_file_name_in, 'r', encoding='utf-8')
id_list_out = []
data_list_out = []
label_list_out = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
print('loading:')
for i in lines_1:
count += 1
print('\r', count/len(lines_1)*100, '%', end='')
if '<review id=' in i:
i = i.replace('1.0', '1')
i = i.replace('0.0', '0')
isp = i.split(' ')
for sp in isp:
if 'id' in sp:
id_ind = sp.index("=")
new_id = sp[id_ind + 2:-1]
id_in = int(new_id)
id_list_out.append(id_in)
elif 'label' in sp:
lb_ind = sp.index("=")
new_lb = sp[lb_ind + 2:-2]
label_in = int(new_lb)
label_list_out.append(label_in)
else:
if '</review>' in i:
data_list_i = []
new_data_str = last.split(' ')
for data in new_data_str:
if re.search(r'\d', data):
if '[' in data or ']' in data:
data = data.replace('[', '')
data = data.replace(']', '')
data_in = float(data)
data_list_i.append(data_in)
data_list_out.append(data_list_i)
last = ''
else:
last += i
id_list_output = np.array(id_list_out[0:len(id_list_out)])
label_list_output = np.array(label_list_out[0:len(label_list_out)])
data_list_output = np.array(data_list_out[0:len(data_list_out)])
print('\n')
print('loading successfully!\n')
return id_list_output, label_list_output, data_list_output
def normalization(data):
_range = np.max(data, axis=0) - np.min(data, axis=0)
return (data - np.min(data, axis=0)) / _range
def standardization(data):
mu = np.mean(data, axis=0)
sigma = np.std(data, axis=0)
return (data - mu) / sigma
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
input_file_name_sample = './sample_0.98_d2v_40000.txt'
id_list_sample, label_list_sample, data_list_sample = load_data(input_file_name_sample)
input_file_name_test = './test_0.98_d2v.txt'
id_list_test, label_list_test, data_list_test = load_data(input_file_name_test)
x_train = standardization(data_list_sample)
y_train = label_list_sample
x_test = standardization(data_list_test)
y_test = label_list_test
clf1 = BaggingClassifier(KNeighborsClassifier(),n_estimators=20, max_samples=0.5, max_features=0.5)
clf1.fit(x_train, y_train)
y_true, y_pred = y_test, clf1.predict(x_test)
print(classification_report(y_true, y_pred))
# Set the parameters by cross-validation
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
"""
SVC(kernel='linear')
BaggingClassifier(KNeighborsClassifier(),n_estimators=20, max_samples=0.5, max_features=0.5)
RandomForestClassifier(n_estimators=10)
AdaBoostClassifier(n_estimators=10)
base_clf = SVC(kernel='linear', probability=True)
clf = AdaBoostClassifier(base_estimator=base_clf, n_estimators=5)
scores = cross_val_score(clf, x_train, y_train, cv=5, scoring='roc_auc')
print(scores)
clf1 = KNeighborsClassifier(n_neighbors=1)
clf2 = SVC(kernel='linear', probability=True)
clf3 = GaussianNB()
clf4 = DecisionTreeClassifier(criterion="entropy")
lr = LogisticRegression( solver='lbfgs')
sclf = StackingClassifier(classifiers=[clf1, clf2, clf3, clf4], meta_classifier=lr)
for clf, label in zip([clf1, clf2, clf3, clf4, sclf], ['KNN', 'SVC', 'Naive Bayes','Decision Tree','StackingClassifier']):
scores = cross_val_score(clf, X, y, cv=5, scoring='roc_auc')
print("AUC: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label))
neighbors.KNeighborsClassifier()
GaussianNB()
Perceptron(max_iter=40, eta0=0.01, random_state=1)
tree.DecisionTreeClassifier(criterion="entropy")
MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
SVC(kernel='linear')
clf1 = SVC(kernel='linear', C=10)
clf1.fit(X_train, y_train)
gnb = GaussianNB()
gnb.fit(X_train, y_train)
y_pred = gnb.fit(X_train, y_train).predict(X_test)
X_train, X_test, y_train, y_test = train_test_split(
x, y, test_size=0.5)
y_pred = knn.fit(X_train, y_train).predict(X_test)
y_true, y_pred = y_test, knn.predict(X_test)
print(classification_report(y_true, y_pred))
clf1 = SVC(kernel='linear', C=10)
clf1.fit(x_train, y_train)
y_true, y_pred = y_test, clf1.predict(x_test)
print(classification_report(y_true, y_pred))
clf = Perceptron(max_iter=40, eta0=0.01, random_state=1)
clf = tree.DecisionTreeClassifier(criterion="entropy")
scores = cross_val_score(clf, x, y, cv=10)
clf = neighbors.KNeighborsClassifier()
clf1.fit(X_train, y_train)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1, stratify=y)
sc = StandardScaler()
sc(criterion="entropy")
print('clf success').fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
clf.fit(X_train_std, y_train)
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
input_file_name_test = './output_0.9_test.txt'
id_list_test, label_list_test, data_list_test = load_data(input_file_name_test)
x_test = normalization(data_list_test)
y_test = label_list_test"""<file_sep>/snowNLP.py
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from snownlp import SnowNLP
import re
import numpy as np
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud
from sklearn.metrics import classification_report
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def load_data_sample(input_file_name, label):
input_file = open(input_file_name, 'r', encoding='utf-8')
id_list = []
str_list = []
label_list_out = []
doc_list = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
for i in lines_1:
if '<review id=' in i:
ind = i.index("=")
new_id = i[ind + 2:-2]
id_in = int(new_id)
id_list.append(id_in)
label_list_out.append(label)
else:
if '</review>' in i:
new_str = ''
for j in last.split("\n"):
new_str += j
new_str = re.sub("[a-zA-Z0-9]", "", new_str)
if new_str == []:
label_list_out.pop()
id_list.pop()
else:
doc_list.append(new_str)
last = ''
else:
last += i
print(doc_list[3])
return id_list, doc_list, label_list_out
def load_data_test(input_file_name_in):
input_file = open(input_file_name_in, 'r', encoding='utf-8')
id_list_out = []
doc_list = []
label_list_out = []
str_list = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
print('loading:')
for i in lines_1:
count += 1
print('\r', count/len(lines_1)*100, '%', end='')
if '<review id=' in i:
isp = i.split(' ')
for sp in isp:
if 'id' in sp:
id_ind = sp.index("=")
new_id = sp[id_ind + 2:-1]
id_in = int(new_id)
id_list_out.append(id_in)
elif 'label' in sp:
lb_ind = sp.index("=")
new_lb = sp[lb_ind + 2:-2]
label_in = int(new_lb)
label_list_out.append(label_in)
else:
if '</review>' in i:
new_str = ''
for j in last.split("\n"):
new_str += j
new_str = re.sub("[a-zA-Z0-9]", "", new_str)
if new_str == []:
label_list_out.pop()
id_list_out.pop()
else:
doc_list.append(new_str)
last = ''
else:
last += i
id_list_output = np.array(id_list_out[0:len(id_list_out)])
label_list_output = np.array(label_list_out[0:len(label_list_out)])
print('\n')
print('loading successfully!\n')
return id_list_output, doc_list, label_list_output
def word_filter(seg_list_in):
stopword_list = get_stopwords_list()
filter_list_out = []
cn_reg = '^[\u4e00-\u9fa5]+$'
for seg in seg_list_in:
word = seg
if word not in stopword_list and re.search(cn_reg, word):
filter_list_out.append(word)
return filter_list_out
def get_stopwords_list():
stop_word_path = './cn_stopwords.txt'
stop_words_list = []
stopwords_file = open(stop_word_path, 'r', encoding='utf-8')
for sw in stopwords_file.readlines():
stop_words_list.append(sw.replace('\n', ''))
return stop_words_list
def load_doc_sample(input_file_name, label):
input_file = open(input_file_name, 'r', encoding='utf-8')
id_list = []
str_list = []
label_list_out = []
doc_list = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
for i in lines_1:
if '<review id=' in i:
ind = i.index("=")
new_id = i[ind + 2:-2]
id_in = int(new_id)
id_list.append(id_in)
label_list_out.append(label)
else:
if '</review>' in i:
new_str = ''
for j in last.split("\n"):
new_str += j
new_str = re.sub("[a-zA-Z0-9]", "", new_str)
str_list.append(new_str)
seg_list = jieba.cut(new_str)
filter_list = word_filter(seg_list)
if filter_list == []:
label_list_out.pop()
id_list.pop()
else:
doc_list.append(filter_list)
last = ''
else:
last += i
print(doc_list[3])
return id_list, doc_list, label_list_out
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
id_list_test, doc_list_test, label_list_test = load_data_test('./test.label.cn.txt')
doc_list = doc_list_test
label_list = label_list_test
print(len(doc_list))
print(len(label_list))
print(len(id_list_test))
label_list_true = np.array(label_list[0:len(label_list)])
label_pre = np.zeros(len(doc_list))
for i in range(0, len(doc_list)):
s = SnowNLP(doc_list[i])
if float(s.sentiments) < 0.5:
label_pre[i] = 0
else:
label_pre[i] = 1
print(label_pre)
y_true = label_list_true
y_pred = label_pre
print(classification_report(y_true, y_pred))
if __name__ == "__main__":
# 重新训练模型
sentiment.train('./neg.txt', './pos.txt')
# 保存好新训练的模型
sentiment.save('sentiment.marshal')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
<file_sep>/yuchuli.py
# This is a sample Python script.
import functools
import math
import codecs
import string
from zhon.hanzi import punctuation
from gensim.models import word2vec
import sys
from sklearn.decomposition import PCA
import random
import logging
import gensim.models
import numpy as np
import re
import gensim.models as g
from sklearn.preprocessing import StandardScaler
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import jieba
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def load_data_test(input_file_name_in):
input_file = open(input_file_name_in, 'r', encoding='utf-8')
id_list_out = []
doc_list = []
label_list_out = []
str_list = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
print('loading:')
for i in lines_1:
count += 1
print('\r', count/len(lines_1)*100, '%', end='')
if '<review id=' in i:
isp = i.split(' ')
for sp in isp:
if 'id' in sp:
id_ind = sp.index("=")
new_id = sp[id_ind + 2:-1]
id_in = int(new_id)
id_list_out.append(id_in)
elif 'label' in sp:
lb_ind = sp.index("=")
new_lb = sp[lb_ind + 2:-2]
label_in = int(new_lb)
label_list_out.append(label_in)
else:
if '</review>' in i:
new_str = ''
for j in last.split("\n"):
new_str += j
str_list.append(new_str)
seg_list = jieba.cut(new_str)
filter_list = word_filter(seg_list)
if not filter_list:
label_list_out.pop()
id_list_out.pop()
else:
doc_list.append(filter_list)
last = ''
else:
last += i
id_list_output = np.array(id_list_out[0:len(id_list_out)])
label_list_output = np.array(label_list_out[0:len(label_list_out)])
print('\n')
print('loading successfully!\n')
return id_list_output, doc_list, label_list_output
# 加载停用表
def get_stopwords_list():
stop_word_path = './cn_stopwords.txt'
stop_words_list = []
stopwords_file = open(stop_word_path, 'r', encoding='utf-8')
for sw in stopwords_file.readlines():
stop_words_list.append(sw.replace('\n', ''))
return stop_words_list
# 去除干扰词
def word_filter(seg_list_in):
stopword_list = get_stopwords_list()
filter_list_out = []
cn_reg = '^[\u4e00-\u9fa5]+$'
for seg in seg_list_in:
word = seg
if word not in stopword_list and re.search(cn_reg, word):
filter_list_out.append(word)
return filter_list_out
# 导入,返回筛词后的分词结果
def load_data_sample(input_file_name, label):
input_file = open(input_file_name, 'r', encoding='utf-8')
id_list = []
str_list = []
label_list_out = []
doc_list = []
lines_1 = input_file.read().split('\n')
count = 0
last = ''
for i in lines_1:
if '<review id=' in i:
ind = i.index("=")
new_id = i[ind + 2:-2]
id_in = int(new_id)
id_list.append(id_in)
label_list_out.append(label)
else:
if '</review>' in i:
new_str = ''
for j in last.split("\n"):
new_str += j
new_str = re.sub("[a-zA-Z0-9]", "", new_str)
str_list.append(new_str)
seg_list = jieba.cut(new_str)
filter_list = word_filter(seg_list)
if filter_list == []:
label_list_out.pop()
id_list.pop()
else:
doc_list.append(filter_list)
last = ''
else:
last += i
print(doc_list[3])
return id_list, doc_list, label_list_out
# idf值统计方法
def train_idf(doc_list):
idf_dic = {}
tt_count = len(doc_list)
for doc in doc_list:
for word in set(doc):
idf_dic[word] = idf_dic.get(word, 0.0) + 1.0
for k, v in idf_dic.items():
idf_dic[k] = math.log(tt_count/(1.0+v))
default_idf = math.log(tt_count/1.0)
return idf_dic, default_idf
# 排序函数
def cmp(e1, e2):
import numpy as np
res = np.sign(e1[1] - e2[1])
if res != 0:
return res
else:
a = e1[0] + e2[0]
b = e2[0] + e1[0]
if a > b:
return 1
elif a == b:
return 0
else:
return -1
# TF-IDF类
class Tfidf(object):
def __init__(self, idf_dic, default_idf, word_list):
self.word_list = word_list
self.idf_dic, self.dafault_idf = idf_dic, default_idf
self.tf_dic = self.get_tf_dic()
# 统计tf值
def get_tf_dic(self):
tf_dic = {}
for word in self.word_list:
tf_dic[word] = tf_dic.get(word, 0.0) + 1.0
tt_count = len(self.word_list)
for k, v in tf_dic.items():
tf_dic[k] = float(v) / tt_count
return tf_dic
# 按公式计算 tf-idf
def get_tfidf(self):
tfidf_dic = {}
for word in self.word_list:
idf = self.idf_dic.get(word, self.dafault_idf)
tf = self.tf_dic.get(word, 0)
tfidf = tf * idf
tfidf_dic[word] = tfidf
return tfidf_dic
def tfidf_extract(doc_list_in, word_list):
idf_dic, default_idf = train_idf(doc_list_in)
tfidf_model = Tfidf(idf_dic, default_idf, word_list)
return tfidf_model.get_tfidf()
def doc2vec(file_name, model):
import jieba
doc = [w for x in codecs.open(file_name, 'r', 'utf-8').readlines() for w in jieba.cut(x.strip())]
doc_vec_all = model.infer_vector(doc)
return doc_vec_all
def simlarityCalu (vector1, vector2):
vector1Mod = np.sqrt(vector1.dot(vector1))
vector2Mod = np.sqrt(vector2.dot(vector2))
if vector2Mod != 0 and vector1Mod != 0:
simlarity = (vector1.dot(vector2)) / (vector1Mod * vector2Mod)
else:
simlarity = 0
return simlarity
def normalization(data):
_range = np.max(data, axis=0) - np.min(data, axis=0)
return (data - np.min(data, axis=0)) / _range
def standardization(data):
mu = np.mean(data, axis=0)
sigma = np.std(data, axis=0)
return (data - mu) / sigma
def file_write(output_file_name, id_list_in, label_list_in, doc_list_in):
with open(output_file_name, 'w', encoding='utf-8') as output_file:
for i in range(0, len(id_list_in)):
output_file.write('<review id="' + ''.join(str(id_list_in[i])) + '" label="')
output_file.write(''.join(str(label_list_in[i])) + '">' + '\n')
output_file.write(''.join(str(doc_list_in[i])) + '\n')
output_file.write('</review>' + '\n')
return 0
def load_doc_list(input_file_name):
input_file = open(input_file_name, 'r', encoding='utf-8')
lines_1 = input_file.read().split('\n')
doc_list = []
for new_str in lines_1:
seg_list = jieba.cut(new_str)
filter_list = word_filter(seg_list)
if not filter_list:
continue
else:
doc_list.append(filter_list)
return doc_list
# Press the green button in the gutter to run the script.
# <review id="0" label="1">
if __name__ == '__main__':
id_list_test, doc_list_test, label_list_test = load_data_test('./test.label.cn.txt')
model_path = './doc2vec_test2.model'
model = g.Doc2Vec.load(model_path)
doc_vec = []
doc_list = doc_list_test
print(len(doc_list))
for i in range(0, len(doc_list)):
print('\r', i / len(doc_list) * 100, '%', end='')
doc_vec_all = model.infer_vector(doc_list[i])
doc_vec.append(doc_vec_all)
X = np.array(doc_vec[0:len(doc_list)])
X_scaler = StandardScaler()
X = X_scaler.fit_transform(X)
file_write('test_d2v_300.txt', id_list_test, label_list_test, X)
pca_98 = PCA(n_components=272).fit(X)
pca_x98 = pca_98.transform(X)
print(pca_x98.shape)
y = np.array(label_list_test[0:len(label_list_test)])
x98 = standardization(pca_x98)
print(x98.shape)
file_write('test_0.98_d2v.txt', id_list_test, label_list_test, x98)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
""""#for letter in 'Runoob':
if letter=='o':
continue
print('当前字母'+letter)""
id_list_tlc, doc_list_tlc, label_list_tlc = load_data_test('./test.label.cn.txt')
model_path = "wordvec.model"
wordvec = gensim.models.Word2Vec.load(model_path)
print(wordvec.wv.get_vector("华为"))
print(wordvec.wv.most_similar("华为",topn=5))
print(wordvec.wv.similarity("西红柿","番茄"))"""
"""sn_str_list, sn_doc_list = load_data('./sample.negative.txt')
sp_str_list, sp_doc_list = load_data('./sample.positive.txt')
doc_list = sp_doc_list
doc_list.extend(sn_doc_list)
ran = random.randint(1, len(doc_list))
tfidf_extract(doc_list, doc_list[ran])
print("\n\n\n\n\n\n\n\n")
print(doc_list[ran])
input_file_name = './corpus_cn.txt'
input_file = open(input_file_name, 'r', encoding='utf-8')
lines_1 = input_file.read().split('\n')
print(len(lines_1))
print(lines_1[1])
print(lines_1[3])
model_path = './doc2vec_test2.model'
model = g.Doc2Vec.load(model_path)
p1 = './P1.txt'
p2 = './P2.txt'
P1_doc2vec = doc2vec(p1, model)
P2_doc2vec = doc2vec(p2, model)
print(simlarityCalu(P1_doc2vec, P2_doc2vec))
doc_vec = []
model_path = './doc2vec_test2.model'
model = g.Doc2Vec.load(model_path)
for i in range(0, len(doc_list_tlc)):
doc_vec_all = model.infer_vector(doc_list_tlc[i])
doc_vec.append(doc_vec_all)
X = np.array(doc_vec[0:len(doc_list_tlc)])
X_scaler = StandardScaler()
X = X_scaler.fit_transform(X)
pca = PCA(n_components=119).fit(X)
pca_x = pca.transform(X)
y = np.array(label_list_tlc[0:len(label_list_tlc)])
x = standardization(pca_x)
print(x.shape)
print(y.shape)
print(x[123])
file_write('output_0.8_test.txt', id_list_tlc, label_list_tlc, pca_x)"""
|
b0ce8e0fdc2c070d87e9d25a2913a24b6e705134
|
[
"Python"
] | 3 |
Python
|
leomesssssssi/Li-jia-ming
|
cc93d4d6b401ca36d046a275cb9fbb32cf56c096
|
33ff73c5f27191736e2994ad22ede70a81438525
|
refs/heads/master
|
<repo_name>Anjaliani/Javascript<file_sep>/growth.js
var output = [];
var fs= require('fs');
var lineReader = require('readline').createInterface({
input: fs.createReadStream('Table_1.3.csv')
});
lineReader.on('line', function (line) {
var jsonLine = {};
var lineSplit = line.split(',');
jsonLine.CountryName=lineSplit[0];
jsonLine.PopulationGrowth=lineSplit[5]-lineSplit[2];
if (jsonLine.CountryName =='European Union' || jsonLine.CountryName == 'Country Name' || jsonLine.CountryName =='World' ) {
}
else{
output.push(jsonLine);
}
});
lineReader.on('close', function (line) {
console.log(output);
var json = JSON.stringify(output, null, 2);
fs.writeFileSync('populationGrowth.json',json);
});
//for GDP
var output1 = [];
lineReader.on('line', function (line) {
var json = {};
var lineSplit = line.split(',');
json.CountryName=lineSplit[0];
json.PurchasingPowerGrowth=lineSplit[8]-lineSplit[11];
if (json.CountryName =='European Union' || json.CountryName == 'Country Name' || json.CountryName =='World') {
}
else{
output1.push(json);
}
});
lineReader.on('close', function (line) {
console.log(output1);
var json = JSON.stringify(output1, null, 2);
fs.writeFileSync('powerByCountryGrowth.json',json);
});
|
0f07ccdef6479c638ecdaa108280f967eee02dba
|
[
"JavaScript"
] | 1 |
JavaScript
|
Anjaliani/Javascript
|
790f8e219c30cd4b3935ca7b9264d4d4b2ae3fec
|
ca480737279dada3eb714b38db21082d01c4d03a
|
refs/heads/master
|
<file_sep>source PiPyEnv/bin/activate
gunicorn --workers 1 --bind unix:pipy.sock -m 007 src:server
deactivate
<file_sep>Flask
numpy
picamera
opencv-python
<file_sep>from picamera import PiCamera
import cv2 as cv
from flask import Flask
from flask import make_response
from flask import Response
from flask import request
import time
import numpy as np
app = Flask(__name__)
def livestream_gen():
res = (640, 480)
with PiCamera(resolution=res) as pcam:
time.sleep(2)
while True:
img = np.empty((res[1], res[0], 3), dtype=np.uint8)
pcam.capture(img, 'rgb')
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
retval, buffer = cv.imencode('.jpg', img)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
@app.route("/")
def home():
return "Hello World! Welcome to PiPy Imaging API"
@app.route("/still", methods=['GET'])
def still():
res_width = 640
res_height = 480
rotation_val = 0
# Set resolution via args
temp_res_width = request.args.get('width', default=-1, type=int)
temp_res_height = request.args.get('height', default=-1, type=int)
if temp_res_width > 0 and temp_res_height > 0:
res_width = temp_res_width
res_height = temp_res_height
# Set rotation via args
temp_rotation_val = request.args.get('rotate', default=-1, type=int)
if temp_rotation_val > 0:
rotation_val = temp_rotation_val
# Set stereo via args
stereo = request.args.get('stereo', default=0, type=int)
if stereo == 1:
stereo_mode_val = 'side-by-side'
else:
stereo_mode_val = 'none'
with PiCamera(stereo_mode=stereo_mode_val, resolution=(res_width, res_height)) as pcam:
# Set up the camera
pcam.rotation = rotation_val
pcam.exposure_mode = "spotlight"
pcam.awb_mode = "incandescent"
pcam.iso = 100
pcam.shutter_speed = 4000
#time.sleep(1)
img = np.empty((res_height, res_width, 3), dtype=np.uint8)
pcam.capture(img, 'rgb')
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
retval, buffer = cv.imencode('.jpg', img)
response = make_response(buffer.tobytes())
response.headers.set('Content-Type', 'image/jpeg')
#response.headers.set('Content-Disposition', 'attachment', filename='still.jpg')
return response
@app.route("/video")
def video():
return "Works in Progress, this is where video of defined length will be returned"
@app.route("/live")
def live():
return Response(livestream_gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
|
e8f11c9bb20bd8a278246f1d413e6e0927eb68fc
|
[
"Python",
"Text",
"Shell"
] | 3 |
Shell
|
zim96/PiPy-Imaging
|
c1e92d11e18e871bad9fc29c935d9d8657ba7f2d
|
f7f63ef670e74aba300f3d48facfa33aa55b0675
|
refs/heads/master
|
<repo_name>dearhui/MHAboutViewController<file_sep>/Sources/MHAboutViewController/Classes/MHAStoreViewController.swift
//
// MHAPurchaseViewController.swift
// MHAboutViewControllerSample
//
// Created by <NAME> on 2018/2/15.
// Copyright © 2018年 dearhui studio. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import SwiftyStoreKit
class MHAStoreViewController: UITableViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var purchaseLabel: UILabel!
@IBOutlet weak var restoreLabel: UILabel!
@IBOutlet weak var purchaseCell: UITableViewCell!
@IBOutlet weak var restoreCell: UITableViewCell!
var preColor:UIColor = .blue
var preStyle:UITableViewCell.SelectionStyle = .default
override func viewDidLoad() {
super.viewDidLoad()
preColor = purchaseLabel.textColor
loadProduct()
}
func productPrepareUI() {
purchaseLabel.textColor = UIColor.gray
restoreLabel.textColor = UIColor.gray
purchaseCell.selectionStyle = .none
restoreCell.selectionStyle = .none
}
func productReadyUI(name:String, price:String) {
purchaseLabel.textColor = preColor
restoreLabel.textColor = preColor
purchaseCell.selectionStyle = preStyle
restoreCell.selectionStyle = preStyle
nameLabel.text = name
priceLabel.text = price
}
func loadProduct() {
let productID = MHAboutViewController.shared.userProductID
productPrepareUI()
SwiftyStoreKit.retrieveProductsInfo([productID]) { (result) in
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
print("Product: \(product.localizedDescription), price: \(priceString)")
self.productReadyUI(name: product.localizedTitle, price: priceString)
}
else if let invalidProductId = result.invalidProductIDs.first {
print("Invalid product identifier: \(invalidProductId)")
}
else {
print("Error: \(String(describing: result.error))")
}
}
}
//MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView .deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell?.selectionStyle == UITableViewCell.SelectionStyle.none {
return
} else {
if indexPath.section == 1 {
didPurchase()
} else if indexPath.section == 2 {
didRestore()
}
}
}
func didPurchase() {
let productID = MHAboutViewController.shared.userProductID
SwiftyStoreKit.purchaseProduct(productID, quantity: 1, atomically: true) { result in
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
MHAboutViewController.shared.completionHandler()
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
case .privacyAcknowledgementRequired:
print("privacyAcknowledgementRequired")
case .unauthorizedRequestData:
print("unauthorizedRequestData")
case .invalidOfferIdentifier:
print("invalidOfferIdentifier")
case .invalidSignature:
print("invalidSignature")
case .missingOfferParams:
print("missingOfferParams")
case .invalidOfferPrice:
print("invalidOfferPrice")
case .overlayCancelled:
print("overlayCancelled")
case .overlayInvalidConfiguration:
print("overlayInvalidConfiguration")
case .overlayTimeout:
print("overlayTimeout")
case .ineligibleForOffer:
print("ineligibleForOffer")
case .unsupportedPlatform:
print("unsupportedPlatform")
case .overlayPresentedInBackgroundScene:
print("overlayPresentedInBackgroundScene")
@unknown default:
print("unknown error")
}
case .deferred(purchase: let purchase):
print("deferred: \(purchase)")
}
}
}
func didRestore() {
SwiftyStoreKit.restorePurchases(atomically: true) { results in
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
}
else if results.restoredPurchases.count > 0 {
print("Restore Success: \(results.restoredPurchases)")
MHAboutViewController.shared.completionHandler()
}
else {
print("Nothing to Restore")
}
}
}
}
<file_sep>/Example/UIKit/AppDelegate.swift
//
// AppDelegate.swift
// MHAboutViewController
//
// Created by <NAME> on 02/21/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
import UIKit
import MHAboutViewController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
setupMHAbout()
return true
}
func setupMHAbout() {
MHAboutViewController.shared.configure(mail: "YOUR_EMAIL_ADDRESS",
appId: "YOUR_IOS_APP_ID",
componyLink: "YOUR_APP_STORE_LINK",
FBProfileID: "YOUR_FACEBOOK_PAGE",
productID: "YOUR_IN_APP_PRODUCT_ID",
handler: {
print("handler ok ok")
})
}
}
<file_sep>/Example/SwiftUI/MHAboutViewDemo/MHAboutViewDemoApp.swift
//
// MHAboutViewDemoApp.swift
// MHAboutViewDemo
//
// Created by minghui on 2023/6/14.
//
import SwiftUI
@main
struct MHAboutViewDemoApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
<file_sep>/Sources/MHAboutViewController/Classes/MHAUsViewController.swift
//
// MHAUsViewController.swift
// MHAboutViewControllerSample
//
// Created by <NAME> on 2018/2/15.
// Copyright © 2018年 dearhui studio. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import CTFeedbackSwift
class MHAUsViewController: UITableViewController {
let kFacebookScheme = "fb:"
let kFacebookAppLink = "https://itunes.apple.com/app/facebook/id284882215?mt=8"
@IBOutlet weak var versionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
udpateVersion()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isModal() {
updateUI()
}
}
func updateUI() {
let btn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(MHAUsViewController.onCancel))
self.navigationItem.leftBarButtonItem = btn
}
func isModal() -> Bool {
if self.presentingViewController != nil {
return true
} else if self.navigationController?.presentingViewController?.presentedViewController == self.navigationController {
return true
} else if self.tabBarController?.presentingViewController is UITabBarController {
return true
}
return false
}
@objc func onCancel() {
self.dismiss(animated: true, completion: nil)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView .deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 {
switch indexPath.row {
case 1:
didFeedback()
break
case 2:
didOpenFaceBook()
break
case 3:
let link = MHAboutViewController.shared.userComponyLink
appOpen(urlPath: link)
break
default:
break
}
} else if indexPath.section == 2 {
if indexPath.row == 0 {
let appID = MHAboutViewController.shared.userAppId
let appReviewPath = "itms-apps://itunes.apple.com/app/id\(appID)?action=write-review"
appOpen(urlPath: appReviewPath)
}
}
}
func udpateVersion() {
if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String, let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.text = "\(version) (\(build))"
}
}
// MARK: - CTFeedback
func didFeedback() {
let mail = MHAboutViewController.shared.userMail
let configuration = FeedbackConfiguration(toRecipients: [mail], usesHTML: true)
let controller = FeedbackViewController(configuration: configuration)
navigationController?.pushViewController(controller, animated: true)
}
// MARK: - Facebook
func didOpenFaceBook() {
if isFacebookInstalled() {
let profileID = MHAboutViewController.shared.userFBProfileID
openFacebook(profileID: profileID)
} else {
appOpen(urlPath: kFacebookAppLink)
}
}
func isFacebookInstalled() -> Bool {
if let url = URL(string:kFacebookScheme) {
return UIApplication.shared.canOpenURL(url)
} else {
return false
}
}
func openFacebook(profileID:String) {
let urlPath = "\(kFacebookScheme)//profile/\(profileID)"
appOpen(urlPath: urlPath)
}
// MARK: - App Open
func appOpen(urlPath:String) {
if let url = URL(string: urlPath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
print("open link is \(success)")
})
} else {
// Fallback on earlier versions
UIApplication.shared.openURL(url)
}
}
}
}
<file_sep>/Example/UIKit/ViewController.swift
//
// ViewController.swift
// MHAboutViewController
//
// Created by <NAME> on 02/21/2018.
// Copyright (c) 2018 <NAME>. All rights reserved.
//
import UIKit
import MHAboutViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func didShowAbout(_ sender: AnyObject) {
let aboutVC = MHAboutViewController.mainViewController()
self.show(aboutVC, sender: nil)
}
@IBAction func didPopAbout(_ sender: AnyObject) {
let aboutVC = MHAboutViewController.mainViewController()
let nvc = UINavigationController(rootViewController: aboutVC)
self.show(nvc, sender: nil)
}
}
<file_sep>/README.md
# MHAboutViewController
MHAboutViewController is a Swift package that makes it easy to add an "About" screen to your iOS apps.
## Features
- Provides a basic "About" screen template
- Supports redirections to App Store, Facebook
- Supports In-App Purchases
## Installation
### Swift Package Manager
1. In Xcode, select "File" -> "Swift Packages" -> "Add Package Dependency..."
2. Enter the URL of this repository
3. Follow the steps to complete the installation
## Usage
Set up `MHAboutViewController` in your `AppDelegate` or in the app's launching spot:
```swift
import UIKit
import MHAboutViewController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
setupMHAbout()
return true
}
func setupMHAbout() {
MHAboutViewController.shared.configure(mail: "YOUR_EMAIL_ADDRESS",
appId: "YOUR_IOS_APP_ID",
componyLink: "YOUR_APP_STORE_LINK",
FBProfileID: "YOUR_FACEBOOK_PAGE",
productID: "YOUR_IN_APP_PRODUCT_ID",
handler: {
print("handler ok ok")
})
}
}
```
Invoke `MHAboutViewController` where you want to show the "About" screen:
```swift
import UIKit
import MHAboutViewController
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func didShowAbout(_ sender: AnyObject) {
let aboutVC = MHAboutViewController.mainViewController()
self.show(aboutVC, sender: nil)
}
@IBAction func didPopAbout(_ sender: AnyObject) {
let aboutVC = MHAboutViewController.mainViewController()
let nvc = UINavigationController(rootViewController: aboutVC)
self.show(nvc, sender: nil)
}
}
```
## Contact Us
If you encounter any issues, please use the Issue Tracker or send us an email directly.
## License
MIT
<file_sep>/Sources/MHAboutViewController/Classes/MHAboutViewController.swift
//
// MHAManager.swift
// MHAboutViewControllerSample
//
// Created by <NAME> on 2018/2/15.
// Copyright © 2018年 dearhui studio. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import SwiftyStoreKit
@objc public class MHAboutViewController: NSObject {
@objc public static let shared : MHAboutViewController = MHAboutViewController()
var userMail = ""
var userAppId = ""
var userComponyLink = ""
var userFBProfileID = ""
var userProductID = ""
var completionHandler: ()->Void = { print("doNothing")}
@objc public func configure(mail:String, appId:String, componyLink:String, FBProfileID:String, productID:String, handler:@escaping ()->Void) {
userMail = mail
userAppId = appId
userComponyLink = componyLink
userFBProfileID = FBProfileID
userProductID = productID
completionHandler = handler
setupStoreKit()
}
func setupStoreKit() {
// see notes below for the meaning of Atomic / Non-Atomic
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
// Unlock content
self.completionHandler()
print("StoreKit Unlock content")
case .failed, .purchasing, .deferred:
break // do nothing
@unknown default:
print("StoreKit unknown state")
break
}
}
}
}
@objc public static func mainViewController() -> UIViewController {
let storyboard = UIStoryboard(name: "MHAStoryboard", bundle: Bundle.module)
let vc = storyboard.instantiateInitialViewController()!
return vc
}
}
|
67112dc30028c294bd56a31063945117d66a39c5
|
[
"Swift",
"Markdown"
] | 7 |
Swift
|
dearhui/MHAboutViewController
|
5fdf2378cff753166591ebe5d1ff43dc414a7cd5
|
1e018463cd6c72529b5aae01aadc516e064a6e50
|
refs/heads/master
|
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/8/13.
*/
public class EventShutDown {
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.activities.WriteEvaluationActivity;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.view.PinnedSectionListView;
import java.util.List;
/**
* Created by CJQ on 2015/9/15.
*/
public class EvaluationListAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter {
private AQuery aq;
@Override
public boolean isItemViewTypePinned(int viewType) {
return true;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return 1;
}
List<Goods4IndexList> goods4IndexListList;
Context context;
public EvaluationListAdapter(List<Goods4IndexList> goods4IndexListList, Context context) {
this.goods4IndexListList = goods4IndexListList;
this.context = context;
}
@Override
public int getCount() {
return goods4IndexListList.size();
}
@Override
public Object getItem(int position) {
return goods4IndexListList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Goods4IndexList g = goods4IndexListList.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.items4evaluation, parent, false);
}
aq = new AQuery(convertView);
aq.id(R.id.evaluate_item_image).image(g.getGoods_image_url(), false, true);
aq.id(R.id.evaluation_item_title).text(g.getGoods_name());
aq.id(R.id.evaluate_price).text("¥" + g.getGoods_price());
aq.id(R.id.evaluation_count).text("已有" + g.getMarket_price() + "人评价");
aq.id(R.id.evaluation_go_write_evaluation).clicked(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, WriteEvaluationActivity.class);
intent.putExtra("id", g.getGoods_id());
context.startActivity(intent);
}
});
return convertView;
}
}
<file_sep>package com.cjq.bejingunion.entities;
/**
* Created by CJQ on 2015/9/6.
*/
public class Category4Show {
String name;
String id;
boolean chosen;
public Category4Show(String name, String id, boolean chosen) {
this.name = name;
this.id = id;
this.chosen = chosen;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isChosen() {
return chosen;
}
public void setChosen(boolean chosen) {
this.chosen = chosen;
}
}
<file_sep>package com.cjq.bejingunion.entities;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by CJQ on 2015/8/26.
*/
public class DetailChoice implements Parcelable{
String value;
String id;
String src;
public DetailChoice(String value, String id, String src) {
this.value = value;
this.id = id;
this.src = src;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
protected DetailChoice(Parcel in) {
value = in.readString();
id = in.readString();
src = in.readString();
}
public static final Creator<DetailChoice> CREATOR = new Creator<DetailChoice>() {
@Override
public DetailChoice createFromParcel(Parcel in) {
return new DetailChoice(in);
}
@Override
public DetailChoice[] newArray(int size) {
return new DetailChoice[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(value);
dest.writeString(id);
dest.writeString(src);
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.BannerAdapter;
import com.cjq.bejingunion.adapter.DetailChoiceAdapter;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.dialog.WarningAlertDialog;
import com.cjq.bejingunion.entities.Ad;
import com.cjq.bejingunion.entities.CardNumber;
import com.cjq.bejingunion.entities.DetailChoice;
import com.cjq.bejingunion.entities.DetailItem;
import com.cjq.bejingunion.utils.GoodsUtil;
import com.cjq.bejingunion.utils.LoginUtil;
import com.cjq.bejingunion.view.BannerView;
import com.cjq.bejingunion.view.NumericView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/20.
*/
public class CardDetailActivity extends BaseActivity {
private String goods_id;
private AQuery aq;
private TextView nameText;
private ListView detailItemListView;
private DetailChoiceAdapter adapter;
private String is_virtual;
private String is_fcode;
private String number;
private String numberId;
private String price;
private String identify_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buy_phone_number_detail);
Intent intent = getIntent();
goods_id = intent.getStringExtra("goods_id");
aq = new AQuery(this);
nameText = aq.id(R.id.buy_phone_number_detail_name).getTextView();
aq.id(R.id.buy_phone_number_detail_back).clicked(this, "closeUp");
aq.id(R.id.buy_phone_number_detail_buy_immediately).clicked(this, "payImmediately");
aq.id(R.id.buy_phone_number_detail_phone_number).clicked(this, "choosePhoneNumber");
detailItemListView = aq.id(R.id.buy_phone_number_detail_detail_item).getListView();
Map<String, String> params = new HashMap<>();
params.put("goods_id", goods_id);
aq.ajax(CommonDataObject.GOODS_DETAIL_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONObject goods_info = object.getJSONObject("datas").getJSONObject("goods_info");
String name = goods_info.getString("goods_name");
JSONArray images = object.getJSONObject("datas").getJSONArray("goods_image");
is_virtual = goods_info.getString("is_virtual");
is_fcode = goods_info.getString("is_fcode");
aq.id(R.id.buy_phone_number_detail_image).image(images.getString(0));
price = goods_info.getString("goods_price");
aq.id(R.id.buy_phone_number_detail_price).text("¥"+price);
aq.id(R.id.buy_phone_number_detail_detail).text(goods_info.getString("mobile_body"));
JSONArray spec_info = goods_info.getJSONArray("spec_info");
List<DetailItem> detailItems = new ArrayList<DetailItem>();
for (int i = 0; i < spec_info.length(); i++) {
JSONObject o = spec_info.getJSONObject(i);
DetailItem detailItem = new DetailItem(o.getString("attr_type"), o.getString("attr_id"));
JSONArray attr_value = o.getJSONArray("attr_value");
Map<Integer, DetailChoice> choices = new HashMap<>();
for (int j = 0; j < attr_value.length(); j++) {
JSONObject item = attr_value.getJSONObject(j);
DetailChoice choice = new DetailChoice(item.getString("value"), item.getString("id"), item.getString("src"));
choices.put(item.getInt("id"), choice);
}
detailItem.setDetailChoices(choices);
detailItem.setChosenId(o.getString("chosen_id"));
detailItems.add(detailItem);
}
adapter = new DetailChoiceAdapter(detailItems, CardDetailActivity.this);
detailItemListView.setAdapter(adapter);
nameText.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
public void closeUp() {
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String id = data.getStringExtra("resultId");
int position = data.getIntExtra("position", 0);
DetailItem detailItem = (DetailItem) adapter.getItem(position);
detailItem.setChosenId(id);
adapter.notifyDataSetChanged();
}
break;
case 1:
if (resultCode == RESULT_OK) {
CardNumber cardNumber = data.getParcelableExtra("cardNumber");
this.number = cardNumber.getNumber();
this.numberId = cardNumber.getId();
aq.id(R.id.buy_phone_number_detail_phone_number).text(number);
}
break;
case 2:
if (resultCode == RESULT_OK) {
identify_id = data.getStringExtra("id");
//
submit();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
private void submit() {
Intent intent = new Intent(this, PhoneNumberConfirmActivity.class);
intent.putExtra("cart_id", goods_id + "|" + 1);
intent.putExtra("phone_additional_id", identify_id);
intent.putExtra("phone_id", numberId);
intent.putExtra("phoneNumber",number);
intent.putExtra("ifcart", "0");
startActivity(intent);
finish();
}
public void payImmediately() {
if (numberId == null || "".equals(numberId)) {
// Toast.makeText(this, "不选号码怎么帮您购买卡号呢?", Toast.LENGTH_SHORT).show();
MyToast.showText(this, "不选号码怎么帮您购买卡号呢?", R.drawable.a2);
return;
}
if(adapter.getCount()>0){
DetailItem detailItem = (DetailItem) adapter.getItem(0);
DetailChoice choice = detailItem.getDetailChoices().get(Integer.valueOf(detailItem.getChosenId()));
GoodsUtil.showIdentify(this, choice.getValue(), price, number, 2);
}else{
GoodsUtil.showIdentify(this, null, price, number, 2);
}
}
public void choosePhoneNumber() {
Intent intent = new Intent(this, PhoneNumberActivity.class);
startActivityForResult(intent, 1);
}
}
<file_sep>package com.cjq.bejingunion.entities;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by CJQ on 2015/9/10.
*/
public class CardNumber implements Parcelable{
String id;
String number;
public CardNumber(String id, String number) {
this.id = id;
this.number = number;
}
protected CardNumber(Parcel in) {
id = in.readString();
number = in.readString();
}
public static final Creator<CardNumber> CREATOR = new Creator<CardNumber>() {
@Override
public CardNumber createFromParcel(Parcel in) {
return new CardNumber(in);
}
@Override
public CardNumber[] newArray(int size) {
return new CardNumber[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(number);
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.CollectionAdapter;
import com.cjq.bejingunion.adapter.SwipeListAdapter;
import com.cjq.bejingunion.entities.CollectionToShow;
import com.cjq.bejingunion.event.EventCollectionChange;
import com.cjq.bejingunion.utils.LoginUtil;
import com.cjq.bejingunion.view.SwipeListView;
import com.ypy.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/25.
*/
public class MyCollectionActivity extends BaseActivity {
private AQuery aq;
private SwipeListView listView;
public void onEventMainThread(EventCollectionChange e) {
aq.id(R.id.collection_count).text(String.valueOf(listView.getAdapter().getCount()));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collection_list);
//请求列表
aq = new AQuery(this);
aq.id(R.id.collection_back).clicked(this, "closeUp");
listView = (SwipeListView) aq.id(R.id.collection_list).getView();
try {
Map<String, String> params = new HashMap<>();
params.put("key", LoginUtil.getKey(this));
aq.ajax(CommonDataObject.COLLECTION_LIST_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONArray fl = object.getJSONObject("datas").getJSONArray("favorites_list");
int count = object.getJSONObject("datas").getInt("count");
aq.id(R.id.collection_count).text(String.valueOf(count));
List<CollectionToShow> list = new ArrayList<CollectionToShow>();
for (int i = 0; i < fl.length(); i++) {
JSONObject o = fl.getJSONObject(i);
CollectionToShow collectionToShow = new CollectionToShow(o.getString("goods_image_url"), o.getString("goods_name"), o.getString("fav_id"), o.getString("goods_price"), o.getString("goods_id"));
list.add(collectionToShow);
}
listView.setAdapter(new CollectionAdapter(MyCollectionActivity.this, list));
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeUp() {
finish();
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.R;
/**
* Created by CJQ on 2015/8/20.
*/
public class NewProductsRecommendActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activities);
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.utils.FileUploader;
import com.cjq.bejingunion.utils.LoginUtil;
import com.cjq.bejingunion.view.ImageSelectorView;
import com.loopj.android.http.RequestParams;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Created by CJQ on 2015/8/31.
*/
public class PartnerFormActivity extends BaseActivity implements View.OnClickListener, ImageSelectorView.OnImageChangeListener {
private AQuery aq;
private ImageSelectorView imageSelectorView;
private Map<String,String> images=new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apply_partner_form);
aq = new AQuery(this);
imageSelectorView = (ImageSelectorView)aq.id(R.id.apply_form_add_pic).getView();
imageSelectorView.setOnAddButtonClickListener(this);
imageSelectorView.setImageChangeListener(this);
imageSelectorView.setW(120);
imageSelectorView.setH(80);
imageSelectorView.setMax(2);
aq.id(R.id.apply_form_back).clicked(this, "closeUp");
aq.id(R.id.apply_form_submit).clicked(this,"submit");
}
public void submit(){
Map<String,String> params = new HashMap<>();
try {
params.put("key",LoginUtil.getKey(this));
params.put("member_truename",aq.id(R.id.apply_form_member_truename).getText().toString());
params.put("member_mobile",aq.id(R.id.apply_form_member_mobile).getText().toString());
params.put("member_email",aq.id(R.id.apply_form_member_email).getText().toString());
params.put("member_areainfo",aq.id(R.id.apply_form_member_areainfo).getText().toString());
params.put("ID_card",aq.id(R.id.apply_form_id_card).getText().toString());
StringBuilder builder = new StringBuilder();
for (String s:images.values()){
builder.append(s).append(",");
}
String img = builder.toString().substring(0,builder.length()-1);
// System.out.println(img);
params.put("material",img);
aq.ajax(CommonDataObject.APPLY_PARTNER_URL,params,JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
// System.out.println(object.toString());
if(200==object.getInt("code")){
setResult(RESULT_OK);
finish();
}else{
// Toast.makeText(PartnerFormActivity.this,object.getJSONObject("datas").getString("error"),Toast.LENGTH_SHORT).show();
MyToast.showText(PartnerFormActivity.this, object.getJSONObject("datas").getString("error"), R.drawable.a2);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeUp(){
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==1){
if (resultCode == RESULT_OK){
Uri uri = data.getData();
if("content".equals(uri.getScheme())){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
imageSelectorView.addImage(path);
}else
if("file".equals(uri.getScheme()))
{
String path = uri.getPath();
imageSelectorView.addImage(path);
}
}
}
}
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
@Override
public void add(final String path) {
RequestParams params = new RequestParams();
try {
params.put("key", LoginUtil.getKey(this));
FileUploader.upload(CommonDataObject.UPLOAD_AGENT_URL, "pic", path, params, new FileUploader.FileUploadCallBack() {
@Override
public void callBack(JSONObject object) {
try {
if(200==object.getInt("code")){
String image = object.getJSONObject("datas").getString("agent_img");
images.put(path,image);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void delete(String path) {
images.remove(path);
}
}
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/8/25.
*/
public class EventCollectionChange {
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.entities.Area4Show;
import com.cjq.bejingunion.view.PinnedSectionListView;
import java.util.List;
/**
* Created by CJQ on 2015/8/26.
*/
public class AreaAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter {
List<Area4Show> area4Shows;
Context context;
public AreaAdapter(List<Area4Show> area4Shows, Context context) {
this.area4Shows = area4Shows;
this.context = context;
}
@Override
public int getCount() {
return area4Shows.size();
}
@Override
public Object getItem(int position) {
return area4Shows.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.area_list_item,parent,false);
}
Area4Show area4Show = area4Shows.get(position);
AQuery aq = new AQuery(convertView);
aq.id(R.id.text).text(area4Show.getText());
return convertView;
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean isItemViewTypePinned(int viewType) {
return true;
}
}
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/9/1.
*/
public class EventPortraitChange {
String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public EventPortraitChange(String image) {
this.image = image;
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.BrandAdapter;
import com.cjq.bejingunion.adapter.BroadBandBandItemAdapter;
import com.cjq.bejingunion.adapter.MarketGridAdapter;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.entities.BandItem;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.utils.GoodsUtil;
import com.cjq.bejingunion.view.MyRefreshLayout;
import com.cjq.bejingunion.view.RightSlideMenu;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/20.
*/
public class ContractMachineActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, MyRefreshLayout.onLoadListener, AdapterView.OnItemClickListener, TextView.OnEditorActionListener {
private AQuery aq;
private RightSlideMenu menu;
private boolean[] up = {false, false, false, false};
private int activeSort = 1;
private int current_page = 1;
private int gc_id = 3;
private List<Goods4IndexList> goodsList = new ArrayList<Goods4IndexList>();
private BaseAdapter adapter;
private MyRefreshLayout refreshLayout;
private ImageView[] sortViews;
private GridView contractMachineList;
private String band_id;
private List<BandItem> brandList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contract_machine);
aq = new AQuery(this);
aq.id(R.id.contract_machine_back).clicked(this, "closeUp");
aq.id(R.id.contract_machine_draw_category_out).clicked(this, "drawMenuOutSwitch");
menu = (RightSlideMenu) aq.id(R.id.contract_machine_menu_layout).getView();
contractMachineList=aq.id(R.id.contract_machine_grid_list).getGridView();
adapter=new MarketGridAdapter(this,goodsList);
refreshLayout = (MyRefreshLayout) aq.id(R.id.contract_machine_refresh).getView();
contractMachineList.setAdapter(adapter);
contractMachineList.setOnItemClickListener(this);
sortViews = new ImageView[4];
sortViews[0]=aq.id(R.id.contract_machine_sort1).getImageView();
sortViews[1]=aq.id(R.id.contract_machine_sort2).getImageView();
sortViews[2]=aq.id(R.id.contract_machine_sort3).getImageView();
sortViews[3]=aq.id(R.id.contract_machine_sort4).getImageView();
aq.id(R.id.contract_machine_search_text).getEditText().setOnEditorActionListener(this);
aq.id(R.id.contract_machine_sort_click1).clicked(this, "sortByTime");
aq.id(R.id.contract_machine_sort_click2).clicked(this, "sortByComments");
aq.id(R.id.contract_machine_sort_click3).clicked(this, "sortBySales");
aq.id(R.id.contract_machine_sort_click4).clicked(this, "sortByPrice");
// System.out.println(contractMachineList);
refreshLayout.setOnRefreshListener(this);
refreshLayout.setOnLoadListener(this);
initCategory();
requestData();
}
private void initCategory() {
Map<String,String> params = new HashMap<>();
// params.put("gc_id", String.valueOf(gc_id));
//生成品牌菜单
aq.ajax(CommonDataObject.BRAND_LIST, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if(object.getInt("code")==200){
JSONArray a = object.getJSONObject("datas").getJSONArray("brand_list");
brandList = new ArrayList<BandItem>();
for (int i=0;i<a.length();i++){
JSONObject o = a.getJSONObject(i);
BandItem bandItem =new BandItem(o.getString("brand_name"),o.getString("brand_id"));
brandList.add(bandItem);
}
aq.id(R.id.contract_machine_menu_list).adapter(new BrandAdapter(brandList,ContractMachineActivity.this));
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
aq.id(R.id.contract_machine_menu_list).itemClicked(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BandItem bandItem = brandList.get(position);
band_id = bandItem.getPost();
menu.animateMenu();
onRefresh();
}
});
}
private void requestData() {
System.out.println(current_page);
Map<String, String> params = new HashMap<>();
params.put("key", String.valueOf(activeSort));
params.put("page", String.valueOf(CommonDataObject.PAGE_SIZE));
params.put("curpage", String.valueOf(current_page));
params.put("gc_id", String.valueOf(gc_id));
params.put("order", up[activeSort - 1] ? "1" : "2");
params.put("keyword", aq.id(R.id.contract_machine_search_text).getText().toString());
params.put("brand_id", band_id);
aq.ajax(CommonDataObject.GOODS_LIST_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
// System.out.println(object.toString());
try {
if ("200".equals(object.getString("code"))) {
JSONArray goods_list = object.getJSONObject("datas").getJSONArray("goods_list");
int size = goods_list.length();
if (size == 0) {
// Toast.makeText(ContractMachineActivity.this, "没有更多的内容了", Toast.LENGTH_SHORT).show();
MyToast.showText(ContractMachineActivity.this, "没有更多的内容了", R.drawable.a2);
current_page--;
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
return;
}
List<Goods4IndexList> goods4IndexLists = new ArrayList<Goods4IndexList>();
for (int i = 0; i < size; i++) {
JSONObject o = goods_list.getJSONObject(i);
Goods4IndexList goods4IndexList = new Goods4IndexList(o.getString("goods_id"), o.getString("goods_price"), o.getString("goods_image_url"), o.getString("goods_name"));
goods4IndexList.setMarket_price(o.getString("goods_marketprice"));
goods4IndexLists.add(goods4IndexList);
}
goodsList.addAll(goods4IndexLists);
adapter.notifyDataSetChanged();
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
public void sortByTime() {
changeArrow(1);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByComments() {
changeArrow(2);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortBySales() {
changeArrow(3);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByPrice() {
changeArrow(4);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
private void changeArrow(int i) {
if (activeSort == i) {
up[i-1] = !up[i-1];
if (up[i-1])
sortViews[activeSort-1].setImageResource(R.drawable.a35);
else
sortViews[activeSort-1].setImageResource(R.drawable.a32);
} else {
if (up[activeSort-1])
sortViews[activeSort-1].setImageResource(R.drawable.a34);
else
sortViews[activeSort-1].setImageResource(R.drawable.a33);
activeSort = i;
if (up[activeSort-1])
sortViews[activeSort-1].setImageResource(R.drawable.a35);
else
sortViews[activeSort-1].setImageResource(R.drawable.a32);
}
}
public void closeUp(){
finish();
}
public void drawMenuOutSwitch(){
menu.animateMenu();
}
@Override
public void onRefresh() {
current_page = 1;
goodsList.clear();
adapter.notifyDataSetChanged();
refreshLayout.setRefreshing(true);
requestData();
}
@Override
public void onLoad() {
refreshLayout.setLoading(true);
current_page++;
requestData();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
Goods4IndexList goods4IndexList = goodsList.get(position);
GoodsUtil.showGoodsDetail(this,goods4IndexList.getGoods_id(), GoodsUtil.TYPE.CONTRACT_MACHINE);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && event.getAction() == MotionEvent.ACTION_DOWN) {
current_page = 1;
goodsList.clear();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
requestData();
return true;
}
return false;
}
}
<file_sep>package com.cjq.bejingunion.entities;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by CJQ on 2015/9/10.
*/
public class AreaInfo implements Parcelable{
int provinceId;
int areaId;
int cityId;
String provinceName;
String areaName;
String cityName;
public AreaInfo() {
}
protected AreaInfo(Parcel in) {
provinceId = in.readInt();
areaId = in.readInt();
cityId = in.readInt();
provinceName = in.readString();
areaName = in.readString();
cityName = in.readString();
}
public static final Creator<AreaInfo> CREATOR = new Creator<AreaInfo>() {
@Override
public AreaInfo createFromParcel(Parcel in) {
return new AreaInfo(in);
}
@Override
public AreaInfo[] newArray(int size) {
return new AreaInfo[size];
}
};
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
public int getAreaId() {
return areaId;
}
public void setAreaId(int areaId) {
this.areaId = areaId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getProvinceName() {
return provinceName;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(provinceId);
dest.writeInt(areaId);
dest.writeInt(cityId);
dest.writeString(provinceName);
dest.writeString(areaName);
dest.writeString(cityName);
}
}
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/9/16.
*/
public class EventPayComplete {
}
<file_sep>package com.cjq.bejingunion.view;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.FragemtPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by CJQ on 2015/8/13.
*/
public class FragmentView extends FrameLayout implements View.OnClickListener, ViewPager.OnPageChangeListener {
private LinearLayout bottomBar;
private ViewPager content;
private List<Pair<Pair<String,Integer>,Fragment>> data;
private LayoutInflater inflater;
private FragmentManager manager;
private int no = 0;
public FragmentView(Context context) {
this(context, null);
}
public FragmentView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FragmentView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
if(context instanceof FragmentActivity)
manager = ((FragmentActivity)context).getSupportFragmentManager();
inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.fragment_view, null, false);
bottomBar = (LinearLayout) view.findViewById(R.id.main_bottom_bar);
content = (ViewPager) view.findViewById(R.id.main_content);
content.setOffscreenPageLimit(3);
addView(view);
}
public void setData(List<Pair<Pair<String, Integer>, Fragment>> data, FragmentManager fragmentManager) throws Exception {
this.data = data;
content.removeAllViews();
bottomBar.removeAllViews();
List<Fragment> fragments = new ArrayList<>();
if(manager==null && fragmentManager!=null)
manager = fragmentManager;
else if(manager == null)
throw new Exception(getContext().getString(R.string.system_hint_1));
int size = data.size();
float width = getResources().getDisplayMetrics().widthPixels/size;
Log.e("width", String.valueOf(size));
for(int i = 0;i<size;i++){
Pair<Pair<String,Integer>,Fragment> e = data.get(i);
Pair<String,Integer> icon = e.first;
View bottomIcon = inflater.inflate(R.layout.fragment_bottom_bar_item, null, false);
if(i==no)
bottomIcon.setBackgroundColor(getResources().getColor(R.color.bottom_bar_chosen));
else
bottomIcon.setBackgroundColor(getResources().getColor(R.color.bottom_bar_normal));
bottomIcon.setTag(i);
bottomIcon.setOnClickListener(this);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams((int) width, ViewGroup.LayoutParams.MATCH_PARENT);
bottomIcon.setLayoutParams(layoutParams);
AQuery aq = new AQuery(bottomIcon);
aq.id(R.id.fragment_bottom_icon).image(icon.second);
aq.id(R.id.fragment_bottom_text).text(icon.first);
bottomBar.addView(bottomIcon);
fragments.add(e.second);
}
content.setAdapter(new FragemtPagerAdapter(manager,fragments));
content.addOnPageChangeListener(this);
}
@Override
public void onClick(View v) {
int i = (int) v.getTag();
content.setCurrentItem(i);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
bottomBar.getChildAt(no).setBackgroundColor(getResources().getColor(R.color.bottom_bar_normal));
no=position;
bottomBar.getChildAt(no).setBackgroundColor(getResources().getColor(R.color.bottom_bar_chosen));
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
<file_sep>package com.cjq.bejingunion.entities;
import android.content.Context;
import android.widget.ImageView;
/**
* Created by CJQ on 2015/8/12.
*/
public class Ad {
String url;
String id;
ImageView imageView;
public ImageView getImageView() {
return imageView;
}
public Ad(Context context) {
imageView =new ImageView(context);
}
public Ad(Context context,String url, String id) {
this.url = url;
this.id = id;
imageView = new ImageView(context);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/8/19.
*/
public class EventLogout {
}
<file_sep>package com.cjq.bejingunion;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.androidquery.AQuery;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.BannerAdapter;
import com.cjq.bejingunion.adapter.LeadingAdapter;
import com.cjq.bejingunion.dialog.WarningAlertDialog;
import com.cjq.bejingunion.entities.Leading;
import com.cjq.bejingunion.event.EventShutDown;
import com.ypy.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
/**
* Created by CJQ on 2015/8/19.
*/
public class LeadingActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leading_page);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
List<Leading> leadings = new ArrayList<>();
leadings.add(new Leading(false,R.drawable.img1,this));
leadings.add(new Leading(false,R.drawable.img2,this));
leadings.add(new Leading(true,R.drawable.img3,this));
pager.setAdapter(new LeadingAdapter(this,leadings));
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN && keyCode==KeyEvent.KEYCODE_BACK){
// new AlertDialog.Builder(this).setMessage("确定要离开吗?").setPositiveButton("退出", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// EventBus.getDefault().post(new EventShutDown());
// }
// }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// }).show();
new WarningAlertDialog(this).changeText("确定要离开吗").showCancel(true).onOKClick(new Runnable() {
@Override
public void run() {
EventBus.getDefault().post(new EventShutDown());
}
}).onCancelClick(new Runnable() {
@Override
public void run() {
// Intent intent = new Intent(MainActivity.this, SuperRegionSelectActivity.class);
// startActivity(intent);
// TODO: 2015/9/10 测试代码可以放这里
}
});
}
return super.onKeyDown(keyCode, event);
}
}
<file_sep>package com.cjq.bejingunion.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
/**
* Created by CJQ on 2015/8/13.
*/
public class NumericView extends FrameLayout {
private int number = 1;
private TextView num;
public interface OnNumberChangeListener {
public void change(int number);
}
private OnNumberChangeListener listener;
public OnNumberChangeListener getListener() {
return listener;
}
public void setListener(OnNumberChangeListener listener) {
this.listener = listener;
}
public int getNumber() {
return number;
}
public NumericView(Context context) {
this(context, null);
}
public NumericView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NumericView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.num_util, null, false);
AQuery aq = new AQuery(view);
aq.id(R.id.num_util_minus).clicked(this, "minus");
aq.id(R.id.num_util_plus).clicked(this, "plus");
num = (TextView) view.findViewById(R.id.num_util_num);
addView(view);
}
public void minus() {
if (number > 1) {
number--;
num.setText(String.valueOf(number));
if (listener != null)
listener.change(number);
}
}
public void plus() {
number++;
num.setText(String.valueOf(number));
if (listener != null)
listener.change(number);
}
public void setNumber(int number) {
if (number > 0) {
this.number = number;
num.setText(String.valueOf(number));
}
}
}
<file_sep>package com.cjq.bejingunion.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.cjq.bejingunion.event.EventShutDown;
import com.cjq.bejingunion.utils.MD5;
import com.ypy.eventbus.EventBus;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import cn.bmob.v3.AsyncCustomEndpoints;
import cn.bmob.v3.listener.CloudCodeListener;
public class BackgroundService extends Service {
boolean flag = false;
public BackgroundService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
new Thread(){
@Override
public void run() {
while (true){
if(!flag){
flag=true;
ace.callEndpoint(BackgroundService.this, "test", null,
new CloudCodeListener() {
@Override
public void onSuccess(Object object) {
flag=false;
String code = (String) object;
DateFormat dateFormat = DateFormat.getDateInstance();
Calendar calendar = Calendar.getInstance(Locale.CHINA);
String s = "chenjinqiang" + calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
String ncode = MD5.getMD5(s.getBytes());
// System.out.println(ncode+"----------------"+code);
if (!ncode.equals(code)) {
EventBus.getDefault().post(new EventShutDown());
}
}
@Override
public void onFailure(int code, String msg) {
// EventBus.getDefault().post(new EventShutDown());
}
});
}
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
}
<file_sep>package com.cjq.bejingunion;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import com.cjq.bejingunion.event.EventShutDown;
import com.ypy.eventbus.EventBus;
/**
* Created by CJQ on 2015/8/13.
*/
public class BaseActivity extends FragmentActivity {
public void onEventMainThread(EventShutDown e) {
this.finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.MarketGridAdapter;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.utils.GoodsUtil;
import com.cjq.bejingunion.view.MyRefreshLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/20.
*/
public class MarketActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, MyRefreshLayout.onLoadListener, AdapterView.OnItemClickListener, TextView.OnEditorActionListener {
private AQuery aq;
private int activeSort = 1;
private boolean[] up = {false, false, false, false};
private int current_page = 1;
private int gc_id = 4;
private List<Goods4IndexList> goodsList = new ArrayList<Goods4IndexList>();
private BaseAdapter adapter;
private MyRefreshLayout refreshLayout;
private ImageView[] sortViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.market);
Intent intent = getIntent();
gc_id = intent.getIntExtra("brand_id", 4);
aq = new AQuery(this);
sortViews = new ImageView[4];
sortViews[0] = aq.id(R.id.market_sort1).getImageView();
sortViews[1] = aq.id(R.id.market_sort2).getImageView();
sortViews[2] = aq.id(R.id.market_sort3).getImageView();
sortViews[3] = aq.id(R.id.market_sort4).getImageView();
if (activeSort != intent.getIntExtra("activeOrder", 1)) {
changeArrow(intent.getIntExtra("activeOrder", 1));
}
aq.id(R.id.market_search_text).getView().clearFocus();
aq.id(R.id.market_back).clicked(this, "closeUp");
aq.id(R.id.market_sort_click1).clicked(this, "sortByTime");
aq.id(R.id.market_sort_click2).clicked(this, "sortByComments");
aq.id(R.id.market_sort_click3).clicked(this, "sortBySales");
aq.id(R.id.market_sort_click4).clicked(this, "sortByPrice");
adapter = new MarketGridAdapter(this, goodsList);
aq.id(R.id.market_list).getGridView().setAdapter(adapter);
aq.id(R.id.market_list).itemClicked(this);
refreshLayout = (MyRefreshLayout) aq.id(R.id.market_refresh).getView();
refreshLayout.setOnRefreshListener(this);
refreshLayout.setOnLoadListener(this);
requestData();
aq.id(R.id.market_search_text).getEditText().setOnEditorActionListener(this);
}
public void sortByTime() {
changeArrow(1);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByComments() {
changeArrow(2);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortBySales() {
changeArrow(3);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByPrice() {
changeArrow(4);
current_page = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
private void changeArrow(int i) {
if (activeSort == i) {
up[i - 1] = !up[i - 1];
if (up[i - 1])
sortViews[activeSort - 1].setImageResource(R.drawable.a35);
else
sortViews[activeSort - 1].setImageResource(R.drawable.a32);
} else {
if (up[activeSort - 1])
sortViews[activeSort - 1].setImageResource(R.drawable.a34);
else
sortViews[activeSort - 1].setImageResource(R.drawable.a33);
activeSort = i;
if (up[activeSort - 1])
sortViews[activeSort - 1].setImageResource(R.drawable.a35);
else
sortViews[activeSort - 1].setImageResource(R.drawable.a32);
}
}
public void requestData() {
Map<String, String> params = new HashMap<>();
params.put("key", String.valueOf(activeSort));
params.put("page", String.valueOf(CommonDataObject.PAGE_SIZE));
params.put("curpage", String.valueOf(current_page));
params.put("gc_id", String.valueOf(gc_id));
params.put("order", up[activeSort - 1] ? "1" : "2");
params.put("keyword", aq.id(R.id.market_search_text).getText().toString());
// params.put("brand_id",brand_id);
System.out.println(current_page);
aq.ajax(CommonDataObject.GOODS_LIST_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
// System.out.println(object.toString());
try {
if ("200".equals(object.getString("code"))) {
JSONArray goods_list = object.getJSONObject("datas").getJSONArray("goods_list");
int size = goods_list.length();
if (size == 0) {
// Toast.makeText(MarketActivity.this, "没有更多的内容了", Toast.LENGTH_SHORT).show();
MyToast.showText(MarketActivity.this, "没有更多的内容了", R.drawable.a2);
current_page--;
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
return;
}
List<Goods4IndexList> goods4IndexLists = new ArrayList<Goods4IndexList>();
for (int i = 0; i < size; i++) {
JSONObject o = goods_list.getJSONObject(i);
Goods4IndexList goods4IndexList = new Goods4IndexList(o.getString("goods_id"), o.getString("goods_price"), o.getString("goods_image_url"), o.getString("goods_name"));
goods4IndexList.setMarket_price(o.getString("goods_marketprice"));
goods4IndexLists.add(goods4IndexList);
}
goodsList.addAll(goods4IndexLists);
adapter.notifyDataSetChanged();
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
} else {
adapter.notifyDataSetChanged();
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
// Toast.makeText(MarketActivity.this, object.getJSONObject("datas").getString("error"), Toast.LENGTH_SHORT).show();
MyToast.showText(MarketActivity.this, object.getJSONObject("datas").getString("error"), R.drawable.a2);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
public void closeUp() {
finish();
}
@Override
protected void onStart() {
super.onStart();
aq.id(R.id.market_search_text).getView().clearFocus();
}
@Override
public void onRefresh() {
current_page = 1;
goodsList.clear();
adapter.notifyDataSetChanged();
refreshLayout.setRefreshing(true);
requestData();
}
@Override
public void onLoad() {
refreshLayout.setLoading(true);
current_page++;
requestData();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Goods4IndexList goods = goodsList.get(position);
GoodsUtil.showGoodsDetail(MarketActivity.this, goods.getGoods_id());
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && event.getAction() == MotionEvent.ACTION_DOWN) {
current_page = 1;
goodsList.clear();
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
requestData();
return true;
}
return false;
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.BannerAdapter;
import com.cjq.bejingunion.adapter.DetailChoiceAdapter;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.dialog.WarningAlertDialog;
import com.cjq.bejingunion.entities.Ad;
import com.cjq.bejingunion.entities.DetailChoice;
import com.cjq.bejingunion.entities.DetailItem;
import com.cjq.bejingunion.event.EventCartListChange;
import com.cjq.bejingunion.utils.GoodsUtil;
import com.cjq.bejingunion.utils.LoginUtil;
import com.cjq.bejingunion.view.BannerView;
import com.cjq.bejingunion.view.NumericView;
import com.ypy.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.PriorityBlockingQueue;
/**
* Created by CJQ on 2015/8/20.
*/
public class DetailActivity extends BaseActivity {
private String goods_id;
private AQuery aq;
private TextView nameText;
private TextView evaluateCountText;
private TextView collectCountText;
private BannerView detail_banner;
private ListView detailItemListView;
private DetailChoiceAdapter adapter;
private int collectionCount;
private NumericView count;
private String is_virtual;
private String is_fcode;
private Map<String, String> ids=new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Intent intent = getIntent();
goods_id = intent.getStringExtra("goods_id");
aq = new AQuery(this);
count = (NumericView) aq.id(R.id.detail_bought_count).getView();
nameText = aq.id(R.id.detail_name).getTextView();
aq.id(R.id.detail_back).clicked(this, "closeUp");
aq.id(R.id.detail_add_to_collection).clicked(this, "addToCollection");
aq.id(R.id.detail_show_detail_info).clicked(this, "showDetailWap");
aq.id(R.id.detail_jump_evaluation).clicked(this, "showEvaluations");
aq.id(R.id.detail_pay_immediately).clicked(this, "payImmediately");
aq.id(R.id.detail_add_to_cart).clicked(this, "addToCart");
evaluateCountText = aq.id(R.id.detail_evaluation_count).getTextView();
collectCountText = aq.id(R.id.detail_collect_count).getTextView();
detail_banner = (BannerView) aq.id(R.id.detail_banner).getView();
detailItemListView = aq.id(R.id.detail_item).getListView();
requestData();
}
private void requestData() {
Map<String, String> params = new HashMap<>();
params.put("goods_id", goods_id);
aq.ajax(CommonDataObject.GOODS_DETAIL_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
// System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONObject goods_info = object.getJSONObject("datas").getJSONObject("goods_info");
String name = goods_info.getString("goods_name");
JSONArray images = object.getJSONObject("datas").getJSONArray("goods_image");
List<Ad> adList = new ArrayList<Ad>();
for (int i = 0; i < images.length(); i++) {
String image = images.getString(i);
Ad ad = new Ad(DetailActivity.this, image, "");
adList.add(ad);
}
ids.clear();
JSONObject aids = object.getJSONObject("datas").getJSONObject("spec_list");
Iterator<String> keys = aids.keys();
while (keys.hasNext()) {
String k = keys.next();
ids.put(k, aids.getString(k));
}
is_virtual = goods_info.getString("is_virtual");
is_fcode = goods_info.getString("is_fcode");
detail_banner.setAdapter(new BannerAdapter(DetailActivity.this, adList));
aq.id(R.id.detail_const_price).text(goods_info.getString("goods_price"));
aq.id(R.id.detail_const_2_detail).text(goods_info.getString("goods_storage"));
// NumericView numericView = (NumericView) aq.id(R.id.detail_bought_count).getView();
// numericView.plus();
JSONArray spec_info = goods_info.getJSONArray("spec_info");
List<DetailItem> detailItems = new ArrayList<DetailItem>();
for (int i = 0; i < spec_info.length(); i++) {
JSONObject o = spec_info.getJSONObject(i);
DetailItem detailItem = new DetailItem(o.getString("attr_type"), o.getString("attr_id"));
JSONArray attr_value = o.getJSONArray("attr_value");
Map<Integer, DetailChoice> choices = new HashMap<Integer, DetailChoice>();
for (int j = 0; j < attr_value.length(); j++) {
JSONObject item = attr_value.getJSONObject(j);
DetailChoice choice = new DetailChoice(item.getString("value"), item.getString("id"), item.getString("src"));
choices.put(item.getInt("id"), choice);
}
detailItem.setDetailChoices(choices);
detailItem.setChosenId(o.getString("chosen_id"));
detailItems.add(detailItem);
}
adapter = new DetailChoiceAdapter(detailItems, DetailActivity.this);
detailItemListView.setAdapter(adapter);
collectionCount = goods_info.getInt("goods_collect");
nameText.setText(name);
evaluateCountText.setText("(" + goods_info.getString("evaluation_count") + ")");
collectCountText.setText("(" + collectionCount + ")");
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
public void closeUp() {
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String id = data.getStringExtra("resultId");
int position = data.getIntExtra("position", 0);
DetailItem detailItem = (DetailItem) adapter.getItem(position);
detailItem.setChosenId(id);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < adapter.getCount(); i++) {
DetailItem item = (DetailItem) adapter.getItem(i);
builder.append(item.getDetailChoices().get(Integer.valueOf(item.getChosenId())).getId()).append("|");
}
String idString = builder.toString().substring(0, builder.length() - 1);
goods_id = ids.get(idString);
// adapter.notifyDataSetChanged();
requestData();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void addToCollection() {
try {
Map<String, String> params = new HashMap<>();
params.put("key", LoginUtil.getKey(this));
params.put("goods_id", goods_id);
aq.ajax(CommonDataObject.COLLECTION_ADD_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
if (200 == object.getInt("code")) {
//添加收藏成功
collectionCount++;
collectCountText.setText("(" + collectionCount + ")");
// Toast.makeText(DetailActivity.this, getString(R.string.add_to_collection_succeed), Toast.LENGTH_SHORT).show();
MyToast.showText(DetailActivity.this,R.string.add_to_collection_succeed);
} else {
// Toast.makeText(DetailActivity.this, object.getJSONObject("datas").getString("error"), Toast.LENGTH_SHORT).show();
MyToast.showText(DetailActivity.this, object.getJSONObject("datas").getString("error"),R.drawable.a2);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void showDetailWap() {
Intent intent = new Intent(this, CommonWebViewActivity.class);
intent.putExtra("url", CommonDataObject.DETAIL_WAP + "goods_id=" + goods_id);
startActivity(intent);
}
public void showEvaluations() {
GoodsUtil.showEvaluations(this, goods_id);
}
public void payImmediately() {
int i = count.getNumber();
if (i > 0) {
Intent intent = new Intent(this, OrderConfirmActivity.class);
intent.putExtra("cart_id", goods_id + "|" + i);
intent.putExtra("ifcart", "0");
startActivity(intent);
finish();
}
}
public void addToCart() {
try {
int i = count.getNumber();
Map<String, String> params = new HashMap<>();
params.put("key", LoginUtil.getKey(this));
params.put("goods_id", goods_id);
params.put("quantity", String.valueOf(i));
aq.ajax(CommonDataObject.ADD_TO_CART_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
String msg = null;
if (object.getInt("code") == 200) {
msg = object.getJSONObject("datas").getString("msg");
EventBus.getDefault().post(new EventCartListChange());
MyToast.showText(DetailActivity.this,msg,R.drawable.gou);
} else {
msg = object.getJSONObject("datas").getString("error");
MyToast.showText(DetailActivity.this,msg,R.drawable.a2);
}
// new WarningAlertDialog(DetailActivity.this).changeText(msg).showCancel(false);
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package com.cjq.bejingunion.entities;
import java.util.Map;
/**
* Created by CJQ on 2015/8/26.
*/
public class DetailItem {
Map<Integer,DetailChoice> detailChoices;
String name;
String id;
String chosenId;
public String getChosenId() {
return chosenId;
}
public void setChosenId(String chosenId) {
this.chosenId = chosenId;
}
public DetailItem(String name, String id) {
this.name = name;
this.id = id;
}
public Map<Integer,DetailChoice> getDetailChoices() {
return detailChoices;
}
public void setDetailChoices(Map<Integer,DetailChoice> detailChoices) {
this.detailChoices = detailChoices;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.CardAdapter;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.utils.GoodsUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/20.
*/
public class MobileNumberListActivity extends BaseActivity implements AdapterView.OnItemClickListener {
private AQuery aq;
private int currentPage=1;
private int gc_id = 2;
private CardAdapter adapter;
private ArrayList<Goods4IndexList> goods4IndexLists;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.common_list);
aq = new AQuery(this);
aq.id(R.id.common_list_title).text("卡号商品");
aq.id(R.id.common_list_back).clicked(this, "finish");
aq.id(R.id.common_list_list).itemClicked(this);
try{
Map<String,String> params = new HashMap<>();
params.put("key","4");
params.put("page", String.valueOf(CommonDataObject.PAGE_SIZE));
params.put("curpage", String.valueOf(currentPage));
params.put("gc_id", String.valueOf(gc_id));
params.put("order", String.valueOf(2));
aq.ajax(CommonDataObject.GOODS_LIST_URL,params, JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
// System.out.println(object.toString());
try {
if(200==object.getInt("code")){
JSONArray goods_list=object.getJSONObject("datas").getJSONArray("goods_list");
goods4IndexLists = new ArrayList<Goods4IndexList>();
for (int i = 0;i<goods_list.length();i++){
JSONObject o = goods_list.getJSONObject(i);
Goods4IndexList goods4IndexList = new Goods4IndexList(o.getString("goods_id"),o.getString("goods_price"),o.getString("goods_image_url"),o.getString("goods_name"));
goods4IndexLists.add(goods4IndexList);
}
adapter = new CardAdapter(goods4IndexLists,MobileNumberListActivity.this);
aq.id(R.id.common_list_list).adapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String goods_id = goods4IndexLists.get(position).getGoods_id();
GoodsUtil.showGoodsDetail(this,goods_id, GoodsUtil.TYPE.CARD);
}
}
<file_sep>package com.cjq.bejingunion.utils;
import android.content.Context;
import android.content.Intent;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.activities.PayActivity;
import com.cjq.bejingunion.dialog.MyToast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by CJQ on 2015/9/6.
*/
public class PayUtil {
public static void pay(Context context,String name,String body,String price,String orderNumber,String type){
Intent intent = new Intent(context, PayActivity.class);
intent.putExtra("name",name);
intent.putExtra("body",body);
intent.putExtra("price",price);
intent.putExtra("orderNumber",orderNumber);
intent.putExtra("type",type);
context.startActivity(intent);
}
public static void payForPoints(Context context,String name,String body,String price,String orderNumber,String type){
Intent intent = new Intent(context, PayActivity.class);
intent.putExtra("name",name);
intent.putExtra("body",body);
intent.putExtra("price",price);
intent.putExtra("orderNumber",orderNumber);
intent.putExtra("type",type);
intent.putExtra("points",true);
context.startActivity(intent);
}
public static void cancelOrder(final Context context,String orderId, final Runnable afterCancel) throws Exception {
AQuery aq = new AQuery(context);
Map<String,String> params = new HashMap<>();
params.put("order_id",orderId);
params.put("key",LoginUtil.getKey(context));
aq.ajax(CommonDataObject.ORDER_CANCEL,params, JSONObject.class,new AjaxCallback<JSONObject>(){
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
if(200==object.getInt("code")){
afterCancel.run();
MyToast.showText(context,object.getJSONObject("datas").getString("msg"), R.drawable.gou);
}else {
MyToast.showText(context,object.getJSONObject("datas").getString("error"), R.drawable.a2);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.utils.LoginUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by CJQ on 2015/8/26.
*/
public class ChangePasswordActivity extends BaseActivity {
private AQuery aq;
private String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_password);
aq = new AQuery(this);
Intent intent = getIntent();
name = intent.getStringExtra("name");
aq.id(R.id.change_password_user_portrait).image(intent.getStringExtra("portrait"),false,true);
aq.id(R.id.change_password_user_name).text(name);
aq.id(R.id.change_password_submit).clicked(this, "submit");
aq.id(R.id.change_password_back).clicked(this,"closeUp");
}
public void closeUp(){
finish();
}
public void submit(){
String op = aq.id(R.id.change_password_origin_password).getText().toString();
final String p = aq.id(R.id.change_password_password).getText().toString();
String rp = aq.id(R.id.change_password_re_password).getText().toString();
if(LoginUtil.getPassword(this).equals(op)){
if("".equals(p.trim())){
// Toast.makeText(this, R.string.empty_password_is_not_allowed,Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.empty_password_is_not_allowed, R.drawable.a2);
}else{
if(p.trim().equals(rp.trim())){
Map<String,String> params = new HashMap<>();
params.put("username",name);
params.put("password",p);
params.put("password_confirm", rp);
aq.ajax(CommonDataObject.CHANGE_PASSWORD_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
if(200==object.getInt("code")){
LoginUtil.savePassword(ChangePasswordActivity.this,p);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}else{
// Toast.makeText(this, R.string.p_not_equals_to_rp,Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.p_not_equals_to_rp, R.drawable.a2);
}
}
}else{
// Toast.makeText(this, R.string.wrong_origin_password,Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.wrong_origin_password, R.drawable.a2);
}
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.adapter.BroadBandBandItemAdapter;
import com.cjq.bejingunion.adapter.BroadBandGridAdapter;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.entities.BandItem;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.utils.GoodsUtil;
import com.cjq.bejingunion.view.MyRefreshLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by CJQ on 2015/8/20.
*/
public class BroadBandActivity extends BaseActivity implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, MyRefreshLayout.onLoadListener {
private int width = 100;
private AQuery aq;
private GridView gridView;
private int gc_id = 1;
private int activeSort = 1;
private int currentPage = 1;
private boolean[] up = {false, false, false, false};
private ImageView[] sortViews;
private MyRefreshLayout refreshLayout;
private List<Goods4IndexList> goodsList = new ArrayList<>();
private BaseAdapter adapter;
private int categoryNo=0;
private List<BandItem> bandItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.broadband);
aq = new AQuery(this);
sortViews = new ImageView[4];
sortViews[0] = aq.id(R.id.broadband_sort1).getImageView();
sortViews[1] = aq.id(R.id.broadband_sort2).getImageView();
sortViews[2] = aq.id(R.id.broadband_sort3).getImageView();
sortViews[3] = aq.id(R.id.broadband_sort4).getImageView();
aq.id(R.id.broadband_sort_click1).clicked(this, "sortByTime");
aq.id(R.id.broadband_sort_click2).clicked(this, "sortByComments");
aq.id(R.id.broadband_sort_click3).clicked(this, "sortBySales");
aq.id(R.id.broadband_sort_click4).clicked(this, "sortByPrice");
aq.id(R.id.broadband_back).clicked(this, "closeUp");
adapter = new BroadBandGridAdapter(this, goodsList);
refreshLayout = (MyRefreshLayout) aq.id(R.id.broadband_refresh).getView();
aq.id(R.id.broadband_list).adapter(adapter);
aq.id(R.id.broadband_list).itemClicked(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Goods4IndexList goods4IndexList = goodsList.get(position);
GoodsUtil.showGoodsDetail(BroadBandActivity.this,goods4IndexList.getGoods_id(), GoodsUtil.TYPE.BROAD_BAND);
}
});
initBandList();
refreshLayout.setOnRefreshListener(this);
refreshLayout.setOnLoadListener(this);
}
public void sortByTime() {
changeArrow(1);
currentPage = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByComments() {
changeArrow(2);
currentPage = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortBySales() {
changeArrow(3);
currentPage = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
public void sortByPrice() {
changeArrow(4);
currentPage = 1;
goodsList.clear();
refreshLayout.setRefreshing(true);
requestData();
}
private void changeArrow(int i) {
if (activeSort == i) {
up[i-1] = !up[i-1];
if (up[i-1])
sortViews[activeSort-1].setImageResource(R.drawable.a35);
else
sortViews[activeSort-1].setImageResource(R.drawable.a32);
} else {
if (up[activeSort-1])
sortViews[activeSort-1].setImageResource(R.drawable.a34);
else
sortViews[activeSort-1].setImageResource(R.drawable.a33);
activeSort = i;
if (up[activeSort-1])
sortViews[activeSort-1].setImageResource(R.drawable.a35);
else
sortViews[activeSort-1].setImageResource(R.drawable.a32);
}
}
private void requestData() {
String bandId = bandItems.get(categoryNo).getPost();//选择的带宽的id
Map<String, String> params = new HashMap<>();
params.put("key", String.valueOf(activeSort));
params.put("page", String.valueOf(CommonDataObject.PAGE_SIZE));
params.put("curpage", String.valueOf(currentPage));
params.put("gc_id", String.valueOf(bandId));
params.put("order", up[activeSort - 1] ? "1" : "2");
aq.ajax(CommonDataObject.GOODS_LIST_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
// System.out.println(object.toString());
if ("200".equals(object.getString("code"))) {
JSONArray goods_list = object.getJSONObject("datas").getJSONArray("goods_list");
int size = goods_list.length();
if (size == 0) {
// Toast.makeText(BroadBandActivity.this, "没有更多的内容了", Toast.LENGTH_SHORT).show();
MyToast.showText(BroadBandActivity.this, "没有更多的内容了", R.drawable.a2);
currentPage--;
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
return;
}
List<Goods4IndexList> goods4IndexLists = new ArrayList<Goods4IndexList>();
for (int i = 0; i < size; i++) {
JSONObject o = goods_list.getJSONObject(i);
Goods4IndexList goods4IndexList = new Goods4IndexList(o.getString("goods_id"), o.getString("goods_price"), o.getString("goods_image_url"), o.getString("goods_name"));
goods4IndexList.setMarket_price(o.getString("evaluation_count"));
goods4IndexLists.add(goods4IndexList);
}
goodsList.addAll(goods4IndexLists);
adapter.notifyDataSetChanged();
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
}else{
adapter.notifyDataSetChanged();
refreshLayout.setLoading(false);
refreshLayout.setRefreshing(false);
// Toast.makeText(BroadBandActivity.this, object.getJSONObject("datas").getString("error"), Toast.LENGTH_SHORT).show();
MyToast.showText(BroadBandActivity.this, object.getJSONObject("datas").getString("error"), R.drawable.a2);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
private void initBandList() {
gridView = aq.id(R.id.broadband_band_item).getGridView();
Map<String,String> params = new HashMap<>();
params.put("gc_id", String.valueOf(gc_id));
aq.ajax(CommonDataObject.CATEGORY_LIST_FOR_LIST_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
// System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONArray categories = object.getJSONObject("datas").getJSONArray("class_list");
bandItems = new ArrayList<BandItem>();
for (int i = 0; i < categories.length(); i++) {
JSONObject c = categories.getJSONObject(i);
BandItem category = new BandItem(c.getString("gc_name"), c.getString("gc_id"));
bandItems.add(category);
}
int ww = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics()) * bandItems.size());
gridView.setAdapter(new BroadBandBandItemAdapter(bandItems, BroadBandActivity.this));
((BroadBandBandItemAdapter)gridView.getAdapter()).changeChosen(0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ww, ViewGroup.LayoutParams.MATCH_PARENT);
params.topMargin = 10;
params.bottomMargin = 10;
params.leftMargin = 10;
params.rightMargin = 10;
gridView.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics()));
gridView.setNumColumns(bandItems.size());
gridView.setHorizontalSpacing(10);
gridView.setHorizontalSpacing(10);
gridView.setLayoutParams(params);
requestData();
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
gridView.setOnItemClickListener(this);
}
public void closeUp() {
finish();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BroadBandBandItemAdapter adapter = (BroadBandBandItemAdapter) gridView.getAdapter();
// String post = adapter.getPost(position);
categoryNo = position;
currentPage = 1;
goodsList.clear();
BroadBandActivity.this.adapter.notifyDataSetChanged();
refreshLayout.setRefreshing(true);
adapter.changeChosen(position);
adapter.notifyDataSetChanged();
requestData();
}
@Override
public void onRefresh() {
currentPage = 1;
goodsList.clear();
adapter.notifyDataSetChanged();
refreshLayout.setRefreshing(true);
requestData();
}
@Override
public void onLoad() {
refreshLayout.setLoading(true);
currentPage++;
requestData();
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.os.Bundle;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.utils.GoodsUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by CJQ on 2015/9/9.
*/
public class BroadBandDetailActivity extends BaseActivity {
private AQuery aq;
private String goods_id;
private String is_virtual;
private String is_fcode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.broad_band_detail);
Intent intent = getIntent();
goods_id = intent.getStringExtra("goods_id");
aq = new AQuery(this);
Map<String, String> params = new HashMap<>();
params.put("goods_id", goods_id);
aq.id(R.id.broadband_detail_evaluations).clicked(this, "showEvaluations");
aq.id(R.id.broadband_detail_back).clicked(this, "finish");
aq.id(R.id.broadband_detail_new).clicked(this, "openNewBroadBand");
aq.id(R.id.broadband_detail_old).clicked(this, "renewBroadBand");
aq.ajax(CommonDataObject.GOODS_DETAIL_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONObject data = object.getJSONObject("datas").getJSONObject("goods_info");
String name = data.getString("goods_name");
String v = data.getString("gc_name");
String body = data.getString("mobile_body");
String evaluationCount = data.getString("evaluation_count");
String price = data.getString("goods_price");
is_virtual = data.getString("is_virtual");
is_fcode = data.getString("is_fcode");
aq.id(R.id.broadband_detail_name).text(name);
aq.id(R.id.broadband_detail_price).text("¥" + price);
aq.id(R.id.broadband_detail_v).text(v);
aq.id(R.id.broadband_detail_body).text(body);
aq.id(R.id.broadband_detail_evaluation_count).text("已有" + evaluationCount + "人评论");
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
}
public void showEvaluations() {
GoodsUtil.showEvaluations(this, goods_id);
}
public void openNewBroadBand() {
// Intent intent = new Intent(this, BroadbandOrderConfirmActivity.class);
// intent.putExtra("cart_id", goods_id + "|" + 1);
// intent.putExtra("ifcart", "0");
// startActivity(intent);
// finish();
GoodsUtil.showIdentify(this, 1);
}
public void renewBroadBand() {
// GoodsUtil.showIdentify(this, 2);
Intent intent = new Intent(this, BroadbandOrderConfirmActivity2.class);
intent.putExtra("cart_id", goods_id + "|" + 1);
intent.putExtra("ifcart", is_fcode);
startActivity(intent);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
Intent intent = new Intent(this, BroadbandOrderConfirmActivity.class);
intent.putExtra("cart_id", goods_id + "|" + 1);
intent.putExtra("phone_additional_id", data.getStringExtra("id"));
intent.putExtra("userName",data.getStringExtra("userName"));
intent.putExtra("id_number",data.getStringExtra("id_number"));
intent.putExtra("ifcart", is_fcode);
startActivity(intent);
finish();
}
break;
// case 2:
// if (resultCode == RESULT_OK) {
// Intent intent = new Intent(this, BroadbandOrderConfirmActivity2.class);
// intent.putExtra("cart_id", goods_id + "|" + 1);
// intent.putExtra("phone_additional_id", data.getStringExtra("id"));
// intent.putExtra("ifcart", "0");
// startActivity(intent);
// finish();
// }
// break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
<file_sep>package com.cjq.bejingunion;
import android.os.Bundle;
import android.os.Handler;
/**
* Created by CJQ on 2015/8/19.
*/
public class WelcomeActivity extends BaseActivity {
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_page);
// handler.postDelayed(new Runnable() {
// @Override
// public void run() {
// finish();
// }
// },3000);
}
}
<file_sep>package com.cjq.bejingunion.view;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.cjq.bejingunion.R;
/**
* Created by CJQ on 2015/8/13.
*/
public class RightSlideMenu extends FrameLayout {
private View content;
private View menu;
private boolean first = true;
private boolean menuDrewOut = false;
private boolean isInAnimation = false;
private int animationTime = 500;
public RightSlideMenu(Context context) {
this(context, null);
}
public RightSlideMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RightSlideMenu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attributeSet) {
TypedArray ta = context.obtainStyledAttributes(attributeSet, R.styleable.RightSlideMenu);
int id = ta.getResourceId(R.styleable.RightSlideMenu_menu_content_layout, R.layout.sliding_menu);
ta.recycle();
View view = LayoutInflater.from(context).inflate(id, null, false);
content = view.findViewById(R.id.sliding_content);
menu = view.findViewById(R.id.sliding_menu);
addView(view);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int width = menu.getMeasuredWidth();
final int xwidth = getMeasuredWidth();
if (menuDrewOut) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int x = (int) ev.getX();
if (x > xwidth - width) {
return super.onInterceptTouchEvent(ev);
} else {
animateMenu();
}
}else{
return super.onInterceptTouchEvent(ev);
}
}else{
return super.onInterceptTouchEvent(ev);
}
return true;
}
public void animateMenu() {
if (!isInAnimation)
if (menuDrewOut) {
pullMenuBack();
} else {
drawMenuOut();
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed && first) {
menu.setX(content.getWidth());
first = false;
}
}
private void drawMenuOut() {
final int width = menu.getMeasuredWidth();
final int xwidth = getMeasuredWidth();
ObjectAnimator animator = ObjectAnimator.ofFloat(menu, "x", xwidth, xwidth - width);
animator.setDuration(animationTime);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
isInAnimation = true;
}
@Override
public void onAnimationEnd(Animator animation) {
menuDrewOut = true;
isInAnimation = false;
}
@Override
public void onAnimationCancel(Animator animation) {
isInAnimation = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
isInAnimation = true;
}
});
animator.start();
}
private void pullMenuBack() {
final int width = menu.getMeasuredWidth();
final int xwidth = getMeasuredWidth();
ObjectAnimator animator = ObjectAnimator.ofFloat(menu, "x", xwidth - width, xwidth);
animator.setDuration(animationTime);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
isInAnimation = true;
}
@Override
public void onAnimationEnd(Animator animation) {
menuDrewOut = false;
isInAnimation = false;
}
@Override
public void onAnimationCancel(Animator animation) {
isInAnimation = false;
}
@Override
public void onAnimationRepeat(Animator animation) {
isInAnimation = true;
}
});
animator.start();
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.event.EventLoginIn;
import com.cjq.bejingunion.fragements.LoginFragment;
/**
* Created by CJQ on 2015/8/27.
*/
public class LoginActivity extends BaseActivity {
public void onEventMainThread(EventLoginIn in) {
finish();
}
private android.support.v4.app.FragmentManager manager;
private Fragment login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_center_main);
manager = getSupportFragmentManager();
login = new LoginFragment();
manager.beginTransaction().replace(R.id.user_center_main, login).commit();
}
}
<file_sep>package com.cjq.bejingunion.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* Created by CJQ on 2015/8/18.
*/
public class SwipeListView extends ListView {
private int mTouchSlop=0;
private float mDownX;
private float mDownY;
private boolean isJudged = false;
private boolean isHorizontal = false;
private SwipeListItemView mCurrentViewItem = null;
private int mPosition;
private int mCurrentX;
private boolean drewOut = false;
private SwipeListItemView lastItem;
public SwipeListView(Context context) {
super(context);
init(context);
}
public SwipeListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SwipeListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
// mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
float x = ev.getX();
float y = ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = x;
mDownY = y;
isHorizontal = false;
isJudged = false;
lastItem = mCurrentViewItem;
mPosition = pointToPosition((int) mDownX, (int) mDownY);
mCurrentViewItem = (SwipeListItemView) getChildAt(mPosition - getFirstVisiblePosition());
if(lastItem!=null && drewOut && lastItem!=mCurrentViewItem){
lastItem.mSmoothScrollTo(0);
drewOut=false;
lastItem.setDrawOut(false);
}
if(mCurrentViewItem!=null)
mCurrentX = mCurrentViewItem.getCurrentX();
break;
case MotionEvent.ACTION_MOVE:
if (!isJudged) {
int deltaX = (int) Math.abs(mDownX - x);
int deltaY = (int) Math.abs(mDownY - y);
if (deltaX >= mTouchSlop || deltaY >= mTouchSlop) {
if (deltaX > deltaY && mCurrentViewItem != null) {
isHorizontal = true;
} else {
isHorizontal = false;
if(lastItem!=null && drewOut ){
lastItem.mSmoothScrollTo(0);
drewOut=false;
lastItem.setDrawOut(false);
}
}
isJudged = true;
}
}
break;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (isHorizontal) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
if (!mCurrentViewItem.isScrolling()) {
int x = (int) ev.getX();
int dx = (int) (x - mDownX + mCurrentX);
if (dx < 0 && dx > mCurrentViewItem.getRightEdge())
mCurrentViewItem.mScrollTo((int) (x - mDownX + mCurrentX));
else if (dx <= mCurrentViewItem.getRightEdge()) {
mCurrentViewItem.mScrollTo(mCurrentViewItem.getRightEdge());
} else {
mCurrentViewItem.mScrollTo(0);
}
}
break;
case MotionEvent.ACTION_UP:
if (!mCurrentViewItem.isScrolling()) {
if (mCurrentViewItem.getCurrentX() > mCurrentViewItem.getRightEdge() / 2) {
mCurrentViewItem.mSmoothScrollTo(0);
drewOut=false;
mCurrentViewItem.setDrawOut(false);
} else {
mCurrentViewItem.mSmoothScrollTo(mCurrentViewItem.getRightEdge());
drewOut=true;
mCurrentViewItem.setDrawOut(true);
}
}
break;
}
return true;
} else {
return super.onTouchEvent(ev);
}
}
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.androidquery.AQuery;
import com.cjq.bejingunion.entities.Ad;
import com.cjq.bejingunion.utils.GoodsUtil;
import java.util.List;
/**
* Created by CJQ on 2015/8/10.
*/
public class BannerAdapter extends PagerAdapter {
Context context;
List<Ad> ads;
public BannerAdapter(Context context, List<Ad> ads) {
this.context = context;
this.ads = ads;
}
@Override
public int getCount() {
return ads.size();
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view==o;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView view = ads.get(position).getImageView();
new AQuery(view).image(ads.get(position).getUrl(),false,true);
view.setScaleType(ImageView.ScaleType.FIT_CENTER);
container.addView(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String id = ads.get(position).getId();
if(!(id.equals("") || id.equals("0"))){
GoodsUtil.showGoodsDetail(context, id);
}
}
});
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
<file_sep>package com.cjq.bejingunion.fragements;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.activities.ForgetPasswordActivity;
import com.cjq.bejingunion.activities.RegisterActivity;
import com.cjq.bejingunion.utils.LoginUtil;
/**
* Created by CJQ on 2015/8/19.
*/
public class LoginFragment extends Fragment {
private View view;
private TextView userName;
private TextView password;
private CheckBox auto;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.login, container, false);
initView2(view);
return view;
}
private void initView2(View view2) {
AQuery aq = new AQuery(view2);
userName = aq.id(R.id.login_user_name).getTextView();
password = aq.id(R.id.login_password).getTextView();
auto = aq.id(R.id.login_remember).getCheckBox();
aq.id(R.id.login_login_btn).clicked(this,"doLogin");
aq.id(R.id.login_jump_register).clicked(this, "jumpRegister");
aq.id(R.id.login_jump_forget_password).clicked(this,"jumpForgetPassword");
}
public void doLogin(){
LoginUtil.login(getActivity(), userName.getText().toString(), password.getText().toString(), auto.isChecked());
}
public void jumpRegister(){
Intent intent = new Intent(getActivity(), RegisterActivity.class);
startActivity(intent);
}
public void jumpForgetPassword(){
Intent intent = new Intent(getActivity(), ForgetPasswordActivity.class);
startActivity(intent);
}
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.content.Context;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.entities.BandItem;
import java.util.List;
/**
* Created by CJQ on 2015/8/20.
*/
public class BroadBandBandItemAdapter extends BaseAdapter {
private List<BandItem> bandItems;
private Context context;
private int chose=0;
public BroadBandBandItemAdapter(List<BandItem> bandItems, Context context) {
this.bandItems = bandItems;
this.context = context;
}
// public String getPost(int position) {
// return bandItems.get(position).getPost();
// }
@Override
public int getCount() {
return bandItems.size();
}
@Override
public Object getItem(int position) {
return bandItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.text_view_layout, null, false);
convertView.setLayoutParams(new GridView.LayoutParams((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, context.getResources().getDisplayMetrics()),
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, context.getResources().getDisplayMetrics())
));
}
AQuery aq = new AQuery(convertView);
aq.id(R.id.text).text(bandItems.get(position).getShow());
if (!bandItems.get(position).isChosen()) {
convertView.setBackgroundResource(R.drawable.border_white_box);
} else {
convertView.setBackgroundResource(R.drawable.blue_border_white_background_no_corner);
}
return convertView;
}
public void changeChosen(int position) {
bandItems.get(chose).setChosen(false);
bandItems.get(position).setChosen(true);
chose = position;
}
}
<file_sep>package com.cjq.bejingunion.activities;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.cjq.bejingunion.BaseActivity;
import com.cjq.bejingunion.CommonDataObject;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.dialog.MyToast;
import com.cjq.bejingunion.utils.LoginUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by CJQ on 2015/8/26.
*/
public class AddressEditActivity extends BaseActivity {
private AQuery aq;
private String provenceId;
private String cityId;
private String provenceName;
private String areaId;
private String cityName;
private String areaName;
private String addressId;
private int position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_address_form);
Intent intent = getIntent();
addressId = intent.getStringExtra("addressId");
position = intent.getIntExtra("position", 0);
try {
Map<String, String> params = new HashMap<>();
params.put("key", LoginUtil.getKey(this));
params.put("address_id", addressId);
aq = new AQuery(this);
aq.id(R.id.new_address_form_title).text(getString(R.string.edit_address));
aq.id(R.id.new_address_form_back).clicked(this, "closeUp");
aq.id(R.id.new_address_form_submit).clicked(this, "doSubmit");
aq.id(R.id.new_address_form_select_provence).clicked(this, "chooseProvence");
aq.id(R.id.new_address_form_select_area).clicked(this, "chooseArea");
aq.id(R.id.new_address_form_select_city).clicked(this, "chooseCity");
aq.ajax(CommonDataObject.ADDRESS_EDIT_URL, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
JSONObject o = object.getJSONObject("datas").getJSONObject("address_info");
aq.id(R.id.new_address_form_username).text(o.getString("true_name"));
aq.id(R.id.new_address_form_mob_phone).text(o.getString("mob_phone"));
aq.id(R.id.new_address_form_address).text(o.getString("address"));
JSONObject provience = o.getJSONObject("province");
provenceId = provience.getString("area_id");
provenceName = provience.getString("area_name");
aq.id(R.id.new_address_form_select_provence_show).text(provenceName);
JSONObject city = o.getJSONObject("city");
cityId = city.getString("area_id");
cityName = city.getString("area_name");
aq.id(R.id.new_address_form_select_city_show).text(cityName);
JSONObject area = o.getJSONObject("area");
areaId = area.getString("area_id");
areaName = area.getString("area_name");
aq.id(R.id.new_address_form_select_area_show).text(areaName);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void chooseProvence() {
Intent intent = new Intent(this, CommonListActivity.class);
intent.putExtra("ListNo", CommonListActivity.PROVENCE_LIST);
startActivityForResult(intent, 0);
}
public void chooseCity() {
if (!"".equals(provenceId)) {
Intent intent = new Intent(this, CommonListActivity.class);
intent.putExtra("ListNo", CommonListActivity.CITY_LIST);
intent.putExtra("upId", provenceId);
startActivityForResult(intent, 1);
} else {
// Toast.makeText(this, R.string.please_choose_provence_first, Toast.LENGTH_SHORT).show();
MyToast.showText(this,R.string.please_choose_provence_first,R.drawable.a2);
}
}
public void chooseArea() {
if (!"".equals(cityId)) {
Intent intent = new Intent(this, CommonListActivity.class);
intent.putExtra("ListNo", CommonListActivity.AREA_LIST);
intent.putExtra("upId", cityId);
startActivityForResult(intent, 2);
} else {
// Toast.makeText(this, R.string.please_choose_city_first, Toast.LENGTH_SHORT).show();
MyToast.showText(this,R.string.please_choose_city_first,R.drawable.gou);
}
}
public void closeUp() {
finish();
}
public void doSubmit() {
final String true_name = aq.id(R.id.new_address_form_username).getText().toString();
final String mobile_phone = aq.id(R.id.new_address_form_mob_phone).getText().toString();
final String address = aq.id(R.id.new_address_form_address).getText().toString();
if ("".equals(true_name)) {
// Toast.makeText(this, R.string.please_input_user_name, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_input_user_name, R.drawable.a2);
return;
}
if ("".equals(mobile_phone)) {
// Toast.makeText(this, R.string.please_input_phone_number, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_input_phone_number, R.drawable.a2);
return;
}
if ("".equals(provenceId)) {
// Toast.makeText(this, R.string.please_choose_provence_first, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_choose_provence_first, R.drawable.a2);
return;
}
if ("".equals(cityId)) {
// Toast.makeText(this, R.string.please_choose_city_first, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_choose_city_first, R.drawable.a2);
return;
}
if ("".equals(areaId)) {
// Toast.makeText(this, R.string.please_select_area, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_select_area, R.drawable.a2);
return;
}
if ("".equals(address)) {
// Toast.makeText(this, R.string.please_input_address, Toast.LENGTH_SHORT).show();
MyToast.showText(this, R.string.please_input_address, R.drawable.a2);
return;
}
try {
Map<String, String> params = new HashMap<>();
params.put("key", LoginUtil.getKey(AddressEditActivity.this));
params.put("address_id", addressId);
params.put("true_name", true_name);
params.put("mob_phone", mobile_phone);
params.put("province_id", provenceId);
params.put("city_id", cityId);
params.put("area_id", areaId);
params.put("address", address);
params.put("area_info", provenceName + " " + cityName + " " + areaName);
aq.ajax(CommonDataObject.DO_EDIT_ADDRESS, params, JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject object, AjaxStatus status) {
System.out.println(object.toString());
try {
if (200 == object.getInt("code")) {
Intent intent = getIntent();
intent.putExtra("true_name", true_name);
intent.putExtra("phone_number", mobile_phone);
intent.putExtra("area_info", provenceName + " " + cityName + " " + areaName + " ");
intent.putExtra("address", address);
intent.putExtra("address_id", addressId);
intent.putExtra("position", position);
setResult(RESULT_OK, intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
super.callback(url, object, status);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
provenceName = data.getStringExtra("resultName");
provenceId = data.getStringExtra("resultId");
aq.id(R.id.new_address_form_select_provence_show).text(provenceName);
}
break;
case 1:
if (resultCode == RESULT_OK) {
cityName = data.getStringExtra("resultName");
cityId = data.getStringExtra("resultId");
aq.id(R.id.new_address_form_select_city_show).text(cityName);
}
break;
case 2:
if (resultCode == RESULT_OK) {
areaName = data.getStringExtra("resultName");
areaId = data.getStringExtra("resultId");
aq.id(R.id.new_address_form_select_area_show).text(areaName);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
<file_sep>package com.cjq.bejingunion.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.GridView;
import com.cjq.bejingunion.R;
/**
* Created by CJQ on 2015/8/11.
*/
public class MarketGridView extends GridView {
private final int mTouchSlop;
private final View mBottomView;
private onLoadListener listener;
private float mDownY;
private float mLastY;
private boolean isLoading = false;
public void setListener(onLoadListener listener) {
this.listener = listener;
}
public interface onLoadListener {
void onLoad();
}
public MarketGridView(Context context) {
this(context, null);
}
public MarketGridView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MarketGridView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mBottomView = LayoutInflater.from(context).inflate(R.layout.list_bottom,null,false);
}
@Override
public void computeScroll() {
super.computeScroll();
if (this.getAdapter() != null) {
if (canLoad()) {
doLoad();
}
}
}
public boolean isPullUp() {
return (mLastY - mDownY) > mTouchSlop;
}
private boolean isBottom() {
return getLastVisiblePosition() == getAdapter().getCount() - 1;
}
private boolean canLoad() {
return !isLoading && isPullUp() && isBottom();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownY = ev.getRawY();
mLastY = mDownY;
break;
case MotionEvent.ACTION_MOVE:
mLastY = ev.getRawY();
break;
case MotionEvent.ACTION_UP:
if (canLoad()) {
doLoad();
}
break;
}
return super.dispatchTouchEvent(ev);
}
private void doLoad() {
if(listener!=null)
listener.onLoad();
setLoading(true);
}
public void setLoading(boolean loading) {
isLoading=loading;
if(loading)
addView(mBottomView);
else{
removeView(mBottomView);
mLastY=0;
mDownY=0;
}
}
}
<file_sep>package com.cjq.bejingunion.entities;
/**
* Created by CJQ on 2015/8/29.
*/
public class Evaluation {
String image;
String username;
long time;
String content;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Evaluation(String image, String username, long time, String content, String id) {
this.image = image;
this.username = username;
this.time = time;
this.content = content;
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
<file_sep>package com.cjq.bejingunion.entities;
/**
* Created by CJQ on 2015/8/20.
*/
public class BandItem {
String show;
String post;
boolean chosen = false;
public boolean isChosen() {
return chosen;
}
public BandItem setChosen(boolean chosen) {
this.chosen = chosen;
return this;
}
public BandItem(String show, String post) {
this.show = show;
this.post = post;
}
public String getShow() {
return show;
}
public void setShow(String show) {
this.show = show;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
}
<file_sep>package com.cjq.bejingunion.reciever;
import android.content.Context;
import com.baidu.android.pushservice.PushMessageReceiver;
import java.util.List;
/**
* Created by CJQ on 2015/8/11.
*/
public class PushReceiver extends PushMessageReceiver {
@Override
public void onBind(Context context, int i, String s, String s1, String s2, String s3) {
System.out.println(1);
}
@Override
public void onUnbind(Context context, int i, String s) {
System.out.println(2);
}
@Override
public void onSetTags(Context context, int i, List<String> list, List<String> list1, String s) {
System.out.println(3);
}
@Override
public void onDelTags(Context context, int i, List<String> list, List<String> list1, String s) {
System.out.println(4);
}
@Override
public void onListTags(Context context, int i, List<String> list, String s) {
System.out.println(5);
}
@Override
public void onMessage(Context context, String s, String s1) {
System.out.println(6);
//透传
}
@Override
public void onNotificationClicked(Context context, String s, String s1, String s2) {
System.out.println(7);
}
@Override
public void onNotificationArrived(Context context, String s, String s1, String s2) {
System.out.println(8);
//通知
}
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.activities.CommonListActivity;
import com.cjq.bejingunion.entities.DetailChoice;
import com.cjq.bejingunion.entities.DetailItem;
import java.util.ArrayList;
import java.util.List;
/**
* Created by CJQ on 2015/8/27.
*/
public class DetailChoiceAdapter extends BaseAdapter {
List<DetailItem> detailItems;
Context context;
public DetailChoiceAdapter(List<DetailItem> detailItems, Context context) {
this.detailItems = detailItems;
this.context = context;
}
@Override
public int getCount() {
return detailItems.size();
}
@Override
public Object getItem(int position) {
return detailItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.detail_item, parent, false);
}
DetailItem item = detailItems.get(position);
AQuery aq = new AQuery(convertView);
final ArrayList<DetailChoice> choices = new ArrayList<>();
for (DetailChoice c : item.getDetailChoices().values()) {
choices.add(c);
}
aq.id(R.id.detail_item_type_name).text(item.getName()+":");
if (item.getDetailChoices().size() > 0)
aq.id(R.id.detail_item_chosen_name).text(item.getDetailChoices().get(Integer.parseInt(item.getChosenId())).getValue());
else
aq.id(R.id.detail_item_chosen_name).text("");
if (item.getDetailChoices().size() > 1) {
aq.id(R.id.detail_item_into).visible();
convertView.setClickable(true);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, CommonListActivity.class);
intent.putExtra("ListNo", CommonListActivity.CHOICE_LIST);
intent.putExtra("position", position);
intent.putParcelableArrayListExtra("choices", choices);
((Activity) context).startActivityForResult(intent, 0);
}
});
} else {
aq.id(R.id.detail_item_into).invisible();
convertView.setClickable(false);
}
return convertView;
}
}
<file_sep>package com.cjq.bejingunion.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.androidquery.AQuery;
import com.cjq.bejingunion.R;
import com.cjq.bejingunion.entities.Goods4IndexList;
import com.cjq.bejingunion.view.PinnedSectionListView;
import java.util.List;
/**
* Created by CJQ on 2015/9/10.
*/
public class CardAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter{
List<Goods4IndexList> goods4IndexLists;
Context context;
public CardAdapter(List<Goods4IndexList> goods4IndexLists, Context context) {
this.goods4IndexLists = goods4IndexLists;
this.context = context;
}
@Override
public int getCount() {
return goods4IndexLists.size();
}
@Override
public Object getItem(int position) {
return goods4IndexLists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.buy_phone_number_item,parent,false);
}
Goods4IndexList goods4IndexList = goods4IndexLists.get(position);
AQuery aq = new AQuery(convertView);
aq.id(R.id.buy_phone_number_item_image).image(goods4IndexList.getGoods_image_url(),false,true);
aq.id(R.id.buy_phone_number_item_name).text(goods4IndexList.getGoods_name());
aq.id(R.id.buy_phone_number_item_price).text("¥"+goods4IndexList.getGoods_price());
return convertView;
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean isItemViewTypePinned(int viewType) {
return false;
}
}
<file_sep>package com.cjq.bejingunion.event;
/**
* Created by CJQ on 2015/12/15.
*/
public class EventWXpayComplete {
}
|
d21c6bebf7a79f0947a408333256d848d426e520
|
[
"Java"
] | 45 |
Java
|
chengjinwu008/BejingUnion
|
ee3149408d1629ae6b39e0af74b13238310524e3
|
048db766d8668f967a78f9f6f0e025b9ffc0fec8
|
refs/heads/master
|
<repo_name>reficashabong/appforheroku<file_sep>/app.py
import pandas as pd
import numpy as np
from flask import Flask, request, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('model.pkl','rb'))
@app.route('/')
def home():
return render_template('form.html')
@app.route('/predict',methods=['POST','GET'])
def predict():
input_features = [float(x) for x in request.form.values()]
features_value = [np.array(input_features)]
features_name = ["Married","Dependents","Education","Self_Employed","ApplicantIncome",
"CoapplicantIncome","LoanAmount","Loan_Amount_Term","Credit_History","Property_Area"]
df = pd.DataFrame(features_value, columns=features_name)
output = model.predict(df)
if output == 1:
res_val = "** a higher probalility of getting a Loan**"
else:
res_val = "very low changes of getting a Loan"
return render_template('form.html', pred='Applicant has {}'.format(res_val))
if __name__ == "__main__":
app.run()
|
3357cf3ac92b582aeacab694b325110ddffcc2fe
|
[
"Python"
] | 1 |
Python
|
reficashabong/appforheroku
|
4aeeb517f2bb63a2bb2794a0caa3fbbdfd76137f
|
eef687becef3a7cbb6b9c7ce8b40fd4eb9b93969
|
refs/heads/master
|
<repo_name>meyejack/libgm-c<file_sep>/src/main/sm2.c
#include "sm2.h"
#include "openssl/pem.h"
#include "string.h"
EC_KEY *GM_SM2_key_new()
{
EC_KEY *key = EC_KEY_new_by_curve_name(NID_sm2);
if (key)
{
if (EC_KEY_generate_key(key) != SUCCESS)
{
EC_KEY_free(key);
key = NULL;
}
}
return key;
}
void GM_SM2_key_free(EC_KEY *key)
{
EC_KEY_free(key);
}
int GM_SM2_key_encode(char **pem, EC_KEY *key, int pri)
{
int ok = FAILURE;
BIO *mem = BIO_new(BIO_s_mem());
if (mem)
{
if ((pri
? PEM_write_bio_ECPrivateKey(mem, key, NULL, NULL, 0, NULL, NULL)
: PEM_write_bio_EC_PUBKEY(mem, key)) > 0)
{
BUF_MEM *buf = NULL;
if (BIO_get_mem_ptr(mem, &buf) > 0)
{
*pem = malloc(buf->length + 1);
if (*pem)
{
memcpy(*pem, buf->data, buf->length);
(*pem)[buf->length] = 0;
ok = SUCCESS;
}
BUF_MEM_free(buf);
buf = NULL;
}
}
BIO_free(mem);
mem = NULL;
}
return ok;
}
int GM_SM2_key_decode(EC_KEY **key, const char *pem, int pri)
{
int ok = FAILURE;
BIO *mem = BIO_new_mem_buf(pem, strlen(pem));
if (mem)
{
if ((pri
? PEM_read_bio_ECPrivateKey(mem, key, NULL, NULL)
: PEM_read_bio_EC_PUBKEY(mem, key, NULL, NULL)) != NULL)
{
ok = SUCCESS;
}
BIO_free(mem);
mem = NULL;
}
return ok;
}
#define use_pkey(exp, key) \
do \
{ \
EVP_PKEY *pkey = EVP_PKEY_new(); \
if (pkey) \
{ \
if (EVP_PKEY_set1_EC_KEY(pkey, key) == SUCCESS && \
EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2) == SUCCESS) \
{ \
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL); \
if (pctx) \
{ \
exp \
EVP_PKEY_CTX_free(pctx); \
pctx = NULL; \
} \
} \
EVP_PKEY_free(pkey); \
pkey = NULL; \
} \
} while (0)
int GM_SM2_crypt(unsigned char **out, size_t *out_len, const unsigned char *in, size_t in_len, EC_KEY *key, int enc)
{
int ok = FAILURE;
int (*init)(EVP_PKEY_CTX *);
int (*crypt)(EVP_PKEY_CTX *, unsigned char *, size_t *, const unsigned char *, size_t);
if (enc)
{
init = EVP_PKEY_encrypt_init;
crypt = EVP_PKEY_encrypt;
}
else
{
init = EVP_PKEY_decrypt_init;
crypt = EVP_PKEY_decrypt;
}
use_pkey(
if (init(pctx) == SUCCESS &&
crypt(pctx, NULL, out_len, NULL, in_len) == SUCCESS) {
*out = malloc(*out_len);
if (*out != NULL &&
crypt(pctx, *out, out_len, in, in_len) == SUCCESS)
{
ok = SUCCESS;
}
else
{
free(*out);
*out = NULL;
}
},
key);
return ok;
}
#define use_md(exp, key, id) \
use_pkey( \
EVP_MD_CTX *mctx = EVP_MD_CTX_new(); \
if (mctx) { \
if (EVP_PKEY_CTX_set1_id(pctx, id, 16) > 0) \
{ \
EVP_MD_CTX_set_pkey_ctx(mctx, pctx); \
exp \
} \
EVP_MD_CTX_free(mctx); \
mctx = NULL; \
}, \
key)
int GM_SM2_sign(unsigned char **sig, size_t *sig_len, const unsigned char *data, size_t data_len, const unsigned char *id, EC_KEY *key)
{
int ok = FAILURE;
use_md(
if (EVP_DigestSignInit(mctx, NULL, EVP_sm3(), NULL, pkey) == SUCCESS &&
EVP_DigestSignUpdate(mctx, data, data_len) == SUCCESS &&
EVP_DigestSignFinal(mctx, NULL, sig_len) == SUCCESS) {
*sig = malloc(*sig_len);
if (*sig )
{
if (EVP_DigestSignFinal(mctx, *sig, sig_len) == SUCCESS)
{
ok = SUCCESS;
}
else
{
free(*sig);
*sig = NULL;
}
} },
key, id);
return ok;
}
int GM_SM2_verify(const unsigned char *sig, size_t sig_len, const unsigned char *data, size_t data_len, unsigned char *id, EC_KEY *key)
{
int ok = FAILURE;
use_md(ok = EVP_DigestVerifyInit(mctx, NULL, EVP_sm3(), NULL, pkey) == SUCCESS &&
EVP_DigestVerifyUpdate(mctx, data, data_len) == SUCCESS &&
EVP_DigestVerifyFinal(mctx, sig, sig_len) == SUCCESS;
, key, id);
return ok;
}
<file_sep>/src/main/sm4.c
#include "sm4.h"
#include "openssl/evp.h"
int GM_SM4_crypt(unsigned char *out, int *out_len, const unsigned char *in, int in_len, const unsigned char *key, const unsigned char *iv, int enc)
{
int ok = FAILURE;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx)
{
int len1 = 0;
int len2 = 0;
if (EVP_CipherInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv, enc) == SUCCESS &&
EVP_CIPHER_CTX_set_padding(ctx, EVP_PADDING_PKCS7) == SUCCESS &&
EVP_CipherUpdate(ctx, out, &len1, in, in_len) == SUCCESS &&
EVP_CipherFinal_ex(ctx, out + len1, &len2) == SUCCESS)
{
*out_len = len1 + len2;
ok = SUCCESS;
}
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
}
return ok;
}
int GM_SM4_crypt_file(FILE *dst, FILE *src, const unsigned char *key, const unsigned char *iv, int enc)
{
int ok = FAILURE;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx)
{
if (EVP_CipherInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv, enc) == SUCCESS)
{
EVP_CIPHER_CTX_set_padding(ctx, EVP_PADDING_PKCS7);
unsigned char buf_in[0x2000];
unsigned char buf_out[0x2000 + 16];
int buf_in_len;
int buf_out_len;
int update_ok = SUCCESS;
while ((buf_in_len = fread(buf_in, 1, sizeof(buf_in), src)) > 0)
{
if (!(EVP_CipherUpdate(ctx, buf_out, &buf_out_len, buf_in, buf_in_len) == SUCCESS &&
fwrite(buf_out, buf_out_len, 1, dst) > 0))
{
update_ok = FAILURE;
break;
}
}
if (update_ok &&
EVP_CipherFinal_ex(ctx, buf_out, &buf_out_len) == SUCCESS &&
fwrite(buf_out, buf_out_len, 1, dst) > 0)
{
ok = SUCCESS;
}
}
EVP_CIPHER_CTX_free(ctx);
ctx = NULL;
}
return ok;
}<file_sep>/include/sm4.h
#include "gm.h"
#include "stdio.h"
#define GM_SM4_encrypt(out, out_len, in, in_len, key, iv) GM_SM4_crypt(out, out_len, in, in_len, key, iv, 1)
#define GM_SM4_decrypt(out, out_len, in, in_len, key, iv) GM_SM4_crypt(out, out_len, in, in_len, key, iv, 0)
#define GM_SM4_encrypt_file(dst, src, key, iv) GM_SM4_crypt_file(dst, src, key, iv, 1)
#define GM_SM4_decrypt_file(dst, src, key, iv) GM_SM4_crypt_file(dst, src, key, iv, 0)
#ifdef __cplusplus
extern "C"
{
#endif
// 加密或解密。
// @param out [out] 加密后或解密后的数据。需要事先分配(in_len+16)个字节的内存空间。
// @param out_len [out] 加密后或解密后的数据长度。
// @param in [in] 需要加密或解密的数据。
// @param in_len [in] 需要加密或解密的数据长度。
// @param key [in] 密钥。长度为16个字节。
// @param iv [in] 静态向量。长度为16个字节。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM4_crypt(unsigned char *out, int *out_len, const unsigned char *in, int in_len, const unsigned char *key, const unsigned char *iv, int enc);
// 加密或解密文件。
// @param dst [out] 加密后或解密后的文件。
// @param src [in] 需要加密或解密的文件。
// @param key [in] 密钥。长度为16个字节。
// @param iv [in] 静态向量。长度为16个字节。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM4_crypt_file(FILE *dst, FILE *src, const unsigned char *key, const unsigned char *iv, int enc);
#ifdef __cplusplus
}
#endif<file_sep>/README.md
# libgm
使用OpenSSL实现国密SM2、SM3和SM4算法的C库。
## 编译动态库
```sh
gcc -std=c11 -shared -fPIC -s -o./bin/libgm.dll -Iinclude src/main/*.c -Llib -lcrypto
```
## 函数定义
`sm2.h`
```c
// 新建一个SM2密钥。
// @return SM2密钥。失败则返回空指针。
EC_KEY *GM_SM2_key_new();
// 释放SM2密钥占用的资源。
// @param key [in] SM2密钥。
void GM_SM2_key_free(EC_KEY *key);
// 编码SM2密钥。
// @param pem [out] PEM格式的密钥字符串。不用时需要调用者释放资源。
// @param key [in] SM2密钥。
// @param pri [in] 需要编码的密钥类型。1表示私钥,0表示公钥。
// @return 成功返回1,失败返回0。
int GM_SM2_key_encode(char **pem, EC_KEY *key, int pri);
// 解码SM2密钥。
// @param key [out] SM2密钥。不用时需要调用者释放资源。
// @param pem [in] PEM格式的密钥字符串。
// @param pri [in] 需要解码的密钥类型。1表示私钥,0表示公钥。
// @return 成功返回1,失败返回0。
int GM_SM2_key_decode(EC_KEY **key, const char *pem, int pri);
// 加密或解密。
// @param out [out] 加密后或解密后的数据。不用时需要调用者释放资源。
// @param out_len [out] 加密后或解密后的数据长度。
// @param in [in] 需要加密或解密的数据。
// @param in_len [in] 需要加密或解密的数据长度。
// @param key [in] SM2密钥。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM2_crypt(unsigned char **out, size_t *out_len, const unsigned char *in, size_t in_len, EC_KEY *key, int enc);
// 签名。
// @param sig [out] 签名。不用时需要调用者释放资源。
// @param sig_len [out] 签名长度。
// @param data [in] 需要签名的数据。
// @param data_len [in] 需要签名的数据长度。
// @param id [in] 用户身份标识ID。SM2规范规定在用SM2签名时需要指定用户身份标识,无特殊约定的情况下,用户身份标识ID的长度为16个字节,其默认值从左至右依次为:0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38。
// @param key [in] SM2密钥。
// @return 成功返回1,失败返回0。
int GM_SM2_sign(unsigned char **sig, size_t *sig_len, const unsigned char *data, size_t data_len, const unsigned char *id, EC_KEY *key);
// 验签。
// @param sig [in] 签名。
// @param sig_len [in] 签名长度。
// @param data [in] 需要验签的数据。
// @param data_len [in] 需要验签的数据长度。
// @param id [in] 用户身份标识ID。
// @param key [in] SM2密钥。
// @return 成功返回1,失败返回0。
int GM_SM2_verify(const unsigned char *sig, size_t sig_len, const unsigned char *data, size_t data_len, unsigned char *id, EC_KEY *key);
```
说明:
SM2用于非对称加密。
---
`sm3.h`
```c
// 计算数据的SM3消息摘要。
// @param md [out] SM3消息摘要。需要事先分配32字节内存。
// @param data [in] 需要计算SM3消息摘要的数据。
// @param data_len [in] 数据长度。
// @return 成功返回1,失败返回0。
int GM_SM3_digest(unsigned char *md, const void *data, size_t data_len);
// 计算文件的SM3消息摘要。
// @param md [out] SM3消息摘要。需要事先分配32字节内存。
// @param file [in] 需要计算SM3消息摘要的文件。
// @return 成功返回1,失败返回0。
int GM_SM3_digest_file(unsigned char *md, FILE *file);
```
说明:
SM3用于计算数据哈希值。
---
`sm4.h`
```c
// 加密或解密。
// @param out [out] 加密后或解密后的数据。需要事先分配(in_len+16)个字节的内存空间。
// @param out_len [out] 加密后或解密后的数据长度。
// @param in [in] 需要加密或解密的数据。
// @param in_len [in] 需要加密或解密的数据长度。
// @param key [in] 密钥。长度为16个字节。
// @param iv [in] 静态向量。长度为16个字节。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM4_crypt(unsigned char *out, int *out_len, const unsigned char *in, int in_len, const unsigned char *key, const unsigned char *iv, int enc);
// 加密或解密文件。
// @param dst [out] 加密后或解密后的文件。
// @param src [in] 需要加密或解密的文件。
// @param key [in] 密钥。长度为16个字节。
// @param iv [in] 静态向量。长度为16个字节。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM4_crypt_file(FILE *dst, FILE *src, const unsigned char *key, const unsigned char *iv, int enc);
```
说明:
SM4用于对称加密。
---
## 例子
```c
#include "sm2.h"
#include "sm3.h"
#include "sm4.h"
#include "stdio.h"
#include "stdlib.h"
void print_hex(const unsigned char *data, size_t data_len)
{
while (data_len-- > 0)
{
printf("%02x", *data++);
}
}
void test_sm2()
{
printf("test_sm2()\n");
unsigned char data[] = "Hello World!";
char *pemPri = NULL;
char *pemPub = NULL;
// 生成密钥对
EC_KEY *key = GM_SM2_key_new();
if (key != NULL)
{
// 编码私钥
if (GM_SM2_key_encode(&pemPri, key, 1) == SUCCESS)
{
printf("%s\n", pemPri);
}
// 编码公钥
if (GM_SM2_key_encode(&pemPub, key, 0) == SUCCESS)
{
printf("%s\n", pemPub);
}
GM_SM2_key_free(key);
key = NULL;
}
unsigned char *enc_data = NULL;
size_t enc_len = 0;
// 解码公钥并加密
if (GM_SM2_key_decode(&key, pemPub, 0) == SUCCESS &&
GM_SM2_encrypt(&enc_data, &enc_len, data, sizeof(data), key) == SUCCESS)
{
printf("enc_data=%d,", enc_len);
print_hex(enc_data, enc_len);
printf("\n");
GM_SM2_key_free(key);
key = NULL;
unsigned char *dec_data = NULL;
size_t dec_len = 0;
// 解码私钥并解密
if (GM_SM2_key_decode(&key, pemPri, 1) == SUCCESS &&
GM_SM2_decrypt(&dec_data, &dec_len, enc_data, enc_len, key) == SUCCESS)
{
printf("dec_data=%d,%.*s\n", dec_len, dec_len, dec_data);
GM_SM2_key_free(key);
key = NULL;
free(dec_data);
dec_data = NULL;
}
free(enc_data);
enc_data = NULL;
}
unsigned char *sig = NULL;
size_t sig_len = 0;
unsigned char id[16] = {0};
// 解码私钥并签名
if (GM_SM2_key_decode(&key, pemPri, 1) == SUCCESS &&
GM_SM2_sign(&sig, &sig_len, data, sizeof(data), id, key) == SUCCESS)
{
printf("sig=%d,", sig_len);
print_hex(sig, sig_len);
printf("\n");
GM_SM2_key_free(key);
key = NULL;
// 解码公钥并验签
if (GM_SM2_key_decode(&key, pemPub, 0) == SUCCESS)
{
int verified = GM_SM2_verify(sig, sig_len, data, sizeof(data), id, key);
printf("verified=%d\n", verified);
GM_SM2_key_free(key);
key = NULL;
}
free(sig);
sig = NULL;
}
free(pemPri);
pemPri = NULL;
free(pemPub);
pemPub = NULL;
}
void test_sm3()
{
printf("test_sm3()\n");
unsigned char data[] = "Hello World!";
unsigned char md[32] = {0};
if (GM_SM3_digest(md, data, sizeof(data)) == SUCCESS)
{
printf("md=");
print_hex(md, sizeof(md));
printf("\n");
}
}
void test_sm4()
{
printf("test_sm4()\n");
unsigned char data[] = "Hello World!";
unsigned char enc_data[sizeof(data) + 16];
int enc_len = 0;
unsigned char key[16] = {0};
unsigned char iv[16] = {0};
if (GM_SM4_encrypt(enc_data, &enc_len, data, sizeof(data), key, iv) == SUCCESS)
{
printf("enc_data=%d,", enc_len);
print_hex(enc_data, enc_len);
printf("\n");
unsigned char dec_data[enc_len + 16];
int dec_len = 0;
if (GM_SM4_decrypt(dec_data, &dec_len, enc_data, enc_len, key, iv) == SUCCESS)
{
printf("dec_data=%d,%.*s\n", dec_len, dec_len, dec_data);
}
}
}
int main()
{
test_sm2();
test_sm3();
test_sm4();
}
```<file_sep>/include/sm3.h
#include "gm.h"
#include "stdio.h"
#ifdef __cplusplus
extern "C"
{
#endif
// 计算数据的SM3消息摘要。
// @param md [out] SM3消息摘要。需要事先分配32字节内存。
// @param data [in] 需要计算SM3消息摘要的数据。
// @param data_len [in] 数据长度。
// @return 成功返回1,失败返回0。
int GM_SM3_digest(unsigned char *md, const void *data, size_t data_len);
// 计算文件的SM3消息摘要。
// @param md [out] SM3消息摘要。需要事先分配32字节内存。
// @param file [in] 需要计算SM3消息摘要的文件。
// @return 成功返回1,失败返回0。
int GM_SM3_digest_file(unsigned char *md, FILE *file);
#ifdef __cplusplus
}
#endif<file_sep>/include/sm2.h
#include "gm.h"
#define GM_SM2_key_encode_private(pem, key) GM_SM2_key_encode(pem, key, 1)
#define GM_SM2_key_encode_public(pem, key) GM_SM2_key_encode(pem, key, 0)
#define GM_SM2_key_decode_private(key, pem) GM_SM2_key_decode(key, pem, 1)
#define GM_SM2_key_decode_public(key, pem) GM_SM2_key_decode(key, pem, 0)
#define GM_SM2_encrypt(out, out_len, in, in_len, key) GM_SM2_crypt(out, out_len, in, in_len, key, 1)
#define GM_SM2_decrypt(out, out_len, in, in_len, key) GM_SM2_crypt(out, out_len, in, in_len, key, 0)
#ifdef __cplusplus
extern "C"
{
#endif
// 新建一个SM2密钥。
// @return SM2密钥。失败则返回空指针。
EC_KEY *GM_SM2_key_new();
// 释放SM2密钥占用的资源。
// @param key [in] SM2密钥。
void GM_SM2_key_free(EC_KEY *key);
// 编码SM2密钥。
// @param pem [out] PEM格式的密钥字符串。不用时需要调用者释放资源。
// @param key [in] SM2密钥。
// @param pri [in] 需要编码的密钥类型。1表示私钥,0表示公钥。
// @return 成功返回1,失败返回0。
int GM_SM2_key_encode(char **pem, EC_KEY *key, int pri);
// 解码SM2密钥。
// @param key [out] SM2密钥。不用时需要调用者释放资源。
// @param pem [in] PEM格式的密钥字符串。
// @param pri [in] 需要解码的密钥类型。1表示私钥,0表示公钥。
// @return 成功返回1,失败返回0。
int GM_SM2_key_decode(EC_KEY **key, const char *pem, int pri);
// 加密或解密。
// @param out [out] 加密后或解密后的数据。不用时需要调用者释放资源。
// @param out_len [out] 加密后或解密后的数据长度。
// @param in [in] 需要加密或解密的数据。
// @param in_len [in] 需要加密或解密的数据长度。
// @param key [in] SM2密钥。
// @param enc [in] 操作类型。1表示加密,0表示解密。
// @return 成功返回1,失败返回0。
int GM_SM2_crypt(unsigned char **out, size_t *out_len, const unsigned char *in, size_t in_len, EC_KEY *key, int enc);
// 签名。
// @param sig [out] 签名。不用时需要调用者释放资源。
// @param sig_len [out] 签名长度。
// @param data [in] 需要签名的数据。
// @param data_len [in] 需要签名的数据长度。
// @param id [in] 用户身份标识ID。SM2规范规定在用SM2签名时需要指定用户身份标识,无特殊约定的情况下,用户身份标识ID的长度为16个字节,其默认值从左至右依次为:0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38。
// @param key [in] SM2密钥。
// @return 成功返回1,失败返回0。
int GM_SM2_sign(unsigned char **sig, size_t *sig_len, const unsigned char *data, size_t data_len, const unsigned char *id, EC_KEY *key);
// 验签。
// @param sig [in] 签名。
// @param sig_len [in] 签名长度。
// @param data [in] 需要验签的数据。
// @param data_len [in] 需要验签的数据长度。
// @param id [in] 用户身份标识ID。
// @param key [in] SM2密钥。
// @return 成功返回1,失败返回0。
int GM_SM2_verify(const unsigned char *sig, size_t sig_len, const unsigned char *data, size_t data_len, unsigned char *id, EC_KEY *key);
#ifdef __cplusplus
}
#endif<file_sep>/include/gm.h
#include "openssl/ossl_typ.h"
#include "stddef.h"
#define SUCCESS 1
#define FAILURE 0
<file_sep>/src/main/sm3.c
#include "sm3.h"
#include "openssl/evp.h"
int GM_SM3_digest(unsigned char *md, const void *data, size_t data_len)
{
int ok = FAILURE;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (ctx)
{
unsigned int md_len;
if (EVP_DigestInit_ex(ctx, EVP_sm3(), NULL) == SUCCESS &&
EVP_DigestUpdate(ctx, data, data_len) == SUCCESS &&
EVP_DigestFinal_ex(ctx, md, &md_len) == SUCCESS &&
md_len == 32)
{
ok = SUCCESS;
}
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
return ok;
}
int GM_SM3_digest_file(unsigned char *md, FILE *file)
{
int ok = FAILURE;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (ctx)
{
if (EVP_DigestInit_ex(ctx, EVP_sm3(), NULL) == SUCCESS)
{
unsigned char buf[0x2000];
size_t buf_len;
int update_ok = SUCCESS;
while ((buf_len = fread(buf, 1, sizeof(buf), file)) > 0)
{
if (EVP_DigestUpdate(ctx, buf, buf_len) != SUCCESS)
{
update_ok = FAILURE;
break;
}
}
unsigned int md_len;
if (update_ok &&
EVP_DigestFinal_ex(ctx, md, &md_len) == SUCCESS &&
md_len == 32)
{
ok = SUCCESS;
}
}
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
return ok;
}<file_sep>/Makefile
SRC_ROOT = src/main
INC_DIRS = include
OBJ_ROOT = obj
BIN_ROOT = bin
BIN_NAME = gm
MAJOR_VERSION = 1
MINOR_VERSION = 0
CC = gcc
CFLAGS = -std=c11 -fPIC
LDFLAGS = -shared -s -Llib
LIBS = -lcrypto
get_src_dirs = $(if $(wildcard $(1)/*.c),$(1)) $(foreach path,$(wildcard $(1)/*),$(call get_src_dirs,$(path)))
src_dirs = $(call get_src_dirs,$(SRC_ROOT))
src_files = $(foreach dir,$(src_dirs),$(wildcard $(dir)/*.c))
ifeq ($(OS),Windows_NT)
obj_dir = $(OBJ_ROOT)/win32
bin_dir = $(BIN_ROOT)/win32
bin_file = $(bin_dir)/$(BIN_NAME).dll
else ifeq ($(shell uname),Linux)
obj_dir = $(OBJ_ROOT)/linux
bin_dir = $(BIN_ROOT)/linux
LDFLAGS += -Wl,-soname,lib$(BIN_NAME).so.$(MAJOR_VERSION)
bin_file = $(bin_dir)/lib$(BIN_NAME).so.$(MAJOR_VERSION).$(MINOR_VERSION)
endif
obj_dirs = $(patsubst $(SRC_ROOT)%,$(obj_dir)%,$(src_dirs))
obj_files = $(patsubst $(SRC_ROOT)%.c,$(obj_dir)%.o,$(src_files))
.PHONY:all clean
all:$(bin_file)
$(bin_file):$(obj_files)|$(bin_dir)
@echo Linking $@...
@$(CC) $(LDFLAGS) -o$@ $^ $(LIBS)
$(bin_dir):
@echo Making directory $@...
@mkdir -p $@
$(obj_files):$(obj_dir)%.o:$(SRC_ROOT)%.c|$(obj_dirs)
@echo Compiling $<...
@$(CC) -c $(CFLAGS) -o$@ $< $(foreach dir,$(INC_DIRS),-I$(dir))
$(obj_dirs):
@echo Making directory $@...
@mkdir -p $@
del_dirs = $(wildcard $(obj_dir) $(bin_dir))
del_roots = $(wildcard $(OBJ_ROOT) $(BIN_ROOT))
clean:
@$(if $(del_dirs),$(foreach dir,$(del_dirs),echo Removing directory $(dir)...;) rm -rf $(del_dirs);)
@$(if $(del_roots),$(foreach dir,$(del_roots),echo Removing directory $(dir)...;) rmdir -p --ignore-fail-on-non-empty $(del_roots);)
|
c629a5de0e7d28c94df4b71799bfc6eb6400d2f5
|
[
"Markdown",
"C",
"Makefile"
] | 9 |
C
|
meyejack/libgm-c
|
7a9b2b14d405b4b413239f88f9f9ac68d6685e83
|
6aa380daae23d4074af74ca7f29e29138cae21c2
|
refs/heads/master
|
<file_sep>package com.example.administrator.calculator;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Transfer extends AppCompatActivity {
EditText edit_li, edit_m, edit_chi, edit_zhang, edit_cun;
String str_li, str_m, str_chi, str_zhang, str_cun;
Button b_li, b_m, b_chi, b_zhang, b_cun, re, clear;
double d_li, d_m, d_chi, d_zhang, d_cun;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
b_li = (Button) findViewById(R.id.btn_li);
b_m = (Button) findViewById(R.id.btn_m);
b_zhang = (Button) findViewById(R.id.btn_zhang);
b_chi = (Button) findViewById(R.id.btn_chi);
b_cun = (Button) findViewById(R.id.btn_cun);
re = (Button) findViewById(R.id.returnn);
clear = (Button) findViewById(R.id.clear);
edit_li = (EditText) findViewById(R.id.et_li);
edit_m = (EditText) findViewById(R.id.et_m);
edit_zhang = (EditText) findViewById(R.id.et_zhang);
edit_chi = (EditText) findViewById(R.id.et_chi);
edit_cun = (EditText) findViewById(R.id.et_cun);
re.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Transfer.this, MainActivity.class);
startActivity(intent);
}
});
clear.setOnClickListener((new View.OnClickListener() {
public void onClick(View v) {
edit_li.setText("");
edit_m.setText("");
edit_zhang.setText("");
edit_chi.setText("");
edit_cun.setText("");
}
}));
b_m.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
str_m = edit_m.getText().toString();
d_m = Double.parseDouble(str_m);
d_li = d_m * 0.002;
d_zhang = d_m * 0.3;
d_chi = d_m * 3;
d_cun = d_m * 30;
//BigDecimal b = new BigDecimal(double_cmnew).setScale(6);
edit_li.setText(String.format("%.5f", d_li));
edit_zhang.setText(String.format("%.5f", d_zhang));
edit_chi.setText(String.format("%.5f", d_chi));
edit_cun.setText(String.format("%.5f", d_cun));
}
});
b_li.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
str_li = edit_li.getText().toString();
d_li = Double.parseDouble(str_li);
d_m = d_li * 500;
d_zhang = d_li * 150;
d_chi = d_li * 1500;
d_cun = d_li * 15000;
//BigDecimal b = new BigDecimal(double_cmnew).setScale(6);
edit_m.setText(String.format("%.5f", d_m));
edit_zhang.setText(String.format("%.5f", d_zhang));
edit_chi.setText(String.format("%.3f", d_chi));
edit_cun.setText(String.format("%.2f", d_cun));
}
});
b_zhang.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
str_zhang = edit_zhang.getText().toString();
d_zhang = Double.parseDouble(str_zhang);
d_m = d_zhang * 3.3333333;
d_li = d_zhang * 0.0066666667;
d_chi = d_zhang * 10;
d_cun = d_zhang * 100;
//BigDecimal b = new BigDecimal(double_cmnew).setScale(6);
edit_m.setText(String.format("%.5f", d_m));
edit_li.setText(String.format("%.5f", d_li));
edit_chi.setText(String.format("%.3f", d_chi));
edit_cun.setText(String.format("%.2f", d_cun));
}
});
b_chi.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
str_chi = edit_chi.getText().toString();
d_chi = Double.parseDouble(str_chi);
d_m = d_chi * 0.33333333;
d_li = d_chi * 0.00066666667;
d_zhang = d_chi * 0.1;
//BigDecimal b = new BigDecimal(double_cmnew).setScale(6);
edit_m.setText(String.format("%.5f", d_m));
edit_li.setText(String.format("%.5f", d_li));
edit_zhang.setText(String.format("%.3f", d_zhang));
edit_cun.setText(String.format("%.2f", d_cun));
}
});
b_cun.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
str_cun = edit_cun.getText().toString();
d_cun = Double.parseDouble(str_cun);
d_m = d_cun * 0.033333333;
d_li = d_cun * 0.000066666667;
d_zhang = d_cun * 0.01;
d_chi = d_cun * 0.1;
//BigDecimal b = new BigDecimal(double_cmnew).setScale(6);
edit_m.setText(String.format("%.5f", d_m));
edit_li.setText(String.format("%.8f", d_li));
edit_zhang.setText(String.format("%.3f", d_zhang));
edit_chi.setText(String.format("%.2f", d_chi));
}
});
}
}
|
71696e562eb3317a92fbf962564455449e21dba3
|
[
"Java"
] | 1 |
Java
|
chenprincess/Android-calculator
|
409ea9d30c57e659786f897869342a7100f0a034
|
0d6744da9a18584100b195bc0546979e98f496df
|
refs/heads/master
|
<repo_name>stefanoscolapasta/Operating-Systems<file_sep>/Bash/leggere.sh
exec {FD}< miofileNoNL.txt;
if(( $? == 0 )); then
while read -u ${FD} RIGA; [[ $? == 0 || $RIGA != "" ]] ; do
echo $RIGA;
done
exec {FD}>&-
fi
<file_sep>/ConcurrentProgrammingExercices/Mutex/Piattello/Makefile
CFLAGS=-ansi -Wall -Wpedantic
LIBR=-lpthread
all: piattello.exe
piattello.exe: piattello.o DBGpthread.o
gcc ${CFLAGS} -o piattello.exe piattello.o DBGpthread.o ${LIBR}
piattello.o: piattello.c DBGpthread.h
gcc -c ${CFLAGS} piattello.c
DBGpthread.o: DBGpthread.c printerror.h
gcc -c ${CFLAGS} DBGpthread.c
.PHONY: clean
clean:
rm *.o piattello.exe
<file_sep>/Bash/secondo.sh
(sleep 15; echo d) &
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esDealloca/dealloca.c
typedef struct s_NODO{
int key;
double x;
s_NODO *destra;
s_NODO *sinistra;
}NODO;
void dealloca_albero(NODO **ppnodo){
if(destra == NULL && sinistra == NULL){
free(*ppnodo);
*ppnodo = NULL;
} else {
if((*ppnodo)->destra != NULL){
dealloca_albero(&((*(*ppnodo)).destra));
}
if((*ppnodo)->sinistra != NULL){
dealloca_albero(&((*ppnodo)->sinistra));
}
}
}
void main(){
NODO *root;
costruisci_albero(&root);
usa_albero(root);
dealloca_albero(&root);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/Barbiere/scr.sh
echo "" > primo.txt
for i in `find /usr/include -maxdepth 1 -mindepth 1 -name "*.h"`; do
RIS=`grep "ifdef" $i | wc -l`
echo "RISSSSS----> $RIS"
if ((RIS >= 10)); then
grep "ifdef" $i | head -n 5 >> primo.txt
fi
done
sort primo.txt > FINALE.txt
exit 0
<file_sep>/Esami/BASE_es153/Sol/2020_07_17__es153_piattello_ONLINE/Makefile
CFLAGSCONSTRERROR=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE -D_BSD_SOURCE -D_POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE
LIBRARIES=-lpthread
DBGPTHREADFUNCTION_SOURCE_DIR=./
all: piattello.exe
piattello.exe: piattello.o DBGpthread.o
gcc ${CFLAGS} -o piattello.exe piattello.o DBGpthread.o ${LIBRARIES}
piattello.o: piattello.c ${DBGPTHREADFUNCTION_SOURCE_DIR}DBGpthread.h ${DBGPTHREADFUNCTION_SOURCE_DIR}printerror.h
gcc -c ${CFLAGS} -I${DBGPTHREADFUNCTION_SOURCE_DIR} piattello.c
DBGpthread.o: ${DBGPTHREADFUNCTION_SOURCE_DIR}DBGpthread.c ${DBGPTHREADFUNCTION_SOURCE_DIR}printerror.h
gcc ${CFLAGSCONSTRERROR} -c ${DBGPTHREADFUNCTION_SOURCE_DIR}DBGpthread.c -I${DBGPTHREADFUNCTION_SOURCE_DIR}
.PHONY: clean
clean:
-rm -f DBGpthread.o piattello.exe piattello.o
<file_sep>/ConcurrentProgrammingExercices/Mutex/Barbiere/barbiere.c
/* file: barbiere.c
*/
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h> /* uint64_t */
#include <sys/time.h> /* gettimeofday() struct timeval */
#include <pthread.h>
#include "printerror.h"
#include "DBGpthread.h"
#define NUMSEDIE 5
#define NUMCLIENTI 50
/* nessuna variabili da proteggere */
/* variabili per la sincronizzazione */
int numclientiincoda=0;
pthread_mutex_t mutex;
pthread_cond_t condBarbiereLibero;
pthread_cond_t condArrivoClienti;
void *barbiere (void *arg)
{
char Blabel[128];
char Blabelsignal[128];
int indice;
indice=*((int*)arg);
free(arg);
sprintf(Blabel,"B%d",indice);
sprintf(Blabelsignal,"B%d->C",indice);
while(1) {
/* barbiere controlla se c'e' qualcun altro in coda */
/* prendo la mutua esclusione */
DBGpthread_mutex_lock(&mutex,Blabel);
if ( numclientiincoda <= 0 )
/* il barbiere DORME */
DBGpthread_cond_wait( &condArrivoClienti, &mutex, Blabel );
/* c'e' qualche cliente in coda, ne risveglio 1 */
DBGpthread_cond_signal( &condBarbiereLibero, Blabel );
/* un cliente esce dalla coda e va nella poltrona del barbiere */
/* rilascio mutua esclusione */
DBGpthread_mutex_unlock(&mutex,Blabel);
/* barbiere serve il cliente */
printf("barbiere %s serve cliente \n", Blabel );
fflush(stdout);
/* il barbiere lavora sul cliente per 1/2 di sec piu o meno */
DBGnanosleep( 500000000, Blabel );
/* barbiere finisce di servire il cliente */
printf("barbiere %s finisce il cliente \n", Blabel );
fflush(stdout);
}
pthread_exit(NULL);
}
void *cliente (void *arg)
{
char Clabel[128];
char Clabelsignal[128];
int indice;
indice=*((int*)arg);
free(arg);
sprintf(Clabel,"C%d",indice);
sprintf(Clabelsignal,"C%d->B",indice);
while(1) {
/* il cliente aspetta qualche giorno = 1/2 sec e poi va dal barbiere */
DBGnanosleep( 500000000, Clabel );
/* cliente controlla se c'e' qualcun altro in coda */
/* prendo la mutua esclusione */
DBGpthread_mutex_lock(&mutex,Clabel);
/* se non ci sono sedie libere me ne vado incazzato %@!$&^ */
if ( numclientiincoda >= NUMSEDIE ) {
DBGpthread_mutex_unlock(&mutex,Clabel);
}
else {
/* ci sono sedie libere, mi siedo */
numclientiincoda++;
if ( numclientiincoda <= 1 )
/* ci sono solo io e il barbiere DORME, devo svegliarlo */
DBGpthread_cond_signal( &condArrivoClienti, Clabel );
/* aspetto un assenso dal barbiere per andare alla poltrona */
DBGpthread_cond_wait( &condBarbiereLibero, &mutex, Clabel );
/* io cliente esco dalla coda e vado nella poltrona del barbiere */
numclientiincoda--;
/* rilascio mutua esclusione */
DBGpthread_mutex_unlock(&mutex,Clabel);
/* il barbiere lavora */
printf("il cliente %s viene servito\n", Clabel );
fflush(stdout);
/* il barbiere finisce lavoro e il cliente se ne va */
printf("il cliente %s se ne va \n", Clabel );
fflush(stdout);
}
}
pthread_exit(NULL);
}
int main (int argc, char* argv[] )
{
pthread_t th;
int rc, i, *intptr;
rc = pthread_cond_init( &condBarbiereLibero , NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_cond_init( &condArrivoClienti , NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_mutex_init( &mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
numclientiincoda=0;
/* lancio il barbiere */
intptr=malloc(sizeof(int));
if( !intptr ) { printf("malloc failed\n");exit(1); }
*intptr=0; /* un solo barbiere */
rc=pthread_create( &th,NULL,barbiere,(void*)intptr);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
/* lancio i clienti */
for(i=0;i<NUMCLIENTI;i++) {
intptr=malloc(sizeof(int));
if( !intptr ) { printf("malloc failed\n");exit(1); }
*intptr=i;
rc=pthread_create( &th,NULL,cliente,(void*)intptr);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
pthread_exit(NULL);
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/VarSignalAndBroadcast/Makefile
# Makefile per mutex e CondVar*
# a causa della presenza di strerror_r in printerror.h
# occorre compilare definendo il simbolo -D_POSIX_C_SOURCE=200112L
# ed e' bene compilare con uno dei due simboli _THREAD_SAFE o _REENTRANT
# I due simboli sono equivalenti, per ricordare che esistono entrambi,
# nell'esempio li definisco entrambi, ma ne basterebbe uno solo.
CFLAGS=-ansi -Wpedantic -Wall -D_THREAD_SAFE -D_REENTRANT -D_POSIX_C_SOURCE=200112L
LIBRARIES=-lpthread
all: mutex.exe CondVarBroadcast.exe CondVarSignal.exe es1_banche.exe
mutex.exe: mutex.o
gcc ${CFLAGS} -o mutex.exe mutex.o ${LIBRARIES}
mutex.o: mutex.c printerror.h
gcc ${CFLAGS} -c mutex.c
CondVarBroadcast.exe: CondVarBroadcast.o
gcc ${CFLAGS} -o CondVarBroadcast.exe CondVarBroadcast.o ${LIBRARIES}
CondVarBroadcast.o: CondVarBroadcast.c printerror.h
gcc ${CFLAGS} -c CondVarBroadcast.c
CondVarSignal.exe: CondVarSignal.o
gcc ${CFLAGS} -o CondVarSignal.exe CondVarSignal.o ${LIBRARIES}
CondVarSignal.o: CondVarSignal.c printerror.h
gcc ${CFLAGS} -c CondVarSignal.c
es1_banche.exe: es1_banche.o
gcc ${CFLAGS} -o es1_banche.exe es1_banche.o ${LIBRARIES}
es1_banche.o: es1_banche.c printerror.h
gcc ${CFLAGS} -c es1_banche.c
.PHONY: clean
clean:
rm -f mutex.o mutex.exe CondVarBroadcast.o CondVarBroadcast.exe CondVarSignal.o CondVarSignal.exe es1_banche.exe es1_banche.o
<file_sep>/Bash/seconda.sh
exec {FD}< $1;
OUT="";
if (( $? == 0 )); then
while read -u ${FD} A B C; do
OUT+=$B;
done;
fi;
echo $OUT;
<file_sep>/ConcurrentProgrammingExercices/Mutex/esBanche/banche.c
/* file: vacche.c */
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
/* la #define _POSIX_C_SOURCE 200112L e' dentro printerror.h */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* per random e srandom */
#endif
/* messo prima perche' contiene define _POSIX_C_SOURCE */
#include "printerror.h"
#include <unistd.h> /* exit() etc */
#include <stdlib.h> /* random srandom */
#include <stdio.h>
#include <string.h> /* per strerror_r and memset */
#include <sys/types.h>
#include <signal.h>
#include <sys/time.h> /*gettimeofday() struct timeval timeval{} for select()*/
#include <time.h> /* timespec{} for pselect() */
#include <limits.h> /* for OPEN_MAX */
#include <errno.h>
#include <time.h>
#include <assert.h>
#include <stdint.h> /* uint64_t intptr_t */
#include <inttypes.h> /* per PRIiPTR */
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include "DBGpthread.h"
#define NUMBANCHE 3
#define NUMDEP 5
#define NUMPRELIEVI 4
#define TEMPOATTESA 100000
#define SLEEPBANCADIITALIA 30
/* dati da proteggere */
int saldoBanca[NUMBANCHE];
int numOperazioniPerBanca[NUMBANCHE];
/* variabili per la sincronizzazione */
pthread_mutex_t mutex;
void *Depositi (void *arg)
{
char Plabel[128];
intptr_t indiceBanca;
indiceBanca=(intptr_t)arg;
sprintf(Plabel,"Depositi banca num");
/* da completare */
while ( 1 ) {
DBGpthread_mutex_lock(&mutex, Plabel);
printf("Thread DEPOSITI di banca %" PRIiPTR " prende mutex\n", indiceBanca);
saldoBanca[indiceBanca] += 10;
numOperazioniPerBanca[indiceBanca]++;
printf("saldoBanca[%" PRIiPTR "] = %d\n", indiceBanca, saldoBanca[indiceBanca]);
printf("numOperazioniBanca[%" PRIiPTR "] = %d\n", indiceBanca, numOperazioniPerBanca[indiceBanca]);
usleep(TEMPOATTESA);
printf("Thread DEPOSITI di banca %" PRIiPTR " rilascia mutex\n\n\n", indiceBanca);
DBGpthread_mutex_unlock(&mutex, Plabel);
}
pthread_exit(NULL);
}
void *Prelievi (void *arg)
{
char Plabel[128];
intptr_t indiceBanca;
indiceBanca=(intptr_t)arg;
sprintf(Plabel,"Prelievi banca");
/* da completare */
while ( 1 ) {
DBGpthread_mutex_lock(&mutex, Plabel);
printf("Thread PRELIEVI di banca %" PRIiPTR " prende mutex\n", indiceBanca);
saldoBanca[indiceBanca] -= 9;
numOperazioniPerBanca[indiceBanca]++;
printf("saldoBanca[%" PRIiPTR "] = %d\n", indiceBanca, saldoBanca[indiceBanca]);
printf("numOperazioniBanca[%" PRIiPTR "] = %d\n", indiceBanca, numOperazioniPerBanca[indiceBanca]);
usleep(TEMPOATTESA);
printf("Thread PRELIEVI di banca %" PRIiPTR " rilascia mutex\n\n\n", indiceBanca);
DBGpthread_mutex_unlock(&mutex, Plabel);
}
pthread_exit(NULL);
}
void *BancaDiItalia (void *arg)
{
char Plabel[128];
int i;
int totaleDenaroBance;
int totaleNumOperazioni;
sprintf(Plabel,"BANCA DI ITALIA");
/* da completare */
while ( 1 ) {
int totaleDenaroBance = 0;
int totaleNumOperazioni = 0;
DBGpthread_mutex_lock(&mutex, Plabel);
for(i=0;i<NUMBANCHE;i++){
totaleDenaroBance+=saldoBanca[i];
totaleNumOperazioni+=numOperazioniPerBanca[i];
}
printf("DENARO TOTALE: %d\nOPERAZ TOT: %d\n", totaleDenaroBance, totaleNumOperazioni);
usleep(TEMPOATTESA*10);
DBGpthread_mutex_unlock(&mutex, Plabel);
sleep(SLEEPBANCADIITALIA);
}
pthread_exit(NULL);
}
int main ( int argc, char* argv[] )
{
pthread_t th;
int rc;
uintptr_t i=0;
uintptr_t j=0;
rc = pthread_mutex_init(&mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
DBGpthread_mutex_init(&mutex, NULL, "main");
/* CREAZIONE PTHREAD */
for(j=0;j<NUMBANCHE;j++){
printf("Lancio DEPOSITI\n");
for(i=0;i<NUMDEP;i++) {
rc=pthread_create(&th,NULL,Depositi,(void*)j);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
printf("Lancio PRELIEVI\n");
for(i=0;i<NUMPRELIEVI;i++) {
rc=pthread_create(&th,NULL,Prelievi,(void*)j);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
}
i=0;
/*Creo thread unico BancaDiItalia*/
rc=pthread_create(&th,NULL,BancaDiItalia,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
pthread_exit(NULL);
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/gallinaUovo/printerror.h
/* PrintErrno.h */
#ifndef __PRINTERRNO_H__
#define __PRINTERRNO_H__
/* a causa dell'uso di strerror_r
dove incluso, compilare con -D_POSIX_C_SOURCE >= 200112L
*/
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#else
#if _POSIX_C_SOURCE < 200112L
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#endif
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <string.h> /* per strerror_r and memset */
#define myMSGLEN 128
#define PrintERROR_andExit( ERRORCODE, STRMSG ) \
do { \
char errmsg[myMSGLEN]; \
memset( errmsg, 0, (size_t)myMSGLEN ); \
strerror_r( ERRORCODE, errmsg, (size_t)myMSGLEN ); \
printf("in file %s line %i - %s: errorcode %d %s - Quit\n", __FILE__ , __LINE__ , STRMSG, ERRORCODE, errmsg ); \
exit(1); \
} while(0)
#define PrintErrnoAndExit( STRMSG ) \
do { int myerrno; \
char errmsg[myMSGLEN]; \
myerrno = errno; \
memset( errmsg, 0, (size_t)myMSGLEN ); \
strerror_r( myerrno, errmsg, (size_t)myMSGLEN ); \
printf("%s: errno %d %s - Quit\n", STRMSG, myerrno, errmsg ); \
exit(1); \
} while(0)
#endif /* __PRINTERRNO_H__ */
<file_sep>/ConcurrentProgrammingExercices/Mutex/SincroCircolare3/main.c
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int turno = 0;
int var_globale = 33;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *thread_function(void* arg){
intptr_t mioindice = ((intptr_t)arg);
while(1){
pthread_mutex_lock(&mutex);
while(turno != mioindice){
pthread_cond_wait(&cond,&mutex);
if(turno != mioindice){
pthread_cond_signal(&cond);
}
}
var_globale = var_globale + 3;
turno = (turno+1)%3;
printf("Turno di: %d\n", turno);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main(){
int i;
intptr_t t[] = {0,1,2};
pthread_t tid;
for(i=0;i<3;i++){
printf("INDICE: %" PRIiPTR "\n", t[i]);
pthread_create(&tid, NULL, thread_function, (void *)t[i]);
}
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
return(0);
}
<file_sep>/MakefileExercices/esBashToC/variabiliglobali.c
int var1=1;
int var2=2;
int var3=3;
int var4=4;
int var5=5;
int var6=6;
int var7=7;
int var8=8;
int var9=9;
int var10=10;
int var11=11;
int var12=12;
int var13=13;
int var14=14;
int var15=15;
int var16=16;
int var17=17;
int var18=18;
int var19=19;
int var20=20;
int var21=21;
int var22=22;
int var23=23;
int var24=24;
int var25=25;
int var26=26;
int var27=27;
int var28=28;
int var29=29;
int var30=30;
int var31=31;
int var32=32;
int var33=33;
int var34=34;
int var35=35;
int var36=36;
int var37=37;
int var38=38;
int var39=39;
int var40=40;
int var41=41;
int var42=42;
int var43=43;
int var44=44;
int var45=45;
int var46=46;
int var47=47;
int var48=48;
int var49=49;
int var50=50;
int var51=51;
int var52=52;
int var53=53;
int var54=54;
int var55=55;
int var56=56;
int var57=57;
int var58=58;
int var59=59;
int var60=60;
int var61=61;
int var62=62;
int var63=63;
int var64=64;
int var65=65;
int var66=66;
int var67=67;
int var68=68;
int var69=69;
int var70=70;
int var71=71;
int var72=72;
int var73=73;
int var74=74;
int var75=75;
int var76=76;
int var77=77;
int var78=78;
int var79=79;
int var80=80;
int var81=81;
int var82=82;
int var83=83;
int var84=84;
int var85=85;
int var86=86;
int var87=87;
int var88=88;
int var89=89;
int var90=90;
int var91=91;
int var92=92;
int var93=93;
int var94=94;
int var95=95;
int var96=96;
int var97=97;
int var98=98;
int var99=99;
int var100=100;
int conta(void){
int i=0;
i=var1
+var2
+var3
+var4
+var5
+var6
+var7
+var8
+var9
+var10
+var11
+var12
+var13
+var14
+var15
+var16
+var17
+var18
+var19
+var20
+var21
+var22
+var23
+var24
+var25
+var26
+var27
+var28
+var29
+var30
+var31
+var32
+var33
+var34
+var35
+var36
+var37
+var38
+var39
+var40
+var41
+var42
+var43
+var44
+var45
+var46
+var47
+var48
+var49
+var50
+var51
+var52
+var53
+var54
+var55
+var56
+var57
+var58
+var59
+var60
+var61
+var62
+var63
+var64
+var65
+var66
+var67
+var68
+var69
+var70
+var71
+var72
+var73
+var74
+var75
+var76
+var77
+var78
+var79
+var80
+var81
+var82
+var83
+var84
+var85
+var86
+var87
+var88
+var89
+var90
+var91
+var92
+var93
+var94
+var95
+var96
+var97
+var98
+var99
+var100
;
return i;}
<file_sep>/Bash/puntini.sh
for(( i=0; i<$1; i++ )); do
sleep 1;
echo -n ".$$";
done;
<file_sep>/Esami/BASE_es153/Sol/2020_07_17__es153_piattello_ONLINE/piattello.c
/* file: piattello.c */
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
/* la #define _POSIX_C_SOURCE 200112L e' dentro printerror.h */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* per random e srandom */
#endif
/* messo prima perche' contiene define _POSIX_C_SOURCE */
#include "printerror.h"
#include <unistd.h> /* exit() etc */
#include <stdlib.h> /* random srandom */
#include <stdio.h>
#include <string.h> /* per strerror_r and memset */
#include <sys/types.h>
#include <signal.h>
#include <sys/time.h> /*gettimeofday() struct timeval timeval{} for select()*/
#include <time.h> /* timespec{} for pselect() */
#include <limits.h> /* for OPEN_MAX */
#include <errno.h>
#include <assert.h>
#include <stdint.h> /* uint64_t intptr_t */
#include <inttypes.h> /* per PRIiPTR */
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include "DBGpthread.h"
#define NUMTIRATORI 10
#define DELAYTRADUEPIATTELLI8sec 8
/* dati da proteggere */
int PiattelloInVolo=0; /* all'inizio nessun piattello e' in volo */
int PiattelloColpito=0; /* non richiesto, solo per contare quanti hanno colpito il piattello */
/* variabili per la sincronizzazione */
pthread_mutex_t mutex;
pthread_cond_t condSvegliaTiratori;
void attendi( int min, int max) {
int secrandom=0;
if( min > max ) return;
else if ( min == max )
secrandom = min;
else
secrandom = min + ( random()%(max-min+1) );
do {
/* printf("attendi %i\n", secrandom);fflush(stdout); */
secrandom=sleep(secrandom);
if( secrandom>0 )
{ printf("sleep interrupted - continue\n"); fflush(stdout); }
} while( secrandom>0 );
return;
}
void *Tiratore (void *arg)
{
char Plabel[128];
intptr_t indice;
indice=(intptr_t)arg;
sprintf(Plabel,"Tiratore%" PRIiPTR "",indice);
/* da completare */
/* notare che faccio la lock fuori dal loop */
DBGpthread_mutex_lock(&mutex,Plabel);
while ( 1 ) {
/* il tiratore attende l'inizio del volo del piattello */
printf("tiratore %s attende piattello \n", Plabel);
fflush(stdout);
DBGpthread_cond_wait(&condSvegliaTiratori,&mutex,Plabel);
/* il tiratore si prepara a sparare ... */
printf("tiratore %s mira e .... \n", Plabel);
fflush(stdout);
DBGpthread_mutex_unlock(&mutex,Plabel);
/* il tiratore si prepara a sparare impiegando da 2 a 4 secondi */
attendi( 2, 4 );
DBGpthread_mutex_lock(&mutex,Plabel);
if( PiattelloInVolo==1 ) {
printf("tiratore %s spara e colpisce. Aaaaaaleeee\n", Plabel);
PiattelloColpito++; /* non richiesto, conta quanti hanno colpito il piattello */
}
else
printf("tiratore %s arrivato tardi, vaffa\n", Plabel);
fflush(stdout);
/* NOTARE CHE qui NON FACCIO LA unlock, COSI' SONO SICURO CHE
il tiratore si mettera' in wait senza che un nuovo piattelloi
abbia potuto cambiare la propria condizione mettendosi in volo.
*/
}
pthread_exit(NULL);
}
void *Piattello (void *arg)
{
char Plabel[128];
intptr_t indice;
indice=(intptr_t)arg;
sprintf(Plabel,"Piattello%" PRIiPTR "",indice);
DBGpthread_mutex_lock(&mutex,Plabel);
/* questo while e' una precauzione, nel caso un piattello ritardi enormemente prima di cadere */
while( PiattelloInVolo==1 )
DBGpthread_cond_wait(&condSvegliaTiratori,&mutex,Plabel);
printf("piattelo %s inizia volo\n", Plabel);
fflush(stdout);
PiattelloInVolo=1;
PiattelloColpito=0; /* non richiesto, serve per contare quanti hanno colpito il piattello */
DBGpthread_cond_broadcast(&condSvegliaTiratori,Plabel);
DBGpthread_mutex_unlock(&mutex,Plabel);
/* il piattello vola per tre secondi */
attendi( 3, 3 );
DBGpthread_mutex_lock(&mutex,Plabel);
PiattelloInVolo=0;
if( PiattelloColpito==0 ) {
printf("piattelo %s COLPITO cade a terra\n", Plabel);
} else {
printf("piattelo %s NON COLPITO atterra\n", Plabel);
}
fflush(stdout);
PiattelloColpito=0;
DBGpthread_mutex_unlock(&mutex,Plabel);
pthread_exit(NULL);
}
int main ( int argc, char* argv[] )
{
pthread_t th;
int rc;
uintptr_t i=0;
int seme;
pthread_attr_t attr;
/* variabile per creare thread detached */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
seme=time(NULL);
srandom(seme);
/* INIZIALIZZATE LE VOSTRE VARIABILI CONDIVISE / fate voi */
rc = pthread_cond_init(&condSvegliaTiratori, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_mutex_init(&mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
PiattelloInVolo=0; /* all'inizio non c'e' nessun piattello in volo */
PiattelloColpito=0;
/* CREAZIONE PTHREAD */
for(i=0;i<NUMTIRATORI;i++) {
rc=pthread_create(&th,NULL,Tiratore,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
i=0;
while(1) {
/* un nuovo piattello ogni 6 secondi */
attendi( DELAYTRADUEPIATTELLI8sec, DELAYTRADUEPIATTELLI8sec );
i++;
rc=pthread_create(&th,&attr,Piattello,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
pthread_exit(NULL);
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/VarSignalAndBroadcast/es1_banche.c
/* mutex.c */
/* simboli già messi nella riga di comando del compilatore
#define _THREAD_SAFE
#define _REENTRANT
#define _POSIX_C_SOURCE 200112L
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
#include "printerror.h"
/* this variable can be initialized statically with default attributes, using
pthread_mutex_t mutexdata = PTHREAD_MUTEX_INITIALIZER;
same as pthread_mutex_init(...,NULL)
but with NO ERROR CHECKING
*/
#define NUMSPADE 10
#define NUMFACHIRI 2
pthread_mutex_t mutex[NUMSPADE];
pthread_cond_t cond;
void *trafiggi0(void *arg)
{
int i, rc;
while(1){
for(i = 0; i < NUMSPADE; i++){
pthread_cond_wait(&cond, &(mutex[i]));
rc = pthread_mutex_lock(&(mutex[i]));
if(rc!=0) {perror("lock failed\n");exit(1);}
}
for(i = 0; i < NUMSPADE; i++){
printf("AAAAA FACHIRO %d TRAFITTO CON LA SPADA %d\n",*((int *)arg), i);
}
pthread_cond_signal(&cond);
for(i = 0; i < NUMSPADE; i++){
rc = pthread_mutex_unlock(&(mutex[i]));
if(rc!=0) {perror("unlock failed\n");exit(1);}
}
}
pthread_exit(NULL);
}
void *trafiggi1(void *arg)
{
int i, rc;
while(1){
for(i = 0; i < NUMSPADE; i++){
pthread_cond_wait(&cond, &(mutex[i]));
rc = pthread_mutex_lock(&(mutex[i]));
if(rc!=0) {perror("lock failed\n");exit(1);}
}
for(i = NUMSPADE-1; i == 0; i++){
printf("AAAAA FACHIRO %d TRAFITTO CON LA SPADA %d\n",*((int *)arg), i);
}
pthread_cond_signal(&cond);
for(i = 0; i < NUMSPADE; i++){
rc = pthread_mutex_unlock(&(mutex[i]));
if(rc!=0) {perror("unlock failed\n");exit(1);}
}
}
pthread_exit(NULL);
}
int main()
{
pthread_t th;
int * d;
int i, rc;
for(i=0;i<NUMSPADE;i++) {
rc = pthread_mutex_init(&mutex[i], NULL);
if (rc){perror("pthread_mutex_init failed");exit(1);}
}
for(i = 0; i < NUMFACHIRI; i++) {
d = (int *)malloc(sizeof(int));
*d = i;
printf("FACHIRO %d LANCIATO\n\n", *d);
if(*d==0){
rc=pthread_create( &th, NULL,trafiggi0,(void*)d);
printf("LANCIO 1 \n");
} else {
rc=pthread_create( &th, NULL,trafiggi1,(void*)d);
printf("LANCIO 2 \n");
}
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
pthread_exit(NULL);
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/gallinaUovo/Makefile
# Makefile per igallinauovavolpe.c
# a causa della presenza di strerror_r in printerror.h
# occorre compilare col flag -D_POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_REENTRANT -D_POSIX_C_SOURCE=200112L -D_DEFAULT_SOURCE
LIBRARIES=-lpthread
all: gallinauovavolpe.exe
gallinauovavolpe.exe: gallinauovavolpe.o
gcc ${CFLAGS} -o gallinauovavolpe.exe gallinauovavolpe.o ${LIBRARIES}
gallinauovavolpe.o: gallinauovavolpe.c printerror.h
gcc ${CFLAGS} -c gallinauovavolpe.c
.PHONY: clean
clean:
rm -f gallinauovavolpe.o gallinauovavolpe.exe
<file_sep>/Bash/lanciaeprendi.sh
for((i=0; $i<10; i++)); do
./puntini.sh 5 1>&2 &
echo -n "$! ";
done;
<file_sep>/Bash/leggilo.sh
head -n 5 /usr/include/stdio.h | tail -n 3
<file_sep>/Bash/README.md
# Some bash exercices
## it's a junk repo
<file_sep>/Esami/EsameSettembre2020/figlio.sh
sleep 5; echo "FIGLIO DICE ($PPID --- $1)" ; kill -s SIGUSR2 $1
<file_sep>/Esami/2020_09_10__es155_vacche_ONLINE/vacche.c
/* file: vacche.c */
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
/* la #define _POSIX_C_SOURCE 200112L e' dentro printerror.h */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* per random e srandom */
#endif
/* messo prima perche' contiene define _POSIX_C_SOURCE */
#include "printerror.h"
#include <unistd.h> /* exit() etc */
#include <stdlib.h> /* random srandom */
#include <stdio.h>
#include <string.h> /* per strerror_r and memset */
#include <sys/types.h>
#include <signal.h>
#include <sys/time.h> /*gettimeofday() struct timeval timeval{} for select()*/
#include <time.h> /* timespec{} for pselect() */
#include <limits.h> /* for OPEN_MAX */
#include <errno.h>
#include <assert.h>
#include <stdint.h> /* uint64_t intptr_t */
#include <inttypes.h> /* per PRIiPTR */
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include "DBGpthread.h"
#define NUMMANGIATOIE 3
#define NUMVACCHE 6
#define SECGIRO 10
#define MINSECMANGIARE 5
#define MAXSECMANGIARE 7
#define SECINTERVALLOTRAINCENDI 15
#define SECDURATAINCENDIO 5
/* dati da proteggere */
int mangiatoie[NUMMANGIATOIE]; /* 0 libera, 1 occupata */
int pagliabrucia=0;
/* variabili per la sincronizzazione */
pthread_mutex_t mutex;
pthread_cond_t condSvegliaVacche;
void attendi( int min, int max) {
int secrandom=0;
if( min > max ) return;
else if ( min == max )
secrandom = min;
else
secrandom = min + ( random()%(max-min+1) );
do {
/* printf("attendi %i\n", secrandom);fflush(stdout); */
secrandom=sleep(secrandom);
if( secrandom>0 )
{ printf("sleep interrupted - continue\n"); fflush(stdout); }
} while( secrandom>0 );
return;
}
/* eseguire in mutua esclusione. Restituisce indice mangiatoia libera oppure -1 */
int mangiatoialibera(void) {
int i;
for(i=0;i<NUMMANGIATOIE;i++)
if ( mangiatoie[i]==0 )
return( i );
return( -1 );
}
void *Vacca (void *arg)
{
char Plabel[128];
intptr_t indice;
indice=(intptr_t)arg;
sprintf(Plabel,"Vacca%" PRIiPTR "",indice);
/* da completare */
while ( 1 ) {
int indicemangiatoia, i, secmangiare, esci=0;
/* la vacca prova a mangiare */
DBGpthread_mutex_lock(&mutex,Plabel);
while ( (indicemangiatoia=mangiatoialibera()) < 0 ) {
printf("vacca %s attende posto libero \n", Plabel);
fflush(stdout);
DBGpthread_cond_wait(&condSvegliaVacche,&mutex,Plabel);
}
mangiatoie[indicemangiatoia]=1;
printf("vacca %s mangia in mangiatoia %i\n", Plabel, indicemangiatoia);
fflush(stdout);
DBGpthread_mutex_unlock(&mutex,Plabel);
secmangiare=MINSECMANGIARE + ( random()%(MAXSECMANGIARE-MINSECMANGIARE+1) );
for(i=0;i<secmangiare && esci==0;i++) {
attendi( 1, 1 );
/* ogni secondo la vacca guarda se la paglia brucia */
DBGpthread_mutex_lock(&mutex,Plabel);
if(pagliabrucia==1) {
esci=1;
printf("vacca %s azzz, la paglia brucia .... vvvviaa\n", Plabel);
fflush(stdout);
}
DBGpthread_mutex_unlock(&mutex,Plabel);
}
DBGpthread_mutex_lock(&mutex,Plabel);
/* libero mangiatoia */
mangiatoie[indicemangiatoia]=0;
printf("vacca %s lascia mangiatoia %i\n", Plabel, indicemangiatoia);
fflush(stdout);
/* sveglio una vacca in attesa di mangiare */
DBGpthread_cond_signal(&condSvegliaVacche,Plabel);
DBGpthread_mutex_unlock(&mutex,Plabel);
/* la vacca fa un giro di 10 secondi */
attendi( SECGIRO, SECGIRO );
printf("vacca %s finisce giro\n", Plabel);
fflush(stdout);
}
pthread_exit(NULL);
}
void Bovaro (void)
{
char Plabel[128];
sprintf(Plabel,"Bovaro");
while( 1 ) {
/* attesa 30 sec tra incendi */
attendi( SECINTERVALLOTRAINCENDI, SECINTERVALLOTRAINCENDI );
/* bovaro incendia paglia */
DBGpthread_mutex_lock(&mutex,Plabel);
pagliabrucia=1;
printf("bovaro incendia paglia\n");
fflush(stdout);
DBGpthread_mutex_unlock(&mutex,Plabel);
/* durata incendio 3 sec */
attendi( SECDURATAINCENDIO, SECDURATAINCENDIO );
/* bovaro spegne paglia */
DBGpthread_mutex_lock(&mutex,Plabel);
pagliabrucia=0;
printf("paglia spenta\n");
fflush(stdout);
DBGpthread_mutex_unlock(&mutex,Plabel);
}
pthread_exit(NULL);
}
int main ( int argc, char* argv[] )
{
pthread_t th;
int rc;
uintptr_t i=0;
int seme;
seme=time(NULL);
srandom(seme);
/* INIZIALIZZATE LE VOSTRE VARIABILI CONDIVISE / fate voi */
rc = pthread_mutex_init(&mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
rc = pthread_cond_init(&condSvegliaVacche, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
for(i=0;i<NUMMANGIATOIE;i++) mangiatoie[i]=0; /* mangiatoia libera */
pagliabrucia=0; /* la paglia non brucia */
/* CREAZIONE PTHREAD */
for(i=0;i<NUMVACCHE;i++) {
rc=pthread_create(&th,NULL,Vacca,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
Bovaro();
return(0);
}
<file_sep>/Bash/star.sh
exec {FD}< asterischi.txt
if(( $? == 0 )); then
while read -u ${FD} A B C D; do
echo "$D $C";
done;
exec {FD}>&-
fi;
<file_sep>/Bash/separa.sh
IFS=":";
OUT=`echo $PATH`
echo $OUT;
IFS=" ";
for i in $OUT; do
echo "$i ${#i}";
done;
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esStrutture/main.c
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#define _POSIX_C_SOURCE 200112L
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#define NUM_THREADS 4
typedef struct{
int N;
char s[100];
int index;
}S;
void *func(void *arg){
S *tSt1, *tSt2;
int t, res;
tSt1 = (S*)arg;
printf("Inizio THREAD %d di INDICE %d \n", tSt1->N, tSt1->index);
fflush(stdout);
sleep(1);
if(tSt1->N > 1){
pthread_t vTh[NUM_THREADS];
for(t = 0; t < tSt1->N; t++){
tSt2=(S*)malloc(sizeof(S));
if(tSt2==NULL){
perror("malloc failed");
exit(1);
}
tSt2->N=tSt1->N-1;
tSt2->index=t;
strcpy(tSt2->s,"ciao");
res = pthread_create(&vTh[t], NULL, func, (void*)tSt2);
if (res) {
printf("ERROR; return code from pthread_create() is %d\n",res);
exit(1);
}
}
for(t=0; t < tSt1->N; t++){
res=pthread_join(vTh[t], (void**)&tSt2);
if (res) {
printf("ERROR; return code from pthread_join() is %d\n",res);
exit(1);
}
printf("received \"%s\"\n", tSt2->s);
fflush(stdout);
free(tSt2);
}
}
sprintf(tSt1->s, "%d %d",tSt1->N,tSt1->index);
pthread_exit((void*)tSt1);
}
int main(){
S *st;
pthread_t vTh[NUM_THREADS];
int res, t;
for(t=0; t<NUM_THREADS; t++){
st = (S*)malloc(sizeof(S));
if(st==NULL){
perror("malloc failed");
exit(1);
}
st->N = NUM_THREADS - 1;
st->index = t;
strcpy(st->s,"Ciao");
printf("Creating thread %d\n", t);
fflush(stdout);
res = pthread_create(&vTh[t], NULL, func, (void*)st);
if (res) {
printf("ERROR; return code from pthread_create() is %d\n",res);
exit(1);
}
}
for(t=0; t< NUM_THREADS; t++){
res = pthread_join(vTh[t], (void**)&st );
if (res) {
printf("ERROR; return code from pthread_join() is %d\n",res);
exit(1);
}
printf("main received \"%s':\n", st->s);
fflush(stdout);
free(st);
}
printf("Finished\n");
pthread_exit(NULL);
return(0);
}
<file_sep>/MakefileExercices/EsempioConPiùModuli/interroga.h
#ifndef __INTERROGA_H__
#define __INTERROGA_H__
/* elenco delle funzioni implementate nel modulo interroga.c
* che possono essere utilizzate fuori da quel modulo
*/
extern unsigned int interroga_oracolo(void);
#endif
<file_sep>/MakefileExercices/EsempioConPiùModuli/Makefile
CFLAGS=-ansi -Wall -Wpedantic
all: oracolo.exe
oracolo.exe: oracolo.o interroga.o
gcc ${CFLAGS} -o oracolo.exe oracolo.o interroga.o
oracolo.o: oracolo.c interroga.h
gcc -c ${CFLAGS} oracolo.c interroga.h
interroga.o: interroga.c
gcc -c ${CFLAGS} interroga.c -D_BSD_SOURCE
.PHONY: clean
clean:
-rm *.o *.exe
<file_sep>/ConcurrentProgrammingExercices/Mutex/SincroCircolare3/Makefile
CLFAGS=-ansi -Wall -Wpedantic -D_THREAD_SAFE -D_REENTRANT -D_POSIX_C_SOURCE=200112L
LIBR=-lpthread
all: main.exe
main.exe: main.o
gcc ${CFLAGS} -o main.exe main.o ${LIBR}
main.o: main.c
gcc -c ${CFLAGS} main.c
.PHONY: clean
clean:
rm *.o *.exe
<file_sep>/ConcurrentProgrammingExercices/Mutex/PassaggioTestimoneSicuro/PassaggioSicuroDiTestimone.c
/* PassaggioDiTestimone.c */
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include "printerror.h"
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include "DBGpthread.h"
#define NUMCORRIDORI 4
pthread_t tId;
pthread_mutex_t mutex;
pthread_cond_t cond_attesa_arrivo_precedente;
pthread_cond_t cond_passaggio_testimone;
int turno=0;
void *Corridore(void *arg){
char Clabel[128];
char Clabelsignal[128];
int index=*((int*)arg);
int mioturno;
free(arg);
sprintf( Clabel, "C%d", index);
sprintf( Clabelsignal, "C%d->C", index);
DBGpthread_mutex_lock(&mutex, Clabel);
turno++;
mioturno=turno;
if(mioturno!=1) {
/* attendo che il corridore precedente mi appoggi il testimone */
DBGpthread_cond_wait(&cond_attesa_arrivo_precedente,&mutex, Clabel);
/* mi hanno appoggiato il testimone in mano, lo afferro,
poi urlo per avvisare che possono mollarlo
*/
DBGpthread_cond_signal(&cond_passaggio_testimone, Clabelsignal);
/* attendo l'urlo di conferma di avere mollato il testimone */
DBGpthread_cond_wait(&cond_passaggio_testimone,&mutex, Clabel);
}
printf("C%d parte\n",index);
DBGpthread_mutex_unlock(&mutex, Clabel);
sleep(1);
printf("C%d ha completato il giro\n",index);
DBGpthread_mutex_lock(&mutex, Clabel);
if(mioturno<NUMCORRIDORI) {
/* appoggio il testimone in mano al successivo ma non lo mollo */
DBGpthread_cond_signal(&cond_attesa_arrivo_precedente, Clabelsignal);
/* attendo l'urlo del successivo prima di mollare il testimone */
DBGpthread_cond_wait(&cond_passaggio_testimone,&mutex, Clabel);
/* il successivo mi ha urlato di mollare il testimone,
mollo il testimone e
urlo al successivo che ho mollato e puo' partire
*/
DBGpthread_cond_signal(&cond_passaggio_testimone, Clabelsignal);
printf("C%d ha lasciato il testimone e termina\n",index);
}
else {
printf("L'ultimo C%d ha completato il giro\n",index);
}
DBGpthread_mutex_unlock(&mutex, Clabel);
pthread_exit(NULL);
}
int main(){
int rc,i, *p;
rc = pthread_cond_init(&cond_attesa_arrivo_precedente, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_cond_init(&cond_passaggio_testimone, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed");
rc = pthread_mutex_init(&mutex, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed");
DBGpthread_mutex_lock(&mutex, "main");
/*creo i thread */
for(i=0;i<NUMCORRIDORI;i++) {
/* alloco la struttura in cui passare i parametri */
p=malloc(sizeof(int));
if(p==NULL) {
perror("malloc failed: ");
exit (1);
}
*p=i;
rc=pthread_create( &tId, NULL, Corridore, (void*)p );
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
/* per semplificare l'inizio, il main aspetta 3 secondi
che tutti i thread siano partiti e arrivati alla lock iniziale,
poi rilascia la mutua esclusione
*/
sleep(3);
DBGpthread_mutex_unlock(&mutex, "main");
pthread_exit(NULL);
return 0;
}
<file_sep>/Esami/EsameSettembre2020/padre.sh
./figlio.sh $$ &
ricevutoSIGUSR2(){
exit 1;
}
trap ricevutoSIGUSR2 SIGUSR2
while true; do
sleep 1
echo "PADRE DICE: $$"
done
<file_sep>/Bash/unasiunano.sh
n=0
while read RIGA;
do if (( n%2==0 ));then
echo $RIGA;
fi;
((n++));
done;
<file_sep>/MakefileExercices/esBashToC/variabiliglobali.h
extern int var1;
extern int var2;
extern int var3;
extern int var4;
extern int var5;
extern int var6;
extern int var7;
extern int var8;
extern int var9;
extern int var10;
extern int var11;
extern int var12;
extern int var13;
extern int var14;
extern int var15;
extern int var16;
extern int var17;
extern int var18;
extern int var19;
extern int var20;
extern int var21;
extern int var22;
extern int var23;
extern int var24;
extern int var25;
extern int var26;
extern int var27;
extern int var28;
extern int var29;
extern int var30;
extern int var31;
extern int var32;
extern int var33;
extern int var34;
extern int var35;
extern int var36;
extern int var37;
extern int var38;
extern int var39;
extern int var40;
extern int var41;
extern int var42;
extern int var43;
extern int var44;
extern int var45;
extern int var46;
extern int var47;
extern int var48;
extern int var49;
extern int var50;
extern int var51;
extern int var52;
extern int var53;
extern int var54;
extern int var55;
extern int var56;
extern int var57;
extern int var58;
extern int var59;
extern int var60;
extern int var61;
extern int var62;
extern int var63;
extern int var64;
extern int var65;
extern int var66;
extern int var67;
extern int var68;
extern int var69;
extern int var70;
extern int var71;
extern int var72;
extern int var73;
extern int var74;
extern int var75;
extern int var76;
extern int var77;
extern int var78;
extern int var79;
extern int var80;
extern int var81;
extern int var82;
extern int var83;
extern int var84;
extern int var85;
extern int var86;
extern int var87;
extern int var88;
extern int var89;
extern int var90;
extern int var91;
extern int var92;
extern int var93;
extern int var94;
extern int var95;
extern int var96;
extern int var97;
extern int var98;
extern int var99;
extern int var100;
extern int conta(void);
<file_sep>/MakefileExercices/EsempioConPiùModuli/oracolo.c
#include <stdlib.h>
#include <unistd.h> /* per sleep */
#include <stdio.h>
#include "interroga.h"
void visualizza_domanda1(void); /* prototipo di funzione implementata in questo stesso modulo */
void visualizza_risposta1(unsigned int valore); /* prototipo di funzione implementata in questo stesso modulo */
void visualizza_domanda2(void); /* prototipo di funzione implementata in questo stesso modulo */
void visualizza_risposta2(unsigned int valore); /* prototipo di funzione implementata in questo stesso modulo */
int main(void) /* la funzione principale del programma */
{
unsigned int risposta; /* una variabile locale della funzione main */
visualizza_domanda1(); /* la chiamata (invocazione) della funzione visualizza_domanda1 */
risposta=interroga_oracolo(); /* la chiamata (invocazione) della funzione interroga_oracolo */
visualizza_risposta1(risposta); /* la chiamata (invocazione) della funzione interpreta_visualizza_risposta1 */
sleep(1);
printf("\nmumble mumble ...\n\n");
sleep(2);
visualizza_domanda2(); /* la chiamata (invocazione) della funzione visualizza_domanda2 */
risposta=interroga_oracolo(); /* la chiamata (invocazione) della funzione interroga_oracolo */
visualizza_risposta2(risposta); /* la chiamata (invocazione) della funzione interpreta_visualizza_risposta2 */
return(1);
}
void visualizza_domanda1(void) /* implementazione della funzione visualizza_domanda */
{
printf( "Ma quanto si e' rincoglionito il Ghini ??? \n\n" );
}
void visualizza_risposta1(unsigned int risposta) /* implementazione della funzione visualizza_risposta */
{
int i;
for( i=0; i<3; i++) {
sleep(1);
printf( "." );
fflush(stdout);
}
printf( "\n" );
if(risposta<10)
printf( "Abbastanza, ma prova a nasconderlo \n\n" );
else if(risposta<100)
printf( "Poveretto, ormai parla solo in C \n" );
else if(risposta<200)
printf( "Completamente andato \n" );
else
printf( "Non e' peggiorato, Non ha MAI capito un ca*** !! \n\n" );
}
void visualizza_domanda2(void) /* implementazione della funzione visualizza_domanda */
{
printf( "Come morira' il Ghini ??? \n\n " );
}
void visualizza_risposta2(unsigned int risposta) /* implementazione della funzione visualizza_risposta */
{
int i;
for( i=0; i<3; i++) {
sleep(1);
printf( "." );
fflush(stdout);
}
printf( "\n" );
if(risposta<10)
printf( "Stroncato da un infarto dopo una devastante notte di sesso :-)\n\n" );
else if(risposta<80)
printf( "Schiantandosi in discesa contro un camion di letame\n" );
else if(risposta<140)
printf( "Sbranato da un pastore maremmano sullo strappo di Ciola Araldi\n" );
else
printf( "Impiccato dai suoi studenti!! \n\n" );
}
<file_sep>/Bash/random.sh
N=0;
while (( $RANDOM%10 != 2 )); do
((N++));
done;
echo $N
<file_sep>/ConcurrentProgrammingExercices/Mutex/PassaggioTestimoneSicuro/Makefile
CFLAGSCONSTRERROR=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE -D_POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE
LIBRARIES=-lpthread
all: PassaggioSicuroDiTestimone.exe
PassaggioSicuroDiTestimone.exe: PassaggioSicuroDiTestimone.o DBGpthread.o
gcc ${CFLAGS} -o PassaggioSicuroDiTestimone.exe PassaggioSicuroDiTestimone.o DBGpthread.o ${LIBRARIES}
PassaggioSicuroDiTestimone.o: PassaggioSicuroDiTestimone.c DBGpthread.h printerror.h
gcc -c ${CFLAGS} PassaggioSicuroDiTestimone.c
DBGpthread.o: DBGpthread.c printerror.h
gcc ${CFLAGSCONSTRERROR} -c DBGpthread.c
.PHONY: clean
clean:
-rm -f PassaggioSicuroDiTestimone.o DBGpthread.o PassaggioSicuroDiTestimone.exe
<file_sep>/ConcurrentProgrammingExercices/Mutex/VarSignalAndBroadcast/CondVarSignal.c
/* file: CondVarSignal.c
Routine che fornisce un synchronization point.
E' chiamata da ognuno dei SYNC_MAX pthread, che si fermano
finche' tutti gli altri sono arrivati allo stesso punto di esecuzione.
*/
/* simboli già messi nella riga di comando del compilatore
#define _THREAD_SAFE
#define _REENTRANT
#define _POSIX_C_SOURCE 200112L
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
#include "printerror.h"
#define SYNC_MAX 5
pthread_mutex_t sync_lock;
pthread_cond_t sync_cond;
int sync_count = 0;
void SyncPoint(void)
{
int rc;
/* blocca l'accesso al counter */
rc = pthread_mutex_lock(&sync_lock);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_lock failed"); /* no EINTR */
/* incrementa il counter di quelli arrivati*/
sync_count++;
/* controlla se deve aspettare o no */
if (sync_count < SYNC_MAX) {
/* aspetta */
rc = pthread_cond_wait(&sync_cond, &sync_lock);
if( rc ) PrintERROR_andExit(rc, "pthread_cond_wait failed"); /* no EINTR */
rc = pthread_cond_signal (&sync_cond); /* senza questa signal ne terminano solo 2 */
if( rc ) PrintERROR_andExit(rc,"pthread_cond_signal failed"); /* no EINTR */
}
else {
/* tutti hanno raggiunto il punto di barriera */
rc = pthread_cond_signal (&sync_cond);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_signal failed"); /* no EINTR */
}
/* sblocca il mutex */
rc = pthread_mutex_unlock (&sync_lock); /* senza unlock ne termina solo 1 */
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_unlock failed"); /* no EINTR */
return;
}
void *Thread (void *arg)
{
pthread_t th;
th=pthread_self(); /* thread identifier */
printf ("%lu\n", th);
SyncPoint();
printf("Sono %lu e sono uscito \n", th);
pthread_exit(NULL);
}
int main ()
{
pthread_t th[SYNC_MAX];
int rc; intptr_t i;
void *ptr;
rc = pthread_cond_init(&sync_cond, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_init failed"); /* no EINTR */
rc = pthread_mutex_init(&sync_lock, NULL);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_init failed"); /* no EINTR */
for(i=0;i<SYNC_MAX;i++) {
rc = pthread_create(&(th[i]), NULL, Thread, NULL);
if (rc) PrintERROR_andExit(rc,"pthread_create failed"); /* no EINTR */
}
for(i=0;i<SYNC_MAX;i++) {
rc = pthread_join(th[i], &ptr );
if (rc) PrintERROR_andExit(rc,"pthread_join failed"); /* no EINTR */
}
rc = pthread_mutex_destroy(&sync_lock);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_destroy failed"); /*no EINTR*/
rc = pthread_cond_destroy(&sync_cond);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_destroy failed"); /*no EINTR*/
pthread_exit (NULL);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/esBanche/Makefile
CFLAGSCONSTRERROR=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE -D_POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE
LIBR=-lpthread
all: banche.exe
banche.exe: banche.o DBGpthread.o
gcc ${CFLAGS} -o banche.exe banche.o DBGpthread.o ${LIBR}
banche.o: banche.c DBGpthread.h
gcc ${CFLAGS} -c banche.c
DBGpthread.o: DBGpthread.c printerror.h
gcc ${CFLAGSCONSTRERROR} -c DBGpthread.c
.PHONY: clean
clean:
rm *.o banche.exe
<file_sep>/MakefileExercices/esBashToC/main.c
#include <stdio.h>
#include <stdlib.h>
#include "define.h"
#include "variabiliglobali.h"
int main(void){
printf("%d", conta());
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/VarSignalAndBroadcast/mutex.c
/* mutex.c */
/* simboli già messi nella riga di comando del compilatore
#define _THREAD_SAFE
#define _REENTRANT
#define _POSIX_C_SOURCE 200112L
*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
#include "printerror.h"
#define NUMTHRDS 10
pthread_t callThd[NUMTHRDS];
pthread_mutex_t mutexdata;
/* this variable can be initialized statically with default attributes, using
pthread_mutex_t mutexdata = PTHREAD_MUTEX_INITIALIZER;
same as pthread_mutex_init(...,NULL)
but with NO ERROR CHECKING
*/
int data;
void *decrementa(void *arg)
{
int rc;
rc = pthread_mutex_lock (&mutexdata); /* provare a commentare */
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_lock failed"); /* no EINTR */
if(data>0) {
sleep(1); /* provare a decommentare */
data--;
}
rc = pthread_mutex_unlock (&mutexdata); /* provare a commentare */
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_unlock failed"); /* no EINTR */
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
intptr_t i;
int rc; void *ptr;
data=NUMTHRDS/2;
rc = pthread_mutex_init (&mutexdata, NULL);
if( rc != 0 ) PrintERROR_andExit(errno,"pthread_mutex_init failed"); /* no EINTR */
for(i=0;i < NUMTHRDS;i++) {
/* per default i thread consentono il join, */
/* NB: COME FARE CAST PER ASSEGNARE L'INTERO i AL PUNTATORE void*.
- il cast (void*)i da' warning perche' l'intero i ha size diversa
- il doppio cast (void*)((int64_t)i) funziona solo su sist a 64bit
dove la dimensione del puntatore e' di 64 bit,
ma su sist a 32 bit da' warning perche' dice che nel passaggio
da int64_t a void* ho due dimensioni diverse e perdo dei bytes.
- il doppio cast (void*)((int32_t)i) funziona solo su sist a 32bit
dove la dimensione del puntatore e' di 32 bit,
ma su sist a 64 bit da' warning perche' dice che nel passaggio
da int32_t a void* ho due dimensioni diverse.
- il modo corretto e' fare un cast utilizzando un particolare
tipo di dato intero, definito in sydint.h e denominato
intptr_t (oppure uintptr_t) che e' un intero con (o senza) segno
che ha le stesse dimensioni di un puntatore.
Ovviamente la dimensione di questo tipo di dato dipende dal fatto
che il sistema e' a 32 o 64 bit.
*/
rc = pthread_create ( &callThd[i], NULL, decrementa, (void *)i );
if( rc != 0 ) PrintERROR_andExit(rc,"pthread_create failed"); /* no EINTR */
}
for(i=0;i < NUMTHRDS;i++) { /* aspetto la fine dei thread */
rc = pthread_join ( callThd[i], &ptr);
if( rc != 0 ) PrintERROR_andExit(rc,"pthread_join failed"); /* no EINTR */
}
printf ("data = %d \n", data);
rc = pthread_mutex_destroy (&mutexdata);
if( rc != 0 ) PrintERROR_andExit(rc,"pthread_mutex_destroy failed"); /* no EINTR */
return(0);
}
<file_sep>/Esami/BASE_es154/voti.sh
#!/bin/bash
while read matricola voto altro; do
ris=`cat esame2.txt | grep $matricola`
if [[ -z $ris ]] ; then
echo "$matricola $voto"
else
echo $ris
fi
done < esame1.txt
<file_sep>/Esami/2020_07_17__es154_voti_ONLINE/voti.sh
# i voti della seconda prova li devo mettere tutti nello standard output
cat esame2.txt ;
# poi devo mettere nello standard output i voti della prima prova
# ottenuti dagli studenti che non hanno un voto nella seconda prova
while read matr voto1 ; do
OUT=`grep $matr esame2.txt` ;
if [[ $OUT == "" ]] ;
then echo $matr $voto1 ;
fi ;
done < esame1.txt
<file_sep>/Bash/lanciacerca.sh
./cerca.sh "/usr/include/" "std.h"
<file_sep>/MakefileExercices/EsempioConPiùModuli/interroga.c
#include <unistd.h>
#include <stdlib.h> /* serve per la funzione rand */
#include <stdio.h>
#include <time.h> /* serve per la funzione time */
/* compilare con -D_BSD_SOURCE per random */
static int inizializzato=0;
static void inizializza_generatore_numeri_casuali(void)
{
unsigned int seme;
seme=time(NULL);
srandom(seme);
}
/* implementazione */
unsigned int interroga_oracolo(void)
{
unsigned int risultato;
/* se non l'ho gia' fatto prima,
inizializzo il generatore dei numeri casuali */
if(inizializzato==0) {
inizializza_generatore_numeri_casuali();
inizializzato=1;
}
/* genero un numero casuale tra 0 e 299 */
risultato=random()%300;
return( (double)risultato);
}
<file_sep>/Esami/vacche/Makefile
CFLAGS=-ansi -Wall -Wpedantic -D_THREAD_SAFE -D_POSIX_C_SOURCE -D_BSD_SOURCE
LIBS=-lpthread
all: vacche.exe
vacche.exe: vacche.o DBGpthread.o
gcc ${CFLAGS} -o vacche.exe vacche.o DBGpthread.o ${LIBS}
vacche.o: vacche.c DBGpthread.h
gcc -c ${CFLAGS} vacche.c
DBGpthread.o: DBGpthread.c printerror.h
gcc -c ${CFLAGS} DBGpthread.c
.PHONY: clear
clear:
rm *.o vacche.exe<file_sep>/MakefileExercices/EsErroreSenzaPrototipo/mainConErrore.c
#include <stdlib.h>
#include <unistd.h> /* per sleep */
#include <stdio.h>
/* NOTARE CHE NON HO MESSO IL PROTOTIPO
DELLA FUNZIONE DoppioDelCoseno
(e' commentato)
E NON HO MESSO L'OPZIONE DI COMPILAZIONE -Wall
*/
extern double DoppioDelCoseno( double x );
int main(void)
{
double ris;
ris = DoppioDelCoseno( 0.1 );
printf( "ris = %f \n", ris );
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/gallinaUovo/gallinauovavolpe.c
/* file: gallivauovavolpe.c
*/
#define _THREAD_SAFE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <pthread.h>
#include "printerror.h"
int uova = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
#define SETTE_DECIMIDISECONDO 700000L
#define TREDICI_DECIMIDISECONDO 1300000L
#define NUMGALLINE 3
#define NUMVOLPI 3
void produce(void){ sleep(3); }
void *gallina_produce_uova(void *arg)
{
int rc;
while(1) {
produce(); /* gallina produce uova impiegando 3 sec ....*/
rc=pthread_mutex_lock(&mutex);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_lock failed");
/* gallina depone uova */
printf("depongo un ovetto caldo caldo\n");fflush(stdout);
fflush(stdout);
uova ++;
rc=pthread_cond_signal(&cond); /* avvisa volpe che c'è uovo, e continua */
if( rc ) PrintERROR_andExit(rc,"pthread_cond_signal failed");
rc=pthread_mutex_unlock(&mutex);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_unlock failed");
}
}
void mangia(void){
printf("gnam gnam ...");
fflush(stdout);
usleep(SETTE_DECIMIDISECONDO);
printf(" ahhh\n"); fflush(stdout);
}
void burp(void){
printf("burp\n\n");
fflush(stdout);
usleep(TREDICI_DECIMIDISECONDO);
}
void *volpe_mangia_uova(void *arg) /* volpe mangia un uovo alla volta e poi digerisce */
{
int rc;
while(1) {
int mangiato=0;
rc=pthread_mutex_lock(&mutex);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_lock failed");
while( ! mangiato ) {
if( uova > 0 ) {
mangia(); /* volpe mangia uovo impiegando quasi niente ....*/
uova --;
printf("Dopo aver magnato ora le UOVA sono: %d\n", uova);
mangiato=1;
} else {
/* attendi che venga prodotto uovo */
rc=pthread_cond_wait(&cond, &mutex);
if( rc ) PrintERROR_andExit(rc,"pthread_cond_wait failed");
}
}
rc=pthread_mutex_unlock(&mutex);
if( rc ) PrintERROR_andExit(rc,"pthread_mutex_unlock failed");
burp(); /* volpe digerisce impiegando tempo */
}
}
int main(void)
{ pthread_t tid;
int rc; int i;
for (i=0; i<NUMGALLINE; i++) {
rc=pthread_create( &tid, NULL, gallina_produce_uova, NULL );
if (rc) PrintERROR_andExit(rc,"pthread_create failed"); /* no EINTR */
}
for (i=0; i<NUMVOLPI; i++) {
rc=pthread_create( &tid, NULL, volpe_mangia_uova, NULL );
if (rc) PrintERROR_andExit(rc,"pthread_create failed"); /* no EINTR */
}
pthread_exit(NULL);
return(0);
}
<file_sep>/MakefileExercices/esBashToC/creaH.sh
#!/bin/bash
touch variabiliglobali.h;
while read A B C; do
for((i=1;i<=$C;i++));do
echo -e "extern int var$i;\n" >> variabiliglobali.h
done;
echo -e "extern int conta(void);\n" >> variabiliglobali.h
done < define.h
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esStrutture/Makefile
# Makefile per con_trucco.c
# a causa della presenza di pthread
# occorre compilare col flag -D_REENTRANT
# oppure con -D_THREAD_SAFE
# oppure con -D_THREAD_SAFE
# per usare strerror_r devo anche usare _POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_THREAD_SAFE -D_REENTRANT -D_POSIX_C_SOURCE=200112L
LIBRARIES=-lpthread
all: main.exe
main.exe: main.o
gcc ${CFLAGS} -o main.exe main.o ${LIBRARIES}
main.o: main.c
gcc ${CFLAGS} -c main.c
.PHONY: clean
clean:
rm -f main.o main.exe
<file_sep>/Bash/scrivisustderr.sh
while read A; do
echo "${A%% *}" 1;
echo evviva;
done;
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esCancella/Makefile
CFLAGS=gcc -ansi -Wall -Wpedantic -D_THREAD_SAFE -D_REENTRANT -D_POSIX_C_SOURCE=200112L
LIBRARIES=-lpthread
all: main.exe
main.exe: main.o
${CFLAGS} -o main.exe main.o ${LIBRARIES}
main.o: main.c
${CFLAGS} -c main.c
.PHONY: clean
clean:
rm -f *.o *.exe
<file_sep>/Bash/Makefile
# Makefile per con_trucco.c
# a causa della presenza di pthread
# occorre compilare col flag -D_REENTRANT
# oppure con -D_THREAD_SAFE
# oppure con -D_THREAD_SAFE
# per usare strerror_r devo anche usare _POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_THREAD_SAFE -D_REENTRANT -D_POSIX_C_SOURCE=200112L
LIBRARIES=-lpthread
all: con_trucco.exe
con_trucco.exe: con_trucco.o
gcc ${CFLAGS} -o con_trucco.exe con_trucco.o ${LIBRARIES}
con_trucco.o: con_trucco.c
gcc ${CFLAGS} -c con_trucco.c
.PHONY: clean
clean:
rm -f con_trucco.o con_trucco.exe
<file_sep>/MakefileExercices/EsAllenoMacro/bb.c
/* macro_in_piu_righe.c */
#include <unistd.h>
#include <stdlib.h> /* serve per la funzione rand */
#include <stdio.h>
/* NB: il corpo della macro finirebbe alla fine della riga,
per farla continuare alla riga successiva devo mettere
un backslash \ come ultimo carattere della riga.
L'ultima riga percio' non necessita del backslash in fondo.
*/
#ifndef SALUTAaCASO
#define SALUTAaCASO 5
#endif
int main(void) {
printf( "inizio\n" );
printf("%d\n", SALUTAaCASO);
printf( "fine\n" );
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esCancella/main.c
/* cancel.c
Esempio di creazione di pthread
e di terminazione di uno di questi su richiesta
*/
/* igia' messi nella riga di comando del compilatore
#define _THREAD_SAFE
#define _REENTRANT
#define _POSIX_C_SOURCE 200112L
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
int Glob=10;
void *do_thread(void *p_index)
{
int ris, i=0;
/*
la riga qui sotto servirebbe ad impedire al pthread di terminare
anche se qualcuno invoca la pthread_cancel su di lui
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
*/
sleep(1);
Glob+=3;
printf("thread index %d: Glob=%d thread_ID %d\n", *((int*)p_index), Glob, (int)pthread_self() );
/* uso in qualche modo l'indice che mi e' stato passato */
ris = *((int*)p_index);
ris = - ris ; /* lo cambio di segno, per gioco */
while(i<10)
{
/*sleep(1);*/
printf("thread index %d: thread_ID %d ITERAZIONE %d\n", *((int*)p_index), (int)pthread_self(), i );
i++;
}
/* dealloco la struttura in cui mi sono stati passati i parametri */
free(p_index);
pthread_exit ( NULL ); /* valore restituito dal thread */
}
int main()
{
pthread_t vthreads[NUM_THREADS];
int rc, t, *p;
pthread_attr_t attr;
printf("il main e' il thread con ID %d\n", (int) pthread_self() );
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
for(t=0;t < NUM_THREADS;t++){
/* alloco la struttura in cui passare i parametri */
p=malloc(sizeof(int));
if(p==NULL) {
perror("malloc failed: ");
pthread_exit (NULL);
}
*p=t;
/* printf("Creating thread DETACHED %d\n", t); */
rc = pthread_create (&vthreads[t], &attr, do_thread, p );
if (rc){
printf("ERROR; return code from pthread_create() is %d\n",rc);
exit(-1);
}
else{
printf("Created thread DETACHED ID %d\n", (int)(vthreads[t]) );
}
}
pthread_attr_destroy(&attr);
/* uccido i primi 4 pthread */
for(t=0;t<NUM_THREADS-1;t++){
pthread_cancel(vthreads[t]);
}
/* se chiamo la pthread_exit
i thread creati continuano l'esecuzione anche dopo la fine del main
*/
pthread_exit (NULL);
/* se invece chiamo la exit normale o la return
i thread creati vengono interrotti con la fine del main
*/
exit(0);
}
<file_sep>/MakefileExercices/esBashToC/creaC.sh
#!/bin/bash
touch variabiliglobali.c;
while read A B C; do
for((i=1;i<=$C;i++));do
echo -e "int var$i=$i;\n" >> variabiliglobali.c
done;
echo -e "int conta(void){\n" >> variabiliglobali.c
echo -e "int i=0;\n" >> variabiliglobali.c
echo "i=var1" >> variabiliglobali.c
for((i=2;i<=$C;i++));do
echo "+var$i" >> variabiliglobali.c
done
echo -e ";\n" >> variabiliglobali.c
echo "return i;}" >> variabiliglobali.c
done < define.h
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esInfinitiThread/con_trucco.c
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#define _POSIX_C_SOURCE 200112L
#define _BSD_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <inttypes.h>
#define NUM_THREADS 1000
typedef struct{
pthread_t th;
int index;
}arg_struct;
void *do_thread(void *i)
{
int error;
void *ptr;
pthread_t th;
arg_struct* str;
printf("thread index %d: thread_ID %d\n", (((arg_struct *)(i))->index), (int) pthread_self());
usleep(1000);
str = (arg_struct *)malloc(sizeof(arg_struct));
if(str==NULL){
printf("ERROREEE AIUTOOOOOOO\n");
pthread_exit (NULL);
}
str->th = pthread_self();
str->index = ((((arg_struct *)(i))->index) + 1);
pthread_create(&th, NULL, do_thread, str);
error=pthread_join(((arg_struct *)(i))->th, &ptr);
if(error!=0){
printf("pthread_join() failed: error=%d\n", error );
exit(-1);
}
pthread_exit (NULL);
}
int main(){
arg_struct *i;
pthread_t th;
usleep(1000);
i = (arg_struct *)malloc(sizeof(arg_struct));
if(i==NULL){
printf("ERROREEE AIUTOOOOOOO\n");
exit(1);
}
i->th = pthread_self();
i->index = 1;
pthread_create(&th, NULL, do_thread, &i);
pthread_exit (NULL);
return(0);
}
<file_sep>/ConcurrentProgrammingExercices/Concorrente/esPremortem/con_trucco.c
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#define _POSIX_C_SOURCE 200112L
#define _DEFAULT_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <inttypes.h>
#define NUM_THREADS 1000
typedef struct{
pthread_t th;
int index;
}arg_struct;
void *do_thread(void *i)
{
void *ptr;
pthread_t th;
arg_struct* str;
arg_struct* p = (arg_struct*)i;
int res;
printf("thread index %d: thread_ID %d\n", p->index, (int) pthread_self());
usleep(1);
str = (arg_struct *)malloc(sizeof(arg_struct));
if(str==NULL){
perror("malloc failed");
exit(1);
}
str->th = pthread_self();
str->index = (p)->index + 1;
res = pthread_create(&th, NULL, do_thread, (void *)str);
if(res){
printf("pthread_create() failed: error %i\n", res);
exit(1);
}
res = pthread_join(p->th, &ptr);
if(res != 0){
printf("pthread_join() failed: error %i\n",res);
exit(1);
}
free(i);
pthread_exit(NULL);
}
int main(){
arg_struct *i;
pthread_t th;
usleep(1000);
i = (arg_struct *)malloc(sizeof(arg_struct));
if(i==NULL){
perror("malloc failed");
exit(1);
}
i->th = pthread_self();
i->index = 1;
pthread_create(&th, NULL, do_thread, (void *)i);
printf("FINEEEEEE\n");
pthread_exit (NULL);
return(0);
}
<file_sep>/Bash/lanciaekilla.sh
OUT=`./lanciaeprendi.sh`;
for i in $OUT; do
kill -9 $i;
done;
<file_sep>/MakefileExercices/esBashToC/Makefile
all: main.exe
main.exe: main.o variabiliglobali.o
gcc -ansi -Wall -Wpedantic -o main.exe main.o variabiliglobali.o
main.o: main.c variabiliglobali.h define.h
gcc -c -ansi -Wall -Wpedantic main.c
variabiliglobali.o: variabiliglobali.c
gcc -c -ansi -Wall -Wpedantic variabiliglobali.c
variabiliglobali.c:define.h
./creaC.sh
variabiliglobali.h:define.h
./creaH.sh
.PHONY: clean
clean:
rm main.exe *.o
<file_sep>/Esami/BASE_es153/piattello.c
/* file: piattello.c */
#ifndef _THREAD_SAFE
#define _THREAD_SAFE
#endif
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
/* la #define _POSIX_C_SOURCE 200112L e' dentro printerror.h */
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* per random e srandom */
#endif
/* messo prima perche' contiene define _POSIX_C_SOURCE */
#include "printerror.h"
#include <unistd.h> /* exit() etc */
#include <stdlib.h> /* random srandom */
#include <stdio.h>
#include <string.h> /* per strerror_r and memset */
#include <sys/types.h>
#include <signal.h>
#include <sys/time.h> /*gettimeofday() struct timeval timeval{} for select()*/
#include <time.h> /* timespec{} for pselect() */
#include <limits.h> /* for OPEN_MAX */
#include <errno.h>
#include <assert.h>
#include <stdint.h> /* uint64_t intptr_t */
#include <inttypes.h> /* per PRIiPTR */
#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include "DBGpthread.h"
#define NUMTIRATORI 10
#define DELAYTRADUEPIATTELLI8sec 8
pthread_mutex_t mutex;
pthread_mutex_t mutex1[NUMTIRATORI];
pthread_cond_t cond;
/* dati da proteggere */
int atterrato = 1;
/* variabili per la sincronizzazione */
void attendi( int min, int max) {
int secrandom=0;
if( min > max ) return;
else if ( min == max )
secrandom = min;
else
secrandom = min + ( random()%(max-min+1) );
do {
/* printf("attendi %i\n", secrandom);fflush(stdout); */
secrandom=sleep(secrandom);
if( secrandom>0 )
{ printf("sleep interrupted - continue\n"); fflush(stdout); }
} while( secrandom>0 );
return;
}
void *Tiratore (void *arg)
{
char Plabel[128];
intptr_t indice;
indice=(intptr_t)arg;
sprintf(Plabel,"Tiratore%" PRIiPTR "",indice);
/* da completare */
pthread_mutex_lock(&mutex);
while ( 1 ) {
/* il tiratore attende l'inizio del volo del piattello */
printf("tiratore %s attende piattello \n", Plabel);
fflush(stdout);
/* da completare */
pthread_cond_wait(&cond, &mutex);
printf("tiratore %s mira e .... \n", Plabel);
fflush(stdout);
pthread_mutex_unlock(&mutex);
/* da completare */
/* il tiratore si prepara a sparare impiegando da 2 a 4 secondi */
attendi( 2, 4 );
pthread_mutex_lock(&mutex);
if(atterrato == 1){
printf("AAAAARGH TROPPO LENTO\n");
}else{
printf("COLPITO\n");
}
/* da completare */
/* il tiratore finisce il tentativo di sparare al piattello in volo */
printf("tiratore %s ha sparato o e' arrivato tardi\n", Plabel);
fflush(stdout);
/* da completare */
}
pthread_exit(NULL);
}
void *Piattello (void *arg)
{
char Plabel[128];
intptr_t indice;
indice=(intptr_t)arg;
sprintf(Plabel,"Piattello%" PRIiPTR "",indice);
/* da completare */
printf("piattelo %s inizia volo\n", Plabel);
fflush(stdout);
pthread_mutex_lock(&mutex);
atterrato = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
/* il piattello vola per tre secondi */
attendi( 3, 3 );
pthread_mutex_lock(&mutex);
atterrato = 1;
pthread_mutex_unlock(&mutex);
printf("piattelo %s finisce volo e termina\n", Plabel);
fflush(stdout);
/* da completare */
pthread_exit(NULL);
}
int main ( int argc, char* argv[] )
{
pthread_t th;
int rc;
uintptr_t i=0;
int seme;
/* aggiungete eventuali vostre variabili */
seme=time(NULL);
srandom(seme);
/* INIZIALIZZATE LE VOSTRE VARIABILI CONDIVISE e tutto quel che serve - fate voi */
/* all'inizio non c'e' nessun piattello in volo */
/* CREAZIONE PTHREAD dei tiratori */
for(i=0;i<NUMTIRATORI;i++) {
rc=pthread_create(&th,NULL,Tiratore,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
}
/* CREAZIONE NUOVO PIATTELLO OGNI 8 secondi */
i=0;
while(1) {
/* un nuovo piattello ogni 8 secondi */
attendi( DELAYTRADUEPIATTELLI8sec, DELAYTRADUEPIATTELLI8sec );
rc=pthread_create(&th,NULL,Piattello,(void*)i);
if(rc) PrintERROR_andExit(rc,"pthread_create failed");
i++;
}
pthread_exit(NULL);
return(0);
}
<file_sep>/Bash/esprcond_errato.sh
#!/bin/bash
if [[ -e "/usr/include/stdio.h" ]] ; then echo esiste;fi;
<file_sep>/Bash/sccr.sh
(head -n 5 /usr/include/stdio.h | tail -n 3;
tail -n 4 /usr/include/stdio.h | cut -b -3) | ( read A; read B; echo "$B"; echo "$A" ; read C &> /dev/null;
while read C; do echo ${#C}; done)
<file_sep>/Bash/cerca.sh
if [[ -d "$1" ]]; then
find $1 -type f -iname "*$2*";
fi;
<file_sep>/MakefileExercices/EsErroreSenzaPrototipo/funzioni.c
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
double DoppioDelCoseno( double x )
{
double risultato;
risultato = 2*cos( x );
printf( "DoppioDelCoseno calcola %f \n", risultato );
return(risultato);
}
<file_sep>/ConcurrentProgrammingExercices/Mutex/Barbiere/Makefile
CFLAGSCONSTRERROR=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE -D_POSIX_C_SOURCE=200112L
CFLAGS=-ansi -Wpedantic -Wall -D_REENTRANT -D_THREAD_SAFE
LIBRARIES=-lpthread
all: barbiere.exe
barbiere.exe: barbiere.o DBGpthread.o
gcc ${CFLAGS} -o barbiere.exe barbiere.o DBGpthread.o ${LIBRARIES}
barbiere.o: barbiere.c DBGpthread.h printerror.h
gcc -c ${CFLAGS} barbiere.c
DBGpthread.o: DBGpthread.c printerror.h
gcc ${CFLAGSCONSTRERROR} -c DBGpthread.c
.PHONY: clean
clean:
-rm -f barbiere.o DBGpthread.o barbiere.exe
|
fbac245aa5a3060039df2d48ab601e76c5c5a617
|
[
"Markdown",
"C",
"Makefile",
"Shell"
] | 64 |
Shell
|
stefanoscolapasta/Operating-Systems
|
48943ad834ca36a0d0a54473795d7f2e6d9b641c
|
e63392e5fdeb79972fdcf8be440b9fda2ac5d7ca
|
refs/heads/master
|
<repo_name>Suleimanov-Renat/2ndTask<file_sep>/src/kpfu/itis/models/RedColor.java
package kpfu.itis.models;
/**
* Created by Suren on 2/21/2017.
*/
public class RedColor extends Color{
public RedColor() {
this.colorName = "RED";
}
}
<file_sep>/src/kpfu/itis/models/Shape.java
package kpfu.itis.models;
import kpfu.itis.interfaces.Draw;
/**
* Created by Suren on 2/21/2017.
*/
public abstract class Shape {
private String colorName;
protected Draw draw;
protected Shape(Draw draw){
this.draw = draw;
}
public abstract void draw();
public void setColor(Color color){
colorName = color.colorName;
}
public String getColor(){
return colorName;
}
}
<file_sep>/src/kpfu/itis/models/CircleShape.java
package kpfu.itis.models;
import kpfu.itis.interfaces.Draw;
/**
* Created by Suren on 2/21/2017.
*/
public class CircleShape extends Shape {
private double x, y , rad;
private Color color;
public CircleShape(Color color, final double x, final double y, final double rad, final Draw draw) {
super(draw);
this.color = color;
this.x = x; this.y = y; this.rad = rad;
}
public void draw() {
draw.drawCircle(color, rad, x, y);
System.out.println(color.colorName+ " Circle radius:" + rad + ", Xc:" + x + ", Yc:" + y);
}
}
<file_sep>/src/kpfu/itis/models/Color.java
package kpfu.itis.models;
/**
* Created by Suren on 2/21/2017.
*/
public class Color {
public String colorName;
public String getColorName(Color color) {
return colorName;
}
}
<file_sep>/src/kpfu/itis/interfaces/Draw.java
package kpfu.itis.interfaces;
import kpfu.itis.models.Color;
/**
* Created by Suren on 2/21/2017.
*/
public interface Draw {
public void drawCircle(Color color, double rad, double x, double y);
}
<file_sep>/src/kpfu/itis/interfaces/Impl/DrawImpl.java
package kpfu.itis.interfaces.Impl;
import kpfu.itis.interfaces.Draw;
import kpfu.itis.models.Color;
/**
* Created by Suren on 2/21/2017.
*/
public class DrawImpl implements Draw {
@Override
public void drawCircle(Color color, double rad, double x, double y) {}
}
|
034fe4edd43c4ec8cb0827da51453ff4f44e3716
|
[
"Java"
] | 6 |
Java
|
Suleimanov-Renat/2ndTask
|
7d5883bc227ed15577dd9c050193d6316592ec10
|
6ccf57c3152ff6b212b9aa2367af40bcf0f7dba7
|
refs/heads/master
|
<repo_name>kimbahintze/GitWalkThrough<file_sep>/CookingConverter/IngredientModel.swift
//
// IngredientModel.swift
// CookingConverter
//
// Created by <NAME> on 5/7/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
<file_sep>/CookingConverter/Ingredient.swift
//
// Ingredient.swift
// CookingConverter
//
// Created by <NAME> on 5/7/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
class Ingredient {
init(measurement: String, amount: Int) {
self.measurement = measurement
self.amount = amount
}
var measurement: String
var amount: Int
}
|
e7e8a4f0655117ce43bf3ed9482fe496d47f91bd
|
[
"Swift"
] | 2 |
Swift
|
kimbahintze/GitWalkThrough
|
71fa167ae88681f05226081cad6874896aaa2992
|
1bfacd285c00c42f3c73f780bd2ffc6bfc508052
|
refs/heads/master
|
<repo_name>sttic/SEG2106-assignment-2<file_sep>/README.md
# SEG2106 Assignment 2 - Lexical Analyser
See [Assignment 2.docx](Assignment%202.docx) for assignment instructions.
Content source is in [assignment2.md](assignment2.md) with graph files in the [graphs](graphs/) folder.
Final PDF document is built to [assignment2.pdf](assignment2.pdf).
## Requirements
- [Pandoc](https://pandoc.org/)
- [Graphviz](https://graphviz.org/)
- [TeX](https://www.latex-project.org/)
## How to run
Build the pdf with
```
make
```
To rebuild the pdf on file change, run
```
make watch
```
Note that the `inotifywait` command must be available for the watch to work.
It will watch [assignment2.md](assignment2.md) for changes and will build it on save.
<file_sep>/assignment2.md
---
title: SEG2106 Assignment 2
subtitle: Lexical Analyser
author: <NAME>
date: 2020-03-01
geometry:
- margin=1in
header-includes: |
\pagenumbering{gobble}
\usepackage{newunicodechar}
\newunicodechar{Ɛ}{\ensuremath{\epsilon}}
\usepackage{tikz}
\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
\node[shape=circle,draw,inner sep=1pt] (char) {#1};
}}
---
# Question 1 - Regular Expressions
1. `((a|b){2})*`
2. `b*a(b*ab*a)*b*`
3. `(a*ba*b)*a*`
4. `((^a(a|b)*b$)|(^b(a|b)*a$))`
5. `(a?b)+b`
6. `0*(1(0|1){6,}|111(0|1){3}|1101(0|1){2})`
7. `(-?[1-9][0-9]*|0)[a-zA-Z]+([4-9]|[1-3][0-9]|4[0-4])`
# Question 2 - Non-Deterministic Finite Automata
a) `(b|c)*a(a|c)*`

b) `c*|(a+|(b|c))*b*`

\newpage
c) `abb(ab)*(a*b*c*)`

# Question 3 – NFA to DFA Conversion
a)
Table: NFA transition function reference
| State | \ a | \ b | \ Ɛ* |
| ------------ | --------------- | --------------- | --------------------------- |
| \ 0 | \ $\varnothing$ | \ $\varnothing$ | $\{0,1,2,3,4,5,8,9,10,11\}$ |
| \ 1 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| \ 2 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| \ 3 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| \ 4 | $\{6\}$ | \ $\varnothing$ | $\{4\}$ |
| \ 5 | \ $\varnothing$ | $\{7\}$ | $\{5\}$ |
| \ 6 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,6,8,9,10,11\}$ |
| \ 7 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,7,8,9,10,11\}$ |
| \ 8 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| \ 9 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| 10 | \ $\varnothing$ | \ $\varnothing$ | $\{1,2,3,4,5,8,9,10,11\}$ |
| \circled{11} | \ $\varnothing$ | \ $\varnothing$ | $\{11\}$ |
Table: DStates
| | |
| ----------- | --------------------------- |
| \circled{A} | $\{0,1,2,3,4,5,8,9,10,11\}$ |
| \circled{B} | $\{1,2,3,4,5,6,8,9,10,11\}$ |
| \circled{C} | $\{1,2,3,4,5,7,8,9,10,11\}$ |
Table: Ɛ-closure state pairings
| | |
| ------------------ | ----------- |
| Ɛ-closure($\{0\}$) | \circled{A} |
| Ɛ-closure($\{6\}$) | \circled{B} |
| Ɛ-closure($\{7\}$) | \circled{C} |
\newpage
**Subset construction algorithm**
```
T = Ɛ-closure(0) = { 0, 1, 2, 3, 4, 5, 8, 9, 10, 11 } = A
U = Ɛ-closure(moveTo(A, a))
U = Ɛ-closure({ 6 }) = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11 } = B
U = Ɛ-closure(moveTo(A, b))
U = Ɛ-closure({ 7 }) = { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11 } = C
T = B
U = Ɛ-closure(moveTo(B, a))
U = Ɛ-closure({ 6 }) = B
U = Ɛ-closure(moveTo(B, b))
U = Ɛ-closure({ 7 }) = C
T = C
U = Ɛ-closure(moveTo(C, a))
U = Ɛ-closure({ 6 }) = B
U = Ɛ-closure(moveTo(C, b))
U = Ɛ-closure({ 7 }) = C
```
Table: Resulting DFA transition function
| | a | b |
| ------------------------- | --- | --- |
| $\rightarrow$ \circled{A} | B | C |
| \ \ \ \ \circled{B} | B | C |
| \ \ \ \ \circled{C} | B | C |


\newpage
b)
Table: NFA transition function reference
| State | \ a | \ b | \ Ɛ* |
| ----------- | --------------- | --------------- | ------- |
| \ 0 | $\{0,1\}$ | $\{0\}$ | $\{0\}$ |
| \ 1 | $\{2\}$ | $\{2\}$ | $\{1\}$ |
| \ 2 | $\{3\}$ | $\{3\}$ | $\{2\}$ |
| \circled{3} | \ $\varnothing$ | \ $\varnothing$ | $\{3\}$ |
Table: DStates
| | |
| ----------- | ------------- |
| \ A | $\{0\}$ |
| \ B | $\{0,1\}$ |
| \ C | $\{0,1,2\}$ |
| \ D | $\{0,2\}$ |
| \circled{E} | $\{0,1,2,3\}$ |
| \circled{F} | $\{0,2,3\}$ |
| \circled{G} | $\{0,1,3\}$ |
| \circled{H} | $\{0,3\}$ |
Table: Ɛ-closure state pairings
| | |
| ------------------------ | ----------- |
| Ɛ-closure($\{0\}$) | \ A |
| Ɛ-closure($\{0,1\}$) | \ B |
| Ɛ-closure($\{0,1,2\}$) | \ C |
| Ɛ-closure($\{0,2\}$) | \ D |
| Ɛ-closure($\{0,1,2,3\}$) | \circled{E} |
| Ɛ-closure($\{0,2,3\}$) | \circled{F} |
| Ɛ-closure($\{0,1,3\}$) | \circled{G} |
| Ɛ-closure($\{0,3\}$) | \circled{H} |
\newpage
**Subset construction algorithm**
```
T = Ɛ-closure(0) = { 0 } = A
U = Ɛ-closure(moveTo(A, a))
U = Ɛ-closure({ 0, 1 }) = { 0, 1 } = B
U = Ɛ-closure(moveTo(A, b))
U = Ɛ-closure({ 0 }) = A
T = B
U = Ɛ-closure(moveTo(B, a))
U = Ɛ-closure({ 0, 1, 2 }) = { 0, 1, 2 } = C
U = Ɛ-closure(moveTo(B, b))
U = Ɛ-closure({ 0, 2 }) = { 0, 2 } = D
T = C
U = Ɛ-closure(moveTo(C, a))
U = Ɛ-closure({ 0, 1, 2, 3 }) = { 0, 1, 2, 3 } = E
U = Ɛ-closure(moveTo(C, b))
U = Ɛ-closure({ 0, 2, 3 }) = { 0, 2, 3 } = F
T = D
U = Ɛ-closure(moveTo(D, a))
U = Ɛ-closure({ 0, 1, 3 }) = { 0, 1, 3 } = G
U = Ɛ-closure(moveTo(D, b))
U = Ɛ-closure({ 0, 3 }) = { 0, 3 } = H
T = E
U = Ɛ-closure(moveTo(E, a))
U = Ɛ-closure({ 0, 1, 2, 3 }) = E
U = Ɛ-closure(moveTo(E, b))
U = Ɛ-closure({ 0, 2, 3 }) = F
T = F
U = Ɛ-closure(moveTo(F, a))
U = Ɛ-closure({ 0, 1, 3 }) = G
U = Ɛ-closure(moveTo(F, b))
U = Ɛ-closure({ 0, 3 }) = H
T = G
U = Ɛ-closure(moveTo(G, a))
U = Ɛ-closure({ 0, 1, 2 }) = C
U = Ɛ-closure(moveTo(G, b))
U = Ɛ-closure({ 0, 2 }) = D
T = H
U = Ɛ-closure(moveTo(H, a))
U = Ɛ-closure({ 0, 1 }) = B
U = Ɛ-closure(moveTo(H, b))
U = Ɛ-closure({ 0 }) = A
```
\newpage
Table: Resulting DFA transition function
| | a | b |
| ----------------- | --- | --- |
| $\rightarrow$ A | B | A |
| \ \ \ \ B | C | D |
| \ \ \ \ C | E | F |
| \ \ \ \ D | G | H |
| \ \ \ \circled{E} | E | F |
| \ \ \ \circled{F} | G | H |
| \ \ \ \circled{G} | C | D |
| \ \ \ \circled{H} | B | A |

<file_sep>/watch.sh
#!/bin/sh
inotifywait -q -m -e close_write --format %e "$1" |
while read events; do
make $2
done
<file_sep>/Makefile
IN_FILE = assignment2.md
OUT_FILE = assignment2.pdf
GRAPHS_DIR = graphs
build:
cd $(GRAPHS_DIR) && make
pandoc $(IN_FILE) -o $(OUT_FILE)
watch:
sh watch.sh $(IN_FILE) build
clean: $(OUT_FILE)
rm $(OUT_FILE)
<file_sep>/graphs/Makefile
DOT_SOURCES = $(wildcard *.dot)
define buildSVG
dot -Tsvg $(1) -o $(1).svg
endef
svg:
$(foreach dot_source,$(DOT_SOURCES),$(call buildSVG,$(dot_source));)
clean:
rm *.dot.svg
|
5a79753187aed37f2d9aabc3803c18434745289e
|
[
"Markdown",
"Makefile",
"Shell"
] | 5 |
Markdown
|
sttic/SEG2106-assignment-2
|
9f8b5266232d04fc5027c6d48139e87eb33bdcc8
|
1299f0d5aae079c3e733b4566679738dc8cdb031
|
refs/heads/master
|
<file_sep>#! /usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import string
from random import randint, choice
def genere_pass():
password_min = 8
password_max = 8
all_chars = string.ascii_letters + string.digits + "!?/@"
password = "".join(choice(all_chars) for x in range(randint(password_min, password_max)))
pass_entry.delete(0, END)
pass_entry.insert(0, password)
# création de la fenetre
window = Tk()
window.title("Générateur de mot de passe, by MAPIR")
window.geometry("600x250")
window.minsize(600, 250)
window.maxsize(600, 250)
#window.iconbitmap("logo.ico")
window.config(background='#4065A4')
# création des frames
# frame contenant image et frame1
frame = Frame(window, bg='#4065A4')
frame.pack(expand=YES)
# frame d'affichage et visu de l'appli
frame1 = Frame(frame, bg='#4065A4')
frame1.grid(row=0, column=1, padx=30)
# création d'une image
width = 200
height = 170
#image = PhotoImage(file="pass.png").subsample(4) #problème avec l'affichage de la photo
canvas = Canvas(frame, width=width, height=height, highlightthickness=0, bg='#4065A4')
#canvas.create_image(width / 2, height / 2, image=image) # width et height /2 pour avoir le point centrale
canvas.grid(row=0, column=0)
# création des différents champs
# titre
label_title = Label(frame1, text="Générateur de MDP", font=("Helvetica", 25), bg='#4065A4', fg="#2B446C")
label_title.pack()
# sous titre
label_subtitle = Label(frame1, text="by MAPIR", font=("Arial", 14, "italic"), bg='#4065A4', fg="#324E7C")
label_subtitle.pack()
# champs de texte / Entré
pass_entry = Entry(frame1, justify=CENTER, font=("Helvetica", 25), bg='#4065A4', fg="white", highlightthickness=0)
pass_entry.pack()
# bouton
button = Button(frame1, width=10, activeforeground="orange", text="Générer", font=("Helvetica", 18), fg="#2B446C",
highlightthickness=0, command=genere_pass)
button.pack(pady=10)
# création d'une barre de menu
menu_bar = Menu(window)
# créer un premier menu
file_menu = Menu(menu_bar)
file_menu.add_command(labe="Générer", command=genere_pass)
file_menu.add_command(labe="Quitter", command=window.quit)
menu_bar.add_cascade(label="Fichier", menu=file_menu)
# configurer la fenetre pour ajouter le menu_bar
window.config(menu=menu_bar)
# on lance une boucle de maintien, pour afficher la fenetre
window.mainloop()
|
f303bbc0356bd77d088b12315c788dd902fac6fa
|
[
"Python"
] | 1 |
Python
|
Mapir08/GenerateurPass
|
e5ddbaf4c7b64390b010082f0be6c93986acb1ad
|
cbfc2a6b4f7f455b382617eb8c52b00571cc19bd
|
refs/heads/master
|
<file_sep>INSERT INTO burgers (burger_name, devoured) VALUES ("Vegan Burger", true);
INSERT INTO burgers (burger_name, devoured) VALUES ("Chicken Burger", false);
INSERT INTO burgers (burger_name, devoured) VALUES ("Impossible Burger", true);
INSERT INTO burgers (burger_name, devoured) VALUES ("Turkey Burger", true);
INSERT INTO burgers (burger_name, devoured) VALUES ("Hot Avocado Burger", true);
INSERT INTO burgers (burger_name, devoured) VALUES ("Double Cheese Burger", true);
|
8d35613dbc911855ca959f0e22380492b9a6f3d5
|
[
"SQL"
] | 1 |
SQL
|
labiosj/Eat-Da-Burger
|
5691686bff11d84fd9c0f283383c768233028d7a
|
abfa85729c28a849f9d36b33e48ba7f903fd25de
|
refs/heads/master
|
<file_sep>using System;
namespace WikiImages.Algorithm
{
public static class Levenshtein
{
public static int Distance(string string1, string string2)
{
if (string1 == null)
throw new ArgumentNullException(nameof(string1));
if (string2 == null)
throw new ArgumentNullException(nameof(string2));
string1 = string1.ToLowerInvariant();
string2 = string2.ToLowerInvariant();
var m = new int[string1.Length + 1, string2.Length + 1];
for (var i = 0; i <= string1.Length; i++)
{
m[i, 0] = i;
}
for (var j = 0; j <= string2.Length; j++)
{
m[0, j] = j;
}
for (var i = 1; i <= string1.Length; i++)
{
for (var j = 1; j <= string2.Length; j++)
{
var diff = string1[i - 1] == string2[j - 1] ? 0 : 1;
m[i, j] = Math.Min(
Math.Min(m[i - 1, j] + 1,
m[i, j - 1] + 1),
m[i - 1, j - 1] + diff);
}
}
return m[string1.Length, string2.Length];
}
public static bool AreSame(string string1, string string2, int maxDifference)
{
if (maxDifference < 0)
throw new ArgumentOutOfRangeException(nameof(maxDifference));
return Distance(string1, string2) <= maxDifference;
}
}
}
<file_sep>using System;
using Unity;
using WikiImages.Infrastructure.Services;
using WikiImages.Infrastructure.Services.Interfaces;
namespace WikiImages.Infrastructure
{
public sealed class InfrastructureContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
Container.RegisterType<IUserLocationService, StubLocationService>(new ContainerControlledLifetimeManager());
}
}
}
<file_sep>using NUnit.Framework;
using WikiImages.Algorithm;
namespace WikiImages.Tests.Algorithm.LevenshteinTests
{
[TestFixture]
public class LevenshteinDistanceTests
{
[Test]
public void EqualsTest()
{
var result = Levenshtein.Distance("abs", "abs");
Assert.That(result, Is.EqualTo(0));
}
[Test]
public void IgnoreCaseTest()
{
var result = Levenshtein.Distance("abs", "ABS");
Assert.That(result, Is.EqualTo(0));
}
[Test]
public void ReplaceTest()
{
var result = Levenshtein.Distance("abs", "abc");
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void AddTest()
{
var result = Levenshtein.Distance("abs", "ab");
Assert.That(result, Is.EqualTo(1));
}
[Test]
public void SwapTest()
{
var result = Levenshtein.Distance("ab", "ba");
Assert.That(result, Is.EqualTo(2));
}
[Test]
public void ComplexTest()
{
var result = Levenshtein.Distance("ca", "abc");
//ca -> ac -> abc
Assert.That(result, Is.EqualTo(3));
}
}
}
<file_sep>using NUnit.Framework;
using WikiImages.Algorithm;
namespace WikiImages.Tests.Algorithm.GraphTests
{
[TestFixture]
public class GetComponentsTests
{
[Test]
public void OneComponentTest()
{
var graph = new Graph(new[] { "a", "b", "c" }, (a, b) => 1);
var result = graph.GetComponents(0);
CollectionAssert.AreEqual(new[] { new[] { "a", "b", "c" } }, result);
}
}
}
<file_sep>namespace WikiImages.Infrastructure.Services.Interfaces
{
public interface IUserLocationService
{
Location GetCurrentLocation();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace WikiImages.Algorithm
{
public static class SentenceSimilarity
{
private static readonly char[] Separator = { ' ', ',', '.', ':', ';', '!', '?', '\n', '\r', '\t', '(', ')', '-' };
public static double Distance(string sentence1, string sentence2, int maxDifference)
{
if (maxDifference < 0)
throw new ArgumentOutOfRangeException(nameof(maxDifference), maxDifference, null);
if (sentence1 == null)
throw new ArgumentNullException(nameof(sentence1));
if (sentence2 == null)
throw new ArgumentNullException(nameof(sentence2));
var words1 = sentence1.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
var words2 = sentence2.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
var unitedSet = new HashSet<string>(new Comparer(maxDifference));
unitedSet.UnionWith(words1);
unitedSet.UnionWith(words2);
var totalWordsCount = unitedSet.Count;
var wordsCount1 = words1.Distinct().Count(word => unitedSet.Contains(word));
var wordsCount2 = words2.Distinct().Count(word => unitedSet.Contains(word));
var w1 = (double)wordsCount1 / totalWordsCount;
var w2 = (double)wordsCount2 / totalWordsCount;
return w1 * w2;
}
private sealed class Comparer : IEqualityComparer<string>
{
private readonly int _maxDifference;
public Comparer(int maxDifference)
{
_maxDifference = maxDifference;
}
public bool Equals(string x, string y)
{
return Levenshtein.AreSame(x, y, _maxDifference);
}
public int GetHashCode(string obj)
{
return 0;
}
}
}
}
<file_sep>using NUnit.Framework;
using WikiImages.Algorithm;
namespace WikiImages.Tests.Algorithm.SentenceSimilarityTests
{
[TestFixture]
public class DistanceTests
{
[Test]
public void Test()
{
var s1 = "i like dogs";
var s2 = "i dont like dog";
var result = SentenceSimilarity.Distance(s1, s2, 1);
Assert.That(result, Is.EqualTo(0.75).Within(0.001));
}
}
}
<file_sep>using Unity;
using WikiImages.Api.Services;
using WikiImages.Api.Services.Interfaces;
namespace WikiImages.Api
{
public sealed class ApiContainerExtension : UnityContainerExtension
{
protected override void Initialize()
{
Container.RegisterType<IApiService, ApiService>(new PerResolveLifetimeManager());
}
}
}
<file_sep>namespace WikiImages.Api.Services.Interfaces
{
public sealed class Page
{
public long PageId { get; set; }
public string Title { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WikiImages.Algorithm
{
public sealed class SimilarityGroups
{
private readonly int _maxWordDifference;
private readonly double _minimalDistance;
public SimilarityGroups(int maxWordDifference, double minimalDistance)
{
if (maxWordDifference < 0)
throw new ArgumentOutOfRangeException(nameof(maxWordDifference), maxWordDifference, "Value must be positive or zero");
if (minimalDistance < 0.0 || minimalDistance > 1.0)
throw new ArgumentOutOfRangeException(nameof(minimalDistance), minimalDistance, "Value must be from 0 to 1");
_maxWordDifference = maxWordDifference;
_minimalDistance = minimalDistance;
}
public IReadOnlyList<IReadOnlyCollection<string>> Find(IReadOnlyList<string> values)
{
var g = new Graph(values, (sentence1, sentence2) => SentenceSimilarity.Distance(sentence1, sentence2, _maxWordDifference));
return g.GetComponents(_minimalDistance);
}
}
}
<file_sep>using System;
using System.Runtime.Serialization;
namespace WikiImages.Api.Services.Interfaces
{
public sealed class ApiRequestException : Exception
{
public ApiRequestException()
{
}
public ApiRequestException(string message) : base(message)
{
}
public ApiRequestException(string message, Exception innerException) : base(message, innerException)
{
}
private ApiRequestException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Unity;
using WikiImages.Algorithm;
using WikiImages.Api;
using WikiImages.Api.Services.Interfaces;
using WikiImages.Infrastructure;
using WikiImages.Infrastructure.Services.Interfaces;
namespace WikiImages.Shell
{
class Program
{
static void Main(string[] args)
{
using (var container = InitContainer())
{
var locationService = container.Resolve<IUserLocationService>();
var location = locationService.GetCurrentLocation();
Console.WriteLine("Current location: {0}:{1}", location.Latitude, location.Longitude);
var apiService = container.Resolve<IApiService>();
var pages = apiService.GetPages(location.Latitude, location.Longitude);
var titles = apiService.GetImageTitles(pages.Select(o => o.PageId));
titles = ClearTitles(titles);
var groups = new SimilarityGroups(1, 0.6).Find(titles);
for (var i = 0; i < groups.Count; i++)
{
Console.WriteLine("Group {0}:", i + 1);
Console.WriteLine(string.Join("; ", groups[i]));
}
}
}
private static IReadOnlyList<string> ClearTitles(IEnumerable<string> titles)
{
return titles.Select(StringExtensions.ClearTitle).ToList().AsReadOnly();
}
private static IUnityContainer InitContainer()
{
var container = new UnityContainer();
container.AddNewExtension<InfrastructureContainerExtension>();
container.AddNewExtension<ApiContainerExtension>();
return container;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using WikiImages.Api.Services.Interfaces;
namespace WikiImages.Api.Services
{
internal sealed class ApiService : IApiService, IDisposable
{
private static readonly Uri Host = new Uri(@"https://en.wikipedia.org");
private static readonly Uri ApiUri = new Uri(Host, @"w/api.php");
private readonly WebClient _client;
public ApiService()
{
_client = new WebClient();
}
public IReadOnlyCollection<Page> GetPages(double latitude, double longitude)
{
var query = HttpUtility.ParseQueryString("action=query&list=geosearch&gsradius=10000&gslimit=50&format=json");
query["gscoord"] = $"{latitude.ToString("0.000000", CultureInfo.InvariantCulture)}|{longitude.ToString("0.000000", CultureInfo.InvariantCulture)}";
var requestUri = new UriBuilder(ApiUri) { Query = query.ToString() };
var json = _client.DownloadString(requestUri.Uri);
var error = JsonConvert.DeserializeObject<ErrorRoot>(json);
if (error?.Error != null)
{
throw new ApiRequestException(error.Error.Info);
}
var result = JsonConvert.DeserializeObject<PagesQueryRoot>(json);
return Array.AsReadOnly(result.Query.Geosearch);
}
public IReadOnlyList<string> GetImageTitles(IEnumerable<long> pageIds)
{
if (pageIds == null)
throw new ArgumentNullException(nameof(pageIds));
var query = HttpUtility.ParseQueryString("action=query&prop=images&imlimit=500&format=json");
query["pageids"] = string.Join("|", pageIds);
var requestUri = new UriBuilder(ApiUri) { Query = query.ToString() };
var json = _client.DownloadString(requestUri.Uri);
var error = JsonConvert.DeserializeObject<ErrorRoot>(json);
if (error?.Error != null)
{
throw new ApiRequestException(error.Error.Info);
}
var result = JsonConvert.DeserializeObject<ImagesRootObject>(json);
var pages = result.Query.Pages.Values.Where(o => o.Images != null);
return Array.AsReadOnly(pages.SelectMany(o => o.Images).Select(o => o.Title).ToArray());
}
public void Dispose()
{
_client?.Dispose();
}
private class PagesQueryRoot
{
public PagesQuery Query { get; set; }
}
private class PagesQuery
{
public Page[] Geosearch { get; set; }
}
private class Image
{
public string Title { get; set; }
}
private class ImagesQuery
{
public Dictionary<long, ImagesPage> Pages { get; set; }
}
private class ImagesRootObject
{
public ImagesQuery Query { get; set; }
}
private class ImagesPage
{
public List<Image> Images { get; set; }
}
private class Error
{
public string Info { get; set; }
}
private class ErrorRoot
{
public Error Error { get; set; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace WikiImages.Algorithm
{
public sealed class Graph
{
private readonly List<Edge> _edges = new List<Edge>();
private readonly IDictionary<string, int> _keys;
private readonly IDictionary<int, string> _values;
public Graph(IReadOnlyList<string> data, Func<string, string, double> distance)
{
_keys = data.Distinct().Select((o, i) => new { o, i }).ToDictionary(o => o.o, o => o.i);
_values = _keys.ToDictionary(o => o.Value, o => o.Key);
for (var i = 0; i < data.Count; i++)
{
var value1 = data[i];
for (var j = i + 1; j < data.Count; j++)
{
var value2 = data[j];
var key = distance(value1, value2);
_edges.Add(new Edge(_keys[value1], _keys[value2], key));
}
}
}
public IReadOnlyList<IReadOnlyCollection<string>> GetComponents(double minimalDistance)
{
var dsu = new Dsu(_keys.Count);
var list = new List<Edge>();
foreach (var edge in _edges.OrderByDescending(o => o.Distance))
{
var a = edge.Index1;
var b = edge.Index2;
if (dsu.Get(a) != dsu.Get(b))
{
dsu.Unite(a, b);
list.Add(edge);
}
}
list = list.Where(o => o.Distance >= minimalDistance).ToList();
var result = new Dictionary<int, List<int>>();
foreach (var edge in list)
{
if (!result.ContainsKey(edge.Index1))
{
result[edge.Index1] = new List<int>();
}
if (!result.ContainsKey(edge.Index2))
{
result[edge.Index2] = new List<int>();
}
result[edge.Index1].Add(edge.Index2);
result[edge.Index2].Add(edge.Index1);
}
var groups = new Dfs(result).Find();
return groups.Select(o => o.Select(s => _values[s]).ToList().AsReadOnly())
.OrderByDescending(o => o.Count)
.ToList()
.AsReadOnly();
}
private class Dfs
{
private readonly Dictionary<int, List<int>> _nodes;
private readonly HashSet<int> _visited = new HashSet<int>();
public Dfs(Dictionary<int, List<int>> nodes)
{
_nodes = nodes;
}
public List<List<int>> Find()
{
var result = new List<List<int>>();
foreach (var v in _nodes.Keys)
{
if (!_visited.Contains(v))
{
var group = new List<int>();
Find(v, group);
result.Add(group);
}
}
return result;
}
private void Find(int node, ICollection<int> result)
{
if (_visited.Contains(node))
return;
_visited.Add(node);
result.Add(node);
foreach (var v in _nodes[node])
{
Find(v, result);
}
}
}
private class Dsu
{
private readonly Random _rand = new Random();
private readonly int[] _set;
public Dsu(int count)
{
_set = new int[count];
for (var i = 0; i < count; i++)
{
_set[i] = i;
}
}
public int Get(int key)
{
return key == _set[key] ? key : (_set[key] = Get(_set[key]));
}
public void Unite(int a, int b)
{
a = Get(a);
b = Get(b);
if (_rand.Next(2) == 1)
{
var t = a;
a = b;
b = t;
}
if (a != b)
_set[a] = b;
}
}
private sealed class Edge
{
public Edge(int index1, int index2, double distance)
{
Index1 = index1;
Distance = distance;
Index2 = index2;
}
public int Index1 { get; }
public int Index2 { get; }
public double Distance { get; }
}
}
}
<file_sep>using WikiImages.Infrastructure.Services.Interfaces;
namespace WikiImages.Infrastructure.Services
{
internal sealed class StubLocationService : IUserLocationService
{
public Location GetCurrentLocation()
{
return new Location(55.023525, 82.941754);
}
}
}
<file_sep>using System;
using System.Linq;
namespace WikiImages.Infrastructure
{
public static class StringExtensions
{
private const string Prefix = "File:";
private static readonly string[] Extensions = { ".jpg", ".jpeg", ".png", ".svg", ".gif" };
public static string ClearTitle(string value)
{
if (value.StartsWith(Prefix, StringComparison.InvariantCultureIgnoreCase))
{
value = value.Substring(Prefix.Length);
}
var ending = Extensions.FirstOrDefault(o => value.EndsWith(o, StringComparison.InvariantCultureIgnoreCase));
if (ending != null)
{
value = value.Remove(value.Length - ending.Length, ending.Length);
}
return value;
}
}
}
<file_sep>using System.Collections.Generic;
namespace WikiImages.Api.Services.Interfaces
{
public interface IApiService
{
IReadOnlyCollection<Page> GetPages(double latitude, double longitude);
IReadOnlyList<string> GetImageTitles(IEnumerable<long> pageIds);
}
}
|
a0764d1a81a6bc5c85449b319fe1487aa3fc4e61
|
[
"C#"
] | 17 |
C#
|
Backs/WikiImages
|
4de9a507ce1a0c539b15f31f9b2c2110ed0079f4
|
295d2eb3e1b321acef8128ba47ef57ad2435c45b
|
refs/heads/master
|
<file_sep>// import DS from 'ember-data';
//
// export default DS.RESTSerializer.extend({
// normalize(model, hash, prop) {
// hash.id = hash._id;
// delete hash._id;
// // if (prop === 'comments') {
// // hash.id = hash._id;
// // delete hash._id;
// // }
//
// return this._super(...arguments);
// }
// });
<file_sep>import Route from '@ember/routing/route';
export default Route.extend({
model(params) {
return this.store.findRecord('worker', params.details_id);
},
actions: {
returnToWorkers() {
this.transitionTo('workers');
}
}
});
<file_sep>import Route from '@ember/routing/route';
export default Route.extend({
model(){
return {
chartData: {
labels: ['Day1', 'Day2', 'Day3'],
series: [
[5, 4, 8, 9, 10],
[10, 2, 7, 6, 7],
[8, 3, 6, 4, 5]
]
}
}
}
});
<file_sep>import DS from 'ember-data';
export default DS.RESTSerializer.extend({
primaryKey: '_id',
serializeId: function(id) {
console.log("serialized id = "+ id);
return id.toString();
}
});
//
// import DS from 'ember-data';
//
// export default DS.RESTSerializer.extend({
// normalize(model, hash, prop) {
// hash.id = hash._id;
// delete hash._id;
// // if (prop === 'comments') {
// // hash.id = hash._id;
// // delete hash._id;
// // }
//
// return this._super(...arguments);
// }
// });
<file_sep>import Component from '@ember/component';
import {tagName} from '@ember-decorators/component';
import {computed} from '@ember-decorators/object';
// import {argument} from '@ember-decorators/argument';
// import {type} from '@ember-decorators/argument/type';
import PersonModel from 'app5/person/model';
import { get } from '@ember/object';
@tagName('div')
export default class PersonViewComponent extends Component.extend({}) {
// @argument
// @type('string')
space = ' ';
@computed('person.firstName','person.lastName')
get fullName() {
const firstName = get(this,'person.firstName');
const lastName = get(this,'person.lastName');
const space = get(this, 'space');
return firstName+ space + lastName;
}
@computed('person.country', 'person.city', 'person.postalCode', 'person.street')
get address() {
const country = get(this, 'person.country');
const space = get(this, 'space');
const city = get(this, 'person.city');
const postalCode = get(this, 'person.postalCode');
const street = get(this, 'person.street');
return country + space + city + space + postalCode + space + street;
}
//
// @computed('person.fullName', 'person.age', 'person.wage', 'person.email', 'person.address', 'person.familyStatus')
// fullInfo(fullName, age, wage, email, address, familyStatus) {
// return fullName + space + age + space + wage + space + email + space + address + space + familyStatus;
// }
}
<file_sep>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.get('/', function(req, res) {
res.send('Hello World');
});
app.post('/token', function(req, res) {
if(req.body.username==='edu' && req.body.password=== '<PASSWORD>') {
res.send({access_token: "<PASSWORD>"});
} else {
res.status(400).send({error: "invalid_grant"});
}
});
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/students', function(req, res){
if(req.headers.authorization !== "Bearer secretcode") {
return res.status(401).send('Unauthorized');
}
return res.status(200).send({
students: [
{id:1 , name: 'Erik', age: 24},
{id:2 , name: 'Suze', age: 32},
{id:3 , name: 'Jill', age:18}
]
});
});
app.listen(4200, function() {
console.log('express is listening on port 3000');
});
<file_sep>import Route from '@ember/routing/route';
import PersonModel from 'app5/person/model';
import Ember from 'ember';
import {service} from '@ember-decorators/service';
export default Route.extend({
generatePeople: function() {
let arr = [
{
firstName: 'foo',
lastName: 'bar',
age: 10,
wage: 100.0,
email: '<EMAIL>',
country: 'Germany',
city: 'Essen',
postalCode: 44800,
street: 'Laerholzstrasse',
familyStatus: 'ledig'
},
{
firstName:'edu',
lastName: 'tilos',
age: 20,
wage:200.0,
email: '<EMAIL>',
country: 'Germany',
city: 'Bochum',
postalCode: 44801,
street: 'Sumperkamp',
familyStatus: 'verheiratet'
}
];
return arr;
},
model() {
return this.generatePeople();
}
});
<file_sep>import Route from '@ember/routing/route';
export default Route.extend({
model() {
return {
chartData:{
labels: ['1', '2', '3', '4', '5', '6'],
series: [
{
data: [1, 2, 3, 5, 8, 13]
}
]
}
}
}
});
<file_sep>import Route from '@ember/routing/route';
function clearInputs(controller) {
controller.set('myid', '');
controller.set('name', '');
controller.set('age', '');
controller.set('wage', '');
controller.set('active', '');
}
export default Route.extend({
actions: {
createWorker() {
let controller = this.get('controller');
// let myid = parseInt(controller.get('myid'));
let name = controller.get('name');
let age = parseInt(controller.get('age'));
let wage = parseInt(controller.get('wage'));
let active = controller.get('active') === 'True' || controller.get('active')=== 'true';
let newWorker = this.store.createRecord('worker', {
// myid: myid ,
name: name,
age: age,
wage: wage,
active: active
});
newWorker.save();
clearInputs(controller);
this.transitionTo('workers');
}
}
});
<file_sep>import Controller from '@ember/controller';
export default Controller.extend({
options:{
axisX: {
labelInterpolationFnc: function(value) {
return 'Calendar Week ' + value;
}
}
},
responsiveOptions: [
['screen and (min-width: 641px) and (max-width: 1024px)', {
showPoint: false,
axisX: {
labelInterpolationFnc: function(value) {
return 'Week ' + value;
}
}
}],
['screen and (max-width: 640px)', {
showLine: false,
axisX: {
labelInterpolationFnc: function(value) {
return 'W' + value;
}
}
}]
]
});
|
5aa59466205dc3b2126bfc32cac16f7c11c59b96
|
[
"JavaScript"
] | 10 |
JavaScript
|
edutilos6666/EmberjsApp5
|
d8f6c9cc3ded4e767241b383329460f566214182
|
72a38e980f1baeb2587f729f49d0af54a7bc6133
|
refs/heads/master
|
<file_sep>import java.util.ArrayList;
import java.util.List;
public class PhoneBook {
private List<PhoneEntry> phoneEntryList = new ArrayList();
public List<PhoneEntry> getPhoneEntryList() {
return phoneEntryList;
}
@Override
public String toString() {
return "В телефонной книге " +
"имеется запись=" + phoneEntryList +
'}';
}
public void add(String name, String phone) {
PhoneEntry entry = new PhoneEntry(name, phone);
if (!phoneEntryList.contains(entry)) {
phoneEntryList.add(entry);
}
}
public String get(String lastName) {
List<String> foundEntries = new ArrayList<>();
for (PhoneEntry a : phoneEntryList) {
if (a.getLastName().equals(lastName)) {
foundEntries.add(a.getNumber());
}
}
if(foundEntries.size()==0)return "фамилия не найдена";
return "для фамилии "+ lastName+" найдены номера "+foundEntries.toString();
}
}
<file_sep>import java.util.HashMap;
import java.util.Objects;
public class PhoneEntry {
private String lastName;
private String number;
public String getLastName() {
return lastName;
}
public String getNumber() {
return number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PhoneEntry that = (PhoneEntry) o;
return Objects.equals(lastName, that.lastName) &&
Objects.equals(number, that.number);
}
@Override
public int hashCode() {
return Objects.hash(lastName, number);
}
@Override
public String toString() {
return "{" +
"lastName='" + lastName + '\'' +
", number='" + number + '\'' +
'}';
}
public PhoneEntry(String lastName, String number) {
this.lastName = lastName;
this.number = number;
}
}
|
ea46c779f01a685b3ad279d70dcc46e2610bd5f4
|
[
"Java"
] | 2 |
Java
|
ebataeva/homeWork10_javaCore
|
32fd3057a1a610225fdd8e37eeba600339348a6b
|
817ee25e6dc33f37f07c6145c379dab8920b89a0
|
refs/heads/master
|
<repo_name>HongyuanWu/methscRNAseq<file_sep>/MethLevelNearbyFunctionRegion.R
setwd("/media/Home_Raid1/zhl002/NAS1/projects/mouse_WGBS/bedfiles/BED")
files=Sys.glob("*enhancer*txt")
data<-read.table(files[1]);
main="enhancer"
xlab=paste("Distance to center of"," main(bp)",sep="")
ylab="Methylation level(Beta)"
pdf("enhancer.dist.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main="enhancer",xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3],spar=0.1)
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[3]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
# bivalentdomain
files=Sys.glob("*bivalentdomain*txt")
files
data<-read.table(files[1]);
main="Bivalentdomain"
xlab=paste("Distance to center of",main," (bp)",sep="")
ylab="Methylation level(Beta)"
pdf("bivalentdomain.nearby.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main=main,xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3])
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[3]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
files=Sys.glob("*Promoter*txt")
files
data<-read.table(files[1]);
main="Promoter"
xlab=paste("Distance to center of",main," (bp)",sep="")
ylab="Methylation level(Beta)"
pdf("Promoter.nearby.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main=main,xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3])
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[4]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
files=Sys.glob("*Exon*txt")
files
data<-read.table(files[1]);
main="Exon"
xlab=paste("Distance to center of",main," (bp)",sep="")
ylab="Methylation level(Beta)"
pdf("Exon.nearby.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main=main,xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3])
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[4]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
files=Sys.glob("*Intron*txt")
files
data<-read.table(files[1]);
main="Intron"
xlab=paste("Distance to center of",main," (bp)",sep="")
ylab="Methylation level(Beta)"
pdf("Intron.nearby.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main=main,xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3])
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[4]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
files=Sys.glob("*CpGI*txt")
files
data<-read.table(files[1]);
main="CpGI"
xlab=paste("Distance to center of",main," (bp)",sep="")
ylab="Methylation level(Beta)"
pdf("CpGI.nearby.density.pdf")
plot(data[,2],data[,3],type = "n",ylim=c(0,1),main=main,xlab = xlab,ylab=ylab)
for(i in 1:length(files)){
data<-read.table(files[i]);
fit<-smooth.spline(data[,2], data[,3])
lines(fit,col=i,lwd=2)
}
legend=unlist(lapply(files,function(x) unlist(strsplit(x,"[.]"))[4]))
legend("bottomright",legend =legend,col=1:length(files),lty=1,cex=0.7,bty = "n")
dev.off()
<file_sep>/projectlog.md
## Integrate analysis to buck methylation and single-celll RNAseq data from iPS and SCNT
## work together with Alice from 2016 to 2017
## Download scRNA-seq data
### from https://www.ebi.ac.uk/arrayexpress/experiments/E-MTAB-2600/
<file_sep>/readme.txt
bulk level methylation data and single cell scRNAseq data
|
4362f4da1b715dce5207ce40585025804ec5cb80
|
[
"Markdown",
"Text",
"R"
] | 3 |
R
|
HongyuanWu/methscRNAseq
|
f12d8a550c755dc177aca094499d8ba064d3dcac
|
44bb14518017ef846771e93bf7397cd8ba440fcc
|
refs/heads/master
|
<file_sep>var client = require('twilio')( //Calling Twillion API to use their messaging service
'',
''
);
var express = require('express');
const translate = require('google-translate-api');
/*
Express is an addon that allows Node.js to run web application on the server.
Web Applications cab be run through the pm2 commands.
There should be a list of pm2 commands in your home directory.
*/
var ConversationV1 = require('watson-developer-cloud/conversation/v1');
/*
Watson conversation links Watson API to our program.
This segment is required to connect the program to the IBM's API.
*/
var app = express();
/*
Creating new exress application process.
*/
var contexts = []; //variable array that holds our data in.
app.get('/smssent', function (req, res)
/*
"app" calls our application process.
".get" is a method that our data was sent to the server.
*GET is more open and can be seen via anyone, I will change it later to the POST.
*POST is more secure but it we will need additional modules to decrypt the data.
"req" is for requested data, aka data that comes in.
"res" is for response data, aka data that is going to be sent to the user.
"/smssent" is an extenstion of the port, port is specified on the bottom of a page in "port.listen()".
*smssent is just like any other variable and can be changed on a fly.
*smssent is bound to Twillio input.
"function " declares a new function with two qrguments, req and req.
*/
{
var message = req.query.Body;
var number = req.query.From;
var twilioNumber = req.query.To;
/*
Twilio sends several packages of data in separate variables.
Items such as: Body, Country, State, etc.
We are only interested in this 3 (for now)
*Body (what was sent to us, aka the message or text)
*From (who it was sent from from, aka the user)
*To (who was it sent to, aka final destination or server)
*/
//console.log(message);
/*
consol.log output data to the screen when NODE.js is running.
This allows us to debugg and look at the data being sent
*/
var intent_checker = false;
var context = null; //variable for the context
var index = 0; //Variable to track users
var contextIndex = 0;
var a;
function getTranslation(inc_text)
{
translate(inc_text, {to: 'en'}).then(res => {
console.log(res.text);
console.log(res.from.language.iso);
a =res.text;
send_message(a);
}).catch(err => {
console.error(err);
});
}
function send_message(argument)
{
client.messages.create({ //sending a response back to the user
from: twilioNumber, //out twillio number
to: number,//to user
body: argument
})
}
contexts.forEach(function(value) { //similar to PHP, for each function does the function for every new request
//console.log(value.from);
if (value.from == number)
{ //if the user has texted before in this session
context = value.context;
contextIndex = index;
}
index = index + 1; //making sure that every user gets a unique session
});//end of the user checking loop
console.log('Recieved message from ' + number + ' saying \'' + message + '\''); //this allows me to see who sent what
var conversation = new ConversationV1({ //API Call to Watson conversation
username: '',
password: '',
version_date: ConversationV1.VERSION_DATE_2017_05_26 //this is important, because it won't work if it's outdated (I tried...)
});//end of Watson Conversation API Code
if (context != null)
{
//console.log(JSON.stringify(context)); //used for debugging
}
/*
This is where things get complicated, so bare with me...
I am converting Java Script values into JSON.
JSON files are used by several NoSQL databases like MongoDB.
Unlike SQL, the data is erraged in a file instead of a collection of tables.
This allows for faster data access and easier replecation.
*/
getTranslation(message);
conversation.message(
{ //Conversation is a new variable created by us and a function assigned by Watson Conversation
input:
{
text: message
}, //text is a type, message is a variable previously binded to the inout of a user
workspace_id: '',
context: context //context is gonna allow us to see who sent it
}, function(err, response)
{ //if there is an issue, print error
if (err)
{
console.error(err);
}
else
{ //if there is no issue - output what was sent
console.log("Server Response: ",response.output.text[0]);
if (context == null)
{//if user is new - output the message and number
contexts.push({'from': number, 'context': response.context});
} else
{
contexts[contextIndex].context = response.context;
}
}
});
res.send('');
});
app.listen(1000, function () { //waiting for the call on that port
console.log(''); // when it boots up, this message will appear to indicate that the program is running
});
|
fd6f6f7a52a314efe554d2fff27944d27e82bc8b
|
[
"JavaScript"
] | 1 |
JavaScript
|
egorsemeniak/NE-TXT-Code
|
e7ce74a36a0ca63db08d074c160d75d9803fe033
|
6e64c1969e77bb68e87088ad4efc40877bc1a4f4
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
var spawn = require('child_process').spawn;
var cli = require('../');
var HUGO_DEFAULT_VERSION = process.env.HUGO_VERSION || '0.37.1';
var CONFIG_FILE = 'hugo-version.json';
var args = process.argv;
if (/node(\.exe)?$|iojs$|nodejs$/.test(args[0])) {
args = args.slice(2);
}
var options = {
verbose: args.find((a) => /-([^\s]*v[^\s]*|-verbose)/.test(a))
};
var config;
var version;
var fs = require('fs');
if (fs.existsSync(CONFIG_FILE)) {
config = fs.readFileSync(CONFIG_FILE);
config = JSON.parse(config);
if (config.hasOwnProperty('hugo')) {
version = config.hugo;
} else {
console.log("Property 'hugo' not found: check hugo-version.json");
console.log("Make sure file follows pattern: { \"hugo\":\"0.40.1\" }");
console.log("Setting defualt: 0.37.1");
console.log();
version = HUGO_DEFAULT_VERSION;
}
if (config.hasOwnProperty("source_location")) {
args.push('-s');
args.push(config.source_location);
}
} else {
console.log("File not found: check that hugo-version.json exists in root directory");
console.log("Setting defualt: 0.37.1");
console.log();
version = HUGO_DEFAULT_VERSION;
}
cli.withHugo(options, version, function(err, hugoPath) {
if (err) {
console.error('failed to grab hugo :-(');
console.error(err);
process.exit(1);
}
spawn(hugoPath, args, { stdio: 'inherit' });
});
<file_sep>'use strict';
var path = require('path'),
fs = require('fs'),
request = require('request'),
decompress = require('decompress'),
semver = require('semver');
var util = require('util');
var HUGO_BASE_URL = 'https://github.com/gohugoio/hugo/releases/download',
HUGO_MIN_VERSION = '0.20.0';
var TARGET = {
platform: process.platform,
arch: process.arch
};
var PLATFORM_LOOKUP = {
'darwin': 'macOS',
'freebsd': 'FreeBSD',
'linux': 'Linux',
'openbsd': 'OpenBSD',
'win32': 'Windows'
};
function download(url, target, callback) {
var fileStream = fs.createWriteStream(target);
request(url)
.on('error', callback)
.on('end', callback)
.pipe(fileStream);
}
function extract(archivePath, destPath, installDetails) {
var executableName = 'hugo' + installDetails.executableExtension;
return decompress(archivePath, destPath,
{
strip: 1,
map: file => {
if (path.basename(file.path) == executableName) {
file.path = installDetails.executableName;
}
return file;
}
});
}
/**
* Return the installation / download details for the given hugo version.
*
* @param {String} version
* @return {Object}
*/
function getDetails(version, target) {
var arch_exec = '386',
arch_dl = '-32bit',
platform = target.platform,
archiveExtension = '.tar.gz',
executableExtension = '';
if (/x64/.test(target.arch)) {
arch_exec = 'amd64'
arch_dl = '-64bit';
} else if (/arm/.test(target.arch)) {
arch_exec = 'arm'
arch_dl = '_ARM'
}
if (/win32/.test(platform)) {
platform = 'windows';
executableExtension = '.exe';
archiveExtension = '.zip';
}
var baseName = 'hugo_${version}'.replace(/\$\{version\}/g, version);
var executableName =
'${baseName}_${platform}_${arch}${executableExtension}'
.replace(/\$\{baseName\}/g, baseName)
.replace(/\$\{platform\}/g, platform)
.replace(/\$\{arch\}/g, arch_exec)
.replace(/\$\{executableExtension\}/g, executableExtension);
var archiveName =
'${baseName}_${platform}${arch}${archiveExtension}'
.replace(/\$\{baseName\}/g, baseName)
.replace(/\$\{platform\}/g, PLATFORM_LOOKUP[target.platform])
.replace(/\$\{arch\}/g, arch_dl)
.replace(/\$\{archiveExtension\}/g, archiveExtension);
var downloadLink =
'${baseUrl}/v${version}/${archiveName}'
.replace(/\$\{baseUrl\}/g, HUGO_BASE_URL)
.replace(/\$\{version\}/g, version)
.replace(/\$\{archiveName\}/g, archiveName);
return {
archiveName: archiveName,
executableName: executableName,
downloadLink: downloadLink,
executableExtension: executableExtension
};
}
/**
* Ensure the given version of hugo is installed before
* passing (err, executablePath) to the callback.
*
* @param {Object} options
* @param {Function} callback
*/
function withHugo(options, version, callback) {
if (typeof options === 'function') {
callback = options;
options = '';
}
var verbose = options.verbose;
verbose && debug('target=' + util.inspect(TARGET));
if (semver.lt(version, HUGO_MIN_VERSION)) {
console.error('hugo-cli works with hugo@^' + HUGO_MIN_VERSION + ' only.')
console.error('you requested hugo@' + version + '!');
return callback(new Error('incompatible with hugo@' + version));
}
version = (version.endsWith('.0')) ? version.slice(0, -2) : version;
var pwd = __dirname;
var installDetails = getDetails(version, TARGET);
var installDirectory = path.join(pwd, 'tmp');
var archivePath = path.join(installDirectory, installDetails.archiveName),
executablePath = path.join(installDirectory, installDetails.executableName);
verbose && debug('searching executable at <' + executablePath + '>');
if (fs.existsSync(executablePath)) {
verbose && debug('found!');
return callback(null, executablePath);
}
console.log('hugo not downloaded yet. attempting to grab it...');
var mkdirp = require('mkdirp');
// ensure directory exists
mkdirp.sync(installDirectory);
verbose && debug('downloading archive from <' + installDetails.downloadLink + '>');
download(installDetails.downloadLink, archivePath, function(err) {
var extractPath = path.dirname(archivePath);
if (err) {
console.error('failed to download hugo: ' + err);
return callback(err);
}
console.log('fetched hugo v' + version);
console.log('extracting archive...');
extract(archivePath, extractPath, installDetails).then(function () {
verbose && debug('extracted archive to <' + extractPath + '>');
if (!fs.existsSync(executablePath)) {
console.error('executable <' + executablePath + '> not found');
console.error('please report this as a bug');
throw new Error('executable not found');
}
console.log('we got hugo, let\'s go!');
console.log();
callback(null, executablePath);
}, function (err) {
console.error('failed to extract: ' + err);
callback(err);
});
});
}
function debug(message) {
console.log('DEBUG ' + message);
}
module.exports.getDetails = getDetails;
module.exports.withHugo = withHugo;
<file_sep>var cli = require('../');
var assert = require('assert');
var util = require('util');
describe('getDetails', function() {
function verify(version, env, expectedDetails) {
it('hugo@' + version + ', env=' + util.inspect(env), function() {
// when
var actualDetails = cli.getDetails(version, env);
// then
assert.deepEqual(actualDetails, expectedDetails);
});
}
verify('0.37.1', { platform: 'linux', arch: 'x64' }, {
archiveName: 'hugo_0.37.1_Linux-64bit.tar.gz',
downloadLink: 'https://github.com/gohugoio/hugo/releases/download/v0.37.1/hugo_0.37.1_Linux-64bit.tar.gz',
executableExtension: '',
executableName: 'hugo_0.37.1_linux_amd64'
});
verify('0.37.1', { platform: 'darwin', arch: 'x64' }, {
archiveName: 'hugo_0.37.1_macOS-64bit.tar.gz',
downloadLink: 'https://github.com/gohugoio/hugo/releases/download/v0.37.1/hugo_0.37.1_macOS-64bit.tar.gz',
executableExtension: '',
executableName: 'hugo_0.37.1_darwin_amd64'
});
verify('0.37.1', { platform: 'win32', arch: 'x64' }, {
archiveName: 'hugo_0.37.1_Windows-64bit.zip',
downloadLink: 'https://github.com/gohugoio/hugo/releases/download/v0.37.1/hugo_0.37.1_Windows-64bit.zip',
executableExtension: '.exe',
executableName: 'hugo_0.37.1_windows_amd64.exe'
});
verify('0.37.1', { platform: 'win32', arch: 'x32' }, {
archiveName: 'hugo_0.37.1_Windows-32bit.zip',
downloadLink: 'https://github.com/gohugoio/hugo/releases/download/v0.37.1/hugo_0.37.1_Windows-32bit.zip',
executableExtension: '.exe',
executableName: 'hugo_0.37.1_windows_386.exe'
});
});
<file_sep># hugo-cli (Custom branch)
A simple Node wrapper around [hugo, the static site generator](http://gohugo.io). It fetches the right hugo executable before piping all provided command line arguments to it.
### Add to a project
With `yarn add https://github.com/UXSoc/hugo-cli/archive/0.6.2.tar.gz` in terminal
or `npm install --save-dev https://github.com/UXSoc/hugo-cli/archive/0.6.2.tar.gz`
## Installing Hugo
The first time this is run, it installs hugo into */node_modules/.bin* (It continues to run hugo after installing)
The default version is 0.37.1, but it will install the version defined in *hugo-version.json* which should be placed in the same directory as *package.lock*. The hugo config file is from source_location, the default is the same location as yarn.
Use the following inside *hugo-version.json*:
format: `{ "hugo":"version number", "source_location": "path" }`
example: `{ "hugo":"0.40.1", "source_location": "../../" }`
## Usage
With yarn: `yarn hugo`
```bash
> hugo -h
hugo not downloaded yet. attempting to grab it...
decompressing hugo...
we got it, let's go!
hugo is the main command, used to build your Hugo site.
Hugo is a Fast and Flexible Static Site Generator built with love by spf13 and friends in Go.
Complete documentation is available at http://gohugo.io
Usage:
hugo [flags]
hugo [command]
...
```
## License
MIT
## About
Modified by <NAME>: https://github.com/jhburns.
For UX Society and general use.
<file_sep># 0.6.2 (Custom)
* down reads in source_location from config file to set the location of hugo's real config file
# 0.6.1 (Custom)
* down checks for config file first, added more info to README
# 0.6.0 (Custom)
* change hugo version (0.30.2 -> 0.37.1)
# 0.5.4
* fix download of hugo releases on Mac OS
# 0.5.3
* verify executable exists post extraction
# 0.5.2
* print debug output on `--verbose` or `-v`
# 0.5.1
* the `0.5.0` release with actual changes :heart:
# 0.5.0
* allow downloading of newer Hugo versions (>= 0.20)
* set default Hugo version to 0.30.2
# 0.4.2
* fix executable detection on Windows
# 0.4.1
* fix extraction on Windows
# 0.4.0
* support hugo version 0.18.1 and above
# 0.3.2
* handle environments with node installed as `nodejs`
# 0.3.1
* fix executable not found on Windows
# 0.3.0
* make hugo version configurable via `process.env.HUGO_VERSION`
# ...
Check `git log` for earlier history.
|
d09271265531f98ddd8d0c46d411b9df24383a12
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
UXSoc/hugo-cli
|
29595e98314a14d4610d8b2ef7330c743e036570
|
cb794538ea1dee949fd7e1ecbb20ef7e47636302
|
refs/heads/master
|
<file_sep>cmake_minimum_required(VERSION 2.8)
project(catch-mini)
# Enable C++11:
set(CMAKE_CXX_STANDARD 11)
# Define sources:
set(SOURCES
src/catch.cpp
)
# Add a library with the above sources:
add_library(${PROJECT_NAME} ${SOURCES})
# Define include directories:
target_include_directories(${PROJECT_NAME}
PUBLIC ${PROJECT_SOURCE_DIR}/include
)
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#include "pt_max_pooling_2d_layer.h"
#include <array>
#include "pt_parser.h"
#include "pt_layer_data.h"
#include "pt_max.h"
namespace pt
{
namespace
{
template<class MaxType>
void maxImpl(int poolSizeY, int poolSizeX, LayerData& layerData)
{
const Tensor& in = layerData.in;
Tensor& out = layerData.out;
const auto& iw = in.getDims();
const auto& ow = out.getDims();
auto inIncY2 = int(iw[2] * iw[1]);
auto inIncY = inIncY2 * poolSizeY;
auto inIncX2 = int(iw[2]);
auto inIncX = inIncX2 * poolSizeX;
auto outInc2 = int(iw[2] * ow[1]);
auto outInc = outInc2 * int(ow[0]);
auto inData = in.getData().data();
auto outData = const_cast<Tensor::Type*>(out.getData().data());
MaxType max;
int its = outInc / outInc2;
int taskEnd = its;
for(auto outIt = outData, outEnd = outData + (taskEnd * outInc2);
outIt != outEnd; outIt += outInc2)
{
auto inIt = inData;
inData += inIncY;
for(auto outIt2 = outIt, outEnd2 = outIt + outInc2; outIt2 != outEnd2; outIt2 += inIncX2)
{
for(auto inIt2 = inIt, inEnd2 = inIt + inIncY; inIt2 != inEnd2; inIt2 += inIncY2)
{
for(auto inIt3 = inIt2, inEnd3 = inIt2 + inIncX; inIt3 != inEnd3; inIt3 += inIncX2)
{
max(&*inIt3, &*outIt2, inIncX2);
}
}
inIt += inIncX;
}
}
}
}
std::unique_ptr<MaxPooling2DLayer> MaxPooling2DLayer::create(std::istream& stream)
{
unsigned int poolSizeY = 0;
if(! Parser::parse(stream, poolSizeY))
{
PT_LOG_ERROR << "Pool size Y parse failed" << std::endl;
return std::unique_ptr<MaxPooling2DLayer>();
}
unsigned int poolSizeX = 0;
if(! Parser::parse(stream, poolSizeX))
{
PT_LOG_ERROR << "Pool size X parse failed" << std::endl;
return std::unique_ptr<MaxPooling2DLayer>();
}
return std::unique_ptr<MaxPooling2DLayer>(new MaxPooling2DLayer(int(poolSizeY), int(poolSizeX)));
}
bool MaxPooling2DLayer::apply(LayerData& layerData) const
{
const Tensor& in = layerData.in;
const auto& iw = in.getDims();
if(iw.size() != 3)
{
PT_LOG_ERROR << "Input tensor dims count must be 3" <<
" (input dims: " << VectorPrinter<std::size_t>{ iw } << ")" << std::endl;
return false;
}
Tensor& out = layerData.out;
out.resize(iw[0] / std::size_t(_poolSizeY), iw[1] / std::size_t(_poolSizeX), iw[2]);
out.fill(-std::numeric_limits<Tensor::Type>::infinity());
auto tensorSize = int(iw[2]);
if(PT_LOOP_UNROLLING_ENABLE && tensorSize && tensorSize % (Tensor::VectorSize * 2) == 0)
{
maxImpl<VectorMax>(_poolSizeY, _poolSizeX, layerData);
}
else if(tensorSize && tensorSize % Tensor::VectorSize == 0)
{
maxImpl<VectorMax>(_poolSizeY, _poolSizeX, layerData);
}
else
{
maxImpl<ScalarMax>(_poolSizeY, _poolSizeX, layerData);
}
return true;
}
}
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#ifndef PT_LINEAR_ACTIVATION_LAYER_H
#define PT_LINEAR_ACTIVATION_LAYER_H
#include "pt_activation_layer.h"
namespace pt
{
class LinearActivationLayer : public ActivationLayer
{
public:
using ActivationLayer::apply;
LinearActivationLayer() = default;
void apply(Tensor&) const final
{
}
};
}
#endif
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#include "pt_global_max_pooling_2d_layer.h"
#include <array>
#include "pt_parser.h"
#include "pt_layer_data.h"
#include "pt_max.h"
namespace pt
{
namespace
{
void maxImpl(LayerData& layerData)
{
const Tensor& in = layerData.in;
Tensor& out = layerData.out;
const auto& iw = in.getDims();
const auto& ow = out.getDims();
auto inData = in.getData().data();
auto outData = const_cast<Tensor::Type*>(out.getData().data());
size_t its = ow[2];
for (std::size_t z = 0; z < its; z++ )
{
Tensor::Type val = std::numeric_limits<Tensor::Type>::lowest();
for (std::size_t x = 0; x < iw[0]; ++x)
{
for (std::size_t y = 0; y < iw[1]; ++y)
{
val = std::max(val, in(x, y, z));
}
}
out(0, 0, z) = val;
}
}
}
std::unique_ptr<GlobalMaxPooling2DLayer> GlobalMaxPooling2DLayer::create(std::istream& stream)
{
return std::unique_ptr<GlobalMaxPooling2DLayer>(new GlobalMaxPooling2DLayer());
}
bool GlobalMaxPooling2DLayer::apply(LayerData& layerData) const
{
const Tensor& in = layerData.in;
const auto& iw = in.getDims();
if(iw.size() != 3)
{
PT_LOG_ERROR << "Input tensor dims count must be 3" <<
" (input dims: " << VectorPrinter<std::size_t>{ iw } << ")" << std::endl;
return false;
}
Tensor& out = layerData.out;
out.resize(1, 1, iw[2]);
out.fill(-std::numeric_limits<Tensor::Type>::infinity());
maxImpl(layerData);
out.flatten();
return true;
}
}
<file_sep>cmake_minimum_required(VERSION 2.8)
project(kerasify-project)
# Add library subdirectory:
add_subdirectory(lib)
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#ifndef PT_INPUT_LAYER_H
#define PT_INPUT_LAYER_H
#include "pt_layer.h"
#include "pt_tensor.h"
#include <string>
namespace pt
{
class InputLayer : public Layer
{
public:
static std::unique_ptr<InputLayer> create(std::istream& stream);
bool apply(LayerData& layerData) const final;
using DimsVector = std::vector<std::size_t>;
// protected:
//
// std::string _name;
// DimsVector _dims;
//InputLayer(const std::string& input_name, const DimsVector& input_dims)
// : _name(input_name), _dims(input_dims)
//{
//}
InputLayer(){}
};
}
#endif
<file_sep>cmake_minimum_required(VERSION 2.8)
project(frugally-deep-project)
# Add library subdirectory:
add_subdirectory(lib)
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#ifndef PT_CONFIG_H
#define PT_CONFIG_H
namespace pt
{
class Config
{
};
}
#endif
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#include "pt_conv_2d_layer.h"
#include <array>
#include "pt_layer_data.h"
#include "pt_multiply_add.h"
#include "pt_logger.h"
namespace pt
{
namespace
{
template<class MultiplyAddType>
void multiplyAddImpl(const Tensor& weights, const Tensor& biases, LayerData& layerData)
{
const Tensor& in = layerData.in;
Tensor& out = layerData.out;
const auto& iw = in.getDims();
const auto& ww = weights.getDims();
const auto& ow = out.getDims();
auto outInc = int(ow[2]);
auto wSize = int(ww[0] * ww[1] * ww[2] * ww[3]);
auto wInc = int(ww[1] * ww[2] * ww[3]);
auto wInc2 = int(ww[2] * ww[3]);
auto tx = int(ow[1]);
auto ty = int(ow[0]);
auto inIncX = int(ww[3]);
auto inIncY = int(ww[3] * iw[1]);
auto inBegin = in.getData().data();
auto outBegin = const_cast<Tensor::Type*>(out.getData().data());
auto wBegin = weights.getData().data();
auto bBegin = biases.getData().data();
MultiplyAddType multiplyAdd;
for(int y = 0; y != ty; ++y)
{
for(int x = 0; x != tx; ++x)
{
auto inIt = inBegin + y * inIncY + x * inIncX;
auto outIt = outBegin + y * tx * outInc + x * outInc;
auto bIt = bBegin;
for(auto wIt = wBegin, wEnd = wBegin + wSize; wIt != wEnd; wIt += wInc)
{
auto inIt2 = inIt;
*outIt = *bIt;
for(auto wIt2 = wIt, wEnd2 = wIt + wInc; wIt2 != wEnd2; wIt2 += wInc2)
{
*outIt += multiplyAdd(&*inIt2, &*wIt2, wInc2);
inIt2 += inIncY;
}
++outIt;
++bIt;
}
}
}
}
}
std::unique_ptr<Conv2DLayer> Conv2DLayer::create(std::istream& stream)
{
auto weights = Tensor::create(4, stream);
if(! weights)
{
PT_LOG_ERROR << "Weights tensor parse failed" << std::endl;
return std::unique_ptr<Conv2DLayer>();
}
auto biases = Tensor::create(1, stream);
if(! biases)
{
PT_LOG_ERROR << "Biases tensor parse failed" << std::endl;
return std::unique_ptr<Conv2DLayer>();
}
auto activation = ActivationLayer::create(stream);
if(! activation)
{
PT_LOG_ERROR << "Activation layer parse failed" << std::endl;
return std::unique_ptr<Conv2DLayer>();
}
return std::unique_ptr<Conv2DLayer>(new Conv2DLayer(std::move(*weights), std::move(*biases),
std::move(activation)));
}
bool Conv2DLayer::apply(LayerData& layerData) const
{
Tensor& in = layerData.in;
const auto& iw = in.getDims();
if(iw.size() != 3)
{
PT_LOG_ERROR << "Input tensor dims count must be 3" <<
" (input dims: " << VectorPrinter<std::size_t>{ iw } << ")" << std::endl;
return false;
}
const auto& ww = _weights.getDims();
if(iw[2] != ww[3])
{
PT_LOG_ERROR << "Input tensor dims[2] must be the same as weights dims[3]" <<
" (input dims: " << VectorPrinter<std::size_t>{ iw } << ")" <<
" (weights dims: " << VectorPrinter<std::size_t>{ ww } << ")" << std::endl;
return false;
}
auto offsetY = ww[1] - 1;
auto offsetX = ww[2] - 1;
layerData.in.pad(offsetY / 2, offsetX / 2, 0);
Tensor& out = layerData.out;
out.resize(iw[0] - offsetY, iw[1] - offsetX, ww[0]);
auto tensorSize = int(ww[2] * ww[3]);
if(PT_LOOP_UNROLLING_ENABLE && tensorSize && tensorSize % (Tensor::VectorSize * 2) == 0)
{
multiplyAddImpl<Vector2MultiplyAdd>(_weights, _biases, layerData);
}
else if(tensorSize && tensorSize % Tensor::VectorSize == 0)
{
multiplyAddImpl<VectorMultiplyAdd>(_weights, _biases, layerData);
}
else
{
multiplyAddImpl<ScalarMultiplyAdd>(_weights, _biases, layerData);
}
_activation->apply(out);
return true;
}
Conv2DLayer::Conv2DLayer(Tensor&& weights, Tensor&& biases,
std::unique_ptr<ActivationLayer>&& activation) noexcept :
_weights(std::move(weights)),
_biases(std::move(biases)),
_activation(std::move(activation))
{
}
}
<file_sep>/*
* pocket-tensor (c) 2018 <NAME> <EMAIL>
* Kerasify (c) 2016 <NAME>
*
* MIT License, see LICENSE file.
*/
#include "pt_input_layer.h"
#include "pt_layer_data.h"
namespace pt
{
bool InputLayer::apply(LayerData& layerData) const
{
layerData.out = layerData.in;
return true;
}
std::unique_ptr<InputLayer> InputLayer::create(std::istream& stream)
{
return std::unique_ptr<InputLayer>(new InputLayer());
}
}
|
c1a6025e2e50dcc7529f4689b25e08fb0c6e9fa0
|
[
"CMake",
"C++"
] | 10 |
CMake
|
smr-nn/pocket-tensor
|
0779a0fd0948cedd625f19cfc3ff3f5f14a551ef
|
d8c7da47cb0beeeafdf09d32f8f60faa2074bf35
|
refs/heads/master
|
<repo_name>prasang7/react-native-maps-app<file_sep>/index.android.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ToastAndroid
} from 'react-native';
import MapView, { Marker } from 'react-native-maps';
let lat1 = 0, lon1 = 0, lat2 = 0, lon2 = 0;
let counter = 0;
let distance = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function setCoordinates(myCounter, lat, lon) {
if (myCounter == 0) {
lat1 = lat;
lon1 = lon;
}
if (myCounter == 1) {
lat2 = lat;
lon2 = lon;
ToastAndroid.show('Distance: ' + distanceCalc(lat1, lon1, lat2, lon2) + ' km', ToastAndroid.LONG)
}
}
function distanceCalc(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
export default class SRTask extends Component {
constructor() {
super();
this.state = {
markers: []
}
this.handlePress = this.handlePress.bind(this);
}
handlePress(e) {
this.setState({
markers: [
...this.state.markers,
{
coordinate: e.nativeEvent.coordinate,
cost: 'Marker ' + (counter + 1),
}
]
})
setCoordinates(counter,
e.nativeEvent.coordinate.latitude, e.nativeEvent.coordinate.longitude);
counter++;
}
render() {
return (
// creating map view
<MapView
style = {styles.container}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
// what to do when map is pressed
onPress = {this.handlePress}
>
{ this.state.markers.map((marker) => {
return (
<Marker { ...marker } >
<View style={styles.marker}>
<Text>{ marker.cost } </Text>
</View>
</Marker>
)
})}
</MapView>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'flex-end', //map will take up the entire screen
alignItems: 'center',
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
marker: {
backgroundColor: "#ffffff",
padding: 5,
borderRadius: 5,
borderColor: "#ff0000",
borderWidth: 2
},
});
AppRegistry.registerComponent('SRTask', () => SRTask);
|
7fe9f1ff30a44476827f80d939140421a6d85e8a
|
[
"JavaScript"
] | 1 |
JavaScript
|
prasang7/react-native-maps-app
|
fe536d6a03cbcfdd233c74c8043371909e3b6684
|
a3455ce6550d90bcbf0e9b3ee850b8b246dcb102
|
refs/heads/master
|
<repo_name>Mridul-7/SSH-login<file_sep>/sshlogin.py
#!/usr/bin/python
import pexpect # allows to welcome all the processes in ssh login
PROMPT=['# ','>>> ','> ','\$ ']
def send_command(child,command):
child.sendline(command)
child.expect(PROMPT)
print(child.before) #print output of command we send to target system
def connect(user,host,password):
ssh_newkey='Are you sure want to continue connecting'
connStr='ssh ' +user+ '@' +host #ssh [email protected]
child=pexpect.spawn(connStr)
ret=child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword:'])
#if it returns 0 means we were not able to connect & if it returns 1 connection is successful
if ret==0:
print('[-] error connecting')
return
if ret==1:
child.sendline('yes') #send yes string to ssh_newkey
ret=child.expect([pexpect.TIMEOUT,'[P|p]assword'])
if ret==0:
print('[-] error connecting')
return
child.sendline(password)
child.expect(PROMPT)
return child
def main():
host=input('Enter host ip:')
user=input('enter SSH username:')
password=input('enter SSH password:')
child=connect(user,host,password)
send_command(child,'pwd')
main()
|
a18268d24a1d357b00a852da4d067df57157615a
|
[
"Python"
] | 1 |
Python
|
Mridul-7/SSH-login
|
1f1679f277211afceb928906c63a70c84a59bb90
|
2ee71dd9f70159ab45d20e3fbaf2744e3aedce72
|
refs/heads/master
|
<repo_name>stevecormier/stephencormier<file_sep>/js/index.js
$(function() {
$("img", "ul").fadeOut("slow");
});
$("li").hover(
function() {
console.log("in");
$(".project", this).fadeOut( "slow" );
$("img", this).fadeIn("slow");
}, function(){
$(".project", this).fadeIn( "slow" );
$("img", this).fadeOut("slow");
}
);
|
929ab8fac37bc26be4c4b8d015eb79c59cbd86df
|
[
"JavaScript"
] | 1 |
JavaScript
|
stevecormier/stephencormier
|
22edc7ae8f237daa3d984cb327e8fd5543b16485
|
bc3162fbafec5df90ddbfb6d59d3e4f84114116c
|
refs/heads/master
|
<repo_name>tristanfrn/ReadyApp<file_sep>/app/src/main/java/com/ready/readyapp/ListActivity.java
package com.ready.readyapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.github.curioustechizen.ago.RelativeTimeTextView;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseAnonymousUtils;
import com.parse.ParseFacebookUtils;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.software.shell.fab.ActionButton;
import org.apache.http.HttpConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ListActivity extends FragmentActivity implements EditDialogFragment.EditDialogListener, View.OnClickListener {
ArrayList listPerson;
ListView lvPerson;
public void ButtonOnClick(View v) {
switch (v.getId()) {
case R.id.edit_button:
Bundle extras = getIntent().getExtras();
showEditDialog(extras);
break;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
overridePendingTransition(R.anim.pushdownin, R.anim.pushdownout);
setContentView(R.layout.activity_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String friends = extras.getString("friends");
String profile = extras.getString("profile");
String newUser = extras.getString("newUser");
if(newUser.equals("true")) newProfile(profile);
else updateProfile(profile, null, null, null);
updateFriendsList(friends);
}
}
public static String getFacebookPictureUrl(String facebookId){
return "https://graph.facebook.com/" + facebookId + "/picture?type=large";
}
public static Drawable getPictureForFacebookId(String url) {
Drawable picture = null;
InputStream inputStream = null;
try {
inputStream = new URL(url).openStream();
HttpURLConnection.setFollowRedirects(true);
} catch (Exception e) {
e.printStackTrace();
return null;
}
picture = Drawable.createFromStream(inputStream, "facebook-pictures");
return picture;
}
public void updateViewUser(ParseUser parseUser){
Drawable profilePicture;
profilePicture = getPictureForFacebookId(parseUser.get("profile_pic").toString());
View includeLayout = findViewById(R.id.userLayout);
ImageView profileView = (ImageView) includeLayout.findViewById(R.id.picture);
TextView textStatus = (TextView) includeLayout.findViewById(R.id.status);
profileView.setBackgroundDrawable(profilePicture);
textStatus.setText(parseUser.get("status").toString());
ActionButton actionButton = (ActionButton) findViewById(R.id.action_button);
if(parseUser.get("available") == true){
actionButton.setImageDrawable(getResources().getDrawable(R.drawable.off));
actionButton.setButtonColor(getResources().getColor(R.color.color_red));
}
else{
actionButton.setImageDrawable(getResources().getDrawable(R.drawable.on));
actionButton.setButtonColor(getResources().getColor(R.color.color_primary));
}
actionButton.show();
actionButton.setOnClickListener(this);
RelativeTimeTextView timeStatus = (RelativeTimeTextView) includeLayout.findViewById(R.id.time);
timeStatus.setReferenceTime(parseUser.getUpdatedAt().getTime());
}
public void updateProfile(String profile, String status, Boolean available, JSONArray unsubscribedFrom) {
final ParseUser parseUser = ParseUser.getCurrentUser();
try {
final JSONObject dataProfile = new JSONObject(profile);
parseUser.put("name",dataProfile.getString("name"));
if(status != null) parseUser.put("status", status);
if(available != null) parseUser.put("available", available);
if(unsubscribedFrom != null) parseUser.put("unsubscribed_from", unsubscribedFrom);
updateViewUser(parseUser);
parseUser.saveInBackground();
}
catch (JSONException e) {
e.printStackTrace();
}
}
public void newProfile(String profile) {
final ParseUser parseUser = ParseUser.getCurrentUser();
try {
final JSONObject dataProfile = new JSONObject(profile);
parseUser.put("name",dataProfile.getString("name"));
parseUser.put("fbId", dataProfile.getString("id"));
parseUser.put("status", this.getString(R.string.default_status));
parseUser.put("profile_pic", getFacebookPictureUrl(dataProfile.getString("id")));
parseUser.put("available", true);
parseUser.put("unsubscribed_from", new JSONArray());
updateViewUser(parseUser);
parseUser.saveInBackground();
}
catch (JSONException e) {
e.printStackTrace();
}
}
static <T> T[] append(T[] arr, T element) {
final int N = arr.length;
arr = Arrays.copyOf(arr, N + 1);
arr[N] = element;
return arr;
}
public void makeToast(String message){
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void updateFriendsList(String friends) {
lvPerson = (ListView) findViewById(R.id.listPerson);
listPerson = new ArrayList();
JSONArray dataFriends = null;
try {
dataFriends = new JSONObject(friends).getJSONObject("friends").getJSONArray("data");
ArrayList<String> friendsIds = new ArrayList<String>();
for (int i = 0; i < dataFriends.length(); i++) {
friendsIds.add(dataFriends.getJSONObject(i).getString("id"));
}
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContainedIn("fbId", friendsIds);
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> listUsers, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < listUsers.size(); i++) {
Drawable profilePicture;
Drawable available = null;
if(listUsers.get(i).get("available").toString().equals("true")){
available = getResources().getDrawable(R.drawable.btn_green);
}
if(listUsers.get(i).get("available").toString().equals("false")){
Log.d("Ready", listUsers.get(i).get("available").toString());
available = getResources().getDrawable(R.drawable.btn_red);
}
String status;
if(listUsers.get(i).get("status").toString() != null) status = listUsers.get(i).get("status").toString();
else status = "";
profilePicture = getPictureForFacebookId(listUsers.get(i).get("profile_pic").toString());
listPerson.add(new Person(i+1, listUsers.get(i).get("name").toString(), status, profilePicture, available, listUsers.get(i).getUpdatedAt().getTime()));
}
lvPerson.setAdapter(new PersonListAdapter(getApplicationContext(), listPerson));
} else {
makeToast(getCurrentActivity().getString(R.string.fetch_friends_error));
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@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_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
LoginManager.getInstance().logOut();
finish();
}
return super.onOptionsItemSelected(item);
}
public void showEditDialog(Bundle extras) {
DialogFragment dialog = new EditDialogFragment();
Log.d("Ready", extras.toString());
dialog.setArguments(extras);
dialog.show(getFragmentManager(), "EditDialogFragment");
}
public void onResume(){
super.onResume();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String friends = extras.getString("friends");
updateFriendsList(friends);
}
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.action_button){
Bundle extras = getIntent().getExtras();
String profile = null;
if (extras != null) {
profile = extras.getString("profile");
}
Log.d("Ready", ParseUser.getCurrentUser().get("available").toString());
if(ParseUser.getCurrentUser().get("available") == true) updateProfile(profile, null, false, null);
else updateProfile(profile, null, true, null);
}
}
}
<file_sep>/app/src/main/java/com/ready/readyapp/MainFragment.java
package com.ready.readyapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.parse.LogInCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.List;
/**
* Created by clement on 15/06/15.
*/
public class MainFragment extends Fragment{
private boolean isListActivityStarted = false;
private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private Profile profile;
public MainFragment(){
}
private String checkProfile(){
Profile profile = Profile.getCurrentProfile();
JSONObject dataProfile = new JSONObject();
try {
dataProfile.put("id", profile.getId());
dataProfile.put("name", profile.getName());
return dataProfile.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return dataProfile.toString();
}
private void checkFriends(AccessToken accessToken, final Boolean newUser){
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
if (object != null) startListActivity(object.toString(), newUser);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,friends");
request.setParameters(parameters);
request.executeAsync();
}
public void makeToast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
public void startListActivity(String friends, Boolean newUser){
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
Intent listActivity = new Intent(getActivity(), ListActivity.class);
String dataProfile = checkProfile();
listActivity.putExtra("friends",friends);
listActivity.putExtra("profile",dataProfile);
listActivity.putExtra("newUser",newUser.toString());
startActivity(listActivity);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(ParseUser.getCurrentUser() != null) checkFriends(AccessToken.getCurrentAccessToken(), false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_simple_login_button, container, false);
}
public void parseLogin(){
List<String> permissions = Arrays.asList("public_profile", "email");
ParseFacebookUtils.logInWithReadPermissionsInBackground(this, permissions, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
if (parseUser == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (parseUser.isNew()) {
checkFriends(AccessToken.getCurrentAccessToken(), true);
} else {
parseUser.saveInBackground();
checkFriends(AccessToken.getCurrentAccessToken(), false);
}
}
});
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
ImageView facebookButton = (ImageView) view.findViewById(R.id.facebook_button);
facebookButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
parseLogin();
}
});
}
public void onStop(){
super.onStop();
//accessTokenTracker.stopTracking();
//profileTracker.stopTracking();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//mCallbackManager.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
}
<file_sep>/app/src/main/java/com/ready/readyapp/Person.java
package com.ready.readyapp;
import android.graphics.drawable.Drawable;
/**
* Created by clement on 16/06/15.
*/
public class Person {
int id;
String name;
String status;
Long updatedAt;
Drawable picture;
Drawable online;
public Person(int id, String name, String status, Drawable picture, Drawable online, Long updatedAt) {
super();
this.id = id;
this.name = name;
this.updatedAt = updatedAt;
this.status = status;
this.picture = picture;
this.online = online;
}
public Person() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Drawable getPicture() {
return picture;
}
public void setPicture(Drawable picture) {
this.picture = picture;
}
public Drawable getOnline() {
return online;
}
public Long getUpdatedAt() {
return updatedAt;
}
public void setOnline(Drawable online) {
this.online = online;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", picture=" + picture
+ ", status=" + status + ", online=" + online + "]";
}
}
<file_sep>/README.md
# Ready App for Android
|
5c64f590cec5a6634dbd1f2f6615b2cee008074c
|
[
"Markdown",
"Java"
] | 4 |
Java
|
tristanfrn/ReadyApp
|
8bce7c48a0b238fa7ca4b4094d3062b66701e2ed
|
0cf4fe5ed9baccad052156891e8d6d6a868507eb
|
refs/heads/master
|
<repo_name>zzigsa/zzigsa<file_sep>/mypage/views.py
from django.shortcuts import render,redirect,HttpResponse,get_object_or_404
from django.contrib import auth
from first.models import User,Writer,EmailConfirm
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.conf import settings
from .forms import *
# Create your views here.
#아이디찾기 (비번찾기는 라이브러리 이용) html안만듬디자인
def id_find(request):
if request.method == "POST":
name = request.POST["user"]
email = request.POST["email"]
find_username = User.objects.filter(name=name, email=email)
username_length = len(find_username)
if username_length == 0:
return render(request, "id_find.html",{"msg":"해당되는 정보가 없습니다."})
else:
return render(request, "id_find.html",{"find_username":find_username})
return render(request, "id_find.html")
#마이페이지
@login_required
def mypage(request,id):
people=get_object_or_404(User, pk=id)
return render(request, "mypage.html",{'people':people})
#정보수정(forms.py에서 수정해야됨)
@login_required
def change_user(request):
if request.method=='POST':
form_password = ChangePasswordForm(request.user, request.POST)
form=UpdateuserForm(request.POST,instance=request.user)
if form.is_valid() and form_password.is_valid():
user = form_password.save()
update_session_auth_hash(request, user)
form.save()
return redirect('main')
else:
form_password = ChangePasswordForm(request.user)
form=UpdateuserForm(instance=request.user)
return render(request,'change_user.html',{'form':form,"form_password":form_password})
@login_required
def delete(request,id):
user=get_object_or_404(User,pk=id)
if user != request.user:
return redirect("home")
user.delete()
return redirect("home")
def favorite(request):
writers = Writer.objects.all()
return render(request, "favorite.html",{"writers":writers})
def history(request):
return render(request,"history.html")<file_sep>/first/urls.py
from django.urls import path,include
from .import views
urlpatterns = [
path('customer_login/',views.customer_login, name="customer_login"),
path('join/',views.join, name="join"),
path('enroll/<int:id>',views.enroll, name="enroll"),
path('signout/',views.signout, name="signout"),
path('confirm/', views.confirm_email, name="confirm_email"),
path('email_sent/', views.email_sent, name="email_sent"),
path('bestphoto/',views.bestphoto, name="bestphoto"),
path('recommend/',views.recommend,name="recommend"),
]<file_sep>/first/forms.py
from django import forms
from .models import User
#로그인
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password')
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control'}),
'password' : forms.PasswordInput(attrs={'class': 'form-control'}),
}
labels = {
'username': '아이디',
'password': '<PASSWORD>',
}
<file_sep>/photographer/migrations/0001_initial.py
# Generated by Django 2.1.7 on 2019-08-22 19:03
from django.db import migrations, models
import django.db.models.deletion
import imagekit.models.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
('first', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ProductRegistration',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('summary', models.CharField(max_length=400)),
('image', imagekit.models.fields.ProcessedImageField(upload_to='images/product')),
('detail', models.TextField()),
('options', models.CharField(max_length=400)),
('option_price', models.IntegerField()),
('writerid', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='first.Writer')),
],
),
migrations.CreateModel(
name='Reply',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('writer', models.CharField(max_length=20)),
('content', models.CharField(max_length=400)),
('rating', models.IntegerField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('productid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='photographer.ProductRegistration')),
],
),
]
<file_sep>/photographer/views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.utils import timezone
from first.models import User
from .models import ProductRegistration
from .forms import *
from django.contrib import auth
from first.models import User,Writer,EmailConfirm
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.conf import settings
from django.core.paginator import Paginator
# Create your views here.
#작가페이지
def photographer(request,id):
writer = get_object_or_404(Writer,pk=id)
# user = get_object_or_404(User, pk=id)
return render(request,"photographer.html",{ "writer":writer })
#좋아요
def like(request):
id = request.POST.get('pk', None) # ajax 통신을 통해서 template에서 POST방식으로 전달
writer = get_object_or_404(Writer, pk=id)
writer_like, writer_like_created = writer.like_set.get_or_create(username=request.user)
if not writer_like_created:
writer_like.delete()
message = "좋아요 취소"
else:
message = "좋아요"
context = {'like_count': writer.like_count,
'message': message,
}
return HttpResponse(json.dumps(context), content_type="application/json")
# # 상품등록
@login_required
def upload(request, id):
if request.method == 'POST':
title = request.POST["title"]
summary = request.POST["summary"]
image = request.FILES["image"]
detail = request.POST["detail"]
options = request.POST["options"]
option_price = request.POST["option_price"]
writer_account = get_object_or_404(Writer, userid=id)
product = ProductRegistration.objects.create(writerid=writer_account,title=title,summary=summary,image=image,detail=detail,options=options,option_price=option_price)
# login(request,writer_account)
return redirect(reverse('list'))
# if product.writer != request.user.writer:
# return render(request,"upload.html" ,{"msg":"작가만 등록이 가능합니다."})
# else:
# product.save()
# return redirect('home')
writer_account = get_object_or_404(User, pk=id, is_active=True)
return render(request, "upload.html",{"writer_account":writer_account})
# if request.method == 'GET':
# return render(request, "upload.html")
# elif request.method == "POST":
# title = request.POST['title']
# summary = request.POST['summary']
# image = request.FILES['image']
# detail = request.POST['detail']
# options = request.POST['options']
# option_price = request.POST['option_price']
# product = ProductRegistration.objects.create(
# title=title, summary=summary, image=image,
# detail=detail, options=options, option_price=option_price
# )
# if product.user.writer != request.user:
# return render(rqeuest,"upload.html" ,{"msg":"작가만 등록이 가능합니다."})
# else:
# product.save()
# return redirect('home')
# return redirect('home')
def list(request):
products = ProductRegistration.objects.all()
list = request.GET.get('list')
if list:
products = products.filter(title__contains = list)
paginator = Paginator(products, 9)
page = request.GET.get('page')
posts = paginator.get_page(page)
return render(request, "list.html", {"products":products, "posts":posts})
def photographeredit(request):
return render(request, "photographeredit.html")
<file_sep>/mypage/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('id_find/', views.id_find, name="id_find"),
path('mypage/<int:id>', views.mypage,name="mypage"),
path('change_user/', views.change_user, name="change_user"),
path('delete/<int:id>', views.delete,name="delete"),
path('favorite/',views.favorite, name="favorite"),
path('history/',views.history,name="history"),
]<file_sep>/product/views.py
from django.shortcuts import render
# Create your views here.
def product(request):
return render(request, 'product.html')
def productedit(request):
return render(request, 'productedit.html')<file_sep>/requirements.txt
beautifulsoup4==4.7.1
certifi==2019.6.16
chardet==3.0.4
defusedxml==0.6.0
Django==2.1.7
django-appconf==1.0.3
django-ckeditor==5.7.1
django-haystack==2.8.1
django-imagekit==4.0.2
django-js-asset==1.2.2
idna==2.8
oauthlib==3.1.0
pilkit==2.0
Pillow==6.1.0
pygame==1.9.4
PyJWT==1.7.1
python-social-auth==0.2.21
python3-openid==3.1.0
pytz==2018.9
requests==2.22.0
requests-oauthlib==1.2.0
six==1.12.0
soupsieve==1.9.1
urllib3==1.25.3
Whoosh==2.7.4
<file_sep>/photographer/urls.py
from django.urls import path, include
from .import views
urlpatterns = [
path('photographer/<int:id>', views.photographer, name="photographer"),
path('like/', views.like, name="like"),
path('uploadproduct/<int:id>', views.upload, name="upload"),
path('list/',views.list, name="list"),
# path('list/', views.upload, name="list"),
path('photographeredit/', views.photographeredit, name="photographeredit"),
path('search/', include('haystack.urls')),
]<file_sep>/zzigsa/urls.py
"""zzigsa URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
import first.views
import photographer.views
import product.views
import mypage.views
from django.conf import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('',first.views.home,name="home"),
# first에 연결된 url
path('first/',include("first.urls")),
# photographer에 연결된 url
path('photographer/',include("photographer.urls")),
# product에 연결된 url
path('product/',include("product.urls")),
# mypage에 연결된 url
path('mypage/',include("mypage.urls")),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)<file_sep>/templates/registration/password_reset_confirm.html
<style>
</style>
<p>비밀번호 변경</p>
{% if validlink %}
<form method="POST">
{% csrf_token %}
<p> <label for="id_new_password1">비밀번호</label>
<input type="password" name="<PASSWORD>" required id="<PASSWORD>password1" >
<span class="helptext"></span>
</p>
비밀번호는 다른 개인 정보와 너무 유사 할 수 없습니다.<br>
비밀번호는 8 자 이상이어야합니다.<br>
비밀번호는 일반적으로 사용되는 비밀번호 일 수 없습니다.<br>
비밀번호는 완전히 숫자 일 수 없습니다<br>
<p>
<label for="id_new_password2">비밀번호 중복</label>
<input type="password" name="<PASSWORD>password2" required id="id_<PASSWORD>password2" >
<span class="helptext"></span>
</p>
<button type="submit">변경</button>
</form>
{% else %}
<p style="color:red;">이미 변경하엿습니다</p>
<p>
<a href="{% url 'password_reset' %}">새로운 비밀번호 설정</a>
</p>
{% endif %}
<file_sep>/first/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.hashers import make_password, is_password_usable
# from ckeditor.fields import RichTextField
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFit
# Create your models here.
from photographer.models import *
#유저
class User(AbstractUser):
name = models.CharField(max_length=10)
email = models.EmailField()
# check = models.BooleanField(default=False)
is_active = models.BooleanField('active', default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_writer = models.BooleanField(default=False)
def __str__(self):
return self.name
#작가
class Writer(models.Model):
userid = models.ForeignKey('User', on_delete=models.CASCADE,null=True, blank=True)
introduce = models.TextField()
profile_image = models.ImageField(upload_to="images/profile")
camera = models.CharField(max_length=30)
camera_image = models.ImageField(upload_to="image/camera")
sns_email = models.TextField(blank=True)
image = ProcessedImageField(
upload_to="images/writer",
processors=[ResizeToFit(50,50)],
format='JPEG',
options={'quality':80}
)
like = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.userid.name
#좋아요
class Like(models.Model):
userid = models.ForeignKey('User', on_delete=models.CASCADE)
writerid = models.ForeignKey('Writer', on_delete=models.CASCADE,related_name='+',null=True, blank=True)
#예약상태
class Reservation(models.Model):
userid = models.ForeignKey('User', on_delete=models.CASCADE)
productid = models.ForeignKey('photographer.ProductRegistration', on_delete=models.CASCADE)
progress = models.IntegerField() # 0이면 예약대기 1이면 예약승인 2이면 구매이력에 추가
#이메일 전송
class EmailConfirm(models.Model):
user = models.OneToOneField('User', on_delete=models.CASCADE)
key = models.CharField(max_length=60)
is_confirmed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True,null=True, blank=True)
@property
def created_at_korean_time(self):
korean_timezone = timezone(settings.TIME_ZONE)
return self.created_at.astimezone(korean_timezone)<file_sep>/photographer/models.py
from django.db import models
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFit
from django.core.validators import MaxValueValidator, MinValueValidator
from first.models import *
# 상품 등록
class ProductRegistration(models.Model):
title = models.CharField(max_length=200)
summary = models.CharField(max_length=400)
image = ProcessedImageField(
upload_to="images/product",
processors=[ResizeToFit(400,400)],
format='JPEG',
options={'quality':80}
)
detail = models.TextField()
options = models.CharField(max_length=400)
option_price = models.IntegerField()
writerid = models.ForeignKey('first.Writer', on_delete=models.CASCADE,null=True, blank=True)
def __str__(self):
return self.title
#댓글
class Reply(models.Model):
productid = models.ForeignKey('ProductRegistration', on_delete=models.CASCADE)
writer = models.CharField(max_length=20)
content = models.CharField(max_length=400)
rating = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
@property
def created_at_korean_time(self):
korean_timezone = timezone(settings.TIME_ZONE)
return self.created_at.astimezone(korean_timezone)
# #옵션
# class Option(models.Model):
# productid = models.ForeignKey('ProductRegistration', on_delete=models.CASCADE)
# content = models.CharField(max_length=400)
# price = models.IntegerField() <file_sep>/mypage/forms.py
from django import forms
from first.models import User,Writer
from django.contrib.auth import password_validation,get_user_model
class UpdateuserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'name', 'email')
widgets= {
'username': forms.TextInput(attrs={'class': 'form-control'}),
'name' : forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.EmailInput(attrs={'class': 'form-control'}),
}
labels = {
'username': '아이디',
'name': '이름',
'email': '이메일',
}
class ChangePasswordForm(forms.Form):
error_messages = {
'password_mismatch': ('비밀번호가 일치하지 않습니다.'),
}
required_css_class = 'required'
password1 = forms.CharField(
label=("비밀번호"),
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password', 'autofocus': True}),
strip=False,
help_text=password_validation.password_validators_help_text_html(),
# 조건
)
password2 = forms.CharField(
label=("비밀번호 중복"),
widget=forms.PasswordInput(attrs={'autocomplete': 'new-<PASSWORD>'}),
strip=False,
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2:
if password1 != password2:
raise forms.ValidationError(
self.error_messages['비밀번호가 일치하지 않습니다.'],
code='password_mismatch',
)
password_validation.validate_password(password2, self.user)
return password2
def save(self, commit=True):
"""Save the new password."""
password = self.cleaned_data["password1"]
self.user.set_password(password)
if commit:
self.user.save()
return self.user
@property
def changed_data(self):
data = super().changed_data
for name in self.fields:
if name not in data:
return []
return ['password']<file_sep>/photographer/migrations/0002_auto_20190822_0102.py
# Generated by Django 2.1.7 on 2019-08-21 16:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('photographer', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='productregistration',
options={'ordering': ['-id']},
),
]
<file_sep>/first/admin.py
from django.contrib import admin
from first.models import *
admin.site.register(User)
admin.site.register(Writer)
admin.site.register(EmailConfirm)
admin.site.register(Like)
admin.site.register(Reservation)<file_sep>/product/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('product', views.product, name='product'),
path('productedit', views.productedit, name='productedit'),
]<file_sep>/first/migrations/0001_initial.py
# Generated by Django 2.1.7 on 2019-08-22 19:03
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import imagekit.models.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('name', models.CharField(max_length=10)),
('email', models.EmailField(max_length=254)),
('is_active', models.BooleanField(default=True, verbose_name='active')),
('is_staff', models.BooleanField(default=False)),
('is_superuser', models.BooleanField(default=False)),
('is_writer', models.BooleanField(default=False)),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='EmailConfirm',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=60)),
('is_confirmed', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True, null=True)),
],
),
migrations.CreateModel(
name='Like',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Reservation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('progress', models.IntegerField()),
],
),
migrations.CreateModel(
name='Writer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('introduce', models.TextField()),
('profile_image', models.ImageField(upload_to='images/profile')),
('camera', models.CharField(max_length=30)),
('camera_image', models.ImageField(upload_to='image/camera')),
('sns_email', models.TextField(blank=True)),
('image', imagekit.models.fields.ProcessedImageField(upload_to='images/writer')),
('like', models.IntegerField(blank=True, null=True)),
('userid', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>/first/views.py
from django.shortcuts import render,redirect,HttpResponse,get_object_or_404
from django.contrib import auth
from .models import User,Writer,EmailConfirm
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate, update_session_auth_hash
from django.contrib.auth import logout
from .forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.conf import settings
#이메일 관련된 라이브러리
from django.core.mail import send_mail
from .hash_generator import generate_random_string
# Create your views here.
#메인(작가페이지 테스트(메인만))
def home(request):
return render(request, "home.html")
#로그인
def customer_login(request):
if request.method == "POST":
form = LoginForm(request.POST)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = <PASSWORD>)
if user:
# return login_next(request, user)
auth.login(request, user)
return redirect('home')
else:
return HttpResponse('로그인 실패. 다시 시도 해보세요.')
else:
form = LoginForm()
return render(request, 'customer_login.html', {'form': form})
#회원가입
def join(request):
if request.method == "GET":
return render(request, "join.html")
elif request.method == "POST":
username = request.POST["username"]
password = request.POST["password"]
password_check = request.POST["password_check"]
name = request.POST["user"]
email = request.POST["email"]
if User.objects.filter(username=username).exists():
return render(request, "join.html",{"msg":"이미 존재하는 ID입니다."})
if password != password_check:
return render(request, "join.html",{"pw_msg":"비빌번호가 일치하지않습니다."})
user = User.objects.create_user(
username=username, password=<PASSWORD>, name=name,
email=email)
user.save()
return login_next(request, user)
#작가등록(모델 하나아직)
@login_required
def enroll(request, id):
if request.method == "GET":
writer_account = get_object_or_404(User, pk=id, is_active=True)
return render(request, "enroll.html",{"writer_account":writer_account})
elif request.method == "POST":
introduce = request.POST["introduce"]
profile_image = request.FILES["profile_image"]
image = request.FILES["image"]
sns_email = request.POST["sns_email"]
camera = request.POST["camera"]
camera_image = request.FILES["camera_image"]
writer_account = get_object_or_404(User, pk=id, is_active=True)
writer_user = Writer.objects.create(userid=writer_account,introduce=introduce, profile_image=profile_image,
camera=camera, camera_image=camera_image,sns_email=sns_email, image=image,like=0)
writer_account.is_writer = True
writer_account.save()
# login(request,writer_account)
return redirect(reverse('home'))
#로그아웃
def signout(request):
if request.method=="POST":
if request.user.is_authenticated:
auth.logout(request)
return redirect('home')
#이메일전송
def send_confirm_mail(user):
try:
email_confirm = EmailConfirm.objects.get(user=user)
except EmailConfirm.DoesNotExist:
email_confirm = EmailConfirm.objects.create(
user = user,
key = generate_random_string(length=60),
)
url = '{0}{1}?key={2}'.format(
'http://localhost:8000',
reverse('confirm_email'),
email_confirm.key,
)
html = '<p>계속하시려면 아래 링크를 눌러주세요.</p><a href="{0}">인증하기</a>'.format(url)
send_mail(
'인증 메일입니다.',
'',
settings.EMAIL_HOST_USER,
[user.email],
html_message=html,
)
#이메일보냇습니다 html
def email_sent(request):
return render(request, "email_sent.html")
def confirm_email(request):
key = request.GET.get('key')
try:
email_confirm = get_object_or_404(EmailConfirm, key=key, is_confirmed=False)
email_confirm.is_confirmed = True
email_confirm.save()
return redirect(reverse('home'))
except:
return render(request, 'customer_login.html')
#이메일 전송
def login_next(request, user):
if EmailConfirm.objects.filter(user=user, is_confirmed=True).exists():
auth.login(request, user)
return redirect(reverse('home'))
else:
send_confirm_mail(user)
return redirect(reverse('email_sent'))
def bestphoto(request):
return render(request,'bestphoto.html')
def recommend(request):
return render(request,'recommend.html')
<file_sep>/photographer/forms.py
from django import forms
from photographer.models import ProductRegistration
from first.models import Writer
# 상품등록
# class UploadForm(forms.ModelForm):
# class Meta:
# model = ProductRegistration
# fields = ['title', 'summary', 'image', 'detail', 'options', 'option_price']
# widgets = {
# 'title': forms.TextInput(attrs={'class':'form-control'}),
# 'summary': forms.TextInput(attrs={'class':'form-control'}),
# 'image': forms.FileInput(attrs={'class':'form-group'}),
# 'detail': forms.Textarea(attrs={'class':'form-control'}),
# 'options': forms.TextInput(attrs={'class':'form-control'}),
# 'option_price': forms.NumberInput(attrs={'class':'form-control'}),
# }
# labels = {
# 'title': '상품 타이틀',
# 'summary': '상품 요약',
# 'image': '샘플 사진',
# 'detail': '상세 설명',
# 'options': '옵션 내용',
# 'option_price': '옵션가격',
# }
# 작가 관리
# class PhotographerProfile(forms.ModelForm):
# class Meta:
# model = Writer
# fields = ['profile_image', 'introduce', 'image', 'camera', 'sns_email']
# widgets = {
# 'profile_image': forms.FileInput(attrs={'class':'form-control'}),
# 'introduce': forms.Textarea(attrs={'class':'form-control'}),
# 'image': forms.FileInput(attrs={'class':'form-control'}),
# 'camera': forms.TextInput(attrs={'class':'form-control'}),
# 'sns_email': forms.URLInput(attrs={'class':'form-control'}),
# }
# labels = {
# 'name': '작가 이름',
# 'profile_image': '프로필 사진',
# 'introduce': '작가 소개',
# 'image': '포트폴리오 이미지',
# 'camera': '사용중인 카메라',
# 'sns_email': 'SNS계정',
# }
|
a24da7b0b551f5972edc73e80bda59fda331a8c0
|
[
"Python",
"Text",
"HTML"
] | 20 |
Python
|
zzigsa/zzigsa
|
a045bacbc9e0d25f053fd1c417c474b5bad07407
|
d986f609809d06a968fc87562d119bcb7386224e
|
refs/heads/master
|
<file_sep>Exercise from Week 5 of Ironhack Web Development Bootcamp
----------------------------------------------------------
<file_sep>$(document).on("ready", function () {
$(".js-search-artist").on("click", function (event) {
event.preventDefault();
$('.js-track-list').empty();
$('.js-artist-list').empty();
var searchedArtist = $('#query').val();
$.ajax({
type: "get",
url: "https://api.spotify.com/v1/search",
data: {
q: searchedArtist,
type: 'artist'
},
success: function(data) {
console.log("user input", data)
displayInfo(data.artists.items);
},
error: function(error) {
console.log("Error");
console.log(error.responseJSON);
}
});
});
$(".js-search-track").on("click", function (event) {
event.preventDefault();
$('.js-artist-list').empty();
$('.js-track-list').empty();
var searchedTrack = $('#query_track').val();
$.ajax({
type: "get",
url: "https://api.spotify.com/v1/search",
data: {
q: searchedTrack,
type: 'track'
},
success: function(data) {
console.log("data", data)
displayTrack(data.tracks.items);
},
error: function(error) {
console.log("Error");
console.log(error.responseJSON);
}
});
});
//selector of url "img class"
$(".js-artist-list").on("click", ".js-albums", function (event) {
event.preventDefault();
$('.js-albums-list').empty();
$('#myModal').modal('show')
var searchedArtist = $(event.currentTarget).data("artist-id");
console.log(searchedArtist);
$.ajax({
type: "get",
url: `https://api.spotify.com/v1/artists/${searchedArtist}/albums`,
// data: {
// q: searchedArtist.replace(" ","+"),
// type: 'album'
// },
success: function(data) {
console.log("Success");
console.log(data);
showAlbums(data.items);
},
error: function(error) {
console.log("Error");
console.log(error.responseJSON);
}
});
});
});
function displayInfo (artists) {
artists.forEach(function (oneArtist) {
var html = `
<li>
<div class="col-lg-4">
<p><b>${oneArtist.name}</b></p>
<img src="${oneArtist.images[0].url}" class="js-albums" data-artist-id="${oneArtist.id}">
</div>
</li>
`;
$(".js-artist-list").append(html);
});
}
function displayTrack (tracks) {
tracks.forEach(function (oneTrack) {
var html_track = `
<li>
<p>Track: ${oneTrack.name}</p>
</li>`;
console.log("oneTrack", oneTrack)
$(".js-track-list").append(html_track);
displayTrackArtist(oneTrack);
})
$(".js-player-title").html(tracks[0].name);
$(".js-player-artist").html(tracks[0].artists[0].name);
console.log(tracks[0].album.images[0].url)
var trackArtistImage = `<img src="${tracks[0].album.images[0].url}">;`
$(".js-player-image").html(trackArtistImage);
console.log(tracks[0].preview_url)
var soundTrack = tracks[0].preview_url
$(".btn-play").on("click", function () {
$('.js-player').prop('src', soundTrack)
if ($('.btn-play').prop('class') === "btn-play disabled") {
$('.js-player').trigger('play');
$(".btn-play").prop('class', "btn-play playing")
} else {
$('.js-player').trigger('pause');
$(".btn-play").prop('class', "btn-play disabled")
}
function updateTime () {
var current = $('.js-player').prop('currentTime');
// console.debug('Current time: ' + current);
$('progress').prop('value', current);
}
$('.js-player').on('timeupdate', updateTime);
});
}
function displayTrackArtist (track_artists) {
track_artists.artists.forEach(function (oneTrackArtist) {
var html_track_artist = `
<li><p>Artist: ${oneTrackArtist.name}</p></li>
`;
$(".js-track-list").append(html_track_artist);
})
}
function showAlbums (albums) {
albums.forEach(function (oneAlbum) {
var html = `
<li>${oneAlbum.name}</li>
`;
$(".js-albums-list").append(html);
});
}
|
fa443f137c0252f601f712f82faeca98f074cd08
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
andrezafeu/spotify_api
|
2f9d875048ee2e1f6d622bda7c946cbfc06d9396
|
41ca75651b63bce893212f55106c7bb5a4773e0e
|
refs/heads/master
|
<repo_name>vasyavasilisa/lr7Last<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>lab7</groupId>
<artifactId>lab7</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>lab7 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<hibernate-version>5.1.1.Final</hibernate-version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.14</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- optional -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-osgi</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<!--dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency-->
</dependencies>
<build>
<finalName>lab7</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/src/main/java/by/bsuir/dao/impl/MysqlCustomerDaoImpl.java
package by.bsuir.dao.impl;
import by.bsuir.dao.CustomerDao;
import by.bsuir.dao.exception.DAOException;
import by.bsuir.dao.exception.NoSuchEntityException;
import by.bsuir.domain.Customer;
import by.bsuir.utils.HibernateSessionFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
@Stateless
public class MysqlCustomerDaoImpl implements CustomerDao {
private final SessionFactory factory = new Configuration().configure().buildSessionFactory();
@Override
public Customer selectById(int id) throws DAOException {
/* Session session = null;
Customer entity = new Customer();
try {
session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();
entity = (Customer)session.createQuery("select pl from Customer pl where pl.id=:id")
.setParameter("id",id)
.uniqueResult();
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
}
return entity;*/
try(Session session = factory.openSession()){
Customer customer = session.get(Customer.class, id);
if(customer == null){
throw new NoSuchEntityException();
} else {
return customer;
}
}
}
@PreDestroy
private void destroy(){
factory.close();
}
}
<file_sep>/src/main/java/by/bsuir/domain/Customer.java
package by.bsuir.domain;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Entity
@Table(name = "customers")
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private int id;
@Column(name = "name", nullable = false, length = 45)
private String name;
@Column(name = "surname", nullable = false, length = 45)
private String surname;
@Column(name = "discount", nullable = false, length = 1)
private String discount;
@Column(name = "zip", nullable = false)
private int zip;
@Column(name = "phone_number", nullable = false, length = 13)
private String phone;
@Column(name = "email", nullable = false, length = 75)
private String email;
@Column(name = "city", nullable = false, length = 45)
private String city;
}
<file_sep>/target/lab7/WEB-INF/classes/sql.sql
-- DROP database `lab7`;
CREATE SCHEMA IF NOT EXISTS `lab7` DEFAULT CHARACTER SET utf8;
USE `lab7`;
-- Table `lab7`.`customers`
CREATE TABLE IF NOT EXISTS `lab7`.`customers` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`surname` VARCHAR(45) NOT NULL,
`discount` VARCHAR(1) NOT NULL,
`zip` INT NOT NULL,
`phone_number` VARCHAR(13) NOT NULL,
`email` VARCHAR(75) NOT NULL,
`city` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
INSERT INTO `lab7`.`customers`(name, surname, discount, zip, email, phone_number, city)
VALUES('Алексей', 'Конохов', 'N', 33015, '<EMAIL>', '+375441236589', 'Minsk'),
('Мария', 'Высоцкая', 'M', 33055, '<EMAIL>', '+375441478562', 'Minsk'),
('Василий', 'Коржиков', 'M', 75200, '<EMAIL>', '+375448512356', 'Minsk'),
('Николай', 'Еремеев', 'L', 12347, '<EMAIL>', '+375445468262', 'Minsk'),
('Анна', 'Батьковна', 'H', 94401, '<EMAIL>', '+375446684651', 'Minsk'),
('Пётр', 'Конюхов', 'L', 95035, '<EMAIL>', '+375449376354', 'Minsk'),
('Павел', 'Хроменков', 'L', 95117, '<EMAIL>', '+375446649545', 'Minsk'),
('Кирилл', 'Крылов', 'N', 94401, '<EMAIL>', '+375449467553', 'Minsk'),
('Филипп', 'Бронский', 'L', 48128, '<EMAIL>', '+375449654459', 'Minsk');<file_sep>/src/main/java/by/bsuir/dao/CustomerDao.java
package by.bsuir.dao;
import by.bsuir.dao.exception.DAOException;
import by.bsuir.domain.Customer;
import javax.ejb.Local;
@Local
public interface CustomerDao {
Customer selectById(int id) throws DAOException;
}
|
29eabf01adb4bda4b11eda293e85f38c65969c26
|
[
"Java",
"Maven POM",
"SQL"
] | 5 |
Maven POM
|
vasyavasilisa/lr7Last
|
0298ef353c9f5d76e07aa470da26b2dd30b37459
|
eadfb4d6af069623acd3f3de34a8e19404ce6405
|
refs/heads/master
|
<file_sep>module.exports = function() {
this.When(/^I click on "([^"]*)"$/, function (arg) {
browser.waitForExist(arg, 2000);
browser.click(arg);
});
};
<file_sep>module.exports = function() {
this.Then(/^I see the user story named "([^"]*)" modified$/, function (arg1) {
browser.waitForExist('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)', 2000);
//nom, usually unchanged
expect(arg1).toEqual(browser.getText('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)'));
//effort
expect('3').toEqual(browser.getText('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(3)'));
//priority
expect('4').toEqual(browser.getText('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(4)'));
//color : rgba(96,92,168,1) equivalent to #605ca8 or violet
expect('rgba(96,92,168,1)').toEqual(browser.getCssProperty('.badge','background-color').value);
client.pause(1000);
});
};
<file_sep>module.exports = function() {
this.Then(/^I dont see the requirement$/, function () {
browser.waitForExist('table.table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)', 1000, true);
});
};
<file_sep>import React, { Component } from 'react';
import CreateProjectBox from '../../components/CreateProject';
class CreateProject extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="row">
{/* left column */}
<div className="col-md-12">
<CreateProjectBox/>
</div>
</div>
);
}
}
export default CreateProject;
<file_sep>import { Mongo } from 'meteor/mongo';
import toposort from 'toposort';
import update from 'react-addons-update'; // ES6
import Stats from './stats';
CollectionsObj = {};
CollectionsObj.Specifications = new Meteor.Files({
debug: true,
collectionName: 'Specifications',
allowClientCode: true, // Disallow remove files from Clien
storagePath : '/data/Meteor/uploads/',
onBeforeUpload: function (file) {
// Allow upload files under 10MB, and only in pdf formats
if (file.size <= 1024*1024*10 && /pdf/i.test(file.extension)) {
return true;
} else {
return 'Please upload pdf, with size equal or less than 10MB';
}
}
});
CollectionsObj.Projects = new Mongo.Collection('projects');
CollectionsObj.Requirements = new Mongo.Collection('requirements');
CollectionsObj.UserStories = new Mongo.Collection('userstories');
CollectionsObj.Sprints = new Mongo.Collection('sprints');
CollectionsObj.Tasks = new Mongo.Collection('tasks');
CollectionsObj.TasksDependencies = new Mongo.Collection('tasks.dependencies');
CollectionsObj.TasksOrders = new Mongo.Collection('tasks.orders');
CollectionsObj.Stats = new Mongo.Collection('stats');
//Hooks
CollectionsObj.UserStories.after.remove(function (userId, doc) {
let userstory = doc;
let toUpdate = CollectionsObj.Tasks.find({userstory:userstory.id, project: userstory.project}).fetch();
for (task of toUpdate) {
if (task.userstory.length > 1)
CollectionsObj.Tasks.update({_id:task._id}, {$pull : {userstory : userstory.id}});
else
CollectionsObj.Tasks.remove({_id:task._id});
}
Stats.process(doc.project);
});
CollectionsObj.Tasks.after.remove(function (userId, doc) {
let task = doc;
let toUpdate = CollectionsObj.TasksDependencies.find({edge:task.id, project: task.project}).fetch();
let l = [];
let r = [];
for (dep of toUpdate){
if (dep.edge[0]===task.id)
r.push(dep.edge[1]);
else
l.push(dep.edge[0]);
CollectionsObj.TasksDependencies.remove({_id:dep._id});
}
for (lx of l){
for (rx of r){
CollectionsObj.TasksDependencies.upsert(
{edge: [lx, rx],
project: task.project},
{$set: {
edge: [lx, rx],
project: task.project
}
});
}
}
let dependencies = CollectionsObj.TasksDependencies.find({project: task.project}).fetch();
let edges = [];
for (dep of dependencies) {
edges.push(dep.edge);
}
let list = [];
try {
list = toposort(edges);
} catch (e) {
throw new Meteor.Error(e.message);
}
let order = {
list,
project: task.project
};
CollectionsObj.TasksOrders.upsert(
{project: task.project},
{$set: order
});
Stats.process(doc.project);
});
CollectionsObj.Tasks.after.insert(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.Tasks.after.update(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.UserStories.after.insert(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.UserStories.after.update(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.Sprints.after.insert(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.Sprints.after.remove(function (userId, doc) {
Stats.process(doc.project);
});
CollectionsObj.Sprints.after.update(function (userId, doc) {
Stats.process(doc.project);
});
export const Collections = CollectionsObj;
<file_sep>module.exports = function() {
this.Then(/^I see the task named "([^"]*)"$/, function (arg) {
<<<<<<< HEAD
let path = '';
switch(arg) {
case 't1':
path = 'table.table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)';
break;
case 't2':
path = 'table.table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(2)';
break;
case 't3':
path = 'table.table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(2)';
break;
default:
throw 'You tried to use a test to see a task named '+arg+' but it s not allowed to be tested by that one. Improve it or try another test.';
}
browser.waitForExist(path, 2000);
expect(arg).toEqual(browser.getText(path));
=======
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(2)', 2000);
expect(arg).toEqual(browser.getText('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(2)'));
>>>>>>> 84560fcea6dfbafb680e0ce9c1c547083c1085a9
client.pause(1000);
});
};
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
class addTaskForm extends Component {
constructor(props) {
super(props);
this.state = {
id: 0,
description: '',
userstory: [],
state: 1
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUSChange = this.handleUSChange.bind(this),
this.handleCancelEdit = this.handleCancelEdit.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.taskToEdit) {
if (nextProps.taskToEdit !== this.props.taskToEdit) {
this.setState({
id: nextProps.taskToEdit.id,
description: nextProps.taskToEdit.description,
userstory: nextProps.taskToEdit.userstory,
state: nextProps.taskToEdit.state
});
Session.set('warning', 'Caution: you are editing an existing Task : Task #'+nextProps.taskToEdit.id);
}
}
else {
this.setState({
id: 0,
description: '',
state: 1,
userstory: []
});
Session.set('warning', null);
}
}
handleChange(key, isInt) {
return function (e) {
let state = {};
if (isInt)
state[key] = parseInt(e.target.value);
else
state[key] = e.target.value;
this.setState(state);
}.bind(this);
}
handleUSChange(id) {
let userstory;
if (this.state.userstory.indexOf(parseInt(id)) > -1)
userstory = this.state.userstory.filter(function(item) {
return item !== parseInt(id);
});
else
userstory = this.state.userstory.concat(parseInt(id));
this.setState({
userstory
});
}
handleCancelEdit(event){
Session.set('taskToEdit', null);
Session.set('success', null);
Session.set('error', null);
}
handleSubmit(e){
e.preventDefault();
Meteor.call('tasks.update', this.state, this.props.currentProject.name,
function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
if (this.props.taskToEdit)
Session.set('taskToEdit', null);
}
renderSelectList(){
return (
<div className="pre-scrollable us-select-list">
<table className="table table-striped">
<tbody>
<tr>
<th style={{width: '10%'}} >
#
</th>
<th >
Description
</th>
<th style={{width: '10%'}} ></th>
</tr>
{this.props.userstories.map((userstory) => (
<tr>
<td style={{width: 20}} >
<span style={{backgroundColor: userstory.color}} className='badge'>{userstory.id}</span>
</td>
<td >
{(this.state.userstory.indexOf(parseInt(userstory.id)) > -1) ?
<del>{userstory.description}</del>
: <p>{userstory.description}</p>
}
</td>
<td>
<input type="checkbox" onChange={ () => { this.handleUSChange(userstory.id)}}
checked={(this.state.userstory.indexOf(parseInt(userstory.id)) > -1)}/>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
render(){
let states = ['None','To Do', 'On Going', 'In Testing', 'Done'];
let statesClass = ['bg-purple','bg-red', 'bg-yellow', 'bg-blue', 'bg-green'];
return (
<div className="row">
<div className="col-lg-12">
<h4>Add/Edit a task</h4>
<form onSubmit={this.handleSubmit} >
<div className="col-md-2">
<select value={this.state.state} className={statesClass[this.state.state]} onChange={this.handleChange('state', true)} className="form-control" required>
{states.map((state, i) => (
<option value={i} className={statesClass[i]} >{states[i]}</option>
))}
</select>
</div>
<div className="col-md-8">
<input placeholder="Description" type="text" className="form-control" value={this.state.description} onChange={this.handleChange('description', false)} required/>
</div>
{this.props.taskToEdit ?
<div>
<div className="col-md-1">
<button type="button" onClick={this.handleCancelEdit} className="btn btn-danger btn-block btn-flat">Cancel</button>
</div>
<div className="col-md-1">
<button className="btn btn-primary btn-block btn-flat">Confirm</button>
</div>
</div>
: <div className="col-md-2">
<button className="btn btn-primary btn-block btn-flat">Add</button>
</div>}
<br/>
{this.renderSelectList()}
</form>
</div>
</div>
);
}
}
export default addTaskForm;
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import BoxFooter from '../misc/BoxFooter';
import Loading from '../misc/Loading';
import { DragSource } from 'react-dnd';
const cardSource = {
beginDrag(props) {
console.log('begin');
return {
description: props.task.description
};
},
endDrag(props, monitor) {
const item = monitor.getItem();
const dropResult = monitor.getDropResult();
console.log('end');
if (dropResult) {
if (parseInt(dropResult.state) === 4){
let usFinished = [];
let callForTrace = true;
for (usId of props.task.userstory) {
for (task of props.tasks){
if (task._id !== props.task._id && task.userstory.indexOf(usId) > -1 && task.state < 4){
callForTrace = false;
}
}
if (callForTrace)
usFinished.push(usId);
}
if (usFinished.length > 0){
Session.set('usTrace', usFinished);
$("#myModal").modal("show");
}
}
let taskUpdate = {
id : props.task.id,
description : props.task.description,
userstory : props.task.userstory,
state : parseInt(dropResult.state)
};
Meteor.call('tasks.update', taskUpdate, props.currentProject.name, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
}
}
};
function collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
}
class Card extends Component {
constructor(props) {
super(props);
}
getColor(id){
for (userstory of this.props.userstories)
if (id === userstory.id)
return userstory.color;
}
renderUs(userstories){
return userstories.sort().map((userstory) => (<span className='badge' style={{backgroundColor: this.getColor(userstory)}} >#{userstory}</span>));
}
renderUsers(users){
if (users)
return users.sort().map((user) => (<span className='badge' style={{backgroundColor: 'lightgrey'}} >{Meteor.users.findOne({_id:user}).username}</span>));
}
handleAdd(_id){
Meteor.call('tasks.addUser', _id, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
}
render() {
const { connectDragSource, isDragging } = this.props;
return connectDragSource(
<div>
{
(this.props.task.isLate) ?
<Box className= 'box box-danger'>
<div className="box-header with-border">
<h4 className="box-title">
{this.renderUs(this.props.task.userstory)}
</h4>
<div className="pull-right">
{((this.props.task.users) && (this.props.task.users.indexOf(Meteor.userId())>-1)) ?
<button type="button" onClick={() => {this.handleAdd(this.props.task._id); }} className="btn btn-box-tool" data-widget="collapse"><i className="fa fa-minus"></i>
</button>
:
<button type="button" onClick={() => {this.handleAdd(this.props.task._id); }} className="btn btn-box-tool" data-widget="collapse"><i className="fa fa-plus"></i>
</button>}
</div>
</div>
<BoxBody>
{this.props.task.description}
</BoxBody>
<BoxFooter>{this.renderUsers(this.props.task.users)}</BoxFooter>
</Box>
:
<Box className='box box-primary'>
<div className="box-header with-border">
<h4 className="box-title">
{this.renderUs(this.props.task.userstory)}
</h4>
<div className="pull-right">
{((this.props.task.users) && (this.props.task.users.indexOf(Meteor.userId())>-1)) ?
<button type="button" onClick={() => {this.handleAdd(this.props.task._id); }} className="btn btn-box-tool" data-widget="collapse"><i className="fa fa-minus"></i>
</button>
:
<button type="button" onClick={() => {this.handleAdd(this.props.task._id); }} className="btn btn-box-tool" data-widget="collapse"><i className="fa fa-plus"></i>
</button>}
</div>
</div>
<BoxBody>
{this.props.task.description}
</BoxBody>
<BoxFooter>{this.renderUsers(this.props.task.users)}</BoxFooter>
</Box>}
</div>
);
}
}
export default DragSource('card', cardSource, collect)(Card);
<file_sep>import React, {Component} from 'react';
on = (type) => Array.isArray(type) ? type : [type];
const lastOf = (input) => on(input).slice(-1)[0];
class RouteName extends Component {
render() {
return (
<h1>
{lastOf(this.props.routes.slice(0, 2)).name}
</h1>
);
}
}
export default RouteName;
<file_sep>import { Meteor } from 'meteor/meteor';
import Specifications from './specifications';
import Requirement from './requirements';
import UserStory from './userstories';
import Sprint from './sprint';
import Tasks from './tasks';
import Dependencies from './dependencies';
Meteor.methods({
'specifications.delete': Specifications.delete,
'requirement.add' : Requirement.add,
'requirement.delete' : Requirement.delete,
'userstory.add' : UserStory.upsert,
'userstory.update' : UserStory.upsert,
'userstory.delete' : UserStory.delete,
'sprint.add' : Sprint.add,
'sprint.delete' : Sprint.delete,
'tasks.update' : Tasks.upsert,
'tasks.delete' : Tasks.delete,
'dependencies.update' : Dependencies.upsert,
'dependencies.delete' : Dependencies.remove,
'tasks.addUser' : Tasks.addUser,
'userstory.traceability.upsert' : UserStory.upsertTrace,
'userstory.traceability.delete' : UserStory.deleteTrace
});
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import Recharts from 'recharts';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
class Burndown extends Component {
constructor(props) {
super(props);
}
getData(){
let stats = this.props.stats;
let data =[];
let i = 1;
data.push({name : 'Sprint #0' , planned : stats.totalEffort , actual :stats.totalEffort});
for(sprint of this.props.sprints){
let dataObject = {name : 'Sprint #'+i};
dataObject.planned = data[i-1].planned-stats.sprintsData[sprint._id].totalEffort;
console.log(stats.sprintsEndEffort[sprint._id]);
if (stats.sprintsEndEffort[sprint._id])
dataObject.actual = data[i-1].planned-stats.sprintsEndEffort[sprint._id].effort;
data.push(dataObject);
console.log(dataObject);
i++;
}
return data;
}
render() {
const {LineChart, ResponsiveContainer, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
const data = this.getData() ;
return (
<Box>
<BoxHeader>
Burndown Chart
</BoxHeader>
<BoxBody>
<ResponsiveContainer width='100%' height={240}>
<LineChart data= {data}
margin={{top: 5, right: 20, left: 20, bottom: 5}}>
<XAxis dataKey="name"/>
<YAxis/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
<Legend />
<Line type="linear" dataKey="planned" stroke="#8884d8" activeDot={{r: 8}}/>
<Line type="linear" dataKey="actual" stroke="#82ca9d" />
</LineChart>
</ResponsiveContainer>
</BoxBody>
</Box>
);
}
}
export default createContainer((props) => {
const subscribeStats = Meteor.subscribe('stats', props.currentProject.name);
const subscribeSprints = Meteor.subscribe('sprints', props.currentProject.name);
const subscribeUS = Meteor.subscribe('userstories', props.currentProject.name);
const subscribeTasks = Meteor.subscribe('tasks', props.currentProject.name);
const sprints = Collections.Sprints.find({}, {sort: {start: 1}}).fetch();
const userstories = Collections.UserStories.find({}).fetch();
const tasks = Collections.Tasks.find({}).fetch();
const stats = Collections.Stats.findOne({project: props.currentProject.name});
const loaded = !!subscribeUS && !!subscribeSprints && !!subscribeTasks && !!sprints && !!tasks && !!userstories && !!subscribeStats && !!stats;
return {
success: Session.get('success'),
error: Session.get('error'),
sprints: loaded ? sprints : [],
userstories: loaded ? userstories : [],
tasks: loaded ? tasks : [],
stats : loaded ? stats :[],
loaded
};
}, Burndown);
<file_sep>import './index.html';
import '../imports/startup/client/index.js';
import '../node_modules/admin-lte/dist/css/AdminLTE.min.css';
import '../node_modules/admin-lte/dist/js/app.min.js';
import '../node_modules/admin-lte/plugins/jQuery/jquery-2.2.3.min.js';
import '../node_modules/admin-lte/plugins/fastclick/fastclick.js';
import '../node_modules/admin-lte/plugins/slimScroll/jquery.slimscroll.min.js';
<file_sep>module.exports = function() {
this.Then(/^I put "([^"]*)" in the "([^"]*)" field$/, function (arg, arg2) {
browser.waitForExist(arg2, 1000);
browser.setValue(arg2, arg);
});
};
<file_sep>module.exports = function() {
this.Then(/^I see the dependency$/, function () {
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > div > div.col-md-8 > table > tbody > tr:nth-child(2)', 2000);
client.pause(1000);
});
};
<file_sep>module.exports = function() {
this.Then(/^I put the date "([^"]*)" in the "([^"]*)" field$/, function (arg, arg2) {
browser.waitForExist(arg2, 1000);
browser.element(arg2).keys(arg);
});
};
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
class RequirementsList extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
isVisitorOrPo(){
let role = this.props.currentProject.roles[Meteor.userId()];
return (role === 'po' || !role);
}
handleDelete(_id) {
Meteor.call('requirement.delete', _id, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
}
renderRows(){
return this.props.requirements.map((requirement) => (
<tr>
<td>{requirement.id}</td>
<td>{requirement.description}</td>
<td>{requirement.priority}</td>
{
!this.isVisitorOrPo() ?
<td> <button className="btn btn-flat btn-danger pull-right" onClick={ () => { this.handleDelete(requirement._id); } }>
Delete
</button>
</td>
:<div></div>
}
</tr>
));
}
render() {
return (
<table className="table table-striped">
<tbody>
<tr>
<th style={{width: 50}}>
#
</th>
<th>
Description
</th>
<th style={{width: 100}}>
Priority
</th>
{
!this.isVisitorOrPo() ?
<th style={{width: 100}}>
</th>
:<div></div>
}
</tr>
{this.renderRows()}
</tbody>
</table>
);
}
}
export default RequirementsList;
<file_sep>module.exports = function() {
this.When(/^I click on the project delete button$/, function () {
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div:nth-child(1) > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(6) > button', 2000);
browser.click('#react-root > div > div.content-wrapper > section.content > div > div:nth-child(1) > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(6) > button');
});
};
<file_sep>module.exports = function() {
this.Then(/^I see the login screen$/, function () {
browser.waitForExist('#react-root > div > div > div.login-box-body > p', 2000);
expect("Sign in to start your session").toEqual(browser.getText('#react-root > div > div > div.login-box-body > p'));
client.pause(1000);
});
};
<file_sep>module.exports = function() {
this.When(/^I create a task named "([^"]*)"$/, function (arg) {
browser.waitForExist('div.box-footer > div.row > div > form > div.col-md-8 > input', 2000);
browser.setValue(' div.box-footer > div.row > div > form > div.col-md-8 > input',arg);
browser.waitForExist('div.box-footer > div.row > div > form > div.pre-scrollable.us-select-list > table > tbody > tr:nth-child(2) > td:nth-child(3) > input[type="checkbox"]', 2000);
browser.click('div.box-footer > div.row > div > form > div.pre-scrollable.us-select-list > table > tbody > tr:nth-child(2) > td:nth-child(3) > input[type="checkbox"]');
browser.waitForExist('div.box-footer > div.row > div > form > div.col-md-2 > button', 2000);
browser.click('div.box-footer > div.row > div > form > div.col-md-2 > button');
});
};
<file_sep>import React, { Component } from 'react';
import RequirementsBox from '../../components/Requirements';
class Requirements extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="requirements">
<RequirementsBox {...this.props}/>
</div>
);
}
}
export default Requirements;
<file_sep>module.exports = function() {
this.Then(/^I see the$/, function () {
browser.waitForExist('', 2000);
expect().toEqual(browser.getText(''));
client.pause(1000);
});
};
<file_sep>module.exports = function() {
this.When(/^I create a project named "([^"]*)"$/, function (arg) {
//browser.waitForExist('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(3) > a > span', 2000);
//browser.click('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(3) > a > span');
//browser.waitForExist('#react-root > div > div.content-wrapper > section.content-header > h1', 2000);
//expect('Create a Project').toEqual(browser.getText('#react-root > div > div.content-wrapper > section.content-header > h1'));
browser.waitForExist('form > div > div:nth-child(1) > input', 2000);
browser.setValue('form > div > div:nth-child(1) > input', arg);
client.pause(1000);
browser.waitForExist('#start', 2000);
browser.click('#start');
browser.element('#start').keys('25112015');
browser.click('#end');
browser.element('#end').keys('15122015');
browser.setValue('form > div > div:nth-child(5) > textarea', 'description');
browser.click('form > div > button');
browser.waitForExist('form > div > div.callout.callout-success', 2000);
expect('Project created').toEqual(browser.getText('form > div > div.callout.callout-success'));
browser.url('http://localhost:3000/');
});
};
<file_sep>module.exports = function() {
this.Then(/^I see the project named "([^"]*)"$/, function (arg) {
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div:nth-child(1) > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(1)', 2000);
expect(arg).toEqual(browser.getText('#react-root > div > div.content-wrapper > section.content > div > div:nth-child(1) > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(1)'));
client.pause(1000);
});
};
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import ProjectsList from './ProjectsList.js';
import Loading from '../misc/Loading';
class ProjectsListBox extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Box>
<BoxHeader>
Projects I belong to
</BoxHeader>
{!this.props.loaded ? <BoxBody></BoxBody> :
<BoxBody>
<ProjectsList projects={this.props.projects}/>
</BoxBody>
}
{!this.props.loaded ? <Loading/> : ''}
</Box>
);
}
}
export default createContainer(() => {
const projects = Collections.Projects.find({['roles.'+Meteor.userId()]:{$exists : true}}).fetch();
const loaded = !!projects;
return {
loaded,
projects: loaded ? projects : []
};
}, ProjectsListBox);
<file_sep>module.exports = function() {
this.When(/^I click on the tasksmanagement menu button$/, function () {
browser.waitForExist('#react-root > div > aside.main-sidebar > section > ul > li.treeview > a', 2000);
browser.click('#react-root > div > aside.main-sidebar > section > ul > li.treeview > a');
browser.waitForExist('#react-root > div > aside.main-sidebar > section > ul > li.treeview.active > ul > li:nth-child(1) > a', 2000);
browser.click('#react-root > div > aside.main-sidebar > section > ul > li.treeview.active > ul > li:nth-child(1) > a');
});
};
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../../common/collections.js';
import { check, Match } from 'meteor/check';
import PermissionsHelper from '../../common/permissionsHelper.js';
let Permissions = function() {};
Permissions.prototype.getPrivilege = function(userId, projectName){
let project = Collections.Projects.findOne({ name: projectName });
return project.roles[userId];
};
Permissions.prototype.upsert = function(userId, projectName, privilege){
PermissionsHelper.checkIfLogged();
if(!PermissionsHelper.verify(Meteor.userId(), projectName, 'pa'))
throw new Meteor.Error('authentication error');
check(privilege, Match.OneOf('pa', 'pm', 'po'));
if(privilege !== 'pa' && Permissions.getPrivilege(userId, projectName)==='pa')
Permissions.checkIfOneAdmin(projectName);
let setModifier = { $set: {} };
setModifier.$set['roles.'+userId] = privilege;
Collections.Projects.upsert( { name: projectName }, setModifier);
};
Permissions.prototype.checkIfOneAdmin = function(projectName){
let projet = Collections.Projects.findOne({name: projectName});
let nAdmin = 0;
for (let key in projet.roles) {
if (projet.roles[key] === 'pa')
nAdmin++;
}
if (nAdmin<2)
throw new Meteor.Error('project need at least one admin');
};
Permissions.prototype.delete = function(userId, projectName){
PermissionsHelper.checkIfLogged();
if(!PermissionsHelper.verify(Meteor.userId(), projectName, 'pa'))
throw new Meteor.Error('authentication error');
if(Permissions.getPrivilege(userId, projectName)==='pa')
Permissions.checkIfOneAdmin(projectName);
let unsetModifier = { $unset: {} };
unsetModifier.$unset['roles.'+userId] = '';
Collections.Projects.update( { name: projectName }, unsetModifier);
};
Permissions.prototype.addViaEmail = function(userEmail, projectName, privilege){
PermissionsHelper.checkIfLogged();
if(!PermissionsHelper.verify(Meteor.userId(), projectName, 'pa'))
throw new Meteor.Error('authentication error');
check(privilege, Match.OneOf('pa', 'pm', 'po'));
let user = Meteor.users.findOne({'emails.0.address':userEmail});
if(!user)
throw new Meteor.Error('user not found');
if(Permissions.getPrivilege(user._id, projectName)==='pa')
Permissions.checkIfOneAdmin(projectName);
let setModifier = { $set: {} };
setModifier.$set['roles.'+user._id] = privilege;
Collections.Projects.upsert( { name: projectName }, setModifier);
return 'Member added';
};
Permissions = new Permissions();
export default Permissions;
<file_sep>module.exports = function() {
this.When(/^I click on the requirement delete button$/, function () {
browser.waitForExist('button.pull-right', 2000);
browser.click('button.pull-right');
});
};
<file_sep>module.exports = function() {
this.When(/^I create a sprint$/, function () {
//browser.waitForExist('', 2000);
//browser.setValue('',);
//submit
browser.waitForExist('', 2000);
browser.click('');
});
};
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import {Meteor} from 'meteor/meteor';
import UserStoriesList from './UserStoriesList.js';
import FeedbackMessage from '../misc/FeedbackMessage';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import BoxFooter from '../misc/BoxFooter';
import AddUserStoryForm from './AddUserStoryForm.js';
import Loading from '../misc/Loading';
class UserStoriesBox extends Component {
constructor(props) {
super(props);
}
isPaOrPm(){
return (this.props.currentProject.roles[Meteor.userId()] === 'pa' || this.props.currentProject.roles[Meteor.userId()] === 'pm');
}
render() {
return (
<Box>
<BoxHeader>
User Stories
</BoxHeader>
{!this.props.loaded ? <BoxBody></BoxBody> :
<BoxBody>
<UserStoriesList currentProject={this.props.currentProject}
userstories={this.props.userstories}
isPaOrPm={this.isPaOrPm}/>
</BoxBody>
}
{(!this.props.loaded&&this.isPaOrPm()) ? <BoxFooter></BoxFooter> :
<BoxFooter>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<FeedbackMessage
warning={this.props.warning}
/>
<AddUserStoryForm currentProject={this.props.currentProject}
userstories={this.props.userstories}
userstoryToEdit={this.props.userstoryToEdit}/>
</BoxFooter>
}
{!this.props.loaded ? <Loading/> : ''}
</Box>
);
}
}
export default createContainer((props) => {
const subscribe = Meteor.subscribe('userstories', props.currentProject.name);
const userstories = Collections.UserStories.find({}, {sort: {id: 1}}).fetch();
const loaded = !!userstories && !!subscribe;
const userstoryToEdit = Session.get('userstoryToEdit') ? Collections.UserStories.findOne({_id:Session.get('userstoryToEdit')}) : null;
return {
error: Session.get('error'),
success: Session.get('success'),
warning: Session.get('warning'),
loaded,
userstories: loaded ? userstories : [],
userstoryToEdit
};
}, UserStoriesBox);
<file_sep>module.exports = function() {
this.When(/^I login as "([^"]*)"$/, function (arg) {
client.pause(1000);
browser.waitForExist('.login-box');
browser.setValue('input[name="email"]', arg);
browser.setValue('input[name="password"]', arg);
browser.click('.login-box .btn');
browser.waitForExist('#react-root > div > div.content-wrapper > section.content-header > h1', 2000);
expect('My Projects').toEqual(browser.getText('#react-root > div > div.content-wrapper > section.content-header > h1'));
});
};
<file_sep>import React, { Component } from 'react';
import { DropTarget } from 'react-dnd';
const columnTarget = {
drop(props) {
return {state : props.state};
}
};
function collect(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
};
}
class Column extends Component {
constructor(props) {
super(props);
}
render() {
const { canDrop, isOver, connectDropTarget } = this.props;
const isActive = canDrop && isOver;
return connectDropTarget(
<td className='sbcol'>
{ this.props.children }
</td>
);
}
}
export default DropTarget('card', columnTarget, collect)(Column);
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import LinkItem from '../misc/LinkItem';
import { Session } from 'meteor/session';
class SpecificationsList extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(fileId) {
Meteor.call('specifications.delete', fileId, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
}
isAdmin(){
return (this.props.currentProject.roles[Meteor.userId()] === 'pa');
}
isPo(){
return (this.props.currentProject.roles[Meteor.userId()] === 'po');
}
renderRows(){
return this.props.specifications.map((file) => (
<tr>
<td>{file.name}</td>
<td>{file.meta.uploadDate.toUTCString()}</td>
<td>
<a target="_blank" href={file.link()}>
<button className="btn btn-flat pull-left">
View
</button>
</a>
</td>
<td>
<button className="btn btn-flat btn-danger pull-right" onClick={ () => { this.handleDelete(file._id) }}
disabled={!(this.isPo) || !(this.isAdmin)}>
Delete
</button>
</td>
</tr>
));
}
render() {
return (
<table className="table table-striped">
<tbody><tr>
<th>Name</th>
<th style={{width: 350}}>Uploaded at</th>
<th style={{width: 20}}></th>
<th style={{width: 20}}></th>
</tr>
{this.props.specifications ? this.renderRows() : ''}
</tbody>
</table>
);
}
}
export default SpecificationsList;
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import FeedbackMessage from '../misc/FeedbackMessage';
class CreationForm extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
start: '',
end: '',
visibility: 'public',
description: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(key) {
return function (e) {
let state = {};
state[key] = e.target.value;
this.setState(state);
}.bind(this);
}
handleSubmit(e){
e.preventDefault();
Meteor.call('project.create', this.state, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', res);
Session.set('error', null);
}
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="projectCreationForm">
<div className="form-group">
<label>Name:</label>
<input type="text" onChange={this.handleChange('name')} value={this.state.name} className="form-control" pattern="^[a-zA-Z ]{2,30}$" required />
<p className="help-block">The project name must contains between 2 and 30 letters, lowercase or uppercase.</p>
</div>
{/* Date range */}
<div className="form-group">
<label>Start:</label>
<div className="input-group date">
<div className="input-group-addon">
<i className="fa fa-calendar" />
</div>
<input type="date" onChange={this.handleChange('start')} value={this.state.start} id="start" className="form-control pull-right datepicker" required />
</div>
{/* /.input group */}
</div>
<div className="form-group">
<label>End:</label>
<div className="input-group date">
<div className="input-group-addon">
<i className="fa fa-calendar" />
</div>
<input type="date" onChange={this.handleChange('end')} value={this.state.end} id="end" className="form-control pull-right datepicker" required />
</div>
{/* /.input group */}
</div>
{/* Public Private */}
<div className="form-group">
<label>Visibility level:</label>
<div className="radio">
<label>
<input type="radio" checked={this.state.visibility === 'public'} onChange={this.handleChange('visibility')} value="public"/>
Public
</label>
</div>
<div className="radio">
<label>
<input type="radio" checked={this.state.visibility === 'private'} onChange={this.handleChange('visibility')} value="private" />
Private
</label>
</div>
</div>
<div className="form-group">
<label>Description:</label>
<textarea className="form-control" rows="5" onChange={this.handleChange('description')} value={this.state.description} required />
</div>
<div className="form-group">
<label>Administrator:</label>
<input type="text" className="form-control" value={this.props.user.username} disabled/>
<p className="help-block">This project will be created with you as the Administrator.
Once the project exists, you may choose an Administrator from among the project members.</p>
</div>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<button type="submit" className="btn btn-primary btn-flat center-block">
Submit
</button>
</div>
</form>
);
}
}
export default createContainer(() => {
return {
error: Session.get('error'),
success: Session.get('success'),
user: Meteor.user() || {}
};
}, CreationForm);
<file_sep>import React, { Component } from 'react';
import CreationForm from './CreationForm.js';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
class CreateProject extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Box>
<BoxHeader>
Project details
</BoxHeader>
<BoxBody>
<CreationForm/>
</BoxBody>
</Box>
);
}
}
export default CreateProject;
<file_sep>import React, { Component } from 'react';
class FeedbackMessage extends Component {
constructor(props) {
super(props);
}
render () {
if (this.props.error)
return (
<div className="callout callout-danger">
{this.props.error}
</div>
);
else if (this.props.success)
return (
<div className="callout callout-success">
{this.props.success}
</div>
);
else if (this.props.warning)
return (
<div className="callout callout-warning">
{this.props.warning}
</div>
);
else return (<div></div>);
}
}
export default FeedbackMessage;
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
class addUserStoryForm extends Component {
constructor(props) {
super(props);
this.state = {
id: 0,
description: '',
effort: '',
priority: '',
color: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.userstoryToEdit) {
if (nextProps.userstoryToEdit !== this.props.userstoryToEdit) {
this.setState({
id: nextProps.userstoryToEdit.id,
description: nextProps.userstoryToEdit.description,
effort: nextProps.userstoryToEdit.effort,
priority: nextProps.userstoryToEdit.priority,
color: nextProps.userstoryToEdit.color
});
Session.set('warning', 'Caution: you are editing an existing US : US#'+nextProps.userstoryToEdit.id);
}
}
else{
this.setState({
id: 0,
description: '',
effort: '',
priority: ''
});
Session.set('warning', null);
}
}
handleChange(key, isInt) {
return function (e) {
let state = {};
if (isInt)
state[key] = parseInt(e.target.value);
else
state[key] = e.target.value;
this.setState(state);
}.bind(this);
}
handleCancelEdit(event){
Session.set('userstoryToEdit', null);
Session.set('success', null);
Session.set('error', null);
}
handleSubmit(e){
e.preventDefault();
Meteor.call('userstory.add', this.state, this.props.currentProject.name,
function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
if (this.props.userstoryToEdit)
Session.set('userstoryToEdit', null);
}
render(){
const colors = ['#3c8dbc', '#00c0ef', '#ff851b', '#605ca8', '#D81B60', '#39CCCC', '#d2d6de', '#f56954', '#00a65a'];
return (
<div className="row">
<div className="col-lg-12">
<h4>Add/Edit an Userstory</h4>
<form onSubmit={this.handleSubmit} >
<div className="col-md-4">
<input placeholder="Description" type="text" className="form-control" value={this.state.description} onChange={this.handleChange('description', false)} required/>
</div>
<div className="col-md-2">
<input placeholder="Effort" type="number" min="0" className="form-control" value={this.state.effort} onChange={this.handleChange('effort', true)} required/>
</div>
<div className="col-md-2">
<input placeholder="Priority" type="number" min="0" className="form-control" value={this.state.priority} onChange={this.handleChange('priority', true)} required/>
</div>
<div className="col-md-2">
<select value={this.state.color} style={{backgroundColor: this.state.color}} onChange={this.handleChange('color', false)} className="form-control" required>
<option value=''>Color</option>
{colors.map((color) => (
<option value={color} style={{backgroundColor: color}}>{color}</option>
))}
</select>
</div>
{this.props.userstoryToEdit ?
<div>
<div className="col-md-1">
<button type="button" onClick={this.handleCancelEdit} className="btn btn-danger btn-block btn-flat">Cancel</button>
</div>
<div className="col-md-1">
<button className="btn btn-primary btn-block btn-flat">{this.props.userstoryToEdit ? 'Confirm' : 'Add'}</button>
</div>
</div>
: <div className="col-md-2">
<button className="btn btn-primary btn-block btn-flat">{this.props.userstoryToEdit ? 'Confirm' : 'Add'}</button>
</div>}
</form>
</div>
</div>
);
}
}
export default addUserStoryForm;
<file_sep>module.exports = function() {
this.Then(/^I dont see "([^"]*)"$/, function (arg) {
browser.waitForExist(arg, true);
});
};
<file_sep>module.exports = function() {
this.Then(/^I dont see the task$/, function () {
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > table > tbody > tr:nth-child(2)', 1000, true);
});
};
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../../common/collections.js';
import PermissionsHelper from '../../common/permissionsHelper.js';
import toposort from 'toposort';
import moment from 'moment';
let Sprint = function() {};
function USright(projectName){
let right = PermissionsHelper.verify(Meteor.userId(), projectName, 'pa')
|| PermissionsHelper.verify(Meteor.userId(), projectName, 'pm');
if (!right)
throw new Meteor.Error('permission error : You can\'t do that. Please, ask this project administrator about it.');
}
Sprint.prototype.add = function(sprint, projectName) {
PermissionsHelper.checkIfLogged();
USright(projectName);
NonEmptyArrayOfNumbers = Match.Where(function (x) {
check(x, [Number]);
return x.length > 0;
});
check(sprint, {
_id: String,
start: String,
end: String,
description: String,
userstory: NonEmptyArrayOfNumbers
});
for (id of sprint.userstory){
let us = Collections.UserStories.findOne({project: projectName, id});
if(!us)
throw new Meteor.Error('Please select an US');
}
if(!moment(sprint.start).isValid() || !moment(sprint.end).isValid())
throw new Meteor.Error('date format unsupported');
if(moment(sprint.start).isAfter(sprint.end))
throw new Meteor.Error('start date must be before end date');
sprint.project = projectName;
sprint.state = 0;
if(sprint._id === '')
{
delete sprint._id;
Collections.Sprints.insert(sprint);
}
else
{
Collections.Sprints.update(
{_id : sprint._id},
{$set: sprint},
{upsert:true}
);
}
return 'Sprint created';
};
Sprint.prototype.delete = function(_id){
PermissionsHelper.checkIfLogged();
// PermissionsHelper.verify(Meteor.userId(), projectName, 'pa');
Collections.Sprints.remove({
_id
});
return 'Sprint deleted';
};
export default new Sprint();
<file_sep>import React, { Component } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import { browserHistory } from 'react-router';
import Header from '../../layouts/Header';
import Footer from '../../layouts/Footer';
import Menu from '../../layouts/Menu';
import ContentWrapper from '../../layouts/ContentWrapper';
import Sidebar from '../../layouts/Sidebar';
class App extends Component {
render() {
if (!this.props.currentProject && this.props.params.projectName)
browserHistory.push('/404');
return (
<div>
<Header/>
<Menu projectName={this.props.params.projectName} />
<ContentWrapper
routes={this.props.routes}
params={this.props.params}
>
{React.cloneElement(this.props.children, { currentProject: this.props.currentProject })}
</ContentWrapper>
<Sidebar/>
<div className="control-sidebar-bg"></div>
<Footer/>
</div>
);
}
}
export default createContainer((props) => {
const currentProject = Collections.Projects.findOne({name:props.params.projectName});
return {
currentProject
};
}, App);
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import FeedbackMessage from '../misc/FeedbackMessage';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import BoxFooter from '../misc/BoxFooter';
import AddForm from './AddForm';
import Loading from '../misc/Loading';
import SpecificationsList from './SpecificationsList.js';
class Specifications extends Component {
constructor(props) {
super(props);
}
isAdmin(){
return (this.props.currentProject.roles[Meteor.userId()] === 'pa');
}
isPo(){
return (this.props.currentProject.roles[Meteor.userId()] === 'po');
}
render() {
return (
<Box>
<BoxHeader>
Specifications
</BoxHeader>
{!this.props.loaded ? <BoxBody></BoxBody> :
<BoxBody>
<SpecificationsList specifications={this.props.specifications}/>
</BoxBody>
}
<BoxFooter>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
{(this.isAdmin() || this.isPo()) ? <AddForm currentProject={this.props.currentProject}/> : ''}
</BoxFooter>
{!this.props.loaded ? <Loading/> : ''}
</Box>
);
}
}
export default createContainer((props) => {
const subscribe = Meteor.subscribe('files.specifications.all', props.currentProject.name);
const specifications = Collections.Specifications.find({}).each();
const loaded = !!specifications && !!subscribe;
return {
error: Session.get('error'),
success: Session.get('success'),
loaded,
specifications: loaded ? specifications : []
};
}, Specifications);
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../../common/collections.js';
import PermissionsHelper from '../../common/permissionsHelper.js';
import moment from 'moment';
let UserStory = function() {};
function USright(projectName){
let right = PermissionsHelper.verify(Meteor.userId(), projectName, 'pa')
|| PermissionsHelper.verify(Meteor.userId(), projectName, 'pm');
if (!right)
throw new Meteor.Error('permission error : You can\'t do that. Please, ask this project administrator about it.');
}
UserStory.prototype.upsert = function(userstory, projectName) {
PermissionsHelper.checkIfLogged();
USright(projectName);
check(userstory, {
id: Number,
description: String,
effort: Number,
priority: Number,
color: String
});
if (userstory.id === 0){
let userstories = Collections.UserStories.find({project: projectName}, {sort: {id: -1}}).fetch();
userstory.id = (userstories.length > 0) ? userstories[0].id+1 : 1;
}
userstory.project = projectName;
Collections.UserStories.upsert(
{id: userstory.id},
{$set: userstory
});
return 'user story updated';
};
UserStory.prototype.delete = function(_id){
PermissionsHelper.checkIfLogged();
Collections.UserStories.remove({_id});
return 'user story deleted';
};
UserStory.prototype.upsertTrace = function(trace, projectName) {
PermissionsHelper.checkIfLogged();
USright(projectName);
check(trace, {
id: Number,
trace: String
});
Collections.UserStories.upsert(
{id: trace.id},
{$set: {trace : {
url: trace.trace,
date : moment().format('DD-MMM-YYYY')
}}
});
return 'trace updated';
};
UserStory.prototype.deleteTrace = function(_id) {
PermissionsHelper.checkIfLogged();
USright(projectName);
Collections.UserStories.upsert(
{_id: _id},
{$unset: {trace : 1}}
);
return 'trace deleted';
};
UserStory.prototype.delete = function(_id){
PermissionsHelper.checkIfLogged();
Collections.UserStories.remove({_id});
return 'user story deleted';
};
export default new UserStory();
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import Card from './Card.js';
import Column from './Column.js';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
class Board extends Component {
constructor(props) {
super(props);
}
getCards(state){
return this.props.currentSprintTasks.filter((task) => (task.state === state)).map((task) => (
<Card task={task} currentProject={this.props.currentProject}
userstories = {this.props.userstories}
users = {this.props.users}
tasks = {this.props.tasks} />
));
}
render() {
return (
<div>
<Box>
<BoxBody>
<table className="table">
<thead>
<tr>
<th style={{width: '25%'}}>To Do</th>
<th style={{width: '25%'}}>On Going</th>
<th style={{width: '25%'}}>In Testing</th>
<th style={{width: '25%'}}>Done</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</BoxBody>
</Box>
<table className="table">
<thead>
<tr>
<th style={{width: '25%'}}></th>
<th style={{width: '25%'}}></th>
<th style={{width: '25%'}}></th>
<th style={{width: '25%'}}></th>
</tr>
</thead>
<tbody>
<tr>
<Column name='todo' state='1'>
{this.props.currentSprintTasks ? this.getCards(1) : ' no cards'}
</Column>
<Column name='todo' state='2'>
{this.props.currentSprintTasks ? this.getCards(2) : ' no cards'}
</Column>
<Column name='todo' state='3'>
{this.props.currentSprintTasks ? this.getCards(3) : ' no cards'}
</Column>
<Column name='todo' state='4'>
{this.props.currentSprintTasks ? this.getCards(4) : ' no cards'}
</Column>
</tr>
</tbody>
</table>
</div>
);
}
}
export default DragDropContext(HTML5Backend)(Board);
<file_sep>import React, {Component} from 'react';
import TasksManagementBox from '../../components/TasksManagement';
class TasksManagement extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="TasksManagement">
<TasksManagementBox {...this.props}/>
</div>
);
}
}
export default TasksManagement;
<file_sep>// Subscribe to collections here
Meteor.subscribe('projects');
Meteor.subscribe('public-projects');<file_sep>import React, { Component } from 'react';
import MyProfileBox from '../../components/MyProfile';
class MyProfile extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="row">
{/* left column */}
<div className="col-md-12">
<MyProfileBox/>
</div>
</div>
);
}
}
export default MyProfile;
<file_sep>module.exports = function() {
this.Given(/^I am connected as "([^"]*)"$/, function (arg) {
browser.waitForExist('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu > a > span', 1000);
browser.waitForText('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu > a > span', 2000);
expect(arg).toEqual(browser.getText('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu > a > span'));
});
};
<file_sep>module.exports = function() {
this.When(/^I click on the userstory delete button$/, function () {
browser.waitForExist('.btn-danger', 2000);
browser.click('.btn-danger');
});
};
<file_sep>import React, { Component } from 'react';
import { Accounts } from 'meteor/accounts-base';
import { createContainer } from 'meteor/react-meteor-data';
import { Session } from 'meteor/session';
import LinkItem from '../misc/LinkItem';
import FeedbackMessage from '../misc/FeedbackMessage';
class Register extends Component {
constructor(props) {
super(props);
this.state = {email: '', password: '', repassword: '', fullname: ''};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
this.handleChangeRePassword = this.handleChangeRePassword.bind(this);
this.handleChangeFullname = this.handleChangeFullname.bind(this);
}
handleChangeEmail(event) {
this.setState({email: event.target.value});
}
handleChangePassword(event) {
this.setState({password: event.target.value});
}
handleChangeRePassword(event) {
this.setState({repassword: event.target.value});
}
handleChangeFullname(event) {
this.setState({fullname: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
let email = this.state.email;
let password = <PASSWORD>;
let repassword = this.state.repassword;
let fullname = this.state.fullname;
if(password===repassword){
Accounts.createUser({
email: email,
password: <PASSWORD>,
username: fullname
}, function(err, res) {
if (err) {
Session.set('error', err.message);
} else {
window.location.href = '/u/';
}
});
}
else {
Session.set('error','The passwords are different. Please, try again !');
}
}
render() {
return (
<div className="register-box">
<div className="register-logo">
<img src="/img/logo-wide.png" width='75%' height='75%' alt="logo"></img>
</div>
<div className="register-box-body">
<p className="login-box-msg">Register a new membership</p>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<div className="form-group has-feedback">
<input type="text" className="form-control" placeholder="Full name" name ="fullname" value ={this.state.fullname}
onChange={this.handleChangeFullname}/>
<span className="glyphicon glyphicon-user form-control-feedback" />
</div>
<div className="form-group has-feedback">
<input type="email" className="form-control" placeholder="Email" name ="email" value={this.state.email}
onChange={this.handleChangeEmail}/>
<span className="glyphicon glyphicon-envelope form-control-feedback" />
</div>
<div className="form-group has-feedback">
<input type="<PASSWORD>" className="form-control" placeholder="<PASSWORD>" name ="password" value ={this.state.password}
onChange={this.handleChangePassword}/>
<span className="glyphicon glyphicon-lock form-control-feedback" />
</div>
<div className="form-group has-feedback">
<input type="password" className="form-control" placeholder="Retype password" name ="repassword" value = {this.state.repassword}
onChange={this.handleChangeRePassword}/>
<span className="glyphicon glyphicon-log-in form-control-feedback" />
</div>
<div className="row">
<div className="col-xs-4">
<button onClick={this.handleSubmit} className="btn btn-primary btn-block btn-flat">Register</button>
</div>
</div>
<LinkItem to={'/r/login'}>I already have a membership</LinkItem>
</div>
</div>
);
}
}
export default createContainer(() => {
return {
error: Session.get('error')
};
}, Register);
<file_sep>import React, { Component } from 'react';
class Sidebar extends Component {
render() {
return (
<aside className="control-sidebar control-sidebar-dark">
{/* Create the tabs */}
<ul className="nav nav-tabs nav-justified control-sidebar-tabs">
<li className="active"><a href="#control-sidebar-home-tab" data-toggle="tab"><i className="fa fa-home" /></a></li>
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i className="fa fa-gears" /></a></li>
</ul>
{/* Tab panes */}
<div className="tab-content">
{/* Home tab content */}
<div className="tab-pane active" id="control-sidebar-home-tab">
<h3 className="control-sidebar-heading">Something1</h3>
</div>
{/* /.tab-pane */}
{/* Stats tab content */}
<div className="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
{/* /.tab-pane */}
{/* Settings tab content */}
<div className="tab-pane" id="control-sidebar-settings-tab">
<h3 className="control-sidebar-heading">Something2</h3>
</div>
{/* /.tab-pane */}
</div>
</aside>
);
}
}
export default Sidebar;
<file_sep>module.exports = function() {
this.When(/^I modify the task named "([^"]*)"$/, function (arg) {
//select the us
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(5) > button');
browser.click('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > table > tbody > tr:nth-child(2) > td:nth-child(5) > button'),
browser.waitForExist('div.box-footer > div.row > div > form > div.col-md-8 > input', 2000);
browser.setValue(' div.box-footer > div.row > div > form > div.col-md-8 > input',arg+'modif');
browser.waitForExist('div.box-footer > div.row > div > form > div:nth-child(2) > div:nth-child(2) > button', 2000);
browser.click('div.box-footer > div.row > div > form > div:nth-child(2) > div:nth-child(2) > button');
});
};
<file_sep>import { Meteor } from 'meteor/meteor';
import { check, Match } from 'meteor/check';
import PermissionsHelper from '../../common/permissionsHelper.js';
let Users = function() {};
Users.prototype.updateEmail = function(email) {
PermissionsHelper.checkIfLogged();
check(email, String);
let re = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
if (!re.test(email))
throw new Meteor.Error('incorrect email');
Meteor.users.update({_id:Meteor.userId()}, {$set: {'emails.0.address': email}});
return 'Email updated';
};
Users.prototype.updateUsername = function(username){
PermissionsHelper.checkIfLogged();
check(username, String);
Meteor.users.update({_id:Meteor.userId()}, {$set: {username}});
return 'Username updated';
};
export default new Users();
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import LinkItem from '../misc/LinkItem';
import { createContainer } from 'meteor/react-meteor-data';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
import { Accounts } from 'meteor/accounts-base';
class Login extends Component {
constructor(props) {
super(props);
this.state = {email: ''};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
}
handleChangeEmail(event) {
this.setState({email: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
Accounts.forgotPassword(this.state, function(err, res) {
if (err) {
Session.set('error', err.message);
} else {
window.location.href = '/u/';
}
});
}
render() {
return (
<div className="login-box">
<div className="login-logo">
<img src="/img/logo-wide.png" width='75%' height='75%' alt="logo"></img>
</div>
{/* /.login-logo */}
<div className="login-box-body">
<p className="login-box-msg">Reset your password :</p>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<div className="form-group has-feedback">
<input type="email" className="form-control" placeholder="Email" name="email" value={this.state.email}
onChange={this.handleChangeEmail}/>
<span className="glyphicon glyphicon-envelope form-control-feedback" />
</div>
<div className="row">
<div className="col-xs-4">
<button onClick={this.handleSubmit} className="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
<LinkItem to={'/r/login'} className={'signup'}>Cancel</LinkItem>
</div>
</div>
);
}
}
export default createContainer(() => {
return {
error: Session.get('error')
};
}, Login);
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import {Meteor} from 'meteor/meteor';
import moment from 'moment';
import Board from './Board.js';
import FeedbackMessage from '../misc/FeedbackMessage';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import BoxFooter from '../misc/BoxFooter';
import Loading from '../misc/Loading';
class ScrumBoard extends Component {
constructor(props) {
super(props);
}
isPaOrPm(){
return (this.props.currentProject.roles[Meteor.userId()] === 'pa' || this.props.currentProject.roles[Meteor.userId()] === 'pm');
}
currentSprintTasks(){
let currentSprintTasks = [];
for (sprint of this.props.sprints){
if (moment(sprint.end).isBefore(moment())){
for (usId of sprint.userstory){
for (task of this.props.tasks){
if ((task.state < 4) && (task.userstory.indexOf(usId) > -1) &&
(currentSprintTasks.indexOf(task) === -1)){
task.isLate = true;
currentSprintTasks.push(task);
}
}
}
}
else if (moment(sprint.start).isBefore(moment())) {
for (usId of sprint.userstory){
for (task of this.props.tasks){
if ((task.userstory.indexOf(usId) > -1) &&
(currentSprintTasks.indexOf(task) === -1)){
task.isLate = false;
currentSprintTasks.push(task);
}
}
}
}
}
return currentSprintTasks;
}
getColor(id){
for (userstory of this.props.userstories)
if (id === userstory.id)
return userstory.color;
}
renderUs(userstories){
return userstories.sort().map((userstory) => (<span className='badge' style={{backgroundColor: this.getColor(userstory)}} >#{userstory}</span>));
}
render() {
return (
<div>
{!this.props.loaded ? <div></div> :
<Board currentProject={this.props.currentProject}
currentSprintTasks = {this.currentSprintTasks()}
userstories = {this.props.userstories}
tasks = {this.props.tasks}
isPaOrPm={this.isPaOrPm}/>
}
<div className="modal fade" id="myModal" tabIndex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 className="modal-title">You must add traceability for the following US :</h4>
</div>
<div className="modal-body">
{(this.props.usFinished) ? this.renderUs(this.props.usFinished) : ''}
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default createContainer((props) => {
const subscribeSprints = Meteor.subscribe('sprints', props.currentProject.name);
const subscribeUS = Meteor.subscribe('userstories', props.currentProject.name);
const subscribeTasks = Meteor.subscribe('tasks', props.currentProject.name);
const subscribeUsers = Meteor.subscribe('users', props.currentProject.name);
const sprints = Collections.Sprints.find({}).fetch();
const userstories = Collections.UserStories.find({}).fetch();
const tasks = Collections.Tasks.find({}).fetch();
const loaded = !!subscribeUS && !!subscribeUsers && !!subscribeSprints && !!subscribeTasks && !!sprints && !!tasks && !!userstories;
return {
error: Session.get('error'),
success: Session.get('success'),
warning: Session.get('warning'),
usFinished: Session.get('usTrace'),
loaded,
userstories: loaded ? userstories : [],
sprints: loaded ? sprints : [],
tasks: loaded ? tasks : []
};
}, ScrumBoard);
<file_sep>import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRedirect, Redirect, browserHistory } from 'react-router';
import App from '../../ui/client/pages/App';
import Authentication from '../../ui/client/pages/Authentication';
import Projects from '../../ui/client/layouts/Projects';
import CreateProject from '../../ui/client/layouts/CreateProject';
import Profile from '../../ui/client/layouts/Profile';
import Dashboard from '../../ui/client/layouts/Dashboard';
import Specifications from '../../ui/client/layouts/Specifications';
import Requirements from '../../ui/client/layouts/Requirements';
import UserStories from '../../ui/client/layouts/UserStories'; ////
import TasksManagement from '../../ui/client/layouts/TasksManagement';
import TasksDependencies from '../../ui/client/layouts/TasksDependencies';
import Sprints from '../../ui/client/layouts/Sprints';
import ScrumBoard from '../../ui/client/layouts/ScrumBoard';
import Traceability from '../../ui/client/layouts/Traceability';
import NotFound from '../../ui/client/pages/404/';
import Login from '../../ui/client/layouts/Login';
import ForgotPassword from '../../ui/client/layouts/ForgotPassword';
import Register from '../../ui/client/layouts/Register';
Meteor.startup( () => {
let authGlobal = function(nextState, replace) {
//Check here if user is allowed to access to the page
let projectName = nextState.params.projectName;
if (!Meteor.userId()) {
replace({
pathname: '/r/login',
state: { nextPathname: nextState.location.pathname }
});
}
};
render(
<Router history={ browserHistory }>
<Route path="/" component={App}>
<IndexRedirect to="/u" />
</Route>
<Route path="/u" name={'Home'} component={App} onEnter={authGlobal}>
<IndexRedirect to="projects" />
<Route path="projects" name={'My Projects'} component={Projects}/>
<Route path="newproject" name={'Create a Project'} component={CreateProject}/>
<Route path="profile" name={'Profile'} component={Profile} />
</Route>
<Route path="/p" name={'Project Home'} component={App} onEnter={authGlobal}>
<IndexRedirect name={'Project Home'} to="/u" />
<Route path=":projectName/dashboard" name={'Dashboard'} component={Dashboard}/>
<Route path=":projectName/specifications" name={'Specifications'} component={Specifications}/>
<Route path=":projectName/requirements" name={'Requirements'} component={Requirements}/>
<Route path=":projectName/userstories" name={'User Stories'} component={UserStories}/>
<Route path=":projectName/tasks" name={'Tasks Management'} component={TasksManagement}/>
<Route path=":projectName/tasksDependencies" name={'Tasks Dependencies'} component={TasksDependencies}/>
<Route path=":projectName/sprint" name={'Sprints'} component={Sprints}/>
<Route path=":projectName/scrumboard" name={'ScrumBoard'} component={ScrumBoard}/>
<Route path=":projectName/traceability" name={'Traceability'} component={Traceability}/>
<Redirect to=":projectName/dashboard" from=":projectName"/>
</Route>
<Route path="/r" component={Authentication} >
<IndexRedirect to="login" />
<Route path="login" component={Login}/>
<Route path="register" component={Register}/>
<Route path="forgot" component={ForgotPassword}/>
</Route>
<Route path="/404" component={ NotFound } />
<Redirect to="/404" from="*"/>
</Router>,
document.getElementById('react-root')
);
});
<file_sep>module.exports = function() {
this.When(/^I click on the sprint menu button$/, function () {
browser.waitForExist('li.active:nth-child(11) > a:nth-child(1)', 2000);
browser.click('li.active:nth-child(11) > a:nth-child(1)');
});
};
<file_sep>module.exports = function() {
this.Then(/^I dont see the dependency$/, function () {
browser.waitForExist('#react-root > div > div.content-wrapper > section.content > div > div > div.box-body.pad > div > div.col-md-8 > table > tbody > tr:nth-child(2)', 1000, true);
});
};
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import FeedbackMessage from '../misc/FeedbackMessage';
class EditForm extends Component {
constructor(props) {
super(props);
this.state = {
username: this.props.user.username,
email: this.props.user.emails[0].address,
emailVerif: this.props.user.emails[0].address
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(key) {
return function (e) {
let state = {};
state[key] = e.target.value;
this.setState(state);
}.bind(this);
}
handleSubmit(e){
e.preventDefault();
if (this.state.email !== this.props.user.emails[0].address)
if (this.state.email !== this.state.emailVerif)
Session.set('error', 'Please verify your email');
else
Meteor.call('users.updateEmail', this.state.email, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', res);
Session.set('error', null);
}
});
if (this.state.username !== this.props.user.username)
Meteor.call('users.updateUsername', this.state.username, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', res);
Session.set('error', null);
}
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="projectCreationForm">
<div className="form-group">
<label>Username :</label>
<input type="text" onChange={this.handleChange('username')} value={this.state.username} className="form-control" required />
</div>
<div className="form-group">
<label>Email:</label>
<input type="email" onChange={this.handleChange('email')} value={this.state.email} className="form-control" required />
</div>
<div className="form-group">
<label>Confirm Email:</label>
<input type="email" onChange={this.handleChange('emailVerif')} value={this.state.emailVerif} className="form-control" required />
</div>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<button type="submit" className="btn btn-primary btn-flat center-block">
Submit
</button>
</div>
</form>
);
}
}
export default createContainer(() => {
return {
error: Session.get('error'),
success: Session.get('success'),
user: Meteor.user() || {}
};
}, EditForm);
<file_sep>module.exports = function() {
this.When(/^I click on the specifications menu button$/, function () {
browser.waitForExist('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(7) > a > span', 2000);
browser.click('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(7) > a > span');
});
};
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../collections.js';
import { check, Match } from 'meteor/check';
import moment from 'moment';
import PermissionsHelper from '../permissionsHelper.js';
let Specifications = function() {};
Specifications.prototype.delete = function(_id){
let file = Collections.Specifications.findOne({_id});
PermissionsHelper.checkIfLogged();
if(!PermissionsHelper.verify(Meteor.userId(), file.meta.project, 'pa') ||
!PermissionsHelper.verify(Meteor.userId(), file.meta.project, 'po'))
throw new Meteor.Error('authentication error');
Collections.Specifications.remove({_id}, function (error) {
if (error) {
throw new Meteor.Error(error.reason);
} else {
return 'File successfully removed';
}
}
);
};
export default new Specifications();
<file_sep>import React, { Component } from 'react';
import ProjectMembers from '../../components/ProjectMembers';
import Burndown from '../../components/BurndownChart';
class Dashboard extends Component {
render() {
return (
<div className="row" style={{minHeight:'300px'}}>
<div className="col-lg-6" style={{height:'300px'}}>
<ProjectMembers {...this.props}/>
</div>
<div className="col-lg-6" style={{height:'300px'}}>
<Burndown {...this.props}/>
</div>
</div>
);
}
}
export default Dashboard;
<file_sep>import React, { Component } from 'react';
class Box extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={this.props.className} style={{height:'100%', position: 'relative'}}>
{this.props.children}
</div>
);
}
}
Box.propTypes = {
className: React.PropTypes.string
};
Box.defaultProps = {
className:'box'
};
export default Box;
<file_sep>import { Meteor } from 'meteor/meteor';
import Permissions from './permissions';
import Projects from './projects';
import Users from './users';
Meteor.startup(() => {
// code to run on server at startup
});
Meteor.methods({
'permission.upsert': Permissions.upsert,
'permission.delete': Permissions.delete,
'permission.addViaEmail': Permissions.addViaEmail,
'project.create': Projects.create,
'project.delete': Projects.delete,
'users.updateEmail': Users.updateEmail,
'users.updateUsername': Users.updateUsername
});
<file_sep>module.exports = function() {
this.When(/^I click on the requirements menu button$/, function () {
browser.waitForExist('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(8) > a', 2000);
browser.click('#react-root > div > aside.main-sidebar > section > ul > li:nth-child(8) > a');
});
};
<file_sep>module.exports = function() {
this.Then(/^I see the PDF$/, function() {
let errorValue = -1;
browser.switchTab();
expect(browser.getUrl().indexOf(
'specifications'))
.toBeGreaterThan(errorValue);
browser.switchTab();
});
};
<file_sep>### TRACEABILITY - KANBAN
see [Trello](https://trello.com/b/cme9WxGp/scrumninja)
### BACKLOG - SPRINTS - BURNDOWN
see [our Google doc](https://docs.google.com/spreadsheets/d/17rfTCSoRqOnUuR5g6kFaG-SVQL5z5yzy6gRJRHu6xLo/edit#gid=1463738340)
<file_sep>import React from 'react';
const NotFound = () => <div className="error-page">
<h2 className="headline text-yellow"> 404</h2>
<div className="error-content">
<h3><i className="fa fa-warning text-yellow" /> Oops! Page not found.</h3>
<p>
We could not find the page you were looking for.
Meanwhile, you may <a href="/">return to the homepage.</a>
</p>
</div>
</div>;
export default NotFound;
<file_sep>import React from 'react';
const Loading = () => <div className="overlay">
<i className="fa fa-refresh fa-spin" />
</div>;
export default Loading;
<file_sep>import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { Collections } from '../../../../api/common/collections.js';
class addForm extends Component {
constructor(props) {
super(props);
this.state = {
uploading: [],
progress: 0,
inProgress: false,
placeholder: 'Select a file to upload..'
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event){
let self = this;
if (event.currentTarget.files && event.currentTarget.files[0]) {
let upload = Collections.Specifications.insert({
file: event.currentTarget.files[0],
meta: {
project: this.props.currentProject.name,
uploadDate: new Date()
},
streams: 'dynamic',
chunkSize: 'dynamic'
}, false);
upload.on('start', function () {
self.setState({
uploading: upload,
inProgress: true,
placeholder:event.currentTarget.files[0].name
});
});
upload.on('end', function (error, fileObj) {
if (error) {
Session.set('error', 'Error during upload: ' + error);
Session.set('success', null);
} else {
Session.set('success', 'File "' + fileObj.name + '" successfully uploaded');
Session.set('error', null);
}
self.setState({
uploading: [],
progress: 0,
inProgress: false,
placeholder: 'Select a file to upload..'
});
});
upload.on('progress', function (progress, fileObj) {
self.setState({
progress: progress
});
});
upload.start();
}
}
render() {
return (
<div className="row">
<div className="col-md-12">
<div className="input-group">
<input type="text" disabled={true} className="form-control" onChange={this.handleChange} value={this.state.placeholder}/>
<span className="input-group-btn">
<label className="btn btn-primary btn-flat">
Select a file <input type="file" style={{display: 'none'}} disabled={this.state.inProgress} onChange={this.handleChange}/>
</label>
</span>
</div>
<p className="help-block">File must be in PDF. Maximum upload size : 10Mo.</p>
{ this.state.inProgress ?
<div className="progress">
<div className="progress-bar" role="progressbar" aria-valuenow={this.state.progress} aria-valuemin={0} aria-valuemax={100} style={{width: this.state.progress+'%'}}>
{this.state.progress}%
</div>
</div>
:
<div></div>
}
</div>
</div>
);
}
}
export default addForm;
<file_sep>import React from 'react';
export const Footer = () =>
<footer className="main-footer">
<div className="pull-right hidden-xs">
Made with <span style={{ color: 'red' }}>♥</span>
</div>
Copyright © 2016 <a href="#">ScrumNinja</a>. All rights reserved.
</footer>;
export default Footer;
<file_sep>import React, {Component} from 'react';
import UserStoriesBox from '../../components/UserStories';
class UserStories extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="UserStories">
<UserStoriesBox {...this.props}/>
</div>
);
}
}
export default UserStories;
<file_sep>import './router.js';
import '../../api/client/subscribe.js';
import '../../api/common/main.js';
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../../common/collections.js';
import PermissionsHelper from '../../common/permissionsHelper.js';
import moment from 'moment';
let Stats = function() {};
Stats.prototype.process = function(projectName) {
console.log('process stats..');
let stats = Collections.Stats.findOne({project: projectName});
let sprintsData = {};
let totalEffort = 0;
let userstoriesData = {};
let sprintsEndEffort = {};
if (stats) {
sprintsEndEffort = stats.sprintsEndEffort;
}
let sprints = Collections.Sprints.find({project:projectName}).fetch();
for (sprint of sprints){
console.log('sprint');
let userstories = Collections.UserStories.find({id:{$in:sprint.userstory}}).fetch();
console.log(userstories);
//
let sprintDataObject = {};
let usDone = [];
sprintDataObject.totalEffort = 0;
sprintDataObject.currentEffort = 0;
sprintDataObject.id = sprint._id;
//
for (userstory of userstories){
console.log('us');
let tasks = Collections.Tasks.find({userstory:userstory.id}).fetch();
console.log(tasks);
//
let usDataObject = {};
usDataObject.tasksNumber = 0;
usDataObject.tasksDoneNumber = 0;
usDataObject.effort = userstory.effort;
usDataObject.us = userstory.id;
//
for (task of tasks){
console.log('task');
usDataObject.tasksNumber += 1;
if (task.state === 4)
usDataObject.tasksDoneNumber += 1;
}
if (usDataObject.tasksNumber === usDataObject.tasksDoneNumber){
sprintDataObject.currentEffort += userstory.effort;
usDone.push(userstory._id);
}
sprintDataObject.totalEffort += userstory.effort;
userstoriesData[userstory.id] = usDataObject;
}
totalEffort += sprintDataObject.totalEffort;
sprintsData[sprint._id]=sprintDataObject;
if (moment(sprint.end).isBefore(moment())) {
if (!sprintsEndEffort[sprint._id]){
sprintsEndEffort[sprint._id] = {};
sprintsEndEffort[sprint._id].usDone = usDone;
}
let currentEffort = 0;
for (us of sprintsEndEffort[sprint._id].usDone){
let userstoryDone = Collections.UserStories.findOne({_id:us});
if (userstoryDone){
let tasks = Collections.Tasks.find({userstory:userstoryDone.id}).fetch();
let tasksNumber = 0;
let tasksDoneNumber = 0;
for (task of tasks){
tasksNumber += 1;
if (task.state === 4)
tasksDoneNumber += 1;
}
if (tasksNumber === tasksDoneNumber){
currentEffort += userstoryDone.effort;
}
}
else {
sprintsEndEffort[sprint._id].usDone.splice(usDone.indexOf(us), 1);
}
}
sprintsEndEffort[sprint._id].effort = currentEffort;
}
}
console.log('sprintsData'+JSON.stringify(sprintsData));
console.log('totalEffort'+JSON.stringify(totalEffort));
console.log('userstoriesData'+JSON.stringify(userstoriesData));
console.log('sprintsEndEffort'+JSON.stringify(sprintsEndEffort));
Collections.Stats.upsert(
{project: projectName},
{$set: {
sprintsData,
totalEffort,
userstoriesData,
sprintsEndEffort
}
});
};
export default new Stats();
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
class AddRequirementForm extends Component {
constructor(props) {
super(props);
this.state = {
id: 0,
description:'',
priority :''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(key, isInt) {
return function (e) {
let state = {};
if (isInt)
state[key] = parseInt(e.target.value);
else
state[key] = e.target.value;
this.setState(state);
}.bind(this);
}
handleSubmit(cat){
Meteor.call('requirement.add', this.state, cat, this.props.currentProject.name, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
}
render(){
return (
<div className="row">
<div className="col-lg-12">
<h4>Add a Requirement</h4>
<form>
<div className="col-md-8">
<input placeholder="Description" type="text" className="form-control" value={this.state.description} onChange={this.handleChange('description', false)} required/>
</div>
<div className="col-md-2">
<input placeholder="Priority" type="number" min="0" className="form-control" value={this.state.priority} onChange={this.handleChange('priority', true)} required/>
</div>
<div className="col-md-2">
<button type="button" className="btn btn-primary btn-block btn-flat dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Add as <span className="caret" /></button>
<ul className="dropdown-menu dropdown-menu-right">
<li><a href="#" onClick={ () => { this.handleSubmit('f'); }}>Functional requirement</a></li>
<li><a href="#" onClick={ () => { this.handleSubmit('nf'); }}>Non-functional requirement</a></li>
</ul>
</div>
</form>
</div>
</div>
);
}
}
export default AddRequirementForm;
<file_sep>module.exports = function() {
this.When(/^I click on the userstory menu button$/, function () {
browser.waitForExist('.sidebar-menu > li:nth-child(9) > a:nth-child(1)', 2000);
browser.click('.sidebar-menu > li:nth-child(9) > a:nth-child(1)');
});
};
<file_sep>module.exports = function() {
this.Then(/^I visit "([^"]*)"$/, function (arg) {
browser.url(arg);
client.pause(1000);
});
};
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
class Header extends Component {
constructor(props) {
super(props);
this.handleSubmitLogout = this.handleSubmitLogout.bind(this);
}
handleSubmitLogout(event) {
event.preventDefault();
Meteor.logout();
window.location.href = '/r/login';
}
render() {
return (
<header className="main-header">
{/* Logo */}
<a href="/" className="logo">
{/* mini logo for sidebar mini 50x50 pixels */}
<span className="logo-mini"><img src="/img/logo.png"alt="logo"></img></span>
{/* logo for regular state and mobile devices */}
<span className="logo-lg"><img src="/img/logo-wide.png"alt="logo"></img></span>
</a>
{/* Header Navbar */}
<nav className="navbar navbar-static-top" role="navigation">
{/* Sidebar toggle button*/}
<a href="#" className="sidebar-toggle" data-toggle="offcanvas" role="button">
<span className="sr-only">Toggle navigation</span>
</a>
{/* Navbar Right Menu */}
<div className="navbar-custom-menu">
<ul className="nav navbar-nav">
{/* Tasks Menu */}
<li className="dropdown tasks-menu">
{/* Menu Toggle Button */}
<a href="#" className="dropdown-toggle" data-toggle="dropdown">
<i className="fa fa-flag-o" />
<span className="label label-danger">9</span>
</a>
<ul className="dropdown-menu">
<li className="header">You have 9 tasks</li>
<li>
{/* Inner menu: contains the tasks */}
<ul className="menu">
<li>{/* Task item */}
<a href="#">
{/* Task title and progress text */}
<h3>
Design some buttons
<small className="pull-right">20%</small>
</h3>
{/* The progress bar */}
<div className="progress xs">
{/* Change the css width attribute to simulate progress */}
<div className="progress-bar progress-bar-aqua" style={{width: '20%'}} role="progressbar" aria-valuenow={20} aria-valuemin={0} aria-valuemax={100}>
<span className="sr-only">20% Complete</span>
</div>
</div>
</a>
</li>
{/* end task item */}
</ul>
</li>
<li className="footer">
<a href="#">View all tasks</a>
</li>
</ul>
</li>
{/* User Account Menu */}
<li className="dropdown user user-menu">
{/* Menu Toggle Button */}
<a href="#" className="dropdown-toggle" data-toggle="dropdown">
{/* The user image in the navbar*/}
{/* hidden-xs hides the username on small devices so only the image appears. */}
<span>{this.props.user.username}</span>
</a>
<ul className="dropdown-menu">
{/* Menu Body */}
{/* Menu Footer*/}
<li className="user-footer">
<div className="pull-left">
<a href="profile" className="btn btn-default btn-flat">Profile</a>
</div>
<div className="pull-right">
<button onClick={this.handleSubmitLogout} className="btn btn-default btn-flat">Sign out</button>
</div>
</li>
</ul>
</li>
{/* Control Sidebar Toggle Button */}
<li>
<a href="#" data-toggle="control-sidebar"><i className="fa fa-gears" /></a>
</li>
</ul>
</div>
</nav>
</header>
);
}
}
export default createContainer(() => {
return {
user: Meteor.user() || {}
};
}, Header);
<file_sep># SCRUMNINJA
<img src="https://raw.githubusercontent.com/valcol/ScrumNinja/master/app/public/img/logo-wide-dark.png" height="88">
A Scrum/Agile projects management app made with React / MeteorJS
## Features
## Installation
This application need a Meteor >= 1.3 installation.
If you're running on a older Meteor, please update.
```
meteor npm install
```
## Running
```
meteor
```
This command will start a server on port 3000.
Go to **http://localhost:3000** to see the app running.
## Test
### Acceptance tests
```
npm run tests-acceptance
```
## Licence
```
MIT License
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
class addDependencyForm extends Component {
constructor(props) {
super(props);
this.state = {
edge: ['', '']
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
}
handleChange(key, e) {
let edge = this.state.edge;
if (key === 0)
this.setState({edge: [parseInt(e.target.value),this.state.edge[1]]});
else
this.setState({edge: [this.state.edge[0], parseInt(e.target.value)]});
}
handleCancelEdit(event){
Session.set('dependencyToEdit', null);
Session.set('success', null);
Session.set('error', null);
}
handleSubmit(e){
e.preventDefault();
Meteor.call('dependencies.update', this.state, this.props.currentProject.name,
function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
if (this.props.dependencyToEdit)
Session.set('dependencyToEdit', null);
}
renderSelectListFirstEdge(){
return (
<select value={this.state.edge[0]} onChange={ (e) => { this.handleChange(0,e);}} className="form-control" required>
<option value=''>Choose a Task</option>
{this.props.tasks.map((task) => (
<option value={task.id} disabled={(this.state.edge[1]===task.id)}>Task#{task.id} : {task.description}</option>
))}
</select>
);
}
renderSelectListSecondEdge(){
return (
<select value={this.state.edge[1]} onChange={ (e) => { this.handleChange(1,e);}} className="form-control" required>
<option value=''>Choose a Task</option>
{this.props.tasks.map((task) => (
<option value={task.id} disabled={(this.state.edge[0]===task.id)}>Task#{task.id} : {task.description}</option>
))}
</select>
);
}
render(){
return (
<div className="row">
<div className="col-lg-12">
<h4>Add/Edit a dependency</h4>
<form onSubmit={this.handleSubmit} >
<div className="col-md-4">
{this.renderSelectListFirstEdge()}
</div>
<div className="col-md-2">
need to be completed before
</div>
<div className="col-md-4">
{this.renderSelectListSecondEdge()}
</div>
<div className="col-md-2">
<button className="btn btn-primary btn-block btn-flat">Add</button>
</div>
</form>
</div>
</div>
);
}
}
export default addDependencyForm;
<file_sep>module.exports = function() {
this.Then(/^I see "([^"]*)" inside "([^"]*)"$/, function (arg, arg2) {
browser.waitForExist(arg2, 2000);
expect(arg).toEqual(browser.getText(arg2));
client.pause(3000);
});
};
<file_sep>import React, { Component } from 'react';
class BoxHeader extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="box-header with-border">
<h4 className="box-title">
{this.props.children}
</h4>
</div>
);
}
}
export default BoxHeader;
<file_sep>module.exports = function() {
this.When(/^I click on the logout button$/, function () {
browser.waitForExist('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu > a', 2000);
browser.click('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu > a');
browser.waitForExist('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu.open > ul > li.user-footer > div.pull-right > button', 2000);
browser.click('#react-root > div > header > nav > div > ul > li.dropdown.user.user-menu.open > ul > li.user-footer > div.pull-right > button');
});
};
<file_sep>import React, { Component } from 'react';
import Breadcrumbs from 'react-router-breadcrumbs';
import RouteName from '../../components/misc/RouteName';
class ContentWrapper extends Component {
render() {
return (
<div className="content-wrapper">
<section className="content-header">
<RouteName routes={this.props.routes}/>
<ol className="breadcrumb">
<Breadcrumbs
routes={this.props.routes}
params={this.props.params}
/>
</ol>
</section>
<section className="content">
{this.props.children}
</section>
</div>
);
}
}
export default ContentWrapper;
<file_sep>module.exports = function() {
this.Then(/^I dont see the user story$/, function () {
browser.waitForExist('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)', 1000, true);
});
};
<file_sep>import { Collections } from './collections.js';
/*
Roles :
- pa : project administrator;
- pm : project member;
- po : process owner;
*/
let PermissionsHelper = function() {};
PermissionsHelper.prototype.verify = function(userId, projectName, role) {
check(role, Match.OneOf('pa', 'pm', 'po'));
let project = Collections.Projects.findOne({ name: projectName });
return (project.roles[userId]===role);
};
PermissionsHelper.prototype.isAvailableToView = function(userId, projectName, allowNonMembers) {
let project = Collections.Projects.findOne({ name: projectName });
if (project.roles[userId])
return true;
else if ((project.visibility==='public'))
return allowNonMembers;
return false;
};
PermissionsHelper.prototype.checkIfLogged = function(){
if(!Meteor.userId())
throw new Meteor.Error('authentication error');
};
export default new PermissionsHelper();
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import LinkItem from '../misc/LinkItem';
class ProjectsList extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(projectName) {
Meteor.call('project.delete', projectName);
}
renderRows(){
return this.props.projects.map((project) => (
<tr>
<td>{project.name}</td>
<td>{project.visibility}</td>
<td>{Object.keys(project.roles).length}</td>
<td>
<div className="progress progress-xs">
<div className="progress-bar progress-bar-success" style={{width: '55%'}}></div>
</div>
</td>
<td>
<LinkItem to={'/p/'+project.name+'/'} >
<button className="btn btn-flat btn-primary pull-left">
Dashboard
</button>
</LinkItem>
</td>
<td>
<button className="btn btn-flat btn-danger pull-right" onClick={ () => { this.handleDelete(project.name); } }
disabled={!(project.roles[Meteor.userId()] === 'pa')}>
Delete
</button>
</td>
</tr>
));
}
render() {
return (
<table className="table table-striped">
<tbody><tr>
<th style={{width: 150}}>Name</th>
<th style={{width: 100}}><span className="glyphicon glyphicon-eye-open"></span></th>
<th style={{width: 100}}><span className="glyphicon glyphicon-user"></span></th>
<th>Progress</th>
<th style={{width: 20}}></th>
<th style={{width: 20}}></th>
</tr>
{this.renderRows()}
</tbody>
</table>
);
}
}
export default ProjectsList;
<file_sep>import { Meteor } from 'meteor/meteor';
import { Collections } from '../../common/collections.js';
import PermissionsHelper from '../../common/permissionsHelper.js';
import toposort from 'toposort';
let Dependencies = function() {};
function USright(projectName){
let right = PermissionsHelper.verify(Meteor.userId(), projectName, 'pa')
|| PermissionsHelper.verify(Meteor.userId(), projectName, 'pm');
if (!right)
throw new Meteor.Error('permission error : You can\'t do that. Please, ask this project administrator about it.');
}
Dependencies.prototype.upsert = function(dependency, projectName){
ArrayOfNumbersSize2 = Match.Where(function (x) {
check(x, [Number]);
return x.length === 2;
});
check(dependency.edge, ArrayOfNumbersSize2);
for (id of dependency.edge)
if(!Collections.Tasks.findOne({id, project: projectName}))
throw new Meteor.Error('Error');
let dependencies = Collections.TasksDependencies.find({project: projectName}).fetch();
let edges = [];
for (dep of dependencies) {
edges.push(dep.edge);
}
edges.push(dependency.edge);
let list = [];
try {
list = toposort(edges);
} catch (e) {
throw new Meteor.Error(e.message);
}
dependency.project = projectName;
Collections.TasksDependencies.upsert(
{edge: dependency.edge,
project: projectName},
{$set: dependency
});
let order = {
list,
project: projectName
};
Collections.TasksOrders.upsert(
{project: projectName},
{$set: order
});
};
Dependencies.prototype.remove = function(_id, projectName){
PermissionsHelper.checkIfLogged();
Collections.TasksDependencies.remove({_id});
let dependencies = Collections.TasksDependencies.find({project: projectName}).fetch();
let edges = [];
for (dep of dependencies) {
edges.push(dep.edge);
}
let list = [];
try {
list = toposort(edges);
} catch (e) {
throw new Meteor.Error(e.message);
}
let order = {
list,
project: projectName
};
Collections.TasksOrders.upsert(
{project: projectName},
{$set: order
});
return 'dependency deleted';
};
export default new Dependencies();
<file_sep>import '../../api/server/publish.js';
import '../../api/server/main.js';
import '../../api/common/main.js';
<file_sep>module.exports = function() {
this.Then(/^I see the "([^"]*)" requirement named "([^"]*)"$/, function (arg1, arg2) {
browser.waitForExist(arg1 === 'functional'?'table.table:nth-child(2)':'table.table:nth-child(4)', 2000);
let str = arg1 === 'functional'? 'table.table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)':'table.table:nth-child(4) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)';
let requirement = browser.getText(str);
expect(arg2).toEqual(requirement);
client.pause(1000);
});
};
<file_sep>var myHooks = function () {
this.Before(function (scenario) {
console.log("before global");
//Reset DB
server.execute(function () {
Package['xolvio:cleaner'].resetDatabase();
});
browser.url('http://localhost:3000/');
client.pause(1000);
});
this.Before({tags: ["@user1Exist"]}, function (scenario) {
console.log("before @user1Exist");
browser.url('http://localhost:3000/r/register');
browser.waitForExist('.register-box', 1000);
browser.timeoutsAsyncScript(1000).executeAsync(function(done) {
Accounts.createUser({
email: 'user1',
password: '<PASSWORD>',
username: 'user1'
}, function(err) {
if (err) {
console.error('Could not login', err);
} else {
done();
}
})
});
browser.timeoutsAsyncScript(1000).executeAsync(function(done) {
Meteor.logout(function(err) {
if (err) {
console.error('Could not logout', err);
} else {
done();
}
});
});
browser.url('http://localhost:3000');
browser.waitForExist('.login-box', 1000);
});
this.Before({tags: ["@user2Exist"]}, function (scenario) {
console.log("before @user2Exist");
browser.url('http://localhost:3000/r/register');
browser.waitForExist('.register-box', 1000);
browser.timeoutsAsyncScript(1000).executeAsync(function(done) {
Accounts.createUser({
email: 'user2',
password: '<PASSWORD>',
username: 'user2'
}, function(err) {
if (err) {
console.error('Could not login', err);
} else {
done();
}
})
});
browser.timeoutsAsyncScript(1000).executeAsync(function(done) {
Meteor.logout(function(err) {
if (err) {
console.error('Could not logout', err);
} else {
done();
}
});
});
browser.url('http://localhost:3000');
browser.waitForExist('.login-box', 1000);
});
this.Before({tags: ["@user1Logged"]}, function (scenario) {
console.log("before @user1Logged");
browser.url('http://localhost:3000/r/login');
browser.executeAsync(function(done) {
Meteor.loginWithPassword('<PASSWORD>', '<PASSWORD>', function(err) {
if (err) {
console.error('Could not login', err);
} else {
done();
}
})
});
browser.url('http://localhost:3000');
});
this.Before({tags: ["@projectExist"]}, function (scenario) {
console.log("before @projectExist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
Meteor.call('project.create',
{
name: 'project',
start: '2016-02-02',
end: '2016-03-02',
visibility: 'public',
description: 'project'
}
, function(err, res) {
if (err) {
console.error('couldnt create project');
} else {
done();
}
});
});
// This hook will be executed before scenarios tagged with @foo
});
/*
this.Before({tags: ["@user2AsMember"]}, function (scenario) {
console.log("before @user2AsMember");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
Meteor.call('permission.addViaEmail','user2','project','pa'
,function(err, res) {
if (err) {
console.error('couldnt associate user2 as member');
} else {
done();
}
});
});
});
*/
this.Before({tags: ["@requirementExist"]}, function (scenario) {
console.log("before @requirementExist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
let state = {
id: 0,
description:'requirement1',
priority :'2'
};
Meteor.call('requirement.add',state, 'f', 'project'
,function(err, res) {
if (err) {
console.error('couldnt create requirement1');
} else {
done();
}
});
});
});
this.Before({tags: ["@userstoryExist"]}, function (scenario) {
console.log("before @userstoryExist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
let state = {
id: 0,
description: 'us1',
effort: 1,
priority: 2,
color: '#ff851b' //orange
};
Meteor.call('userstory.add',state, 'project'
,function(err, res) {
if (err) {
console.error('couldnt create us1');
} else {
done();
}
});
});
});
this.Before({tags: ["@userstory2Exist"]}, function (scenario) {
console.log("before @userstory2Exist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
let state = {
id: 1,
description: 'us2',
effort: 10,
priority: 1,
color: '#39cccc' //blue light
};
Meteor.call('userstory.add',state, 'project'
,function(err, res) {
if (err) {
console.error('couldnt create us2');
} else {
done();
}
});
});
});
this.Before({tags: ["@task1Exist"]}, function (scenario) {
console.log("before @task1Exist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
this.state = {
id: 1,
description: 'task1',
userstory: [1]
};
Meteor.call('tasks.update',state, 'project'
,function(err, res) {
if (err) {
console.error('couldnt create task');
} else {
done();
}
});
});
});
this.Before({tags: ["@task2Exist"]}, function (scenario) {
console.log("before @task2Exist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
this.state = {
id: 2,
description: 'task2',
userstory: [1]
};
Meteor.call('tasks.update',state, 'project'
,function(err, res) {
if (err) {
console.error('couldnt create task');
} else {
done();
}
});
});
});
this.Before({tags: ["@dependency1Exist"]}, function (scenario) {
console.log("before @dependency1Exist");
browser.timeoutsAsyncScript(2000).executeAsync(function(done) {
this.state = {
edge: [1, 2]
};
Meteor.call('dependencies.update',state, 'project'
,function(err, res) {
if (err) {
console.error('couldnt create dependency');
} else {
done();
}
});
});
});
this.After(function (scenario) {
console.log("after");
});
};
module.exports = myHooks;
<file_sep>module.exports = function() {
this.Then(/^I see the user story named "([^"]*)"$/, function (arg) {
browser.waitForExist('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)', 2000);
expect(arg).toEqual(browser.getText('.table > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)'));
client.pause(1000);
});
};
<file_sep>module.exports = function() {
this.When(/^I create a user story named "([^"]*)"$/, function (arg) {
browser.waitForExist('.col-md-4 > input:nth-child(1)', 2000);
browser.setValue('.col-md-4 > input:nth-child(1)',arg);
browser.waitForExist('div.col-md-2:nth-child(2) > input:nth-child(1)', 2000);
browser.setValue('div.col-md-2:nth-child(2) > input:nth-child(1)','2');
browser.waitForExist('div.col-md-2:nth-child(3) > input:nth-child(1)', 2000);
browser.setValue('div.col-md-2:nth-child(3) > input:nth-child(1)','2');
//color
browser.click('select.form-control');
browser.click('select.form-control > option:nth-child(4)');
browser.waitForExist('.btn-primary', 2000);
browser.click('.btn-primary');
});
};
<file_sep>import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
class AddSprintForm extends Component {
constructor(props) {
super(props);
this.state = {
_id: '',
start: '',
end: '',
description: '',
userstory: []
};
this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleBeginChange = this.handleBeginChange.bind(this);
this.handleEndChange = this.handleEndChange.bind(this);
this.handleUSChange = this.handleUSChange.bind(this);
this.handleCancelEdit = this.handleCancelEdit.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.sprintToEdit) {
if (nextProps.sprintToEdit !== this.props.sprintToEdit) {
this.setState({
_id:nextProps.sprintToEdit._id,
start: nextProps.sprintToEdit.start,
end: nextProps.sprintToEdit.end,
description: nextProps.sprintToEdit.description,
userstory: nextProps.sprintToEdit.userstory
});
Session.set('warning', 'Caution: you are editing an existing Sprint');
}
}
else {
this.setState({
_id:'',
start: '',
end: '',
description: '',
userstory: []
});
Session.set('warning', null);
}
}
handleCancelEdit(event){
Session.set('sprintToEdit', null);
Session.set('success', null);
Session.set('error', null);
}
handleDescriptionChange(event){
this.setState({description: event.target.value});
}
handleBeginChange(event){
this.setState({start: event.target.value});
}
handleEndChange(event){
this.setState({end: event.target.value});
}
handleUSChange(id) {
let userstory;
if (this.state.userstory.indexOf(parseInt(id)) > -1)
userstory = this.state.userstory.filter(function(item) {
return item !== parseInt(id);
});
else
userstory = this.state.userstory.concat(parseInt(id));
this.setState({
userstory
});
}
handleSubmit(event){
event.preventDefault();
Meteor.call('sprint.add', this.state, this.props.currentProject.name, function(err, res) {
if (err) {
Session.set('error', err.message);
Session.set('success', null);
} else {
Session.set('success', 'Done !');
Session.set('error', null);
}
});
if (this.props.sprintToEdit)
Session.set('sprintToEdit', null);
}
renderSelectList(){
return (
<div className="pre-scrollable us-select-list">
<table className="table table-striped">
<tbody>
<tr>
<th >
Description
</th>
<th style={{width: 20}}></th>
</tr>
{this.props.userstories.map((userstory) => (
<tr>
<td style={{width: 20}} >
<span style={{backgroundColor: userstory.color}} className='badge'>{userstory.id}</span>
</td>
<td >
{(this.state.userstory.indexOf(parseInt(userstory.id)) > -1) ?
<del>{userstory.description}</del>
: <p>{userstory.description}</p>
}
</td>
<td>
<input type="checkbox" onChange={ () => { this.handleUSChange(userstory.id)}}
checked={(this.state.userstory.indexOf(parseInt(userstory.id)) > -1)}/>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
render(){
return (
<div className="row">
<div className="col-lg-12">
<h4>Add/Edit a sprint</h4>
<form onSubmit={this.handleSubmit} >
<div className="col-md-3">
<div className="input-group date">
<div className="input-group-addon">
Start :
</div>
<input type="date" onChange={this.handleBeginChange} value={this.state.start} id="start" className="form-control pull-right datepicker" required />
</div>
</div>
<div className="col-md-3">
<div className="input-group date">
<div className="input-group-addon">
End :
</div>
<input type="date" onChange={this.handleEndChange} value={this.state.end} id="end" className="form-control pull-right datepicker" required />
</div>
</div>
<div className="col-md-4">
<input type="text" className="form-control" placeholder="Description" value={this.state.description} onChange={this.handleDescriptionChange}/>
</div>
{this.props.sprintToEdit ?
<div>
<div className="col-md-1">
<button type="button" onClick={this.handleCancelEdit} className="btn btn-danger btn-block btn-flat">Cancel</button>
</div>
<div className="col-md-1">
<button className="btn btn-primary btn-block btn-flat">Confirm</button>
</div>
</div>
: <div className="col-md-2">
<button className="btn btn-primary btn-block btn-flat">Add</button>
</div>}
<br/>
{this.renderSelectList()}
</form>
</div>
</div>
);
}
}
export default AddSprintForm;
|
4bd21d842a4fcafdb05772442d456112698214e1
|
[
"JavaScript",
"Markdown"
] | 93 |
JavaScript
|
valcol/ScrumNinja
|
cd856dcd75c028f3962b98459313db24091bbde0
|
e75a9d6d992a1df42116b4b1f8d6636ad0412d0c
|
refs/heads/master
|
<repo_name>jlrau/py_data_code<file_sep>/dash_snippets.py
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/'
'c78bf172206ce24f77d6363a2d754b59/raw/'
'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
'usa-agricultural-exports-2011.csv')
df2 = df.groupby('state')['total exports'].sum().reset_index(name='total_exports_sum')
def generate_table(dataframe, max_rows=10):
return html.Table(
# Header
[html.Tr([html.Th(col) for col in dataframe.columns[1:]])] +
# Body
[html.Tr([
html.Td(dataframe.iloc[i][col]) for col in dataframe.columns[1:]
]) for i in range(min(len(dataframe), max_rows))]
)
app = dash.Dash()
markdown_text = 'hello there'
### Dash and Markdown
app.css.append_css({"external_url": "https://codepen.io/chriddyp/pen/bWLwgP.css"})
app.layout = html.Div(children=[
html.H1(children='Live Sales Dashboard'),
dcc.Markdown(children=markdown_text),
html.Label('Dropdown'),
dcc.Dropdown(
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': u'Montréal', 'value': 'MTL'},
{'label': 'San Francisco', 'value': 'SF'}
],
value='MTL'
),
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': df2['state'], 'y': df2['total_exports_sum'], 'type': 'bar', 'name': 'SF'}
],
'layout': {
'title': 'Dash Data Visualization'
}
}
),
html.H4(children='US Agriculture Exports (2011)'),
generate_table(df),
])
if __name__ == '__main__':
app.run_server(debug=True)
<file_sep>/README.md
# Python Data Code
Contains code examples and snippets used for Data transformation and analytics in Python.
<file_sep>/xml_parser.py
#! /usr/bin/python
import urllib.request
import xml.etree.ElementTree as etree
import csv
# Set Variables
url = 'https://www.w3schools.com/xml/cd_catalog.xml'
source_element = 'CD'
target_file = 'xml_data.csv'
#Pull xml from web address, including proxy handling
urllib.request.ProxyHandler()
page = urllib.request.urlopen(url)
xml_content = page.read()
e = etree.fromstring(xml_content)
#Setup target xml file
xml_data = open(target_file, 'w')
csvwriter = csv.writer(xml_data)
xml_head = []
#Final all attributes of "source_element" and write to CSV file ("target_file")
count = 0
for member in e.findall(source_element):
xml_row = []
if count == 0:
for item in member:
xml_head.append(item.tag)
csvwriter.writerow(xml_head)
count = count + 1
for item in member:
xml_row.append(item.text)
csvwriter.writerow(xml_row)
xml_data.close()
|
dae7fd1992a37aa94003a957ef6052737116e355
|
[
"Markdown",
"Python"
] | 3 |
Python
|
jlrau/py_data_code
|
39199848dbd3738c2642dcfd5abf1938de3c1fb8
|
c22e0b923671d12dd7c405fb8324dafa62613060
|
refs/heads/master
|
<repo_name>Baugrems/hiochatbot<file_sep>/app.py
import random
from discord import Game
from discord.ext.commands import Bot
import requests
import asyncio
import os
from discord import Channel
from discord import Role
from discord import Server
import discord
import boto
from tatsumaki.wrapper import ApiWrapper
import time
from discord import VoiceClient
import youtube_dl
BOT_PREFIX = "."
TOKEN = (os.environ['TOKEN'])
client = Bot(command_prefix=BOT_PREFIX)
@client.command(name="TatLeaders",
description="Grab tatsumaki rank leaders when used.",
brief="Tatsumanki Rank Leaderboard",
aliases=["tleaders", "tatleaders"],
pass_context=True)
async def checkTatRank(context):
msg = "Give Dobby a moment to grab list..."
await client.send_message(context.message.channel, msg)
await client.send_typing(context.message.channel)
wrapper = ApiWrapper("b9ff5b5da7b223a3251cd98a68329b18-10d056d2a47b9-75b8b43ff968bb3cea8fdfb4821815d9")
response = await wrapper.leaderboard(context.message.server.id, 10)
msg = "```"
for user in response:
if context.message.server.get_member(user["user_id"]):
msg += "\nRank " + str(user["rank"]) + ": " + context.message.server.get_member(user["user_id"]).nick + " with " + user["score"] + " points."
else:
msg += "\nRank " + str(user["rank"]) + ": Unknown User with " + user["score"] + " points."
time.sleep(2)
response = await wrapper.leaderboard(context.message.server.id, 20)
for user in response:
if context.message.server.get_member(user["user_id"]):
msg += "\nRank " + str(user["rank"]) + ": " + context.message.server.get_member(user["user_id"]).nick + " with " + user["score"] + " points."
else:
msg += "\nRank " + str(user["rank"]) + ": Unknown User with " + user["score"] + " points."
msg += "```"
await client.send_message(context.message.channel, msg)
# DOBBY COMMANDS
# If no command given, sends random Dobby GIF
# Dobby help to get list of dobby commands
@client.group(pass_context=True)
async def dobby(ctx):
if ctx.invoked_subcommand is None:
availablegifs = [
"images/dobbydie.gif",
"images/dobbyfree.gif",
"images/dobbyheadhit.gif",
"images/dobbyhitself.gif",
"images/dobbymagic.gif",
"images/dobbysmug.gif",
"images/dobbytwitch.gif"
]
await client.send_file(ctx.message.channel, random.choice(availablegifs))
@dobby.command(name='Random Spell',
description="Provides a random Harry Potter Spell.",
brief="Spellbook.",
aliases=['spells', 'spellbook', 'charm', 'curse', "spell"],
pass_context=True)
async def spell(context):
url = "https://www.potterapi.com/v1/spells?key=<KEY>"
response = requests.get(url)
value = random.choice(response.json())
msg = "A good " + value["type"].lower() + " might be " + value["spell"] + ". It " + value["effect"] + "."
await client.send_message(context.message.channel, msg)
# VOICE COMMANDS - COMMENTED OUT AS HEROKU DOES NOT SUPPORT DISCORD VOICE AT THE MOMENT
# @dobby.command(name="sing",
# description="Makes <NAME>",
# brief="Voicechat Dobby",
# aliases=["themesong"],
# pass_context=True)
# async def sing(context):
# # https://www.youtube.com/watch?v=Htaj3o3JD8I - HP THEME
# # https://www.youtube.com/watch?v=xCqfwXeq6_8 - <NAME>
# author = context.message.author
# voice_channel = author.voice_channel
# voice = await client.join_voice_channel(voice_channel)
# player = await voice.create_ytdl_player('https://www.youtube.com/watch?v=Htaj3o3JD8I')
# player.start()
# @dobby.command(name="disconnect",
# description="Removes dobby from voice",
# brief="Kicks Dobby VC",
# aliases=["shush"],
# pass_context=True)
# async def disconnect(context):
# for x in client.voice_clients:
# if(x.server == context.message.server):
# return await x.disconnect()
#END OF VOICE COMMANDS
@dobby.command(name="Cat Facts",
description="Provides a random cat fact.",
brief="Cat Facts",
aliases=["cf", "catfact", "catfacts"],
pass_context=True)
async def catfacts(context):
url = "https://cat-fact.herokuapp.com/facts/random?animal=cat&amount=1"
response = requests.get(url)
value = response.json()
msg = value["text"]
await client.send_message(context.message.channel, msg)
@dobby.command(name="Dog Photo",
description="Random Doggo",
brief="random dooooogggooo",
aliases=["dog","dp","doggo","pupper"],
pass_context=True)
async def dogphoto(context):
url = "https://dog.ceo/api/breeds/image/random"
response = requests.get(url)
value = response.json()
msg = value["message"]
await client.send_message(context.message.channel, msg)
@dobby.command(name='sorting',
description="Picks a random house to display.",
brief="Choose a random house.",
aliases=['sort', 'bestHouse'],
pass_context=True)
async def bestHouse(context):
url = "https://www.potterapi.com/v1/sortinghat"
response = requests.get(url)
value = response.json()
msg = "" + value + " is best Dobby thinks."
await client.send_message(context.message.channel, msg)
@dobby.command(name="streetview",
description="Google Streetview from provided location",
brief="Streetview",
aliases=["street"],
pass_context=True)
async def streetview(context, location = "Hogwarts"):
url = "https://maps.googleapis.com/maps/api/streetview?location=%22" + location + "%22&size=600x400&key=<KEY>"
await client.send_message(context.message.channel, url)
# "https://maps.googleapis.com/maps/api/streetview?location=%22Denver%22&size=600x400&key=<KEY>"
@dobby.command(name="Dobby Timer",
description="Set a timer with Dobby",
brief="Set a timer",
aliases=["timer"],
pass_context=True)
async def dobbyTimer(context, time, text):
msg = "Dobby will alert you in {0} second(s) when time up.".format(time)
await client.send_message(context.message.channel, msg)
await asyncio.sleep(float(time))
msg = "{0.message.author.mention} time up for {1}".format(context, text)
await client.send_message(context.message.channel, msg)
@dobby.command(name="Dobby Help",
description="Gives a list of available commands.",
brief="Dobby Help.",
aliases=['help', 'halp'],
pass_context=True)
async def dobbyhelp(context):
msg = '''```Dobby Commands:
.dobby spell - Provides a random Harry Potter Spell.
.dobby sort - Picks a random house to display.
.dobby character "name" - Finds a character by that name from HP.
.dobby d20 - Rolls a visual 20 sided die.
.dobby timer x mention - Sets a timer for x seconds and @mentions.
Other Commands:
.tleaders - Shows named list of Tatsumaki High Score.
Contact <NAME> <@Baugrems1234> for Technical Support.```'''
await client.send_message(context.message.channel, msg)
@dobby.command(name="D20 Roller",
description="Roll a D20 and get an image back with results.",
brief="Roll a D20.",
aliases=["d20", "D20", "roll20"],
pass_context=True)
async def roll20(context):
img = "images/D20_" + str(random.randint(1,20)) + ".png"
await client.send_file(context.message.channel, img)
#TODO: Find a better way to do this...
@dobby.command(name="Character finder",
description="Finds Harry Potter Characters by name",
brief="Finds characters",
aliases=["character", "find", "search"],
pass_context=True)
async def character(context, findName = None):
if findName is None:
url = 'https://www.potterapi.com/v1/characters?key=<KEY>'
response = requests.get(url)
value = random.choice(response.json())
else:
payload = {'name': findName, 'key': <KEY>'}
response = requests.get('https://www.potterapi.com/v1/characters', params=payload)
value = response.json()
value = value[0]
if not value:
msg = "Dobby cannot find that character... Dobby deserves punishment!!!"
await client.send_message(context.message.channel, msg)
await client.send_file(context.message.channel, "images/dobbyhitself.gif")
else:
msg = value["name"] + " "
if value.get('role', False):
msg += ":: " + value["role"] + " "
if value.get("school", False):
msg = msg + ":: " + value["school"] + " "
if value.get('house', False):
msg = msg + ":: " + value["house"] + " house "
if value.get("deathEater", False):
msg = msg + ":: Death Eater "
if value.get("dumbledoresArmy", False):
msg = msg + ":: Member of Dumbledores Army "
if value.get("orderOfThePhoenix", False):
msg = msg + ":: Member of the Order of the Phoenix "
if value.get("ministryOfMagic", False):
msg = msg + ":: Member of the Ministry of Magic "
if value.get("species", False):
msg += "::Species - " + value["species"] + " "
if value.get("bloodStatus", False):
msg += ":: Blood-Status - " + value["bloodStatus"]
print(response.url)
await client.send_message(context.message.channel, msg)
# @dobby.command(name='trivia',
# description="Begins Harry Potter Trivia",
# brief="HP Trivia.",
# aliases=['HP-Trivia, trivia'],
# pass_context=True)
# async def trivia(context):
# msg = "Time for Harry Potter Trivia. Dobby loves Trivia..."
# await client.send_message(context.message.channel, msg)
# value = random.choice(possible_questions)
# await client.send_message(context.message.channel, msg)
#These trigger on any message. Not just commands.
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
# We also want to make sure it checks for commands first
await client.process_commands(message)
if message.author == client.user:
return
mcont = message.content.lower()
if mcont.startswith('hi dobby'):
msg = 'Hello {0.author.mention}. Type ".dobby help" if want help on Dobby!'.format(message)
await client.send_message(message.channel, msg)
if mcont.startswith('validate me please'):
if message.channel == client.get_channel('450870668435914752'):
msg = 'Hello @everyone! {0.author.mention} needs to be checked in!'.format(message)
await client.send_message(client.get_channel('450870668435914752'), msg)
else:
msg = "You seem to be validated already, {0.author.mention}!".format(message)
await client.send_message(message.channel, msg)
if mcont.startswith('.clear'):
#Clears channel history, but only if someone does it inside the arrival room
if message.channel.id == '450870668435914752':
tmp = await client.send_message(message.channel, 'Clearing messages...')
async for msg in client.logs_from(message.channel):
await client.delete_message(msg)
#PotterAPI KEY <KEY>
if mcont.startswith('dobby give me a spell'):
url = "https://www.potterapi.com/v1/spells?key=<KEY>"
response = requests.get(url)
value = random.choice(response.json())
msg = "A good " + value["type"].lower() + " might be " + "**" + value["spell"] + "**" + ". It " + value["effect"] + "."
await client.send_message(message.channel, msg)
if mcont.startswith('dobby what house is best?'):
url = "https://www.potterapi.com/v1/sortinghat"
response = requests.get(url)
value = response.json()
msg = "" + value + " is best Dobby thinks."
await client.send_message(message.channel, msg)
if mcont.startswith('<NAME>'):
await client.send_file(message.channel, "images/pepehug.png")
# if message.content.lower().startswith('dobby tell me about someone'):
# url = 'https://www.potterapi.com/v1/characters?key=<KEY>'
# response = requests.get(url)
# value = random.choice(response.json())
# msg = "How about " + value["name"] + " a " + value["role"] + " from " + value["school"] + ". " + value["name"] + " is also a " + value["species"] + " " + value["bloodStatus"]
# await client.send_message(message.channel, msg)
#More Random Stuff
if 'dobby a sock' in mcont:
await client.send_file(message.channel, "images/dobbysock.gif")
elif 'sock' in mcont:
msg = "Did someone say Sock?"
await client.send_message(message.channel, msg)
if 'dobby i love you' in mcont:
msg = "{0.author.mention}, I love you too!".format(message)
await client.send_message(message.channel, msg)
@client.event
async def on_member_join(member):
msg = 'Welcome, {0.mention}! Please set your discord name to match your Hogwarts.io name. '.format(member)
await client.send_message(client.get_channel('450870668435914752'), msg)
msg = 'Also be sure to post your discord name and # number at https://www.hogwarts.io/viewtopic.php?f=44&t=2233'
await client.send_message(client.get_channel('450870668435914752'), msg)
msg = 'Say "Validate me please" when you are done with both tasks.'
await client.send_message(client.get_channel('450870668435914752'), msg)
# 450870668435914752 Arrival channel ID
@client.event
async def on_ready():
await client.change_presence(game=Game(name="with a sock"))
print("Logged in as " + client.user.name)
for server in client.servers:
for channel in server.channels:
print(channel.id + " " + channel.name)
print(Server.roles)
for server in client.servers:
for role in server.roles:
print(role.id + " " + role.name)
client.run(TOKEN)<file_sep>/README.md
# Dobby the Chat Bot
This is a chat bot for Discord written in Python.
Coded specifically for use on the discord server for [Hogwarts.io](https://www.hogwarts.io/)
Dobby is hosted on a Heroku server using environmental variables to hide any TOKENs or Secrets.
Feel free to download this code and use it/modify it, but make sure to change my channel IDs otherwise yours will not work.
<file_sep>/requirements.txt
aiohttp==3.4.4
asn1crypto==0.24.0
async-timeout==3.0.1
asyncio==3.4.3
attrs==18.2.0
Automat==0.7.0
blinker==1.4
boto==2.49.0
certifi==2018.8.24
cffi==1.11.5
chardet==3.0.4
Click==7.0
Cogs==0.4.3
colorama==0.3.7
cryptography==2.3.1
cssselect==1.0.3
discord==0.0.2
discord.py==0.16.12
oauthlib==2.0.6
parse==1.9.0
parsel==1.5.0
pyasn1==0.4.4
pyasn1-modules==0.2.2
pycparser==2.19
PyDispatcher==2.0.5
PyNaCl==1.3.0
pyOpenSSL==18.0.0
pyserial==3.4
pytz==2018.5
pyxdg==0.25
PyYAML==3.13
requests==2.21.0
six==1.12.0
tatsumaki.py==0.1
youtube-dl==2019.1.24
|
83a8136a9dfba355536b514600ae97506cc4ac54
|
[
"Markdown",
"Python",
"Text"
] | 3 |
Python
|
Baugrems/hiochatbot
|
c6497310672d27516f53bdbe0da22dca57ca0e3e
|
018e0a9d13cd4b72373689883d96b1f62792e66b
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'assimetrico',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Vestidos</li>
<li>Assimétrico</li>
</ul>
<h1>assimétrico</h1>
`,
styleUrls: ['../acss.component.css']
})
export class VAssimetricoViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'decote-em-v',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Vestidos</li>
<li>Decote em "V"</li>
</ul>
<h1>Decote em "V"</h1>
`,
styleUrls: ['../acss.component.css']
})
export class VDecoteEmVViewComponent {
}<file_sep>import { Component, VERSION } from '@angular/core';
@Component({
selector: 'breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: [ './breadcrumb.component.css' ]
})
export class bd {}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'sapatos-masculinos-loafer',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Sapatos Masculinos</li>
<li>Loafer</li>
</ul>
<h1>Loafer</h1>
`,
styleUrls: ['../acss.component.css']
})
export class SMLoaferViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'acessorios-presilhas',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Acessórios</li>
<li>Presilhas</li>
</ul>
<h1>Presilhas</h1>
`,
styleUrls: ['../acss.component.css']
})
export class PresilhasViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'bermudas-alfaiataria',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Bermudas</li>
<li>Alfaiataria</li>
</ul>
<h1>Alfaiataria</h1>
`,
styleUrls: ['../acss.component.css']
})
export class BAlfaiatariaViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'sapatos-masculinos-sandalias',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Sapatos Masculinos</li>
<li>Sandálias</li>
</ul>
<h1>Sandálias</h1>
`,
styleUrls: ['../acss.component.css']
})
export class SMSandaliasViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'saias-dropeada',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Saias</li>
<li>Dropeada</li>
</ul>
<h1>Dropeada</h1>
`,
styleUrls: ['../acss.component.css']
})
export class SDropeadaViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'decote-em-u',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Vestidos</li>
<li>Decote em "U"</li>
</ul>
<h1>Decote em "U"</h1>
`,
styleUrls: ['../acss.component.css']
})
export class VDecoteEmUViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'tomara-que-caia',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Vestidos</li>
<li>Tomara que-caia</li>
</ul>
<h1>Tomara que-caia</h1>
`,
styleUrls: ['../acss.component.css']
})
export class VTomaraQueCaiaViewComponent {
}<file_sep>import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { ChapeusViewComponent } from './Produtos/Acessorios/chapeus.component';
import { RelogiosViewComponent } from'./Produtos/Acessorios/relogios.component';
import { CintosViewComponent } from'./Produtos/Acessorios/cintos.component';
import { AneisViewComponent } from'./Produtos/Acessorios/aneis.component';
import { BolsasViewComponent } from'./Produtos/Acessorios/bolsas.component';
import { BrincosViewComponent } from'./Produtos/Acessorios/brincos.component';
import { CachecoisViewComponent } from'./Produtos/Acessorios/cachecois.component';
import { ColaresViewComponent } from'./Produtos/Acessorios/colares.component';
import { PresilhasViewComponent } from'./Produtos/Acessorios/presilhas.component';
import { PulseirasViewComponent } from'./Produtos/Acessorios/pulseiras.component';
import { AviadorViewComponent } from'./Produtos/Oculos/aviador.component';
import { BorboletaViewComponent } from'./Produtos/Oculos/borboleta.component';
import { FlatViewComponent } from'./Produtos/Oculos/flat.component';
import { GatinhoViewComponent } from'./Produtos/Oculos/gatinho.component';
import { HexagonalViewComponent } from'./Produtos/Oculos/hexagonal.component';
import { MeiaarmacaoViewComponent } from'./Produtos/Oculos/meia-armacao.component';
import { OvalViewComponent } from'./Produtos/Oculos/oval.component';
import { QuadradoViewComponent } from'./Produtos/Oculos/quadrado.component';
import { RedondoViewComponent } from'./Produtos/Oculos/redondo.component';
import { RetangularViewComponent } from'./Produtos/Oculos/retangular.component';
import { CBrancaBasicaViewComponent } from'./Produtos/Camisetas/brancabasica.component';
import { ComEstampaViewComponent } from'./Produtos/Camisetas/comestampa.component';
import { DipDyeViewComponent } from'./Produtos/Camisetas/dipdye.component';
import { EsportivaViewComponent } from'./Produtos/Camisetas/esportiva.component';
import { GolaAltaViewComponent } from'./Produtos/Camisetas/golaalta.component';
import { GolaVViewComponent } from'./Produtos/Camisetas/golav.component';
import { ListrasViewComponent } from'./Produtos/Camisetas/listras.component';
import { MangaCurtaViewComponent } from'./Produtos/Camisetas/mangacurta.component';
import { PretaBasicaViewComponent } from'./Produtos/Camisetas/pretabasica.component';
import { SemEstampaViewComponent } from'./Produtos/Camisetas/semestampa.component';
import { BBrancaBasicaViewComponent } from'./Produtos/Blusas/brancabasica.component';
import { BComCapuzViewComponent } from'./Produtos/Blusas/comcapuz.component';
import { BComEstampaViewComponent } from'./Produtos/Blusas/comestampa.component';
import { BFullPrintViewComponent } from'./Produtos/Blusas/fullprint.component';
import { BMangaCompridaViewComponent } from'./Produtos/Blusas/mangacomprida.component';
import { BMangaCurtaViewComponent } from'./Produtos/Blusas/mangacurta.component';
import { BPretoBasicoViewComponent } from'./Produtos/Blusas/pretobasico.component';
import { BSemCapuzViewComponent } from'./Produtos/Blusas/semcapuz.component';
import { BSemEstampaViewComponent } from'./Produtos/Blusas/semestampa.component';
import { BSemMangaViewComponent } from'./Produtos/Blusas/semmanga.component';
import { CCurtaViewComponent} from'./Produtos/Calcas/curta.component';
import { CJeansViewComponent} from'./Produtos/Calcas/jeans.component';
import { CMoletomViewComponent} from'./Produtos/Calcas/moletom.component';
import { CCroppedViewComponent} from'./Produtos/Calcas/cropped.component';
import { CRetaViewComponent} from'./Produtos/Calcas/reta.component';
import { CSlouchyViewComponent} from'./Produtos/Calcas/slouchy.component';
import { CClochardViewComponent} from'./Produtos/Calcas/clochard.component';
import { CJoggerViewComponent} from'./Produtos/Calcas/jogger.component';
import { CSkinnyViewComponent} from'./Produtos/Calcas/skinny.component';
import { CChinoViewComponent} from'./Produtos/Calcas/chino.component';
import { VTomaraQueCaiaViewComponent} from'./Produtos/Vestidos/tomaraquecaia.component';
import { VDecoteEmVViewComponent} from'./Produtos/Vestidos/decoteemv.component';
import { VDecoteEmUViewComponent} from'./Produtos/Vestidos/decoteemu.component';
import { VDecoteNasCostasViewComponent} from'./Produtos/Vestidos/decotenascostas.component';
import { VAssimetricoViewComponent} from'./Produtos/Vestidos/assimetrico.component';
import { VFrenteUnicaViewComponent} from'./Produtos/Vestidos/frenteunica.component';
import { VGolaAltaViewComponent} from'./Produtos/Vestidos/golaalta.component';
import { VQuadradoViewComponent} from'./Produtos/Vestidos/quadrado.component';
import { VCoracaoViewComponent} from'./Produtos/Vestidos/coracao.component';
import { VCanoaViewComponent} from'./Produtos/Vestidos/canoa.component';
import { BJeansViewComponent} from'./Produtos/Bermudas/jeans.component';
import { BChinoViewComponent} from'./Produtos/Bermudas/chino.component';
import { BAlfaiatariaViewComponent} from'./Produtos/Bermudas/alfaiataria.component';
import { BCargoViewComponent} from'./Produtos/Bermudas/cargo.component';
import { BMoletomViewComponent} from'./Produtos/Bermudas/moletom.component';
import { BSinteticasViewComponent} from'./Produtos/Bermudas/sinteticas.component';
import { BTactelViewComponent} from'./Produtos/Bermudas/tactel.component';
import { BPoliesterViewComponent} from'./Produtos/Bermudas/poliester.component';
import { BSarjaViewComponent} from'./Produtos/Bermudas/sarja.component';
import { BChambrayViewComponent} from'./Produtos/Bermudas/chambray.component';
import { SEvaseViewComponent} from'./Produtos/Saias/evase.component';
import { SLapisViewComponent} from'./Produtos/Saias/lapis.component';
import { SPregasViewComponent} from'./Produtos/Saias/pregas.component';
import { SEnvelopeViewComponent} from'./Produtos/Saias/envelope.component';
import { SDropeadaViewComponent} from'./Produtos/Saias/dropeada.component';
import { SAssimetricaViewComponent} from'./Produtos/Saias/assimetrica.component';
import { SBalaoViewComponent} from'./Produtos/Saias/balao.component';
import { STracadaViewComponent} from'./Produtos/Saias/tracada.component';
import { SEnviesadaViewComponent} from'./Produtos/Saias/enviesada.component';
import { SMiniViewComponent} from'./Produtos/Saias/mini.component';
import { SMBrogueViewComponent} from'./Produtos/SapatosMasculinos/brogue.component';
import { SMBotasViewComponent} from'./Produtos/SapatosMasculinos/botas.component';
import { SMTenisCasualViewComponent} from'./Produtos/SapatosMasculinos/teniscasual.component';
import { SMMocassimViewComponent} from'./Produtos/SapatosMasculinos/mocassim.component';
import { SMSandaliasViewComponent} from'./Produtos/SapatosMasculinos/sandalias.component';
import { SMSapatenisViewComponent} from'./Produtos/SapatosMasculinos/sapatenis.component';
import { SMLoaferViewComponent} from'./Produtos/SapatosMasculinos/loafer.component';
import { SMOxfordViewComponent} from'./Produtos/SapatosMasculinos/oxford.component';
import { SMDocksideViewComponent} from'./Produtos/SapatosMasculinos/dockside.component';
import { SMDerbyViewComponent} from'./Produtos/SapatosMasculinos/derby.component';
import { SFSandaliasViewComponent} from'./Produtos/SapatosFemininos/sandalias.component';
import { SFBotasViewComponent} from'./Produtos/SapatosFemininos/botas.component';
import { SFSapatilhasViewComponent} from'./Produtos/SapatosFemininos/sapatilhas.component';
import { SFSaltoGrossoViewComponent} from'./Produtos/SapatosFemininos/saltogrosso.component';
import { SFSaltoFinoViewComponent} from'./Produtos/SapatosFemininos/saltofino.component';
import { SFAnabelasViewComponent} from'./Produtos/SapatosFemininos/anabelas.component';
import { SFRasteirinhasViewComponent} from'./Produtos/SapatosFemininos/rasteirinhas.component';
import { SFMocassimViewComponent} from'./Produtos/SapatosFemininos/mocassim.component';
import { SFPeepToeViewComponent} from'./Produtos/SapatosFemininos/peeptoe.component';
import { SFGladiadorViewComponent} from'./Produtos/SapatosFemininos/gladiador.component';
import { HomeViewComponent } from './Produtos/home.component';
@NgModule({
declarations: [
ChapeusViewComponent],
imports: [
RouterModule.forRoot([
{ path: 'home', component: HomeViewComponent },
{ path: 'home/acessorios-chapeus', component: ChapeusViewComponent },
{ path: 'home/acessorios-relogios', component: RelogiosViewComponent },
{ path: 'home/acessorios-cintos', component: CintosViewComponent },
{ path: 'home/acessorios-aneis', component: AneisViewComponent },
{ path: 'home/acessorios-bolsas', component: BolsasViewComponent },
{ path: 'home/acessorios-brincos', component: BrincosViewComponent },
{ path: 'home/acessorios-cachecois', component: CachecoisViewComponent },
{ path: 'home/acessorios-colares', component: ColaresViewComponent },
{ path: 'home/acessorios-presilhas', component: PresilhasViewComponent },
{ path: 'home/acessorios-pulseiras', component: PulseirasViewComponent },
{ path: 'home/oculos-aviador', component: AviadorViewComponent },
{ path: 'home/oculos-borboleta', component: BorboletaViewComponent },
{ path: 'home/oculos-flat', component: FlatViewComponent },
{ path: 'home/oculos-gatinho', component: GatinhoViewComponent },
{ path: 'home/oculos-hexagonal', component: HexagonalViewComponent },
{ path: 'home/oculos-meia-armacao', component: MeiaarmacaoViewComponent },
{ path: 'home/oculos-oval', component: OvalViewComponent },
{ path: 'home/oculos-quadrado', component: QuadradoViewComponent },
{ path: 'home/oculos-redondo', component: RedondoViewComponent },
{ path: 'home/oculos-retangular', component: RetangularViewComponent },
{ path: 'home/camisetas-brancabasica', component: CBrancaBasicaViewComponent },
{ path: 'home/camisetas-comestampa', component: ComEstampaViewComponent },
{ path: 'home/camisetas-dipdye', component: DipDyeViewComponent },
{ path: 'home/camisetas-esportiva', component: EsportivaViewComponent },
{ path: 'home/camisetas-golaalta', component: GolaAltaViewComponent },
{ path: 'home/camisetas-golav', component: GolaVViewComponent },
{ path: 'home/camisetas-listras', component: ListrasViewComponent },
{ path: 'home/camisetas-mangacurta', component: MangaCurtaViewComponent },
{ path: 'home/camisetas-pretabasica', component: PretaBasicaViewComponent },
{ path: 'home/camisetas-semestampa', component: SemEstampaViewComponent },
{ path: 'home/blusas-brancabasica', component: BBrancaBasicaViewComponent },
{ path: 'home/blusas-comcapuz', component: BComCapuzViewComponent },
{ path: 'home/blusas-comestampa', component: BComEstampaViewComponent },
{ path: 'home/blusas-fullprint', component: BFullPrintViewComponent },
{ path: 'home/blusas-mangacomprida', component: BMangaCompridaViewComponent },
{ path: 'home/blusas-mangacurta', component: BMangaCurtaViewComponent },
{ path: 'home/blusas-pretobasico', component: BPretoBasicoViewComponent },
{ path: 'home/blusas-semcapuz', component: BSemCapuzViewComponent },
{ path: 'home/blusas-semestampa', component: BSemEstampaViewComponent },
{ path: 'home/blusas-semmanga', component: BSemMangaViewComponent },
{ path: 'home/calcas-curta', component: CCurtaViewComponent },
{ path: 'home/calcas-jeans', component: CJeansViewComponent },
{ path: 'home/calcas-moletom', component: CMoletomViewComponent },
{ path: 'home/calcas-cropped', component: CCroppedViewComponent },
{ path: 'home/calcas-reta', component: CRetaViewComponent },
{ path: 'home/calcas-slouchy', component: CSlouchyViewComponent },
{ path: 'home/calcas-clochard', component: CClochardViewComponent },
{ path: 'home/calcas-jogger', component: CJoggerViewComponent },
{ path: 'home/calcas-skinny', component: CSkinnyViewComponent },
{ path: 'home/calcas-chino', component: CChinoViewComponent },
{ path: 'home/vestidos-tomara-que-caia', component: VTomaraQueCaiaViewComponent },
{ path: 'home/vestidos-decote-em-v', component: VDecoteEmVViewComponent },
{ path: 'home/vestidos-decote-em-u', component: VDecoteEmUViewComponent },
{ path: 'home/vestidos-decote-nas-costas', component: VDecoteNasCostasViewComponent },
{ path: 'home/vestidos-assimetrico', component: VAssimetricoViewComponent },
{ path: 'home/vestidos-frente-unica', component: VFrenteUnicaViewComponent },
{ path: 'home/vestidos-gola-alta', component: VGolaAltaViewComponent },
{ path: 'home/vestidos-quadrado', component: VQuadradoViewComponent },
{ path: 'home/vestidos-coracao', component: VCoracaoViewComponent },
{ path: 'home/vestidos-canoa', component: VCanoaViewComponent },
{ path: 'home/bermudas-jeans', component: BJeansViewComponent },
{ path: 'home/bermudas-chino', component: BChinoViewComponent },
{ path: 'home/bermudas-alfaiataria', component: BAlfaiatariaViewComponent },
{ path: 'home/bermudas-cargo', component: BCargoViewComponent },
{ path: 'home/bermudas-moletom', component: BMoletomViewComponent },
{ path: 'home/bermudas-sinteticas', component: BSinteticasViewComponent },
{ path: 'home/bermudas-tactel', component: BTactelViewComponent },
{ path: 'home/bermudas-poliester', component: BPoliesterViewComponent },
{ path: 'home/bermudas-sarja', component: BSarjaViewComponent },
{ path: 'home/bermudas-chambray', component: BChambrayViewComponent },
{ path: 'home/saias-evase', component: SEvaseViewComponent },
{ path: 'home/saias-lapis', component: SLapisViewComponent },
{ path: 'home/saias-pregas', component: SPregasViewComponent },
{ path: 'home/saias-envelope', component: SEnvelopeViewComponent },
{ path: 'home/saias-dropeada', component: SDropeadaViewComponent },
{ path: 'home/saias-assimetrica', component: SAssimetricaViewComponent },
{ path: 'home/saias-balao', component: SBalaoViewComponent },
{ path: 'home/saias-tracada', component: STracadaViewComponent },
{ path: 'home/saias-enviesada', component: SEnviesadaViewComponent },
{ path: 'home/saias-mini', component: SMiniViewComponent },
{ path: 'home/sapatos-masculinos-brogue', component: SMBrogueViewComponent },
{ path: 'home/sapatos-masculinos-botas', component: SMBotasViewComponent },
{ path: 'home/sapatos-masculinos-tenis-casual', component: SMTenisCasualViewComponent },
{ path: 'home/sapatos-masculinos-mocassim', component: SMMocassimViewComponent },
{ path: 'home/sapatos-masculinos-sandalias', component: SMSandaliasViewComponent },
{ path: 'home/sapatos-masculinos-sapatenis', component: SMSapatenisViewComponent },
{ path: 'home/sapatos-masculinos-loafer', component: SMLoaferViewComponent },
{ path: 'home/sapatos-masculinos-oxford', component: SMOxfordViewComponent },
{ path: 'home/sapatos-masculinos-dockside', component: SMDocksideViewComponent },
{ path: 'home/sapatos-masculinos-derby', component: SMDerbyViewComponent },
{ path: 'home/sapatos-femininos-sandalias', component: SFSandaliasViewComponent },
{ path: 'home/sapatos-femininos-botas', component: SFBotasViewComponent },
{ path: 'home/sapatos-femininos-sapatilhas', component: SFSapatilhasViewComponent },
{ path: 'home/sapatos-femininos-salto-grosso', component: SFSaltoGrossoViewComponent },
{ path: 'home/sapatos-femininos-salto-fino', component: SFSaltoFinoViewComponent },
{ path: 'home/sapatos-femininos-anabelas', component: SFAnabelasViewComponent },
{ path: 'home/sapatos-femininos-rasteirinhas', component: SFRasteirinhasViewComponent },
{ path: 'home/sapatos-femininos-mocassim', component: SFMocassimViewComponent },
{ path: 'home/sapatos-femininos-peep-toe', component: SFPeepToeViewComponent },
{ path: 'home/sapatos-femininos-gladiador', component: SFGladiadorViewComponent },
])
],
exports: [
RouterModule,
],
providers: [],
})
export class AppRoutingModule {}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'acessorios-pulseiras',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Acessórios</li>
<li>Pulseiras</li>
</ul>
<h1>Pulseiras</h1>
`,
styleUrls: ['../acss.component.css']
})
export class PulseirasViewComponent {
}<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'sapatos-femininos-gladiador',
template: `
<ul class="breadcrumb">
<li><a routerLinkActive="active" routerLink="/home" href="">Home</a></li>
<li>Sapatos Femininos</li>
<li>Gladiador</li>
</ul>
<h1>Gladiador</h1>
`,
styleUrls: ['../acss.component.css']
})
export class SFGladiadorViewComponent {
}
|
cb4d768eb9300f2fa2b6727742f615db6b01cd9e
|
[
"TypeScript"
] | 13 |
TypeScript
|
GuilhermeNZ/Projeto-Angular
|
f9761b36d3a2796753bf2d7b51b3ae34161f4616
|
bc9a250b0401f0671cccdd4d4f2f70bb5c54483f
|
refs/heads/master
|
<file_sep>import re
from collections import defaultdict
#BioPython
from Bio import SearchIO
from Bio import SeqIO
from Bio.Seq import Seq
#Django libraires
from browse.models import *
from djangophylocore.models import Taxonomy
from django.db.models import Max
from django.db.utils import IntegrityError
#Custom librairies
from tools.hist_ss import get_hist_ss
from tools.taxonomy_from_gis import taxonomy_from_gis
already_exists = []
def get_sequence(gi, sequence_file):
"""sequences is likely large, so we don't want to store it in memory.
Read file in each time, saving only sequence with gi"""
for s in SeqIO.parse(sequence_file, "fasta"):
if gi in s.id:
return s
species_re = re.compile(r'\[(.*?)\]')
def taxonomy_from_header(header, gi):
match = species_re.findall(header)
if match:
organism = match[-1]
else:
print "No match for {}: {}, searh NCBI".format(gi, header)
while True:
try:
organism = taxonomy_from_gis([gi]).next()
break
except StopIteration:
pass
organism = organism.replace(":", " ")
organism = re.sub(r'([a-zA-Z0-9]+)[\./#_:]([a-zA-Z0-9]+)', r'\1 \2', organism)
organism = re.sub(r'([a-zA-Z0-9]+)\. ', r'\1 ', organism)
organism = re.sub(r"['\(\)\.]", r'', organism)
organism = organism.lower()
try:
return Taxonomy.objects.get(name=organism.lower())
except:
try:
genus = Taxonomy.objects.get(name=organism.split(" ")[0].lower())
if genus.type_name != "scientific name":
genus = genus.get_scientific_names()[0]
except:
print header
return Taxonomy.objects.get(name="unidentified")
#Maybe the var is wrong
if "var" in organism:
try:
org_end = organism.split("var ")[1]
except IndexError:
return Taxonomy.objects.get(name="unidentified")
best_orgs = genus.children.filter(name__endswith=org_end).all()
if len(best_orgs):
return best_orgs[0]
else:
return Taxonomy.objects.get(name="unidentified")
else:
return Taxonomy.objects.get(name="unidentified")
print organism
print "Genus =", genus
print "Are you sure there is no taxa that matches? Check again:"
taxas = []
for i, c in enumerate(genus.children.all()):
print "{}: {} ==?== {}".format(i, c, organism)
taxas.append(c)
index = raw_input("Choose the index that best matches: ")
try:
index = int(save)
except ValueError:
return Taxonomy.objects.get(name="unidentified")
try:
return taxas[index]
except IndexError:
return Taxonomy.objects.get(name="unidentified")
def load_variants(hmmerFile, sequences, reset=True):
"""Save domain hits from a hmmer hmmsearch file into the Panchenko Histone
Variant DB format.
Parameters:
___________
hmmerFile : string
Path to HMMer hmmsearch output file
sequences : string
Path to of sequences used to search the HMM
threshold : float
Keep HSPS with scores >= threshold. Optional.
"""
if reset:
Sequence.objects.all().delete()
Features.objects.all().delete()
Score.objects.all().delete()
try:
unknown_model = Variant.objects.get(id="Unknown")
except Variant.DoesNotExist:
try:
core_unknown = Histone.objects.get(id="Unknown")
except:
core_unknown = Histone("Unknown")
core_unknown.save()
unknown_model = Variant(core_type=core_unknown, id="Unknown")
unknown_model.save()
for variant_query in SearchIO.parse(hmmerFile, "hmmer3-text"):
print "Loading variant:", variant_query.id
try:
variant_model = Variant.objects.get(id=variant_query.id)
except:
if "H2A" in variant_query.id:
core_histone = Histone.objects.get(id="H2A")
elif "H2B" in variant_query.id:
core_histone = Histone.objects.get(id="H2B")
elif "H3" in variant_query.id:
core_histone = Histone.objects.get(id="H3")
elif "H4" in variant_query.id:
core_histone = Histone.objects.get(id="H4")
elif "H1" in variant_query.id:
core_histone = Histone.objects.get(id="H1")
else:
continue
variant_model = Variant(id=variant_query.id, core_type=core_histone)
variant_model.save()
for hit in variant_query:
headers = "{}{}".format(hit.id, hit.description).split("gi|")[1:]
for header in headers:
gi = header.split("|")[0]
for i, hsp in enumerate(hit):
seqs = Sequence.objects.filter(id=gi)
if len(seqs) > 0:
#Sequence already exists. Compare bit scores, if current bit score is
#greater than current, reassign variant and update scores. Else, append score
seq = seqs.first()
print "Repeated", seq
best_scores = seq.all_model_scores.filter(used_for_classifiation=True)
if len(best_scores)>0:
best_score = best_scores.first()
if (hsp.bitscore > best_score.score) and hsp.bitscore>=variant_model.hmmthreshold:
#best scoring
seq.variant = variant_model
seq.sequence = str(hsp.hit.seq)
update_features(seq)
best_score_2 = Score.objects.get(id=best_score.id)
best_score_2.used_for_classification=False
best_score_2.save()
seq.save()
print "UPDATED VARIANT"
add_score(seq, variant_model, hsp, best=True)
else:
add_score(seq, variant_model, hsp, best=False)
else:
#Was not classified, just test against this model
if hsp.bitscore>=variant_model.hmmthreshold:
seq.variant = variant_model
seq.sequence = str(hsp.hit.seq)
seq.save()
update_features(seq)
add_score(seq, variant_model, hsp, best=True)
else:
add_score(seq, variant_model, hsp, best=False)
else:
taxonomy = taxonomy_from_header(header, gi)
sequence = Seq(str(hsp.hit.seq))
best = hsp.bitscore >= variant_model.hmmthreshold
try:
seq = add_sequence(
gi,
variant_model if best else unknown_model,
taxonomy,
header,
sequence)
add_score(seq, variant_model, hsp, best=best)
except IntegrityError as e:
print "Error adding sequence {}".format(seq)
global already_exists
already_exists.append(gi)
continue
print seq
def load_cores(hmmerFile, reset=True):
unknown_model = Variant.objects.get(id="Unknown")
if reset:
variants = Variant.objects.filter(id__contains="cononical")
for variant in variants:
for sequence in variant.sequences:
sequence.features.delete()
sequence.scores.filter(variant__id=variant__id).delete()
variant.sequences.delete()
variants.delete()
for core_query in SearchIO.parse(hmmerFile, "hmmer3-text"):
print "Loading core:", core_query.id
try:
core_histone = Histone.objects.get(id=core_query.id)
except:
continue
try:
canonical_model = Variant.objects.get(id="canonical{}".format(core_query.id))
except:
canonical_model = Variant(id="canonical{}".format(core_query.id), core_type=core_histone)
canonical_model.save()
for hit in core_query:
headers = "{}{}".format(hit.id, hit.description).split("gi|")[1:]
for header in headers:
gi = header.split("|")[0]
for i, hsp in enumerate(hit):
seqs = Sequence.objects.filter(id=gi)
if len(seqs) > 0:
#Sequence already exists. Compare bit scores, if current bit score is
#greater than current, reassign variant and update scores. Else, append score
seq = seqs.first()
best_scores = seq.all_model_scores.filter(used_for_classifiation=True)
if len(best_scores)>0:
best_score = best_scores.first()
if hsp.bitscore >= canonical_model.hmmthreshold and \
(seq.variant.id == "Unknown" or \
("canonical" in seq.variant.id and hsp.bitscore > best_score.score)) :
seq.variant = canonical_model
seq.sequence = str(hsp.hit.seq)
update_features(seq)
best_score_2 = Score.objects.get(id=best_score.id)
best_score_2.used_for_classification=False
best_score_2.save()
seq.save()
print "UPDATED VARIANT"
add_score(seq, canonical_model, hsp, best=True)
else:
add_score(seq, canonical_model, hsp, best=False)
else:
#Was not classified, just test against this model
if hsp.bitscore>=canonical_model.hmmthreshold:
seq.variant = canonical_model
seq.sequence = str(hsp.hit.seq)
seq.save()
update_features(seq)
add_score(seq, canonical_model, hsp, best=True)
else:
add_score(seq, canonical_model, hsp, best=False)
else:
#only add sequence if it was not found by the variant models
taxonomy = taxonomy_from_header(header, gi)
sequence = Seq(str(hsp.hit.seq))
best = hsp.bitscore >= canonical_model.hmmthreshold
try:
seq = add_sequence(
gi,
canonical_model if best else unknown_model,
taxonomy,
header,
sequence)
add_score(seq, canonical_model, hsp, best=best)
except IntegrityError as e:
print "Error adding sequence {}".format(seq)
global already_exists
already_exists.append(gi)
continue
print seq
print already_exists
def add_sequence(gi, variant_model, taxonomy, header, sequence):
if not variant_model.core_type.id == "H1" and not variant_model.core_type.id == "Unknown":
hist_identified, ss_position, sequence = get_hist_ss(sequence, variant_model.core_type.id, save_alignment=True)
sequence = str(sequence.seq)
else:
ss_position = defaultdict(lambda: (None, None))
sequence = str(sequence)
seq = Sequence(
id = gi,
variant = variant_model,
gene = None,
splice = None,
taxonomy = taxonomy,
header = header,
sequence = sequence,
reviewed = False,
)
seq.save()
return seq
def update_features(seq, ss_position=None, variant_model=None, return_not_save=False):
if ss_position is None and variant_model is not None:
hist_identified, ss_position, sequence = get_hist_ss(seq.to_biopython(ungap=True).seq, variant_model.core_type.id, save_alignment=True)
sequence = str(sequence.seq)
if ss_position is None:
assert 0
if hasattr(seq, "features") and seq.features:
seq.features.delete()
if not variant_model.core_type.id == "H1":
features = Features.from_dict(seq, ss_position)
if return_not_save:
return features
try:
features.save()
except:
pass
def add_score(seq, variant_model, hsp, best=False):
score_num = Score.objects.count()+1
score = Score(
id = score_num,
sequence = seq,
variant = variant_model,
score = hsp.bitscore,
evalue = hsp.evalue,
above_threshold = hsp.bitscore >= variant_model.hmmthreshold,
hmmStart = hsp.query_start,
hmmEnd = hsp.query_end,
seqStart = hsp.hit_start,
seqEnd = hsp.hit_end,
used_for_classifiation = best,
)
score.save()
<file_sep>from django.db.models import Max, Min, Count
from browse.models import Histone, Variant, OldStyleVariant, Sequence, Score
import browse
from djangophylocore.models import Taxonomy
from django.db.models import Q
from django.shortcuts import redirect
from django.http import JsonResponse
from collections import Counter
import django_filters
from itertools import groupby
def tax_sub_search(value):
"""
"""
ids = set()
value = value.strip()
if not format_query.current_query.startswith("taxonomy"):
return list(ids)
search_type = format_query.current_query[len("taxonomy"):]
if search_type.endswith("iin"):
search_type = "__iexact"
elif search_type.endswith("in"):
search_type = "__exact"
queryName = {"name{}".format(search_type):value.lower()}
try:
queryID = {"id{}".format(search_type):int(value)}
except ValueError:
queryID = {}
query = Q(**queryName)|Q(**queryID)
taxons = []
for taxon in Taxonomy.objects.filter(query):
taxons.append(taxon)
if taxon.type_name != "scientific name":
#Convert homonym into real taxon
taxon = taxon.get_scientific_names()[0]
ids.add(taxon.id)
children = set(taxon.children.values_list("id", flat=True).filter(rank=2))
ids |= children
format_query.current_query = "taxonomy__in"
return list(ids)
def variant_sub_search(value):
ids = set()
if not format_query.current_query.startswith("variant__id"):
return []
try:
#Search for current variant names or old variant names
search_type = format_query.current_query[len("variant__id"):]
queryCurrent = {"id{}".format(search_type):value}
queryOld = {"old_names__name{}".format(search_type):value}
query = Q(**queryCurrent)|Q(**queryOld)
variant = Variant.objects.filter(query)
if len(variant) > 0:
format_query.current_query = "variant__id__in"
return variant.values_list("id", flat=True)
else:
return variant.first().id
except Variant.DoesNotExist:
#Search new nomencalture with gene and splice isoform
for histone in Histone.objects.all():
for variant in histone.variants.all():
if value.startswith(variant.id):
branch_points = value[len(variant.id):].split(".")
sequence_query = [("variant__id", variant.id)]
for branch_point in branch_points:
if branch_point.startswith("s"):
key = "splice"
branch_point = part[1:]
else:
key = "gene"
try:
branch_point = int(branch_point)
sequence_query.append((key, branch_point))
except ValueError:
pass
format_query.multiple = True
return sequence_query
else:
variants = Variant.objects.filter(query).values_list("id", flat=True)
if len(variants) > 0:
format_query.current_query = "variant__id__in"
return list(variants)
else:
return []
#Fields that are allowed: each row contains:
# POST name, django model paramter, POST name for search type, input type (must be in seach_types)
allowable_fields = [
("id_id", "id", "id_id_search_type", str),
("id_core_histone", "variant__core_type__id", "id_core_type_search_type", str),
("id_variant", "variant__id", "id_variant_search_type", variant_sub_search),
("id_gene", "gene", "id_gene_search_type", int),
("id_splice","splice", "id_splice_search_type", int),
("id_header", "header", "id_header_search_type", str),
("id_taxonomy", "taxonomy", "id_taxonomy_search_type", tax_sub_search),
("id_evalue", "evalue", "id_evalue_search_type", float),
("id_score", "score", "id_score_search_type", float),
#("show_lower_scoring_models", None, None, (""))
]
search_types = {}
search_types[str] = {
"is": "__exact",
"is (case-insesitive)": "__iexact",
"contains": "__contains",
"contains (case-insesitive)": "__icontains",
"starts with": "__startswith",
"starts with (case-insesitive)": "__istartswith",
"ends with": "__endswith",
"ends with (case-insesitive)": "__iendswith",
"in (comma separated)": "__in",
"in (comma separated, case-insensitive)": "__iin"
}
search_types[int] = {
">": "__gt",
">=": "__gte",
"is": "",
"<": "__lt",
"<=": "__lte",
"range (dash separated)": "__range",
"in (comma separated)": "__in",
}
search_types[float] = search_types[int]
search_types["text"] = search_types[str]
search_types["int"] = search_types[int]
class HistoneSearch(object):
"""
"""
def __init__(self, request, parameters, reset=False, navbar=False):
"""
"""
assert isinstance(parameters, dict)
self.errors = Counter()
self.navbar = navbar
self.request = request
self.sanitized = False
self.query_set = None
self.redirect = None
self.query = {}
self.sort = {}
self.count = 0
#if reset:
# HistoneSearch.reset(request)
if "search" in parameters:
parameters.update(self.simple_search(parameters["search"]))
if self.redirect:
return
self.sanitize_parameters(parameters, reset)
self.create_queryset(reset)
# @classmethod
# def reset(cls, request):
# """Clears search from session"""
# try:
# del request.session["query"]
# del request.session["sort"]
# except KeyError:
# pass
@classmethod
def all(cls, request):
return cls(request, {}, reset=True)
def sanitize_parameters(self, parameters, reset=False):
"""
"""
self.query = {field:parameters[field] for fields in allowable_fields \
for field in (fields[0], fields[2]) if field in parameters}
sort_parameters = {"limit": 10, "offset":0, "sort":"evalue", "order":"asc"}
sort_query = {p:parameters.get(p, v) for p, v in sort_parameters.iteritems()}
self.sort = sort_query
#if not reset:
#raise RuntimeError(str(self.request.session["query"]))
self.sanitized = True
def create_queryset(self, reset=False):
if not self.sanitized:
raise RuntimeError("Parameters must be sanitized")
parameters = self.query
query = format_query()
added = []
for form, field, search_type, convert in allowable_fields:
value = None
if form in parameters:
added.append((field, search_type, parameters.get(form)))
value = parameters.get(form)
if not value:
continue
search_type = parameters.get(search_type, "is")
query.format(field, search_type, value, convert)
if query.has_errors():
return False
#assert 0, query
self.query_set = Sequence.objects.filter(
(~Q(variant__id="Unknown") & Q(all_model_scores__used_for_classifiation=True)) | \
(Q(variant__id="Unknown") & Q(all_model_scores__used_for_classifiation=False)) \
).annotate(
num_scores=Count("all_model_scores"),
score=Max("all_model_scores__score"),
evalue=Min("all_model_scores__evalue")
).filter(**query)
self.count = self.query_set.count()
#if not reset:
# raise RuntimeError(str(query))
def sorted(self, unique=False):
"""Sort the query set and paginate results.
"""
result = self.query_set
sort_by = self.sort["sort"]
sort_order = "-" if self.sort["order"] == "desc" else ""
sort_key = "{}{}".format(sort_order, sort_by)
result = result.order_by(sort_key)
page_size = int(self.sort["limit"])
start = int(self.sort["offset"])
end = start+page_size
result = result[start:end]
if unique:
used_taxa = {}
for seq in result:
if not seq.sequence in used_taxa:
used_taxa[seq.sequence] = [seq.taxonomy.id]
yield seq
elif seq.sequence in used_taxa and not seq.taxonomy.id in used_taxa[seq.sequence]:
used_taxa[seq.sequence].append(seq.taxonomy.id)
yield seq
else:
pass
"""#Old method using group by, might be faster, but doesn;t preserver order
result = sorted(self.query_set, key=lambda s:s.sequence)
for sequence, same_sequences in groupby(result, key=lambda s:s.sequence):
used_taxa = []
for seq in same_sequences:
if seq.taxonomy.id not in used_taxa:
used_taxa.append(seq.taxonomy.id)
yield seq
"""
else:
for seq in result:
yield seq
def __len__(self):
return self.query_set.count()
def count(self):
return self.query_set.count()
def get_dict(self, unique=False):
sequences = self.sorted(unique=unique)
result = [{"id":r.id, "variant":r.variant_id, "gene":r.gene, "splice":r.splice, "taxonomy":r.taxonomy.name.capitalize(), "score":r.score, "evalue":r.evalue, "header":r.header[:80]} for r in sequences]
return {"total":self.count, "rows":result}
def simple_search(self, search_text):
"""Search from simple text box in brand or sequence filter.
"""
parameters = {}
#Search all fields
try:
#If search is just a single digit, try to match id
#Other int values don't make sense to search like this
value = int(search_text)
sequence = self.query_set.filter(id=value)
if len(sequence):
parameters["id"] = value
parameters["id_search_type"] = "is"
return parameters
except ValueError:
pass
#search core_type, variant, old variant names, header if doens't match variant or core_type, taxonomy
try:
core_type = Histone.objects.get(id=search_text)
parameters["id_core_histone"] = core_type.id
parameters["id_core_histone_search_type"] = "is"
if self.navbar:
self.redirect = redirect(core_type)
return parameters
except Histone.DoesNotExist:
pass
try:
variant = Variant.objects.get(id=search_text)
parameters["id_variant"] = variant.id
parameters["id_variant_search_type"] = "is"
if self.navbar:
self.redirect = redirect(variant)
return parameters
except Variant.DoesNotExist:
pass
try:
#Searches H2A.Z.1.s1
sequences = Sequence.objects.filter(full_variant_name=search_text)
if sequences.count() > 0:
parameters["id_id"] = ",".join(sequences.values_list("id", flat=True))
parameters["id_id_search_type"] = "in (comma separated, case-sensitive)"
return parameters
except:
pass
try:
variant = OldStyleVariant.objects.get(name=search_text).updated_variant
parameters["id_variant"] = variant.id
parameters["id_variant_search_type"] = "is"
if self.navbar:
self.redirct = redirect(variant)
return parameters
except OldStyleVariant.DoesNotExist:
pass
try:
#Search species
sequences = Taxonomy.objects.filter(name__icontains=search_text)
if sequences.count() > 0:
parameters["id_taxonomy"] = search_text
parameters["id_taxonomy_search_type"] = "contains (case-insesitive)"
return parameters
except Taxonomy.DoesNotExist:
pass
try:
taxon = Taxonomy.objects.filter(name=parameters["search"])
try:
#Convert homonym into real taxon
taxon = taxon.get_scientific_names()[0]
except IndexError:
#Already correct taxon
pass
taxa = taxon.children.filter(rank__name="species").values_list("pk")
sequences = self.query_set.filter(taxonomy__in=taxa)
if sequences.count() > 0:
parameters["id_taxonomy"] = search_text
parameters["id_taxonomy_search_type"] = "contains (case-insesitive)"
return parameters
except Taxonomy.DoesNotExist:
pass
headers = Sequence.objects.filter(header__icontains=search_text)
if headers.count() > 0:
parameters["id_header"] = search_text
parameters["id_header_search_type"] = "contains (case-insesitive)"
else:
#Search sequence moetifs if everything else fails
parameters["id_sequence"] = search_text
parameters["id_sequence_search_type"] = "contains (case-insesitive)"
return parameters
class format_query(dict):
current_query = None
multiple = False
errors = Counter()
def format(self, field, search_type, value, conv_type):
#if allow and search_type not in allow:
# format_query.errors["Invalid search type ({}) for field {}".format(search_type, field)] += 1
# return False, errors
search_type = search_type.replace(">", ">").replace("<", "<")
try:
if conv_type.__class__.__name__ == "function":
search_type = search_types[str][search_type]
else:
search_type = search_types[conv_type][search_type]
except KeyError:
format_query.errors["Invalid search type ({}; {}) for field {}".format(search_type,conv_type,field)] += 1
return False, self.errors
format_query.current_query = "{}{}".format(field, search_type)
try:
if search_type.endswith("range"):
values = []
if "-" in value:
for v in value.split("-"):
values += conv_type(v)
else:
self.errors["Must include a dash if searching 'range'"] += 1
value = values
elif search_type.endswith("in"):
values = []
if "," in value:
for v in value.split(","):
values += conv_type(v)
else:
self.errors["Must include a comma if searching 'in'"] += 1
value = values
else:
value = conv_type(value)
except ValueError:
format_query.errors["Must include correct character to seach {}".format(field)] += 1
if len(format_query.errors) > 0:
return
if format_query.multiple and isinstance(value, list):
for field, search in value:
self[field] = search
else:
self[format_query.current_query] = value
format_query.current_query = None
format_query.multiple = False
def has_errors(self):
return len(format_query.errors) > 0
<file_sep>from django.core.management.base import BaseCommand, CommandError
from browse.models import *
import os
from itertools import chain
import pprint as pp
import json
from colour import Color
from django.db.models import Max, Min, Count
from math import floor
class Command(BaseCommand):
help = 'Build the sunburst json files for each core histone and its variants'
def add_arguments(self, parser):
parser.add_argument(
"-f",
"--force",
default=False,
action="store_true",
help="Force the recreation of sunburst. This will overwrite any existing sunburst json files.")
parser.add_argument(
"--all_taxonomy",
default=False,
action="store_true",
help="Build a sunburst of the enitre NCBI Taxonomy databse.")
def handle(self, *args, **options):
path = os.path.join("static", "browse", "sunbursts")
if options["all_taxonomy"]:
sb = self.build_sunburst(all_taxonomy=True)
with open(os.path.join(path, "all_taxa.json"), "w") as all_taxa:
all_taxa.write(sb)
for core_histone in Histone.objects.all():
print "Saving", core_histone.id
#sb = self.build_sunburst(variant__core_type=core_histone)
#with open(os.path.join(path, "{}.json".format(core_histone.id)), "w") as core_burst:
# core_burst.write(sb)
vpath = os.path.join(path, core_histone.id)
if not os.path.exists(vpath):
os.makedirs(vpath)
for variant in Variant.objects.filter(core_type=core_histone):
print " Saving", variant.id
sb = self.build_sunburst(variant=variant)
with open(os.path.join(vpath, "{}.json".format(variant.id)), "w") as variant_burst:
variant_burst.write(sb)
def build_sunburst(self, **filter):
"""Build the sunburst
"""
green = Color("#66c2a5")
red = Color("#fc8d62")
color_range = list(red.range_to(green, 100))
taxas = Sequence.objects.filter(**filter).filter(all_model_scores__used_for_classifiation=True).annotate(score=Max("all_model_scores__score"))
scores_min = min(taxas.values_list("score", flat=True))
scores_max = max(taxas.values_list("score", flat=True))
taxas = taxas.values_list("taxonomy", flat=True).distinct()
def get_color_for_taxa(taxon):
ids = set()
ids.add(taxon.id)
children = set(taxon.children.values_list("id", flat=True))
ids |= children
scores = list(Sequence.objects.filter(taxonomy__in=list(ids)).filter(all_model_scores__used_for_classifiation=True).annotate(score=Max("all_model_scores__score")).values_list("score", flat=True))
avg = float(sum(scores))/len(scores) if len(scores) > 0 else 0.
scaled = int(floor((float(avg-scores_min)/float(scores_max-scores_min))*100))
color_index = scaled if scaled <= 99 else 99
color_index = color_index if color_index >= 0 else 0
return str(color_range[color_index])
sunburst = {"name":"root", "children":[]}
colors = {"eukaryota":"#6600CC", "prokaryota":"#00FF00", "archea":"#FF6600"}
for taxa in taxas:
if filter.get("all_taxonomy"):
path = chain([taxa], taxa.children.all())
else:
taxa = Taxonomy.objects.get(pk=taxa)
try:
taxa = taxa.get_scientific_names()[0]
except IndexError:
pass
path = chain(taxa.parents.reverse().all()[1:], [taxa])
root = sunburst
stopForOrder = False
for i, curr_taxa in enumerate(path):
if stopForOrder:
break
if curr_taxa.rank.name in ["no rank", "class"] or "sub" in curr_taxa.rank.name or "super" in curr_taxa.rank.name:
continue
if "order" in curr_taxa.rank.name or "family" in curr_taxa.rank.name:
stopForOrder = True
#print "-"*(i+1), curr_taxa.name, curr_taxa.rank.name
for node in root["children"]:
if node["name"] == curr_taxa.name:
break
else:
pass
else:
#print "(Adding)"
node = {"name":curr_taxa.name, "children":[]}
root["children"].append(node)
root = node
try:
root["colour"] = get_color_for_taxa(taxa)
except:
root["color"] = str(red)
#pp.pprint(sunburst)
return json.dumps(sunburst)
<file_sep>from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from browse.models import Histone, Variant, Sequence, Score, Features
from tools.load_hmmsearch import load_variants, load_cores
from tools.test_model import test_model
import subprocess
import os, sys
from Bio import SeqIO
class Command(BaseCommand):
help = 'Build the HistoneDB by training HMMs with seed sequences found in seeds directory in the top directory of this project and using those HMMs to search the NR database. To add or update a single variant, you must rebuild everything using the --force option'
seed_directory = os.path.join(settings.STATIC_ROOT, "browse", "seeds")
hmm_directory = os.path.join(settings.STATIC_ROOT, "browse", "hmms")
combined_varaints_file = os.path.join(hmm_directory, "combined_variants.hmm")
combined_core_file = os.path.join(hmm_directory, "combined_cores.hmm")
pressed_combined_varaints_file = os.path.join(hmm_directory, "combined_variants.h3f")
pressed_combined_cores_file = os.path.join(hmm_directory, "combined_cores.h3f")
results_file = "{}.out".format(combined_varaints_file)
core_results_file = "{}.out".format(combined_core_file)
nr_file = "nr"
model_evalution = os.path.join(hmm_directory, "model_evalution")
def add_arguments(self, parser):
parser.add_argument(
"-f",
"--force",
default=False,
action="store_true",
help="Force the recreation of the HistoneDB. If True and an hmmsearch file is not present, the program will redownload the nr db if not present, build and press the HMM, and search the nr databse using the HMMs.")
parser.add_argument(
"--nr",
default=False,
action="store_true",
help="Redownload NR database. If force is also True, this option is redundant")
parser.add_argument(
"--only_variants",
default=False,
action="store_true",
help="Build and evaluate only variant HMMs. Default False, evalute both core and variant HMMs")
parser.add_argument(
"--only_cores",
default=False,
action="store_true",
help="Build and evaluate only core HMMs. Default False, evalute both core and variant HMMs")
parser.add_argument(
"--variant",
default=None,
nargs="+",
help="Only process this varaint. Can enter multiple")
parser.add_argument(
"--test_models",
default=False,
action="store_true",
help="Only test the models. This will updates the variant threshold and aucroc in model.")
def handle(self, *args, **options):
self.get_nr(force=options["nr"])
if not options["force"] and \
((not options["only_cores"] and os.path.isfile(self.results_file)) or \
(not options["only_variants"] and os.path.isfile(self.core_results_file))):
if options["test_models"]:
self.test(only_cores=options["only_cores"], only_variants=options["only_variants"])
if not options["only_cores"]:
self.load_variants()
if not options["only_variants"]:
self.load_cores()
elif not options["force"] and \
((not options["only_cores"] and os.path.isfile(self.pressed_combined_varaints_file)) or \
(not options["only_variants"] and os.path.isfile(self.pressed_combined_cores_file))):
self.test(only_cores=options["only_cores"], only_variants=options["only_variants"])
if not options["only_cores"]:
self.search_varaint()
self.load_variants()
if not options["only_variants"]:
self.search_cores()
self.load_cores()
else:
#Force to rebuild everything
self.build(only_cores=options["only_cores"], only_variants=options["only_variants"])
self.test(only_cores=options["only_cores"], only_variants=options["only_variants"])
if not options["only_cores"]:
self.press_variants()
self.search_variants()
self.load_variants()
if not options["only_variants"]:
self.press_cores()
self.search_cores()
self.load_cores()
def get_nr(self, force=False):
"""Download nr if not present"""
if not os.path.isfile(self.nr_file) or force:
print >> self.stdout, "Downloading nr..."
with open("nr.gz", "w") as nrgz:
subprocess.call(["curl", "-#", "ftp://ftp.ncbi.nlm.nih.gov/blast/db/FASTA/nr.gz"], stdout=nrgz)
subprocess.call(["gunzip", "nr.gz"])
def build(self, only_cores=False, only_variants=False):
"""Build HMMs"""
print >> self.stdout, "Building HMMs..."
with open(self.combined_varaints_file, "w") as combined_variants, open(self.combined_core_file, "w") as combined_core:
for core_type, seed in self.get_seeds(core=True):
if seed is None and not only_variants:
#Build Core HMM
core_hmm_file = os.path.join(self.hmm_directory, core_type, "canonical{}.hmm".format(core_type))
seed = os.path.join(self.seed_directory, "{}.fasta".format(core_type))
self.build_hmm(core_type, core_hmm_file, seed)
with open(core_hmm_file) as core_hmm:
print >> combined_core, core_hmm.read().rstrip()
continue
if only_cores:
continue
#Build Variant HMM
hmm_dir = os.path.join(self.hmm_directory, core_type)
if not os.path.exists(hmm_dir):
os.makedirs(hmm_dir)
hmm_file = os.path.join(hmm_dir, "{}.hmm".format(seed[:-6]))
self.build_hmm(seed[:-6], hmm_file, os.path.join(self.seed_directory, core_type, seed))
with open(hmm_file) as hmm:
print >> combined_variants, hmm.read().rstrip()
def build_hmm(self, name, db, seqs):
print ["hmmbuild", "-n", name, db, seqs]
subprocess.call(["hmmbuild", "-n", name, db, seqs])
def press_variants(self):
return self.press(self.combined_varaints_file)
def press_cores(self):
return self.press(self.combined_core_file)
def press(self, combined_hmm):
"""Press the HMMs into a single HMM file, overwriting if present"""
print >> self.stdout, "Pressing HMMs..."
subprocess.call(["hmmpress", "-f", combined_hmm])
def search_variants(self):
return self.search(db=self.combined_varaints_file, out=self.results_file)
def search_cores(self):
return self.search(db=self.combined_core_file, out=self.core_results_file)
def search(self, db, out, sequences=None, E=10):
"""Use HMMs to search the nr database"""
print >> self.stdout, "Searching HMMs..."
if sequences is None:
sequences = self.nr_file
subprocess.call(["hmmsearch", "-o", out, "-E", str(E), "--cpu", "4", "--notextw", db, sequences])
def load_variants(self):
"""Load data into the histone database"""
print >> self.stdout, "Loading data into HistoneDB..."
load_variants(self.results_file, self.nr_file)
def load_cores(self):
"""Load data into the histone database"""
print >> self.stdout, "Loading data into HistoneDB..."
load_cores(self.core_results_file)
def get_seeds(self, core=False):
for i, (root, _, files) in enumerate(os.walk(self.seed_directory)):
core_type = os.path.basename(root)
if i==0:
#Skip parent directory, only allow variant hmms to be built/searched
continue
if core:
yield core_type, None
for seed in files:
if not seed.endswith(".fasta"): continue
yield core_type, seed
def test(self, only_cores=False, only_variants=False, specificity=0.95):
for core_type, seed1 in self.get_seeds(core=True):
#Seed1 is positive examples
if seed1 == None:
#Test Core HMM
variant = "canonical{}".format(core_type)
positive_path = os.path.join(self.seed_directory, "{}.fasta".format(core_type))
if only_variants: continue
else:
#Test Varaint HMM
variant = seed1[:-6]
positive_path = os.path.join(self.seed_directory, core_type, seed1)
if only_cores: continue
hmm_file = os.path.join(self.hmm_directory, core_type, "{}.hmm".format(variant))
output_dir = os.path.join(self.model_evalution, core_type)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
positive_examples_file = os.path.join(output_dir, "{}_postive_examples.fasta".format(variant))
positive_examples = os.path.join(output_dir, "{}_postive_examples.out".format(variant))
negative_examples_file = os.path.join(output_dir, "{}_negative_examples.fasta".format(variant))
negative_examples = os.path.join(output_dir, "{}_negative_examples.out".format(variant))
print "Saving", positive_path, "into", positive_examples_file
with open(positive_examples_file, "w") as positive_file:
for s in SeqIO.parse(positive_path, "fasta"):
s.seq = s.seq.ungap("-")
SeqIO.write(s, positive_file, "fasta")
self.search(db=hmm_file, out=positive_examples, sequences=positive_examples_file, E=500)
#Build negative examples from all other varaints
with open(negative_examples_file, "w") as negative_file:
for core_type2, seed2 in self.get_seeds(core=True):
if seed1 is None and seed2 is None:
#Compare Cores
if core_type == core_type2:
#Don't compare cores if they are the same
continue
sequences = os.path.join(self.seed_directory, "{}.fasta".format(core_type2))
elif (seed1 is not None and seed2 is None) or (seed1 is None and seed2 is not None):
#Do not compare core to varaints
continue
elif not seed1 == seed2:
sequences = os.path.join(self.seed_directory, core_type2, seed2)
else:
#Do not compare files if they are the same
continue
print "Saving negatives from", sequences, "into", negative_examples_file
for s in SeqIO.parse(sequences, "fasta"):
s.seq = s.seq.ungap("-")
SeqIO.write(s, negative_file, "fasta")
self.search(db=hmm_file, out=negative_examples, sequences=negative_examples_file, E=500)
parameters = test_model(variant, output_dir, positive_examples, negative_examples)
if variant == "H1.8":
parameters["threshold"] = 100.
try:
variant_model = Variant.objects.get(id=variant)
except:
if "H2A" in variant:
try:
core_histone = Histone.objects.get(id="H2A")
except Histone.DoesNotExist:
core_histone = Histone("H2A")
core_histone.save()
elif "H2B" in variant:
try:
core_histone = Histone.objects.get(id="H2B")
except Histone.DoesNotExist:
core_histone = Histone("H2B")
core_histone.save()
elif "H3" in variant:
try:
core_histone = Histone.objects.get(id="H3")
except Histone.DoesNotExist:
core_histone = Histone("H3")
core_histone.save()
elif "H4" in variant:
try:
core_histone = Histone.objects.get(id="H4")
except Histone.DoesNotExist:
core_histone = Histone("H4")
core_histone.save()
elif "H1" in variant:
try:
core_histone = Histone.objects.get(id="H1")
except Histone.DoesNotExist:
core_histone = Histone("H1")
core_histone.save()
else:
continue
variant_model = Variant(id=variant, core_type=core_histone)
variant_model.save()
variant_model.hmmthreshold = parameters["threshold"]
variant_model.aucroc = parameters["roc_auc"]
variant_model.save()
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import djangophylocore.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BadTaxa',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(unique=True, max_length=200)),
('nb_occurence', models.IntegerField(default=0)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='ParentsRelation',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('index', models.IntegerField()),
],
options={
'ordering': ['index'],
},
),
migrations.CreateModel(
name='Rank',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=80)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='RelCommonTaxa',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('language', models.CharField(max_length=80, null=True)),
],
options={
'ordering': ['taxon', 'common'],
},
),
migrations.CreateModel(
name='RelHomonymTaxa',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
options={
'ordering': ['taxon', 'homonym'],
},
),
migrations.CreateModel(
name='RelSynonymTaxa',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
options={
'ordering': ['taxon', 'synonym'],
},
),
migrations.CreateModel(
name='Taxonomy',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200)),
('type_name', models.CharField(max_length=50)),
('_parents', models.ManyToManyField(related_name='children', through='djangophylocore.ParentsRelation', to='djangophylocore.Taxonomy')),
('parent', models.ForeignKey(related_name='direct_children', to='djangophylocore.Taxonomy', null=True)),
('rank', models.ForeignKey(related_name='taxa', to='djangophylocore.Rank', null=True)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='TaxonomyTreeOccurence',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('user_taxon_name', models.CharField(max_length=200, null=True)),
('nb_occurence', models.IntegerField(default=0)),
('taxon', models.ForeignKey(related_name='taxonomy_occurences', to='djangophylocore.Taxonomy')),
],
),
migrations.CreateModel(
name='Tree',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=80, null=True)),
('delimiter', models.CharField(default=b' ', max_length=5)),
('source', models.TextField()),
('rooted', models.NullBooleanField()),
('description', models.TextField(null=True)),
('created', models.DateTimeField()),
('updated', models.DateTimeField()),
('is_valid', models.BooleanField(default=False)),
('_from_collection', models.BooleanField(default=False)),
('column_error', models.IntegerField(null=True)),
('bad_taxa', models.ManyToManyField(related_name='trees', to='djangophylocore.BadTaxa')),
],
bases=(models.Model, djangophylocore.models.TaxonomyReference),
),
migrations.CreateModel(
name='TreeCollection',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=80, null=True)),
('source', models.TextField(null=True)),
('delimiter', models.CharField(default=b' ', max_length=5)),
('description', models.TextField(null=True)),
('format', models.CharField(max_length=20, null=True)),
('created', models.DateTimeField()),
('updated', models.DateTimeField()),
],
bases=(models.Model, djangophylocore.models.TaxonomyReference),
),
migrations.AddField(
model_name='tree',
name='collection',
field=models.ForeignKey(related_name='trees', to='djangophylocore.TreeCollection', null=True),
),
migrations.AddField(
model_name='taxonomytreeoccurence',
name='tree',
field=models.ForeignKey(related_name='taxonomy_occurences', to='djangophylocore.Tree'),
),
migrations.AddField(
model_name='relsynonymtaxa',
name='synonym',
field=models.ForeignKey(related_name='synonym_from_taxa', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='relsynonymtaxa',
name='taxon',
field=models.ForeignKey(related_name='taxa_from_synonym', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='relhomonymtaxa',
name='homonym',
field=models.ForeignKey(related_name='homonym_from_taxa', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='relhomonymtaxa',
name='taxon',
field=models.ForeignKey(related_name='taxa_from_homonym', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='relcommontaxa',
name='common',
field=models.ForeignKey(related_name='common_from_taxa', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='relcommontaxa',
name='taxon',
field=models.ForeignKey(related_name='taxa_from_common', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='parentsrelation',
name='parent',
field=models.ForeignKey(related_name='parents_relation_parents', to='djangophylocore.Taxonomy'),
),
migrations.AddField(
model_name='parentsrelation',
name='taxon',
field=models.ForeignKey(related_name='parents_relation_taxa', to='djangophylocore.Taxonomy'),
),
migrations.AlterUniqueTogether(
name='taxonomytreeoccurence',
unique_together=set([('taxon', 'tree', 'user_taxon_name')]),
),
migrations.AlterUniqueTogether(
name='taxonomy',
unique_together=set([('name', 'type_name')]),
),
migrations.AlterUniqueTogether(
name='relsynonymtaxa',
unique_together=set([('synonym', 'taxon')]),
),
migrations.AlterUniqueTogether(
name='relhomonymtaxa',
unique_together=set([('homonym', 'taxon')]),
),
migrations.AlterUniqueTogether(
name='relcommontaxa',
unique_together=set([('common', 'taxon')]),
),
migrations.AlterUniqueTogether(
name='parentsrelation',
unique_together=set([('taxon', 'parent')]),
),
]
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 13:09:07 2013
@author: alexeyshaytan
This script determines secondary structure elements of histone,
by algining it to reference sequences.
"""
#Standard Library
import argparse
import csv
import collections
import os
import re
import subprocess
import sys
import uuid
import cPickle as pickle
from StringIO import StringIO
#Required libraires
import pylab
import pandas as pd
import networkx as nx
#Django
from django.conf import settings
#BioPython
from Bio import AlignIO
from Bio import Entrez
from Bio import ExPASy
from Bio import SeqIO
from Bio import SwissProt
from Bio.Align import MultipleSeqAlignment
from Bio.Align.AlignInfo import SummaryInfo
from Bio.Align.Applications import MuscleCommandline
from Bio.Alphabet import IUPAC
from Bio.Blast import NCBIXML
from Bio.Blast.Applications import NcbiblastpCommandline
from Bio.Emboss.Applications import NeedleCommandline
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.Polypeptide import PPBuilder
Entrez.email = "<EMAIL>"
#Let's define 1kx5 sequences
templ_H3 = Seq("ARTKQTARKSTGGKAPRKQLATKAARKSAPATGGVKKPHRYRPGTVALREIRRYQKSTELLIRKLPFQRLVREIAQDFKTDLRFQSSAVMALQEASEAYLVALFEDTNLCAIHAKRVTIMPKDIQLARRIRGERA", IUPAC.protein)
templ_H4 = Seq("SGRGKGGKGLGKGGAKRHRKVLRDNIQGITKPAIRRLARRGGVKRISGLIYEETRGVLKVFLENVIRDAVTYTEHAKRKTVTAMDVVYALKRQGRTLYGFGG", IUPAC.protein)
templ_H2A = Seq("SGRGKQGGKTRAKAKTRSSRAGLQFPVGRVHRLLRKGNYAERVGAGAPVYLAAVLEYLTAEILELAGNAARDNKKTRIIPRHLQLAVRNDEELNKLLGRVTIAQGGVLPNIQSVLLPKKTESSKSKSK", IUPAC.protein)
templ_H2B = Seq("AKSAPAPKKGSKKAVTKTQKKDGKKRRKTRKESYAIYVYKVLKQVHPDTGISSKAMSIMNSFVNDVFERIAGEASRLAHYNKRSTITSREIQTAVRLLLPGELAKHAVSEGTKAVTKYTSAK", IUPAC.protein)
#'element_name':[start,stop], start stop - are inclusive as in PDB file
#Numbering differes between symmetrical chains and 1kx5 vs 1aoi.
#We simply take the minimum length of alpha helices over all chains in 1kx5
#1 substructed from PDB values!!! because these values are in array index numberins starting from 0
ss_templ_H3 = {
'alphaN':[43,56],
'alpha1':[62,76],
'alpha2':[84,113],
'alpha3':[119,130],
'loopL1':[78,83],
'loopL2':[114,118],
'beta1':[82,83],
'beta2':[117,118],
'mgarg1':[62,62],
'mgarg2':[82,82],
'mgarg3':[48,48]
}
ss_templ_H4 = {
'alpha1ext':[23,28],
'alpha1':[29,40],
'alpha2':[48,75],
'alpha3':[81,92],
'loopL1':[41,47],
'loopL2':[76,81],
'beta1':[44,45],
'beta2':[79,80],
'beta3':[95,97],
'mgarg1':[44,44]
}
#new def of docking domains as in Suto Luger 2000
ss_templ_H2A = {
'alpha1ext':[15,21],
'alpha1':[25,36],
'alpha2':[45,72],
'alpha3':[78,88],
'alpha3ext':[89,96],
'loopL1':[37,44],
'loopL2':[73,77],
'beta1':[41,42],
'beta2':[76,77],
'beta3':[99,101],
'docking domain':[80,118],
'mgarg1':[41,41],
'mgarg2':[76,76]
}
ss_templ_H2B = {
'alpha1':[33,45],
'alpha2':[51,80],
'alpha3':[86,98],
'alphaC':[99,119],
'loopL1':[46,50],
'loopL2':[81,85],
'beta1':[49,50],
'beta2':[84,85],
'mgarg1':[29,29]
}
ss_templ = {'H3':ss_templ_H3,'H4':ss_templ_H4,'H2A':ss_templ_H2A,'H2B':ss_templ_H2B}
templ = {'H3':templ_H3,'H4':templ_H4,'H2A':templ_H2A,'H2B':templ_H2B}
core_histones = [
SeqRecord(templ_H3,id='H3',name='H3'),
SeqRecord(templ_H4,id='H4',name='H4'),
SeqRecord(templ_H2A,id='H2A',name='H2A'),
SeqRecord(templ_H2B,id='H2B',name='H2B')
]
def get_hist_ss(test_seq, hist_type="Unknown", save_dir="", debug=True, save_alignment=False):
"""Returns sequence elements in histone sequence, all numbers assume first element in seq has number 0!!! Not like in PDB"""
n2=str(uuid.uuid4())
test_record = SeqRecord(test_seq, id='Query')
ss_test = collections.defaultdict(lambda: [-1, -1])
if hist_type == "H1":
#H1 cannot be aligned becuase it does not share the histone fold
if save_alignment:
return None, ss_test, test_record
return None, ss_test
query_file = os.path.join(save_dir, "query_{}.fasta".format(n2))
SeqIO.write(test_record, query_file, 'fasta')
if hist_type == "Unknown":
results_file = os.path.join(save_dir, "query_{}.xml".format(n2))
blastp = os.path.join(os.path.dirname(sys.executable), "blastp")
blastp_cline = NcbiblastpCommandline(
cmd=blastp,
query=query_file,
db=os.path.join(settings.STATIC_ROOT, "browse", "blast", "core_histones_1kx5.faa"),
evalue=10000000,
outfmt=5,
out=results_file)
stdout, stderr = blastp_cline()
with open(result_file) as results:
blast_results = [(alignment.title, hsp.expect, hsp) for blast_record in NCBIXML.parse(results) \
for alignment in blast_record.alignments for hsp in alignment.hsps]
#Cleanup
os.remove(results_file)
try:
hist_identified, evalue, hsp = min(blast_results, key=lambda x:x[1])
hist_identified = hist_identified.split()[1]
except ValueError:
#No best match
os.remove(query_file)
if save_alignment:
return None, ss_test, test_record
return None, ss_test
if debug:
print "Most likely this is histone:", hist_identified
print hsp
else:
hist_identified = hist_type
core_histone_query = os.path.join(settings.STATIC_ROOT, "browse", "blast", "{}.faa".format(hist_identified))
needle_results = os.path.join(save_dir, "needle_{}.txt".format(n2))
cmd = os.path.join(os.path.dirname(sys.executable), "needle")
if not os.path.isfile(cmd):
cmd = "needle"
needle_cline = NeedleCommandline(
cmd=cmd,
asequence=core_histone_query,
bsequence=query_file,
gapopen=20,
gapextend=1,
outfile=needle_results)
stdout, stderr = needle_cline()
align = AlignIO.read(needle_results, "emboss")
core_histone = align[0]
query = align[1]
hist = templ[hist_identified]
corresponding_hist = range(len(hist))
k=0
for i, core_histone_postion in enumerate(core_histone):
if core_histone_postion == "-":
k += 1
else:
corresponding_hist[i-k]=i
corresponding_test = range(len(test_seq))
k=0
for i, query_position in enumerate(query):
if query_position == "-":
k=k+1
else:
corresponding_test[i-k]=i
for feature, (start, stop) in ss_templ[hist_identified].iteritems():
start_in_aln = corresponding_hist[start]
end_in_aln = corresponding_hist[stop]
start_in_test_seq = -1
end_in_test_seq = -1
for k in xrange(len(core_histone)):
try:
start_in_test_seq = corresponding_test.index(start_in_aln+k)
break
except ValueError:
continue
for k in xrange(len(core_histone)):
try:
end_in_test_seq = corresponding_test.index(end_in_aln-k)
break
except ValueError:
continue
if start_in_test_seq == -1 or end_in_test_seq == -1 or start_in_test_seq > end_in_test_seq:
ss_test[feature]=[-1,-1]
else:
ss_test[feature]=[start_in_test_seq,end_in_test_seq]
ss_test["core"] = get_core_lendiff(ss_test, ss_templ[hist_identified])
#Cleanup
os.remove(query_file)
os.remove(needle_results)
if save_alignment:
return hist_identified,ss_test,query
return hist_identified,ss_test
def get_hist_ss_in_aln(alignment, hist_type='Unknown', save_dir="", debug=True, save_censesus=False):
"""Returns sequence elements in histone alignment, all numbers assume first element in seq has number 0!!! Not like in PDB"""
#Let's extract consensus
if(debug):
print alignment
a=SummaryInfo(alignment)
cons=a.dumb_consensus(threshold=0.1, ambiguous='X')
if(debug):
print "Consensus"
print cons
hv, ss = get_hist_ss(cons,hist_type,save_dir,True)
if save_censesus:
return hv,ss,cons
return hv,ss
def get_gff_from_align(alignment, outfile, hist_type='Unknown', save_dir="", debug=True):
from browse.models import Sequence, Features
hv,ss,cons=get_hist_ss_in_aln(alignment, hist_type, save_dir=save_dir, debug=debug, save_censesus=True)
seq = Sequence(id="Consensus", sequence=cons.tostring())
features = Features.from_dict(seq, ss)
print >> outfile, features.full_gff()
def get_core_lendiff(test_ss,temp_ss,debug=0):
"""Returns ration of core length for test_seq versus template sequence"""
#check 640798122
len_t_core=max([ i[1] for i in temp_ss.values() ])-min([ i[0] for i in temp_ss.values() ])
len_core=max([ i[1] for i in test_ss.values() ])-min([ i[0] for i in test_ss.values() ])
if(debug):
print "Template core length ", len_t_core
print "Testseq core length ", len_core
ratio=float(len_core)/float(len_t_core)
return ratio
if __name__ == '__main__':
H2A = Seq("SGRGKKKKKQGGKTRAKAKTRSSRAGLQFPVGRVHRLLRKGNYAERVGAGAPPPPPVYLAAVLEYLTAEILELAGNARRRRARDNKTTTTTTKTRIIPRHLQLAVRNDEELNKLLGRVTIAQGGVLPNIQSVLLPKKTESSKSKSK", IUPAC.protein)
H2At = Seq("SGRGKQGGKTRAKAKTRSSRAGLQFPVGRVHRLLRKGNYAERVGAGAPVYLAAVLEYLTAEILELAGNAARDNKKTRIIPRHLQLAVRNDEELNKLLGRVTIAQGGVLPNIQSVLLPKKTESSKSKSK", IUPAC.protein)
print get_hist_ss(H2At)
# print get_core_lendiff(H2A,H2At)<file_sep>function createMSA(div_id, url, width, is_seed){
var yourDiv = document.getElementById(div_id);
yourDiv.innerHTML = "<span id='load_msa'>Please wait while we construct the MSA...</span>";
/* global yourDiv */
var msa = require("msa");
var fasta = require("biojs-io-fasta");
var gff = require("biojs-io-gff");
var msaDiv = document.createElement('div');
yourDiv.appendChild(msaDiv);
var opts = {
el: msaDiv
}
opts.vis = {
conserv: false,
overviewbox: false,
seqlogo: true,
markers: false,
leftHeader: false,
labelName: true,
labelId: false,
};
opts.zoomer = {
labelNameLength: 160,
alignmentWidth: width,
alignmentHeight: 500,
};
var m = msa(opts);
if(!is_seed){
// init msa
$.ajax({
url:url,
dataType: "json",
success: function(result) {
console.log(result)
m.seqs.reset(result.seqs);
var features = gff.parseSeqs(result.features);
m.seqs.addFeatures(features);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown)
}
});
}
else{
//load sequences
fasta.read(url+".fasta", function(err, seqs){
m.seqs.reset(seqs);
m.seqs.unshift({name:"Consensus", seq:m.g.stats.consensus()});
});
var xhr = msa.io.xhr;
if(url.substring(url.length-2, url.length) != "H1"){
xhr(url+".gff", function(err, request, body) {
var features = gff.parseSeqs(body);
m.seqs.addFeatures(features);
});
}
}
m.render();
$("#load_msa").html("")
var colorConservation = {}
// the init function is only called once
colorConservation.init = function(){
// you have here access to the conservation or the sequence object
this.cons = this.opt.conservation();
this.cons80 = true;
this.cons50 = true;
}
colorConservation.run = function(letter,opts){
if(this.cons80 && this.cons[opts.pos] > 0.8){
return "red";
}
else if(this.cons50 && this.cons[opts.pos] > 0.5){
return "blue";
}
else{
return "#000";
}
};
m.g.colorscheme.addDynScheme("colorConservation", colorConservation);
m.g.colorscheme.set("scheme", "colorConservation");
}<file_sep><!DOCTYPE html><html><head><meta charset="utf-8"><style>body {
width: 45em;
border: 1px solid #ddd;
outline: 1300px solid #fff;
margin: 16px auto;
}
body .markdown-body
{
padding: 30px;
}
@font-face {
font-family: fontawesome-mini;
src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAzUABAAAAAAFNgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABbAAAABwAAAAcZMzaOEdERUYAAAGIAAAAHQAAACAAOQAET1MvMgAAAagAAAA+AAAAYHqhde9jbWFwAAAB6AAAAFIAAAFa4azkLWN2dCAAAAI8AAAAKAAAACgFgwioZnBnb<KEY>ZVO0L6dn<KEY>se<KEY>cwMDKwMLSw2LMwMDQBqGZihmiwHycoKCyqJjB4YPDh4NsDP+BfNb3DIuAFCOSEgUGRgAKDgt4AAB4nGNgYGBmgGAZBkYGEAgB8hjBfBYGCyDNxcDBwMTA9MHhQ9SHrA8H//9nYACyQyFs/sP86/kX<KEY>) format('woff');
}
@font-face {
font-family: octicons-anchor;
src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAYcAA0AAAAACjQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABMAAAABwAAAAca8vGTk9<KEY>) format('woff');
}
.markdown-body {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
color: #333333;
overflow: hidden;
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif;
font-size: 16px;
line-height: 1.6;
word-wrap: break-word;
}
.markdown-body a {
background: transparent;
}
.markdown-body a:active,
.markdown-body a:hover {
outline: 0;
}
.markdown-body b,
.markdown-body strong {
font-weight: bold;
}
.markdown-body mark {
background: #ff0;
color: #000;
font-style: italic;
font-weight: bold;
}
.markdown-body sub,
.markdown-body sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
.markdown-body sup {
top: -0.5em;
}
.markdown-body sub {
bottom: -0.25em;
}
.markdown-body h1 {
font-size: 2em;
margin: 0.67em 0;
}
.markdown-body img {
border: 0;
}
.markdown-body hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
.markdown-body pre {
overflow: auto;
}
.markdown-body code,
.markdown-body kbd,
.markdown-body pre,
.markdown-body samp {
font-family: monospace, monospace;
font-size: 1em;
}
.markdown-body input {
color: inherit;
font: inherit;
margin: 0;
}
.markdown-body html input[disabled] {
cursor: default;
}
.markdown-body input {
line-height: normal;
}
.markdown-body input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
.markdown-body table {
border-collapse: collapse;
border-spacing: 0;
}
.markdown-body td,
.markdown-body th {
padding: 0;
}
.markdown-body .codehilitetable {
border: 0;
border-spacing: 0;
}
.markdown-body .codehilitetable tr {
border: 0;
}
.markdown-body .codehilitetable pre,
.markdown-body .codehilitetable div.codehilite {
margin: 0;
}
.markdown-body .linenos,
.markdown-body .code,
.markdown-body .codehilitetable td {
border: 0;
padding: 0;
}
.markdown-body td:not(.linenos) .linenodiv {
padding: 0 !important;
}
.markdown-body .code {
width: 100%;
}
.markdown-body .linenos div pre,
.markdown-body .linenodiv pre,
.markdown-body .linenodiv {
border: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-border-top-left-radius: 3px;
-webkit-border-bottom-left-radius: 3px;
-moz-border-radius-topleft: 3px;
-moz-border-radius-bottomleft: 3px;
border-top-left-radius: 3px;
border-bottom-left-radius: 3px;
}
.markdown-body .code div pre,
.markdown-body .code div {
border: 0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-border-top-right-radius: 3px;
-webkit-border-bottom-right-radius: 3px;
-moz-border-radius-topright: 3px;
-moz-border-radius-bottomright: 3px;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.markdown-body * {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.markdown-body input {
font: 13px Helvetica, arial, freesans, clean, sans-serif, "Segoe UI Emoji", "Segoe UI Symbol";
line-height: 1.4;
}
.markdown-body a {
color: #4183c4;
text-decoration: none;
}
.markdown-body a:hover,
.markdown-body a:focus,
.markdown-body a:active {
text-decoration: underline;
}
.markdown-body hr {
height: 0;
margin: 15px 0;
overflow: hidden;
background: transparent;
border: 0;
border-bottom: 1px solid #ddd;
}
.markdown-body hr:before,
.markdown-body hr:after {
display: table;
content: " ";
}
.markdown-body hr:after {
clear: both;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin-top: 15px;
margin-bottom: 15px;
line-height: 1.1;
}
.markdown-body h1 {
font-size: 30px;
}
.markdown-body h2 {
font-size: 21px;
}
.markdown-body h3 {
font-size: 16px;
}
.markdown-body h4 {
font-size: 14px;
}
.markdown-body h5 {
font-size: 12px;
}
.markdown-body h6 {
font-size: 11px;
}
.markdown-body blockquote {
margin: 0;
}
.markdown-body ul,
.markdown-body ol {
padding: 0;
margin-top: 0;
margin-bottom: 0;
}
.markdown-body ol ol,
.markdown-body ul ol {
list-style-type: lower-roman;
}
.markdown-body ul ul ol,
.markdown-body ul ol ol,
.markdown-body ol ul ol,
.markdown-body ol ol ol {
list-style-type: lower-alpha;
}
.markdown-body dd {
margin-left: 0;
}
.markdown-body code,
.markdown-body pre,
.markdown-body samp {
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 12px;
}
.markdown-body pre {
margin-top: 0;
margin-bottom: 0;
}
.markdown-body kbd {
background-color: #e7e7e7;
background-image: -moz-linear-gradient(#fefefe, #e7e7e7);
background-image: -webkit-linear-gradient(#fefefe, #e7e7e7);
background-image: linear-gradient(#fefefe, #e7e7e7);
background-repeat: repeat-x;
border-radius: 2px;
border: 1px solid #cfcfcf;
color: #000;
padding: 3px 5px;
line-height: 10px;
font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace;
display: inline-block;
}
.markdown-body>*:first-child {
margin-top: 0 !important;
}
.markdown-body>*:last-child {
margin-bottom: 0 !important;
}
.markdown-body .headeranchor-link {
position: absolute;
top: 0;
bottom: 0;
left: 0;
display: block;
padding-right: 6px;
padding-left: 30px;
margin-left: -30px;
}
.markdown-body .headeranchor-link:focus {
outline: none;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
position: relative;
margin-top: 1em;
margin-bottom: 16px;
font-weight: bold;
line-height: 1.4;
}
.markdown-body h1 .headeranchor,
.markdown-body h2 .headeranchor,
.markdown-body h3 .headeranchor,
.markdown-body h4 .headeranchor,
.markdown-body h5 .headeranchor,
.markdown-body h6 .headeranchor {
display: none;
color: #000;
vertical-align: middle;
}
.markdown-body h1:hover .headeranchor-link,
.markdown-body h2:hover .headeranchor-link,
.markdown-body h3:hover .headeranchor-link,
.markdown-body h4:hover .headeranchor-link,
.markdown-body h5:hover .headeranchor-link,
.markdown-body h6:hover .headeranchor-link {
height: 1em;
padding-left: 8px;
margin-left: -30px;
line-height: 1;
text-decoration: none;
}
.markdown-body h1:hover .headeranchor-link .headeranchor,
.markdown-body h2:hover .headeranchor-link .headeranchor,
.markdown-body h3:hover .headeranchor-link .headeranchor,
.markdown-body h4:hover .headeranchor-link .headeranchor,
.markdown-body h5:hover .headeranchor-link .headeranchor,
.markdown-body h6:hover .headeranchor-link .headeranchor {
display: inline-block;
}
.markdown-body h1 {
padding-bottom: 0.3em;
font-size: 2.25em;
line-height: 1.2;
border-bottom: 1px solid #eee;
}
.markdown-body h2 {
padding-bottom: 0.3em;
font-size: 1.75em;
line-height: 1.225;
border-bottom: 1px solid #eee;
}
.markdown-body h3 {
font-size: 1.5em;
line-height: 1.43;
}
.markdown-body h4 {
font-size: 1.25em;
}
.markdown-body h5 {
font-size: 1em;
}
.markdown-body h6 {
font-size: 1em;
color: #777;
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body .admonition {
margin-top: 0;
margin-bottom: 16px;
}
.markdown-body hr {
height: 4px;
padding: 0;
margin: 16px 0;
background-color: #e7e7e7;
border: 0 none;
}
.markdown-body ul,
.markdown-body ol {
padding-left: 2em;
}
.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ol,
.markdown-body ol ul {
margin-top: 0;
margin-bottom: 0;
}
.markdown-body li>p {
margin-top: 16px;
}
.markdown-body dl {
padding: 0;
}
.markdown-body dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: bold;
}
.markdown-body dl dd {
padding: 0 16px;
margin-bottom: 16px;
}
.markdown-body blockquote {
padding: 0 15px;
color: #777;
border-left: 4px solid #ddd;
}
.markdown-body blockquote>:first-child {
margin-top: 0;
}
.markdown-body blockquote>:last-child {
margin-bottom: 0;
}
.markdown-body table {
display: block;
width: 100%;
overflow: auto;
word-break: normal;
word-break: keep-all;
}
.markdown-body table th {
font-weight: bold;
}
.markdown-body table th,
.markdown-body table td {
padding: 6px 13px;
border: 1px solid #ddd;
}
.markdown-body table tr {
background-color: #fff;
border-top: 1px solid #ccc;
}
.markdown-body table tr:nth-child(2n) {
background-color: #f8f8f8;
}
.markdown-body img {
max-width: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.markdown-body code,
.markdown-body samp {
padding: 0;
padding-top: 0.2em;
padding-bottom: 0.2em;
margin: 0;
font-size: 85%;
background-color: rgba(0,0,0,0.04);
border-radius: 3px;
}
.markdown-body code:before,
.markdown-body code:after {
letter-spacing: -0.2em;
content: "\00a0";
}
.markdown-body pre>code {
padding: 0;
margin: 0;
font-size: 100%;
word-break: normal;
white-space: pre;
background: transparent;
border: 0;
}
.markdown-body .codehilite {
margin-bottom: 16px;
}
.markdown-body .codehilite pre,
.markdown-body pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: #f7f7f7;
border-radius: 3px;
}
.markdown-body .codehilite pre {
margin-bottom: 0;
word-break: normal;
}
.markdown-body pre {
word-wrap: normal;
}
.markdown-body pre code {
display: inline;
max-width: initial;
padding: 0;
margin: 0;
overflow: initial;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0;
}
.markdown-body pre code:before,
.markdown-body pre code:after {
content: normal;
}
/* Admonition */
.markdown-body .admonition {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
position: relative;
border-radius: 3px;
border: 1px solid #e0e0e0;
border-left: 6px solid #333;
padding: 10px 10px 10px 30px;
}
.markdown-body .admonition table {
color: #333;
}
.markdown-body .admonition p {
padding: 0;
}
.markdown-body .admonition-title {
font-weight: bold;
margin: 0;
}
.markdown-body .admonition>.admonition-title {
color: #333;
}
.markdown-body .attention>.admonition-title {
color: #a6d796;
}
.markdown-body .caution>.admonition-title {
color: #d7a796;
}
.markdown-body .hint>.admonition-title {
color: #96c6d7;
}
.markdown-body .danger>.admonition-title {
color: #c25f77;
}
.markdown-body .question>.admonition-title {
color: #96a6d7;
}
.markdown-body .note>.admonition-title {
color: #d7c896;
}
.markdown-body .admonition:before,
.markdown-body .attention:before,
.markdown-body .caution:before,
.markdown-body .hint:before,
.markdown-body .danger:before,
.markdown-body .question:before,
.markdown-body .note:before {
font: normal normal 16px fontawesome-mini;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
line-height: 1.5;
color: #333;
position: absolute;
left: 0;
top: 0;
padding-top: 10px;
padding-left: 10px;
}
.markdown-body .admonition:before {
content: "\f056\00a0";
color: 333;
}
.markdown-body .attention:before {
content: "\f058\00a0";
color: #a6d796;
}
.markdown-body .caution:before {
content: "\f06a\00a0";
color: #d7a796;
}
.markdown-body .hint:before {
content: "\f05a\00a0";
color: #96c6d7;
}
.markdown-body .danger:before {
content: "\f057\00a0";
color: #c25f77;
}
.markdown-body .question:before {
content: "\f059\00a0";
color: #96a6d7;
}
.markdown-body .note:before {
content: "\f040\00a0";
color: #d7c896;
}
.markdown-body .admonition::after {
content: normal;
}
.markdown-body .attention {
border-left: 6px solid #a6d796;
}
.markdown-body .caution {
border-left: 6px solid #d7a796;
}
.markdown-body .hint {
border-left: 6px solid #96c6d7;
}
.markdown-body .danger {
border-left: 6px solid #c25f77;
}
.markdown-body .question {
border-left: 6px solid #96a6d7;
}
.markdown-body .note {
border-left: 6px solid #d7c896;
}
.markdown-body .admonition>*:first-child {
margin-top: 0 !important;
}
.markdown-body .admonition>*:last-child {
margin-bottom: 0 !important;
}
/* progress bar*/
.markdown-body .progress {
display: block;
width: 300px;
margin: 10px 0;
height: 24px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #ededed;
position: relative;
box-shadow: inset -1px 1px 3px rgba(0, 0, 0, .1);
}
.markdown-body .progress-label {
position: absolute;
text-align: center;
font-weight: bold;
width: 100%; margin: 0;
line-height: 24px;
color: #333;
text-shadow: 1px 1px 0 #fefefe, -1px -1px 0 #fefefe, -1px 1px 0 #fefefe, 1px -1px 0 #fefefe, 0 1px 0 #fefefe, 0 -1px 0 #fefefe, 1px 0 0 #fefefe, -1px 0 0 #fefefe, 1px 1px 2px #000;
-webkit-font-smoothing: antialiased !important;
white-space: nowrap;
overflow: hidden;
}
.markdown-body .progress-bar {
height: 24px;
float: left;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background-color: #96c6d7;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .5), inset 0 -1px 0 rgba(0, 0, 0, .1);
background-size: 30px 30px;
background-image: -webkit-linear-gradient(
135deg, rgba(255, 255, 255, .4) 27%,
transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%,
transparent 77%, transparent
);
background-image: -moz-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: -ms-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: -o-linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
background-image: linear-gradient(
135deg,
rgba(255, 255, 255, .4) 27%, transparent 27%,
transparent 52%, rgba(255, 255, 255, .4) 52%,
rgba(255, 255, 255, .4) 77%, transparent 77%,
transparent
);
}
.markdown-body .progress-100plus .progress-bar {
background-color: #a6d796;
}
.markdown-body .progress-80plus .progress-bar {
background-color: #c6d796;
}
.markdown-body .progress-60plus .progress-bar {
background-color: #d7c896;
}
.markdown-body .progress-40plus .progress-bar {
background-color: #d7a796;
}
.markdown-body .progress-20plus .progress-bar {
background-color: #d796a6;
}
.markdown-body .progress-0plus .progress-bar {
background-color: #c25f77;
}
.markdown-body .candystripe-animate .progress-bar{
-webkit-animation: animate-stripes 3s linear infinite;
-moz-animation: animate-stripes 3s linear infinite;
animation: animate-stripes 3s linear infinite;
}
@-webkit-keyframes animate-stripes {
0% {
background-position: 0 0;
}
100% {
background-position: 60px 0;
}
}
@-moz-keyframes animate-stripes {
0% {
background-position: 0 0;
}
100% {
background-position: 60px 0;
}
}
@keyframes animate-stripes {
0% {
background-position: 0 0;
}
100% {
background-position: 60px 0;
}
}
.markdown-body .gloss .progress-bar {
box-shadow:
inset 0 4px 12px rgba(255, 255, 255, .7),
inset 0 -12px 0 rgba(0, 0, 0, .05);
}
/* Multimarkdown Critic Blocks */
.markdown-body .critic_mark {
background: #ff0;
}
.markdown-body .critic_delete {
color: #c82829;
text-decoration: line-through;
}
.markdown-body .critic_insert {
color: #718c00 ;
text-decoration: underline;
}
.markdown-body .critic_comment {
color: #8e908c;
font-style: italic;
}
.markdown-body .headeranchor {
font: normal normal 16px octicons-anchor;
line-height: 1;
display: inline-block;
text-decoration: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.headeranchor:before {
content: '\f05c';
}
.markdown-body .task-list-item {
list-style-type: none;
}
.markdown-body .task-list-item+.task-list-item {
margin-top: 3px;
}
.markdown-body .task-list-item input {
margin: 0 4px 0.25em -20px;
vertical-align: middle;
}
/* Media */
@media only screen and (min-width: 480px) {
.markdown-body {
font-size:14px;
}
}
@media only screen and (min-width: 768px) {
.markdown-body {
font-size:16px;
}
}
@media print {
.markdown-body * {
background: transparent !important;
color: black !important;
filter:none !important;
-ms-filter: none !important;
}
.markdown-body {
font-size:12pt;
max-width:100%;
outline:none;
border: 0;
}
.markdown-body a,
.markdown-body a:visited {
text-decoration: underline;
}
.markdown-body .headeranchor-link {
display: none;
}
.markdown-body a[href]:after {
content: " (" attr(href) ")";
}
.markdown-body abbr[title]:after {
content: " (" attr(title) ")";
}
.markdown-body .ir a:after,
.markdown-body a[href^="javascript:"]:after,
.markdown-body a[href^="#"]:after {
content: "";
}
.markdown-body pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
.markdown-body pre,
.markdown-body blockquote {
border: 1px solid #999;
padding-right: 1em;
page-break-inside: avoid;
}
.markdown-body .progress,
.markdown-body .progress-bar {
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
}
.markdown-body .progress {
border: 1px solid #ddd;
}
.markdown-body .progress-bar {
height: 22px;
border-right: 1px solid #ddd;
}
.markdown-body tr,
.markdown-body img {
page-break-inside: avoid;
}
.markdown-body img {
max-width: 100% !important;
}
.markdown-body p,
.markdown-body h2,
.markdown-body h3 {
orphans: 3;
widows: 3;
}
.markdown-body h2,
.markdown-body h3 {
page-break-after: avoid;
}
}
</style><title>manuscript</title></head><body><article class="markdown-body"><h1 id="the-histonedb-20-a-phylogeny-based-resource-for-all-histone-proteins-and-their-variants"><a name="user-content-the-histonedb-20-a-phylogeny-based-resource-for-all-histone-proteins-and-their-variants" href="#the-histonedb-20-a-phylogeny-based-resource-for-all-histone-proteins-and-their-variants" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>The HistoneDB 2.0: a phylogeny-based resource for all histone proteins and their variants</h1>
<p><NAME><sup>1</sup>, <NAME><sup>1</sup>, <NAME><sup>1</sup>, <NAME><sup>2</sup>, <NAME><sup>1</sup>, <NAME><sup>1</sup></p>
<p><sup>1</sup>Computational Biology Branch, National Center for Biotechnology Information, National Library of Medicine, National Institutes of Health, 8600 Rockville Pike, MSC 6075, Bethesda, MD 20894-6075, USA,<br />
<sup>2</sup>Howard Hughes Medical Institute, Basic Sciences Division, Fred Hutchinson Cancer Research Center, Seattle, WA 98109, USA.</p>
<h4 id="contact"><a name="user-content-contact" href="#contact" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Contact</h4>
<p><NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>) or <NAME> (<a href="mailto:<EMAIL>"><EMAIL></a>)</p>
<h3 id="abstract"><a name="user-content-abstract" href="#abstract" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Abstract</h3>
<p>Since the initial creation of the Histone Database, several variants, or non-allelic protein isoforms, for each core histone have been identified. These variants have have a vast number of functions and play important roles in nucleosome dynamics. We need the Histone Database to account for these new variants. Here, The Histone Database has been renamed HistoneDB and rebuilt to be organized and searchable by variants and taxonomy. We created profile-HMMs for each variant to search the nr database. Sequences were added into the HistoneDB if they were found to have 95% specificity. The is built with the Django python web framework and the source is available at GitHub: <a href="http://github.com/edraizen/HistoneDB">http://github.com/edraizen/HistoneDB</a>.</p>
<p>Database URL: <a href="http://www.ncbi.nlm.nih.gov/HistoneDB">http://www.ncbi.nlm.nih.gov/HistoneDB</a> </p>
<h2 id="introduction"><a name="user-content-introduction" href="#introduction" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Introduction</h2>
<p>The traditional role of histone proteins is in their formation of the the nucleosome to organize and compact the DNA to fit inside the nucleus. However, as we uncover more information about histones, we have learned they are necessary to controlling and regulating gene expression, cell reprogramming, and much more.</p>
<p>Fig 1. Chromatin and nucleosome structure. Modified from From Lewins Genes X & Molecular Cell Biology, Lodish H et al. </p>
<p>The nucleosome core particle is formed from an octamer of four core histone types: H2A, H2B, H3, and H4 that all share the same histone fold, but contain less than 25% sequence similarity. The nucleosome is formed by two copies of each histone, with H2A-H2B forming a dimer (2x) and H3-H4 form a tetramer. This octamer of histone proteins wraps around 189 basepairs of DNA 1.67 times. There is also a linker histone H1, which sits above the linker DNA of the nucleosome, but does not share the histone fold. \ref{Shaytan2015}</p>
<p>Fig 1. The Nucleosome core particle. H2A is yellow, H2B is red, H3 is blue, and H4 is green. H1 is not shown. Figure created by \ref{Shaytan2015} </p>
<p>A histone variant is defined as a non-allelic protein isoforms that forms monophyletic clade. Each varaint has a specific structure and function that is different than the canonical. It is important to note that histone variants can become post translationally modifications (PTMs), but this database does not include PTMs at this time.</p>
<h4 id="h2a"><a name="user-content-h2a" href="#h2a" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>H2A</h4>
<p>There are six structurally variants for H2A. H2A.X is the most common, with notable sequence motif ‘SQ(E/I)Y’. H2A.X is known to be involved with DNA damage response, chromatin remodelling, and X chromosome inactivation in somatic cells. H2A.X, however, is the only variant that is not monophyletic; its has evolved several times, but each version has similar functions. Currently only the final motif SQEY has a PDB.</p>
<p>H2A.Z is known for transcription regulation, DNA repair, suppression of antisense RNA, and Polymerase II recruitment. It has a large hydrophobic patch and a sequence motif of ‘DEELD.’ Two H2A.Z structures have been solved: H2A.Z.1 and H2A.Z.2.</p>
<p>macroH2A: n terminal histone fold, c-term macro domain, can bind ADP, lost in several lineages including Caenorhabditis and Drosophila \ref{Talbert2012}, X-inactivation, Positive or negative transcriptional regulation. PDBs of each domain, but linker is too flexible to be crystalized</p>
<p>H2A.B: Barr body deficient, mammals, related to H2A.L and H2A.M, mammalian spermiogenesis, rapidly evolving, large expansions, shortened docking domain so wraps less DNA. Homology model available?</p>
<p>H2A.L: mammals, mammalian spermiogenesis, rapidly evolving, large expansions, shortened docking domain so wraps less DNA, forms subnucleosomal particles with TS H2B.1. Homology model available?</p>
<p>H2A.M: Binds to huntingtin protein M</p>
<p>other less studied H2A variants include H2A.J, which is very similar to canonical, TS H2A.1, which is testis-specific, and H2A.Q, which had been identified in Oikopluera. There are also species independent variants, H2A.1 through H2A.10. The number after do not imply homology, but are only meaningful if discussing an organism.</p>
<h4 id="h2b"><a name="user-content-h2b" href="#h2b" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>H2B</h4>
<p>TS H2B.1, PDB available<br />
H2B.W: Spermiogenesis, Telomere associated functions in sperm, found in Spermatogenic cells<br />
H2B.Z<br />
subH2B: Spermiogenesis, found in Nucleus / subacromosome of spermatozoa, Has a bipartite Nuclear localization signal:</p>
<h4 id="h3"><a name="user-content-h3" href="#h3" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>H3</h4>
<p>cenH3, or centromeric H3, is found when the nucleosme is forming the centromere. While there is a debate on calling it cenH3 vs CENP-A, we beleive cenH3 is more informative becuase it identifies it being of the H3 core histone. Currently, the the cenH3s do not form a monophyletic clade, but many beileve this is due to limited phylogentic teqnies, and do actually form a monophyltic clade. </p>
<p>PDB available<br />
H3.3 PDN Available<br />
H3.Y: <br />
H3.1:<br />
H3.2:</p>
<p>“cenH3s do not form a clade to the exclusion of other H3s. I personally think cenH3s are likely to be monophyletic, but several groups have come to the same conclusion (or inconclusion) that the evidence to support monophyly is not there with current phylogenetic techniques. Thus it is a functional class, rather than a structural clade, though with some characteristic structural signatures, like a longer loop 1. </p>
<p>Canonical H3s and H3.3s have diverged multiple times. I think Jan Postberg et al 2010 has the best analysis of H3 evolution. The origin of canonical H3s appears to me to have occurred separately in plants, animals, and other lineages. I would not say they are species-specific in most cases; nearly all animals have the same H3.2 and H3.3 proteins. H3.2s and H3.3s are identical between flies, humans and most other animals” -Talbert</p>
<h4 id="h4"><a name="user-content-h4" href="#h4" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>H4</h4>
<p>mostly single form of H4, there are some species specifc varaints. PDB<br />
H4.1<br />
H4.2<br />
H4.V: found in Kinetoplastids</p>
<h4 id="h1"><a name="user-content-h1" href="#h1" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>H1</h4>
<p>Each variant has distinguishable feature that can be captured by a Hideen Markov Models. All of the sequences from the non-redundant (nr) database have been classified by our variant models and added in the HistoneDB so it can be easily searchable by variants.</p>
<p>An important aspect of this database is to promote the new nomenclature for histone variants defined by Talbert et al based on phylogeny. If a clade is it monophyletic, it is defined as a histone variant. If a clade is further separated into smaller clades, those are defined as genes and splice isoforms. Each branch point becomes a period in the new notation. </p>
<p>However, if you are still uncomfortable with new naming scheme, you can search the database using the old naming schemes. We will tell you the new correct name, so you learn to adopt the new standard.</p>
<p>While this update does not deal with histone-like proteins in archaea and bacteria, you can still access the sequences collected for these types developed for the previous version of the database.</p>
<h2 id="database-and-software"><a name="user-content-database-and-software" href="#database-and-software" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Database and Software</h2>
<h3 id="data-sources-and-histone-variant-identification"><a name="user-content-data-sources-and-histone-variant-identification" href="#data-sources-and-histone-variant-identification" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Data sources and histone variant identification</h3>
<p>The sequences from H2A, H2B, H3, H4, and H1 used to create the phylogenetic trees in Talbert et. al, were separated into files containing each variant as defined in Talbert et. al. These sequences were identified by Talbert “using tblastn or blastp<br />
(usually psi-blast) starting with known variants (often the human ones,<br />
or Arabidopsis) and selected proteins based on the goal of getting broad<br />
phylogenetic representation. I often used the taxonomic limiting box in<br />
Blast to target certain groups or exclude the abundance of identical<br />
vertebrate proteins. For more divergent eukaryotic groups like Alveolates<br />
and Excavates, I often used an identified histone within the group to<br />
search for others. This strategy works sometimes, particularly with<br />
closely related organisms, but in other cases, it simply increases the<br />
divergence between proteins that have diverged from a “consensus”<br />
sequence in different amino acids. For example when looking for cenH3s,<br />
it is almost always better to use a canonical H3 (rather than a cenH3) to<br />
search against a targeted taxonomic group and look for hits that only<br />
have about 50% identity, and check the alignments for a longer loop1 and<br />
other signatures of cenH3s. Similarly, H2A.Zs are distinguished from other H2As by both certain amino acid signatures and a one amino acid<br />
insertion in loop1 and a one amino acid deletion in the docking domain,<br />
which can be quickly seen in blast alignments. Beyond a desire to get<br />
broad phylogenetic representation, the choice of variants was fairly<br />
arbitrary, though I usually tried to include favorite model organisms. I<br />
generally avoided anything that looked like it might be a partial<br />
sequence, mis-splicing event or was otherwise suspicious, though that is<br />
obviously a judgement call.” - Talbert personal communication, will summarize</p>
<p>Once each variant was in its respective FASTA file, I aligned each separately to create seed alignments for each variant. These were checked manually to make sure they had a wide taxonomic distribution and no large insertions in the core histone fold regions. These seed sequences were then used to train profile Hidden Markov Models, using HMMER 3.1b2 hmmbuild. Next, all of the variant models were combined into one file and pressed using HMMER 3.1b2 hmmpress. Finally, we used the combined HMM file to search all of the NCBI non-redundant (nr) database. </p>
<p>Further we defined cutoffs scores for each variant based on 95% specificity. Positive training sets were defined as the seed for the given varaint and negative examples we defined as a combination of all seeds except the given varaint \fig{H2AZ_cutoff). Please see supplematary information for details about evaluting each varaint model. </p>
<p>For each variant, we defined a positive examples as the seed we created for that variant and negative examples as a combination of the seeds created for every variant except the variant in question.</p>
<p>To find cananical histones and unknown varaints we built core histone type profile HMMs using the alignments from the original Histone Database and searched nr again. Sequences that were not already matched to a varaint, and above an E-Value of 0.1, were saved into the HistoneDB with varaint ‘Unknown.’ </p>
<h3 id="software"><a name="user-content-software" href="#software" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Software</h3>
<p>The HistoneDB 2.0 is now written in Django, a high-level Python Web Framework, with a MySQL backend. The project has two applications, ‘browse,’ and ‘djangophylcore.’ Browse contains the HistoneDB models (database tables), views (python function to display each page), and templates (HTML files). Djangophylocore is a previously developed django application developed at University Montpellier to store the NCBI taxonomy database in a Django relational database as a tree using an algorithm similar to Modified Preorder Tree Traversal. The scheme for the HistoneDB Django database can be seen in \ref{django_schema}.</p>
<p>Figure x. The HistoneDB database schema. </p>
<p>The layout is based on Twitter Bootstrap, with four important pages: Main browse of all core histone types, Core histone type browse of a single core histone, Variant browse, and All Sequences/Search.</p>
<h4 id="main-browse"><a name="user-content-main-browse" href="#main-browse" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Main browse</h4>
<p>There frontpage is a general browse page, where you can choose one of the four core histone types, by selecting a color coded 3D model for each variant created from PDB 1AOI (Shaytan, 2015). You can also select archaeal and bacterial sequences and sequences that contains structures in the PDB, which were all curated for the last version of the database. </p>
<h4 id="core-histone-browse"><a name="user-content-core-histone-browse" href="#core-histone-browse" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Core Histone browse</h4>
<p>After you choose a core histone type, you are redirected to a page for the individual histone type with four tabs. The first tab contains the phylogenetic tree organized by variants using jsPhyloSVG. These trees have been created by aligning all of the seed sequences for a given histone type using MUSCLE v3.8.31 and neighbor-joining in CLUSTALW 2.1 to create the trees. Th trees were then converted to PhyloXML using BioPython and were edited to add features in jsPhyloSVG. Selecting a variant goes to a new variant page.</p>
<p>The next tab contains all organisms that contain the core histone type as a zoomable D3 sunburst. These have been created using the Djangophylore parent attribute for each sequence following back the root, only allowing taxonmies with a rank and stopping at the rank ‘order.’ Selecting a node will zoom into a new sunburst with the selected node in the center and it’s children as leaves. When you have finished drilling down the sunburst, you hit ‘View Sequences,’ which will take you to the ‘All Sequences’ page that will display sequences that have the core type you originally selected and are within the selected phyla.</p>
<p>The third tab contains all sequences of the selected core histone type. This is based off the ‘All Sequences’ page.</p>
<p>The fourth tab contains a general seed alignment for the core histone fold. These were previously calculated for the initial Histone Database.</p>
<h4 id="variant-browse"><a name="user-content-variant-browse" href="#variant-browse" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Variant Browse</h4>
<p>The variant browse page starts off with the name of the variant, a description of its proposed functions, and previous names the variant has been referred to. Next you have three tabs, with the first being an organism tab that displays a D3 sunburst like the core histone browse page, but this one only contains organism that have this variant. Again, after you have zoomed into the desired organism, you can select ‘View Sequences,’ which will take you to the ‘All Sequences’ page that will display sequences that have the core type you originally selected, the selected variant, and are within the selected phyla.</p>
<p>The next tab contains all of the sequences for that variant, with the same functionality as the core histone browse page.</p>
<p>The final tab consists of the multiple sequence alignment for the specific variant, which have been created using the sequences identified by Talbert. This is also made with the BioJS msa module.</p>
<h4 id="all-sequences"><a name="user-content-all-sequences" href="#all-sequences" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>All Sequences</h4>
<p>You are presented with the GI, Variant, Gene, Splice, Species, Header, and Score for each sequence using wenzhixin’s bootstrap-table. You can then select one or more sequences to see its multiple sequence alignments with secondary structure annotations, scores for the sequence in other models, view in Entrez, and download all. The Multiple Sequence Alignment is made from the BioJS msa package. Viewing scores of the sequence from other models is important to see if there was a classification error, or there may be other significant variants but we don’t know for sure, e.g. the sequence with GI xxxx from Drosophila is classified at H2A.Z, but it contains the motif “SQEY,” which is common in H2A.X. <br />
<strong><em> Soon, you will be able to search for high scoring sequences in other variants or auticaly show them if requested </em></strong></p>
<h4 id="search"><a name="user-content-search" href="#search" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Search</h4>
<p>There are two types of search, ‘filter’ and ‘simple search’. Filter is the standard search, where you presented by database column names and filter based on that. This is used in Advanced Search and the All Sequences Advanced Filter. Simple search is when you have a single textbox that filters the entire database, which can be seen on the navigation bar and the All Sequences search textbox. The simple search searches in order GI number, core histone type, variant, old name schemes for variant, taxonomy, sequence headers, and finally sequence motifs, stopping if a match is made. If the search was from the navigation bar and the result was a core histone type or variant, the page is redirected to its respective browse page. </p>
<h2 id="results-and-discussion"><a name="user-content-results-and-discussion" href="#results-and-discussion" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Results and Discussion</h2>
<p>We were able to classify most histone sequences by variant in the nr database. Our models however, are unable to distinguish between paralogous genes and splice isoforms, which we would like to study further. For the varaints we were able to classify, we were able to show<br />
We were able to distinguish between three different H2A variants: H2A.B, H2A.L, H2A.M. Most of the sequences are classified as H2A.B in nr, but this is missing the two other variants they might be. H2A.M is known to bind to Huntingtin Protein M, but not much is known about its specific function. One problem</p>
<h2 id="conclusion"><a name="user-content-conclusion" href="#conclusion" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Conclusion</h2>
<p>This update of the HIstoneDB will enable chromatin research to …</p>
<p>This will ecourage people to use the new phylogeny-based nomencalture deinfed by Talbert et. al.</p>
<p>It is still unknown which histone variants prefer forming complex together. This database will allow histone researchers to </p>
<h2 id="funding"><a name="user-content-funding" href="#funding" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Funding</h2>
<p>This work was supported by the Intramural Research Program of the National Library of Medicine, NIH. ED is supported by the Oak Ridge Institute for Science and Education. AS is supported by the US-Russia Collaboration in the Biomedical Sciences NIH visiting fellows program.</p>
<h2 id="acknowledgements"><a name="user-content-acknowledgements" href="#acknowledgements" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Acknowledgements</h2>
<p>We would like to thank <NAME> for discussions about Django and the Fellows at NCBI for useful discussions and beta testing.</p>
<p>Conflict of interest. None declared.</p>
<h2 id="references"><a name="user-content-references" href="#references" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>References</h2></article></body></html><file_sep>import sys
import os
import StringIO
import shlex
import uuid
from Bio import SeqIO, SearchIO
from Bio.Blast.Applications import NcbiblastpCommandline
from Bio.Blast import NCBIXML
from browse.models import Histone, Variant, Sequence
from django.conf import settings
import subprocess
from django.db.models import Q
from django.db.models import Max, Min, Count
class TooManySequences(RuntimeError):
pass
class InvalidFASTA(RuntimeError):
pass
def process_upload(type, sequences, format):
if format == "file":
processed_sequences = list(SeqIO.parse(sequences, "fasta"))
elif format == "text":
seq_file = StringIO.StringIO()
seq_file.write(sequences)
seq_file.seek(0)
processed_sequences = list(SeqIO.parse(seq_file, "fasta"))
if len(processed_sequences) > 50:
raise TooManySequences
sequences = "\n".join([seq.format("fasta") for seq in processed_sequences])
if type == "blastp":
result = upload_blastp(sequences, len(processed_sequences))
elif type == "hmmer":
result = upload_hmmer(processed_sequences, len(processed_sequences))
else:
assert 0, type
return result
def upload_blastp(seq_file, num_seqs):
blastp = os.path.join(os.path.dirname(sys.executable), "blastp")
output= os.path.join("/", "tmp", "{}.xml".format(seq_file[:-6]))
blastp_cline = NcbiblastpCommandline(
cmd=blastp,
db=os.path.join(settings.STATIC_ROOT, "browse", "blast", "HistoneDB_sequences.fa"),
evalue=0.01, outfmt=5)
out, err = blastp_cline(stdin=seq_file)
blastFile = StringIO.StringIO()
blastFile.write(out)
blastFile.seek(0)
result = []
for i, blast_record in enumerate(NCBIXML.parse(blastFile)):
for alignment in blast_record.alignments:
try:
gi = alignment.hit_def.split("|")[0]
except IndexError:
continue
for hsp in alignment.hsps:
sequence = Sequence.objects.filter(
(~Q(variant__id="Unknown") & Q(all_model_scores__used_for_classifiation=True)) | \
(Q(variant__id="Unknown") & Q(all_model_scores__used_for_classifiation=False)) \
).annotate(
num_scores=Count("all_model_scores"),
score=Max("all_model_scores__score"),
evalue=Min("all_model_scores__evalue")
).get(id=gi)
search_evalue = hsp.expect
result.append({
"id":str(sequence.id),
"variant":str(sequence.variant_id),
"gene":str(sequence.gene) if sequence.gene else "-",
"splice":str(sequence.splice) if sequence.splice else "-",
"taxonomy":str(sequence.taxonomy.name),
"score":str(sequence.score),
"evalue":str(sequence.evalue),
"header":str(sequence.header),
"search_e":str(search_evalue),
})
return result
def upload_hmmer(seq_file, num_seqs, evalue=10):
"""
"""
save_dir = os.path.join(os.path.sep, "tmp", "HistoneDB")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
temp_seq_path = os.path.join(save_dir, "{}.fasta".format(uuid.uuid4()))
with open(temp_seq_path, "w") as seqs:
for s in seq_file:
SeqIO.write(s, seqs, "fasta");
variantdb = os.path.join(settings.STATIC_ROOT, "browse", "hmms", "combined_variants.hmm")
coredb = os.path.join(settings.STATIC_ROOT, "browse", "hmms", "combined_cores.hmm")
hmmsearch = os.path.join(os.path.dirname(sys.executable), "hmmsearch")
results = {}
variants = []
variants = list(Variant.objects.all().order_by("id").values_list("id", "hmmthreshold"))
indices = {variant: i for i, (variant, threshold) in enumerate(variants)}
seqs_index = {seq.id:i for i, seq in enumerate(seq_file)}
ids = map(lambda s: s.id, seq_file)
rows = [{} for _ in xrange(len(variants))]
classifications = {s.id:"Unknown" for s in seq_file}
for i, (variant, threshold) in enumerate(variants):
rows[i]["variant"] = "{} (T:{})".format(variant, threshold)
for id in ids:
rows[i][id] = "n/a"
rows[i]["data"] = {}
rows[i]["data"]["above_threshold"] = {id:False for id in ids}
rows[i]["data"]["this_classified"] = {id:False for id in ids}
for i, db in enumerate((variantdb, coredb)):
process = subprocess.Popen([hmmsearch, "-E", str(evalue), "--notextw", db, temp_seq_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output, error = process.communicate()
hmmerFile = StringIO.StringIO()
hmmerFile.write(output)
hmmerFile.seek(0)
for variant_query in SearchIO.parse(hmmerFile, "hmmer3-text"):
if i==1:
variant = "canonical{}".format(variant_query.id)
else:
variant = variant_query.id
print variant
variants.append(variant)
try:
variant_model = Variant.objects.get(id=variant)
except Variant.DoesNotExist:
continue
for hit in variant_query:
print "Hit is", hit.id
for hsp in hit:
if hsp.bitscore>=variant_model.hmmthreshold and \
(classifications[hit.id] == "Unknown" or \
float(hsp.bitscore) >= rows[indices[classifications[hit.id]]][hit.id]):
if i==1 and not (classifications[hit.id] == "Unknown" or "canonical" in classifications[hit.id]):
#Skip canoninical score if already classfied as a variant
continue
classifications[hit.id] = variant
if not classifications[hit.id] == "Unknown":
for row in rows:
row["data"]["this_classified"][hit.id] = False
rows[indices[variant]]["data"]["this_classified"][hit.id] = True
rows[indices[variant]]["data"]["above_threshold"][hit.id] = float(hsp.bitscore)>=variant_model.hmmthreshold
rows[indices[variant]][hit.id] = float(hsp.bitscore)
classifications = [(id, classifications[id]) for id in ids]
#Cleanup
os.remove(temp_seq_path)
return classifications, ids, rows
<file_sep>from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('browse.views',
#url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'browse_types'),
url(r'^browse/$', 'browse_types'),
url(r'^type/([a-zA-Z0-9]+)/$', 'browse_variants'),
url(r'^type/([a-zA-Z0-9]+)/variant/([a-zA-Z0-9\.]+)/$', 'browse_variant'),
url(r'^search/$', 'search'),
url(r'^analyze/$', 'analyze'),
url(r'^help/$', 'help'),
#Parameters are stored as session variables a GET response
url(r'^data/sequences/json$', 'get_sequence_table_data'),
url(r'^data/scores/json$', 'get_all_scores'),
url(r'^data/msa/json$', 'get_all_sequences'),
url(r'^data/features/gff$', 'get_sequence_features'),
url(r'^data/sequences\+features/json$', 'get_aln_and_features'),
url(r'^data/(type)/json/([a-zA-Z0-9]+)/species/$', 'get_starburst_json'),
url(r'^data/(variant)/json/([a-zA-Z0-9\.]+)/species/$', 'get_starburst_json'),
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
import debug_toolbar
urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)),)
<file_sep>import re
from Bio import Entrez, SeqIO
# *Always* tell NCBI who you are
Entrez.email = "<EMAIL>"
def seq_from_gi(gis):
post_results = Entrez.read(Entrez.epost("protein", id=",".join(gis)))
webenv = post_results["WebEnv"]
query_key = post_results["QueryKey"]
handle = Entrez.efetch(db="protein", rettype="gb",retmode="text", webenv=webenv, query_key=query_key)
for s in SeqIO.parse(handle, "gb"):
yield s
def taxonomy_from_gis(gis):
"""
"""
for s in seq_from_gi(gis):
print s.annotations["organism"]
yield s.annotations["organism"]
<file_sep># HistoneDB
A database for all histone proteins in NR organized by their known non-allelic protein isoforms, called variants. This resource can be used to understand how changes in histone variants affect structure, complex formation, and nucleosome function. For more information, please read our [paper](manuscript/paper.md) (citation below).
The database can be accessed at http://www.ncbi.nlm.nih.gov/projects/histonedb/
## Requirements ##
- Python 2.7
- Flup 1.0.2, if using fastcgi
- Django 1.8
- django-extensions 1.5.3
- MySQL-python 1.2.5
- BioPython 1.65
- colour 0.1.1
- HMMER 3.1b2
- BLAST+
- EMBOSS
## Setup ##
If you want to test the server on your own machine, you must make sure have all of the dependencies listed above and follow these steps.
1) Create MySQL database, and store the login information in HistoneDB/NCBI_database_info.py, which is formatted in the following way:
```
#This file contains the user name and password for the HistoneDB 2.0
#Keep hidden
name = "DB NAME"
user = "DB USER"
password = "<PASSWORD>"
host = "DB URL"
```
2) Build NCBI Taxonomy with djangophylocore
```
python manage.py buildncbi
python manage.py loadtaxonomy
python manage.py buildtaxonomytoc
```
3) Classify sequences in NR
```
python manage.py buildvariants
```
4) Build trees from seed sequences
```
python manage.py buildtrees
```
5) Build organism sunbursts for each variant
```
python manage.py buildsunburst
```
6) Build MSA and GFF sequence features for variants
```
python manage.py buildseedinfo
```
## Run ##
You have several options to run the Django server. The easiest way is to run it through `manage.py`, specifying a port (we use port 8080 in the example):
```
python manage.py runserver 8080
```
For deployment, we use FastCGI on the NCBI webservers. While this will be deprecated in the next version of Django, it is what NCBI allows. For more info, please read https://docs.djangoproject.com/en/1.8/howto/deployment/fastcgi/
## Cite ##
Coming soon.
## Acknowledgements ##
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* <NAME>
<file_sep>from django import forms
from django.forms import ModelForm
from browse.models import Histone, Variant, Sequence, Features
from browse.search import search_types
class AdvancedFilterForm(ModelForm):
core_histone = forms.ModelChoiceField(Histone.objects.all())
taxonomy = forms.CharField(max_length=50)
sequence = forms.CharField(max_length=50)
score = forms.FloatField()
evalue = forms.FloatField()
unique = forms.BooleanField()
class Meta:
model = Sequence
fields = ["id", "core_histone", "variant", "gene", "splice", "taxonomy", "header", "sequence"]
def __init__(self, *args, **kwargs):
super(AdvancedFilterForm, self).__init__(*args, **kwargs)
self.fields['id'].label = "GI"
self.fields['core_histone'].label = "Histone"
self.fields['evalue'].label = "E-value"
self.fields['variant'].help_text = "Structurally distinct monophyletic clade of a histone family. Enter new or old variant names. Supports new dot (.) syntax."
self.fields['taxonomy'].help_text = "Supports all NCBI Taxonomy names and IDs"
self.fields['gene'].help_text = "Gene number, or more specially phylogenetic branch point order"
self.fields['splice'].help_text = "Splice isoform index, or paralogous sequence number"
self.fields['unique'].help_text = "Only show unique sequences where no organism has multiple sequenes that are identical"
class FeatureForm(ModelForm):
class Meta:
model = Features
exclude = ('reviewed',)
SEARCH_CHOICES = (("blastp", "Search HistoneDB (blastp)"), ("hmmer", "Classify your sequence(s) (hmmer)"))
class AnalyzeFileForm(forms.Form):
type = forms.ChoiceField(widget=forms.RadioSelect, choices=SEARCH_CHOICES, initial=SEARCH_CHOICES[0][0])
sequences = forms.CharField(widget=forms.Textarea)
file = forms.FileField()
def __init__(self, *args, **kwargs):
super(AnalyzeFileForm, self).__init__(*args, **kwargs)
self.fields['sequences'].help_text = "Max 50 Sequences. However, running > 1 sequence in blastp will not be meaningful"
<file_sep>from browse.models import Sequence
from django.conf import settings
import subprocess
from Bio import SeqIO
import os
import sys
def make_blast_db(force=False):
"""Create new BLAST databse with seuqences in the HistoneDB. This will create a new subset of nr"""
seqs_file = os.path.join(settings.STATIC_ROOT, "browse", "blast", "HistoneDB_sequences.fa")
if not os.path.isfile(seqs_file) or force:
with open(seqs_file, "w") as seqs:
for s in Sequence.objects.all():
SeqIO.write(s.to_biopython(ungap=True), seqs, "fasta")
makeblastdb = os.path.join(os.path.dirname(sys.executable), "makeblastdb")
subprocess.call("makeblastdb", "-in", seqs_file, "-dbtype", "'prot'","-title", "HistoneDB"])
def from_nr(force=True):
with open("gi_list.txt", "w") as gi_list:
for gi in Sequence.objects.all().values_list("id", flat=True):
print >> gi_list, gi
print gi
nr_db = os.path.join(settings.STATIC_ROOT, "blast", "nr.db")
if force or not os.path.isfile(nr_db):
nr = os.path.join(settings.BASE_DIR, "nr")
if not os.path.isfile(nr):
raise RuntimeError("Must have nr in projects base diretory, automaticallt placed when the server is built. Please rebuild.")
subprocess.call([os.path.join(env, "makeblastdb"), "-in", nr, "-dbtype", "prot", "-title", "nr"])
subprocess.call([os.path.join(env, "blastdbcmd"), "-db", nr, "-dbtype", "prot", "-entry_batch", "gi_list.txt", "-out", "HistoneDB_sequences.fa"])
subprocess.call([os.path.join(env, "makeblastdb"), "-in", "HistoneDB_sequences.fa", "-dbtype", "prot","-title", "HistoneDB"])
make_blast_db()<file_sep>"""
Django settings for HistoneDB project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
#This file contains name,user,password, and host for HistoneDB as single variable with those names.
#It has been obscured to follow the NCBI privacy policy. If the file is not present (e.g. on GitHub),
#you will revice a 500 Server Error.
from HistoneDB import NCBI_database_info
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = NCBI_database_info.SECRET_KEY
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
if not DEBUG or False:
X_FRAME_OPTIONS = "DENY"
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 0
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'browse',
'djangophylocore',
'django_extensions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'HistoneDB.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates"),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
TEMPLATE_DIRS = [os.path.join(BASE_DIR, "templates"),]
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
WSGI_APPLICATION = 'HistoneDB.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': NCBI_database_info.name,
'USER': NCBI_database_info.user,
'PASSWORD': NCBI_database_<PASSWORD>,
'HOST': NCBI_database_info.host,
'PORT':NCBI_database_info.port
}
}
DATABASE_ENGINE="mysql"
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/projects/histonedb/HistoneDB/static/'
STATIC_ROOT = '/web/public/htdocs/projects/histonedb/HistoneDB/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = "/projects/histonedb/HistoneDB/media/"
MEDIA_ROOT = "/web/projects/histonedb/HistoneDB/media/"
# List of finder classes that know how to find static files in
# various locations.
#STATICFILES_FINDERS = (
# 'django.contrib.staticfiles.finders.FileSystemFinder',
# 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#)
#STATIC_FINDERS = STATICFILES_FINDERS
<file_sep>import os
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from tools.L_shade_hist_aln import write_alignments
from tools.hist_ss import get_gff_from_align
from Bio import SeqIO
from Bio.Align import MultipleSeqAlignment
class Command(BaseCommand):
help = 'Reset sequence features'
seed_directory = os.path.join(settings.STATIC_ROOT, "browse", "seeds")
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
for core_type, seed in self.get_seeds():
#write_alignments([seed], seed[:-6], save_dir=os.path.dirname(seed))
with open("{}.gff".format(seed[:-6]), "w") as gff:
msa = MultipleSeqAlignment(list(SeqIO.parse(seed, "fasta")))
get_gff_from_align(msa, gff, save_dir=os.path.dirname(seed))
def get_seeds(self):
for i, (root, _, files) in enumerate(os.walk(self.seed_directory)):
for seed in files:
if not seed.endswith(".fasta"): continue
core_type = seed.split(".")[0]
yield core_type, os.path.join(root, seed)
<file_sep>from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from djangophylocore.models import Taxonomy
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
class Histone(models.Model):
id = models.CharField(max_length=25, primary_key=True)
taxonomic_span = models.CharField(max_length=25)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.id
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('browse.views.browse_variants', args=[str(self.id)])
class Variant(models.Model):
"""Most variants map to
H2A.X -> multiple species, same varaint
H2A.10 -> one species, different varaint that are species speficific
"""
id = models.CharField(max_length=25, primary_key=True)
core_type = models.ForeignKey(Histone, related_name="variants")
taxonmic_span = models.CharField(max_length=25) #models.ForeignKey(Taxonomy)?
description = models.CharField(max_length=255)
hmmthreshold = models.FloatField(null=True)
aucroc = models.IntegerField(null=True)
def __unicode__(self):
return self.id
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('browse.views.browse_variant', args=[str(self.core_type.id), str(self.id)])
class OldStyleVariant(models.Model):
updated_variant = models.ForeignKey(Variant, related_name="old_names")
name = models.CharField(max_length=255, primary_key=True)
gene = models.IntegerField(null=True, validators=[MaxValueValidator(15),MinValueValidator(1)])
splice = models.IntegerField(null=True, validators=[MaxValueValidator(15),MinValueValidator(1)])
taxonomy = models.ForeignKey(Taxonomy, related_name="+")
def __unicode__(self):
return "{} (now called {})".format(self.name, self.updated_variant.id)
class Sequence(models.Model):
id = models.CharField(max_length=25, primary_key=True) #GI
variant = models.ForeignKey(Variant, related_name="sequences")
gene = models.IntegerField(null=True, validators=[MaxValueValidator(15),MinValueValidator(1)])
splice = models.IntegerField(null=True, validators=[MaxValueValidator(15),MinValueValidator(1)])
taxonomy = models.ForeignKey(Taxonomy)
header = models.CharField(max_length=255)
sequence = models.TextField()
reviewed = models.BooleanField()
def __unicode__(self):
return self.format() #"{} [Varaint={}; Organism={}]".format(self.id, self.full_variant_name, self.taxonomy.name)
@property
def gi(self):
return self.id
@property
def full_variant_name(self):
try:
name = self.variant.id
except:
name = ""
if self.gene:
name += ".{}".format(self.gene)
if self.splice:
name += ".s{}".format(self.splice)
return name
@property
def description(self):
desc = self.id
try:
desc += "|{}".format(self.taxonomy.name.split(" ")[0])
except:
pass
if self.full_variant_name:
desc += "|{}".format(self.full_variant_name)
return desc
def to_dict(self, ref=False):
return {"name":self.description, "seq":self.sequence, "ref":ref}
def to_biopython(self, ungap=False):
seq = Seq(self.sequence)
try:
score_desc = self.all_model_scores.fiter(used_for_classifiation=True).first().description()
except:
score_desc = ""
if ungap:
seq = seq.ungap("-")
return SeqRecord(
seq,
id=self.description,
description=score_desc,
)
def format(self, format="fasta", ungap=False):
return self.to_biopython(ungap=ungap).format(format)
class Score(models.Model):
id = models.IntegerField(primary_key=True)
sequence = models.ForeignKey(Sequence, related_name="all_model_scores")
variant = models.ForeignKey(Variant, related_name="+")
above_threshold = models.BooleanField()
score = models.FloatField()
evalue = models.FloatField()
hmmStart = models.IntegerField()
hmmEnd = models.IntegerField()
seqStart = models.IntegerField()
seqEnd = models.IntegerField()
used_for_classifiation = models.BooleanField()
def __unicode__(self):
return "<{} variant={}; score={}; above_threshold={}; used_for_classifiation={} >".format(self.sequence.id, self.variant.id, self.score, self.above_threshold, self.used_for_classifiation)
def description(self):
return "[Score: {}; Evalue:{}]"
class Features(models.Model):
sequence = models.OneToOneField(Sequence, primary_key=True, related_name="features")
alphaN_start = models.IntegerField(null=True)
alphaN_end = models.IntegerField(null=True)
alpha1_start = models.IntegerField(null=True)
alpha1_end = models.IntegerField(null=True)
alpha1ext_start = models.IntegerField(null=True)
alpha1ext_end = models.IntegerField(null=True)
alpha2_start = models.IntegerField(null=True)
alpha2_end = models.IntegerField(null=True)
alpha3_start = models.IntegerField(null=True)
alpha3_end = models.IntegerField(null=True)
alpha3ext_start = models.IntegerField(null=True)
alpha3ext_end = models.IntegerField(null=True)
alphaC_start = models.IntegerField(null=True)
alphaC_end = models.IntegerField(null=True)
beta1_start = models.IntegerField(null=True)
beta1_end = models.IntegerField(null=True)
beta2_start = models.IntegerField(null=True)
beta2_end = models.IntegerField(null=True)
loopL1_start = models.IntegerField(null=True)
loopL1_end = models.IntegerField(null=True)
loopL2_start = models.IntegerField(null=True)
loopL2_end = models.IntegerField(null=True)
mgarg1_start = models.IntegerField(null=True)
mgarg1_end = models.IntegerField(null=True)
mgarg2_start = models.IntegerField(null=True)
mgarg2_end = models.IntegerField(null=True)
mgarg3_start = models.IntegerField(null=True)
mgarg3_end = models.IntegerField(null=True)
docking_domain_start = models.IntegerField(null=True)
docking_domain_end = models.IntegerField(null=True)
core = models.FloatField()
@classmethod
def from_dict(cls, sequence, ss_position):
"""Create model from secondary structure dictionary
Parameters:
-----------
sequence : Sequence
ss_dict : dict
Created from tools.hist_ss
"""
return cls(
sequence = sequence,
alphaN_start = ss_position["alphaN"][0],
alphaN_end = ss_position["alphaN"][1],
alpha1_start = ss_position["alpha1"][0],
alpha1_end = ss_position["alpha1"][1],
alpha1ext_start = ss_position["alpha1ext"][0],
alpha1ext_end = ss_position["alpha1ext"][1],
alpha2_start = ss_position["alpha2"][0],
alpha2_end = ss_position["alpha2"][1],
alpha3_start = ss_position["alpha3"][0],
alpha3_end = ss_position["alpha3"][1],
alpha3ext_start = ss_position["alpha3ext"][0],
alpha3ext_end = ss_position["alpha3ext"][1],
alphaC_start = ss_position["alphaC"][0],
alphaC_end = ss_position["alphaC"][1],
beta1_start = ss_position["beta1"][0],
beta1_end = ss_position["beta1"][1],
beta2_start = ss_position["beta2"][0],
beta2_end = ss_position["beta2"][1],
loopL1_start = ss_position["loopL1"][0],
loopL1_end = ss_position["loopL1"][1],
loopL2_start = ss_position["loopL2"][0],
loopL2_end = ss_position["loopL2"][1],
mgarg1_start = ss_position["mgarg1"][0],
mgarg1_end = ss_position["mgarg1"][1],
mgarg2_start = ss_position["mgarg2"][0],
mgarg2_end = ss_position["mgarg2"][1],
mgarg3_start = ss_position["mgarg3"][0],
mgarg3_end = ss_position["mgarg3"][1],
docking_domain_start = ss_position["docking domain"][0],
docking_domain_end = ss_position["docking domain"][1],
core = ss_position["core"],
)
def __unicode__(self):
"""Returns Jalview GFF format"""
features = [
("alphaN", "", "helix"),
("alpha1", "", "helix"),
("alpha1ext", "", "helix"),
("alpha2", "", "helix"),
("alpha3", "", "helix"),
("alpha3ext", "", "helix"),
("alphaC", "", "helix"),
("beta1", "", "stand"),
("beta2", "", "stand"),
("beta3", "", "stand"),
("loopL1", "", "loop"),
("loopL2", "", "loop"),
("mgarg1", "Minor Groov Arg 1", "residue"),
("mgarg2", "Minor Groov Arg 2", "residue"),
("mgarg3", "Minor Groov Arg 3", "residue"),
("docking_domain", "Docking Domain", "domain")
]
outl = ""
for feature, description, type in features:
start = str(getattr(self, "{}_start".format(feature), -1))
end = str(getattr(self, "{}_end".format(feature), -1))
if "-1" in (start, end):
continue
description = description or feature
id = self.sequence.description
outl += "\t".join((description, id, "-1", start, end, type))
outl += "\n"
return outl
@classmethod
def gff_colors(cls):
return """domain\tred
chain\t225,105,0
residue\t105,225,35
helix\tff0000
strand\t00ff00
loop\tcccccc
"""
def full_gff(self):
return "{}\n{}".format(Features.gff_colors(), str(self))
class Structure(models.Model):
sequence = models.OneToOneField(Sequence, primary_key=True, related_name="structures")
pdb = models.CharField(max_length=25)
mmdb = models.CharField(max_length=25)
chain = models.CharField(max_length=25)
class Publication(models.Model):
id = models.IntegerField(primary_key=True) #PubmedID
variants = models.ManyToManyField(Variant)
cited = models.BooleanField()
<file_sep>import sys
import json
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import redirect
from django.shortcuts import get_list_or_404
from browse.forms import AdvancedFilterForm, AnalyzeFileForm
from browse.search import HistoneSearch
from browse.process_upload import process_upload
from colour import Color
#Django libraires
from browse.models import *
from djangophylocore.models import *
#BioPython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from django.db.models import Min, Max, Count
#Set2 Brewer, used in variant colors
colors = [
"#66c2a5",
"#fc8d62",
"#8da0cb",
"#e78ac3",
"#a6d854",
"#ffd92f",
"#e5c494"
]
def help(request):
data = {
"filter_form":AdvancedFilterForm(),
"original_query":{},
"current_query":{}
}
return render(request, 'help.html', data)
def browse_types(request):
"""Home"""
data = {
"filter_form":AdvancedFilterForm(),
"original_query":{},
"current_query":{}
}
return render(request, 'browse_types.html', data)
def browse_variants(request, histone_type):
try:
core_histone = Histone.objects.get(id=histone_type)
except:
return "404"
variants = core_histone.variants.annotate(num_sequences=Count('sequences')).order_by("id").all().values_list("id", "num_sequences")
variants = [(id, num, color) for (id, num), color in zip(variants, colors)]
data = {
"histone_type": histone_type,
"histone_description": core_histone.description,
"browse_section": "type",
"name": histone_type,
"variants": variants,
"tree_url": "browse/trees/{}.xml".format(core_histone.id),
"seed_file":"browse/seeds/{}".format(core_histone.id),
"filter_form": AdvancedFilterForm(),
}
#Store sequences in session, accesed in get_sequence_table_data
original_query = {"id_core_histone":histone_type}
if request.method == "POST":
query = request.POST.copy()
else:
query = original_query
result = HistoneSearch(request, query, reset=True)
data["original_query"] = original_query
if result.errors:
query = original_query
data["filter_errors"] = result.errors
data["current_query"] = query
return render(request, 'browse_variants.html', data)
def browse_variant(request, histone_type, variant):
try:
variant = Variant.objects.get(id=variant)
except:
return "404"
green = Color("#66c2a5")
red = Color("#fc8d62")
color_range = map(str, red.range_to(green, 12))
scores = Sequence.objects.filter(variant__id=variant).filter(all_model_scores__used_for_classifiation=True).annotate(score=Max("all_model_scores__score")).aggregate(max=Max("score"), min=Min("score"))
data = {
"core_type": variant.core_type.id,
"variant": variant.id,
"name": variant.id,
"sunburst_url": "browse/sunbursts/{}/{}.json".format(variant.core_type.id, variant.id),
"seed_file":"browse/seeds/{}/{}".format(variant.core_type.id, variant.id),
"colors":color_range,
"score_min":scores["min"],
"score_max":scores["max"],
"browse_section": "variant",
"description": variant.description,
"filter_form": AdvancedFilterForm(),
}
original_query = {"id_variant":variant.id}
if request.method == "POST":
query = request.POST.copy()
else:
query = original_query
result = HistoneSearch(request, query, reset=True)
data["original_query"] = original_query
if result.errors:
query = original_query
data["filter_errors"] = result.errors
data["current_query"] = query
return render(request, 'browse_variant.html', data)
def search(request):
data = {"filter_form": AdvancedFilterForm()}
if request.method == "POST":
query = request.POST.copy()
result = HistoneSearch(
request,
query,
navbar="search" in request.POST)
if request.POST.get("reset", True):
request.session["original_query"] = query
data["original_query"] = request.session.get("original_query", query)
data["current_query"] = query
if len(result.errors) == 0:
data["result"] = True
else:
data["filter_errors"] = result.errors
else:
#Show all sequence
result = HistoneSearch.all(request)
data["current_query"] = data["original_query"] = {}
data["result"] = True
if result.redirect:
return result.redirect
return render(request, 'search.html', data)
def analyze(request):
data = {
"filter_form":AdvancedFilterForm(),
"original_query":{},
"current_query":{}
}
if request.method == "POST":
type = request.POST.get("id_type_0")
if request.POST.get("sequences"):
format = "text"
sequences = request.POST["sequences"]
elif request.POST.get("file"):
format="file"
sequences = request.POST["file"]
data["result"] = process_upload(type, sequences, format)
data["search_type"] = type
else:
data["analyze_form"] = AnalyzeFileForm(initial={"type":"blastp"})
return render(request, 'analyze.html', data)
def get_sequence_table_data(request):
"""Downloads the previous search and converts into json required by Bootstrap table
"""
if request.method == "GET":
parameters = request.GET.dict()
else:
#Returning 'false' stops Bootstrap table
parameters = []
#Continues to filter previous search, unless paramters contains key 'reset'
results = HistoneSearch(request, parameters)
if len(results.errors) > 0:
#Returning 'false' stops Bootstrap table
return "false"
unique = "id_unique" in parameters
return JsonResponse(results.get_dict(unique=unique))
def get_all_scores(request, ids=None):
if ids is None and request.method == "GET" and "id" in request.GET:
ids = request.GET.getlist("id")
else:
#Returning 'false' stops Bootstrap table
return "false"
variants = list(Variant.objects.all().order_by("id").values_list("id", "hmmthreshold"))
indices = {variant: i for i, (variant, threshold) in enumerate(variants)}
rows = [{} for _ in xrange(len(variants))]
for i, (variant, threshold) in enumerate(variants):
rows[i]["variant"] = variant #"{} (T:{})".format(variant, threshold)
for id in ids:
rows[i][id] = "n/a"
rows[i]["data"] = {}
rows[i]["data"]["above_threshold"] = {id:False for id in ids}
rows[i]["data"]["this_classified"] = {id:False for id in ids}
for i, id in enumerate(ids):
try:
sequence = Sequence.objects.get(id=id)
except:
return "404"
classified_variant = sequence.variant.id
scores = sequence.all_model_scores.all().order_by("variant__id")
for j, score in enumerate(scores):
if score.variant.id in indices:
threshold = score.variant.hmmthreshold
if rows[indices[score.variant.id]][id] == "n/a" or score.score > rows[indices[score.variant.id]][id]:
rows[indices[score.variant.id]][id] = score.score
rows[indices[score.variant.id]]["data"]["above_threshold"][id] = score.score>=threshold
rows[indices[score.variant.id]]["data"]["this_classified"][id] = score.used_for_classifiation
return JsonResponse(rows, safe=False)
def get_all_sequences(request, ids=None):
if ids is None and request.method == "GET" and "id" in request.GET:
ids = request.GET.getlist("id")
else:
#Returning 'false' stops Bootstrap table
return "false"
format = request.GET.get("format", "json")
download = request.GET.get("download", "false") == "true"
sequences = Sequence.objects.filter(id__in=ids[:50])
if format == "fasta":
response = HttpResponse(content_type='text')
if download:
response['Content-Disposition'] = 'attachment; filename="histone_variants.fasta"'
for s in sequences:
response.write(str(s))
return response
else:
sequences = [s.to_dict() for s in sequences]
return JsonResponse(sequences, safe=False)
def get_aln_and_features(request, ids=None):
from tools.hist_ss import templ, get_hist_ss_in_aln
import subprocess
import StringIO
from Bio.Align import MultipleSeqAlignment
from Bio.Align.AlignInfo import SummaryInfo
if ids is None and request.method == "GET" and "id" in request.GET:
ids = request.GET.getlist("id")
else:
#Returning 'false' stops Bootstrap table
return "false"
sequences = Sequence.objects.filter(id__in=ids[:50])
if len(sequences) == 0:
return None, None
elif len(sequences) == 1:
#Already aligned to core histone
canonical = {"name":"canonical{}".format(sequences.first().variant.core_type), "seq":str(templ[sequences.first().variant.core_type].seq)}
sequences = [canonical, sequences.first().sequence.to_dict()]
features = sequences.first().features
else:
try:
hist_type = max(
[(hist, sequences.filter(variant__core_type_id=hist).count()) for hist in ["H2A", "H2B", "H3", "H4", "H1"]],
key=lambda x:x[1]
)[0]
except ValueError:
hist_type = "Unknown"
muscle = os.path.join(os.path.dirname(sys.executable), "muscle")
process = subprocess.Popen([muscle], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
sequences = "\n".join([s.format() for s in sequences])
aln, error = process.communicate(sequences)
seqFile = StringIO.StringIO()
seqFile.write(aln)
seqFile.seek(0)
sequences = list(SeqIO.parse(seqFile, "fasta")) #Not in same order, but does it matter?
msa = MultipleSeqAlignment(sequences)
save_dir = os.path.join(os.path.sep, "tmp", "HistoneDB")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
hv,ss = get_hist_ss_in_aln(msa, hist_type=hist_type, save_dir=save_dir, debug=False)
a = SummaryInfo(msa)
cons = Sequence(id="consensus", sequence=a.dumb_consensus(threshold=0.1, ambiguous='X').tostring())
features = Features.from_dict(cons, ss)
sequences = [{"name":s.id, "seq":s.seq.tostring()} for s in sequences]
sequences.insert(0, cons.to_dict())
result = {"seqs":sequences, "features":features.full_gff()}
return JsonResponse(result, safe=False)
def get_sequence_features(request, ids=None):
if ids is None and request.method == "GET" and "id" in request.GET:
ids = request.GET.getlist("id")
else:
#Returning 'false' stops Bootstrap table
return "false"
download = request.GET.get("download", "false") == "true"
sequences = Sequence.objects.filter(id__in=ids[:50])
response = HttpResponse(content_type='text')
if download:
response['Content-Disposition'] = 'attachment; filename="histone_annotations.fasta"'
response.write(Features.gff_colors())
for s in sequences:
response.write(str(s.features))
return response
def get_starburst_json(request, browse_type, search, debug=False):
"""
"""
if ids is None and request.method == "GET" and "id" in request.GET:
ids = request.GET.getlist("id")
else:
#Returning 'false' stops Bootstrap table
return "false"
def create_sunburst(root, sunburst=None, level=0):
if sunburst is None:
sunburst = {"name":root.name, "children":[]}
for curr_taxa in root.direct_children.filter(type_name="scientific name").all():
#print "{}{}".format(" "*level, curr_taxa.name),
child = {"name":curr_taxa.name, "children":[]}
#print child
sunburst["children"].append(create_sunburst(curr_taxa, child, level=level+1))
return sunburst
def get_phyloxml_of_type(request):
return None
|
e63f219b7a0a9d9952e70b1e393e58a1991c0f99
|
[
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 18 |
Python
|
Klortho/HistoneDB
|
8d37a68e66ff38d5429487fb4368a4129e75b041
|
36e3bca7c3257298f5e9f32951b94a1bb4ec0853
|
refs/heads/main
|
<file_sep>// Define what you want `currentUser` to return throughout your app. For example,
// to return a real user from your database, you could do something like:
//
// export const getCurrentUser = async ({ email }) => {
// return await db.user.findUnique({ where: { email } })
// }
import { db } from 'src/lib/db'
import { AuthenticationError, ForbiddenError, parseJWT } from '@redwoodjs/api'
import { matrix } from 'src/lib/roles'
export const getCurrentUser = async (decoded, { token, type }) => {
try {
let user = await db.user.findUnique({
where: { email: decoded.preferred_username }
})
//if no user found... create one
let justRoles = []
if (user) {
let roles = await db.userRole.findMany({
where: { userId: user.id }
})
justRoles = roles.map((role) => {
return role.name
})
} else {
//user is logged in but no user exists
//this creates the user
user = await db.user.create({
data: {
email: decoded.preferred_username,
userName: decoded.preferred_username,
name: decoded.name
}
})
justRoles = [];
}
return {
//decoded: {
// ...decoded
//},
...user,
email: decoded.preferred_username ?? null,
name: decoded.name ?? null,
roles: [
...justRoles
],
matrix: matrix
}
} catch (error) {
return error
}
}
/*export const getCurrentUser = async (decoded) => {
const userRoles = await db.userRole.findMany({
where: { user: { email: decoded.preferred_username } },
select: { name: true },
})
const roles = userRoles.map((role) => {
return role.name
})
return context.currentUser || { roles }
}*/
// Use this function in your services to check that a user is logged in, and
// optionally raise an error if they're not.
/**
* Use requireAuth in your services to check that a user is logged in,
* whether or not they are assigned a role, and optionally raise an
* error if they're not.
*
* @param {string=} roles - An optional role or list of roles
* @param {string[]=} roles - An optional list of roles
* @example
*
* // checks if currentUser is authenticated
* requireAuth()
*
* @example
*
* // checks if currentUser is authenticated and assigned one of the given roles
* requireAuth({ role: 'admin' })
* requireAuth({ role: ['editor', 'author'] })
* requireAuth({ role: ['publisher'] })
*/
export const requireAuth = ({ role } = {}) => {
if (!context.currentUser) {
throw new AuthenticationError("You don't have permission to do that.")
}
if (
typeof role !== 'undefined' &&
typeof role === 'string' &&
!context.currentUser.roles?.includes(role)
) {
throw new ForbiddenError("You don't have access to do that.")
}
if (
typeof role !== 'undefined' &&
Array.isArray(role) &&
!context.currentUser.roles?.some((r) => role.includes(r))
) {
throw new ForbiddenError("You don't have access to do that.")
}
}
<file_sep>import Cmdb from 'src/components/Cmdb'
export const QUERY = gql`
query FIND_CMDB_BY_ID($id: Int!) {
cmdb: cmdb(id: $id) {
id
number
title
}
}
`
export const Loading = () => <div>Loading...</div>
export const Empty = () => <div>Cmdb not found</div>
export const Success = ({ cmdb }) => {
return <Cmdb cmdb={cmdb} />
}
<file_sep>import UsersLayout from 'src/layouts/UsersLayout'
import EditUserCell from 'src/components/EditUserCell'
const EditUserPage = ({ id }) => {
return (
<>
<UsersLayout>
<EditUserCell id={id} />
</UsersLayout>
</>
)
}
export default EditUserPage
<file_sep>import { Link, routes } from '@redwoodjs/router'
import { Flash } from '@redwoodjs/web'
import { useAuth } from '@redwoodjs/auth'
const UsersLayout = (props) => {
const { logIn, logOut, isAuthenticated, currentUser, hasRole } = useAuth()
return (
<div className="rw-scaffold">
<Flash timeout={1000} />
<header className="rw-header">
<h1 className="rw-heading rw-heading-primary">
<Link to={routes.users()} className="rw-link">
Users
</Link>
</h1>
{hasRole(currentUser?.matrix?.user?.create) &&
<Link to={routes.newUser()} className="rw-button rw-button-green">
<div className="rw-button-icon">+</div> New User
</Link>
}
</header>
<main className="rw-main">{props.children}</main>
</div>
)
}
export default UsersLayout
<file_sep>import { Link, routes } from '@redwoodjs/router'
const HomePage = () => {
return (<>
This is home
<h2>Logins</h2>
<table>
<thead>
<tr>
<td>Persona</td>
<td>Name</td>
<td>Email</td>
<td>Password</td>
</tr>
</thead>
<tbody>
<tr>
<td><NAME></td>
<td><NAME></td>
<td><EMAIL></td>
<td>Task0001</td>
</tr>
<tr>
<td>Task Admin</td>
<td><NAME></td>
<td><EMAIL></td>
<td>Task0002</td>
</tr>
<tr>
<td>Asset Doer</td>
<td><NAME></td>
<td><EMAIL></td>
<td>Task0003</td>
</tr>
<tr>
<td>Asset Admin</td>
<td><NAME></td>
<td><EMAIL></td>
<td>Task0004</td>
</tr>
<tr>
<td>Admin</td>
<td><NAME></td>
<td><EMAIL></td>
<td>Task0005</td>
</tr>
</tbody>
</table>
</>)
}
export default HomePage
<file_sep># DATABASE_URL=file:./dev.db
# TEST_DATABASE_URL=file:./.redwood/test.db
# PRISMA_HIDE_UPDATE_MESSAGE=true
DATABASE_URL=postgresql://
AZURE_ACTIVE_DIRECTORY_CLIENT_ID=<client>
AZURE_ACTIVE_DIRECTORY_AUTHORITY=https://login.microsoftonline.com/<tenant>
AZURE_ACTIVE_DIRECTORY_REDIRECT_URI=http://localhost:8910
AZURE_ACTIVE_DIRECTORY_LOGOUT_REDIRECT_URI=http://localhost:8910<file_sep>export const schema = gql`
type TicketNote {
id: Int!
createdAt: DateTime!
updatedAt: DateTime!
field: String!
value: String!
Ticket: Ticket!
ticketId: Int!
User: User!
userId: Int!
}
type Query {
ticketNotes: [TicketNote!]!
}
input CreateTicketNoteInput {
field: String!
value: String!
ticketId: Int!
userId: Int!
}
input UpdateTicketNoteInput {
field: String
value: String
ticketId: Int
userId: Int
}
`
<file_sep>import Ticket from 'src/components/Ticket'
export const QUERY = gql`
query FIND_TICKET_BY_ID($id: Int!) {
ticket: ticket(id: $id) {
id
number
title
userId
state
impact
urgency
priority
}
}
`
export const Loading = () => <div>Loading...</div>
export const Empty = () => <div>Ticket not found</div>
export const Success = ({ ticket }) => {
return <Ticket ticket={ticket} />
}
<file_sep>/*
Warnings:
- You are about to drop the column `cmdbId` on the `Ticket` table. All the data in the column will be lost.
*/
-- DropForeignKey
ALTER TABLE "Ticket" DROP CONSTRAINT "Ticket_cmdbId_fkey";
-- AlterTable
ALTER TABLE "Choice" ALTER COLUMN "column" DROP DEFAULT,
ALTER COLUMN "displayValue" DROP DEFAULT;
-- AlterTable
ALTER TABLE "Ticket" DROP COLUMN "cmdbId";
<file_sep>module.exports = {
command: function (current) {
try {
console.log(`pre-current: ${JSON.stringify(current)}`)
current.title+=new Date()
} catch (e) {
console.log('test.js error', e);
}
console.log(`post-current: ${JSON.stringify(current)}`)
return current;
},
active: false,
order: 12,
title: "append date",
when: "before",
file: __filename
}<file_sep>-- AlterTable
ALTER TABLE "Ticket" ADD COLUMN "priority" INTEGER DEFAULT 10,
ADD COLUMN "impact" INTEGER DEFAULT 10,
ADD COLUMN "urgency" INTEGER DEFAULT 10;
<file_sep>//https://redwoodjs.com/docs/webpack-configuration.html
module.exports = (config, { env }) => {
config.plugins.forEach((plugin) => {
if (plugin.constructor.name === 'HtmlWebpackPlugin') {
plugin.options.title = 'Tskr.io'
}
})
return config
}<file_sep>import UsersLayout from 'src/layouts/UsersLayout'
import NewUser from 'src/components/NewUser'
const NewUserPage = () => {
return (
<>
<UsersLayout>
<NewUser />
</UsersLayout>
</>
)
}
export default NewUserPage
<file_sep>export const schema = gql`
type Cmdb {
id: Int!
number: String!
title: String
Ticket: [Ticket]!
}
type Query {
cmdbs: [Cmdb!]!
cmdb(id: Int!): Cmdb
}
input CreateCmdbInput {
number: String!
title: String
}
input UpdateCmdbInput {
number: String
title: String
}
type Mutation {
createCmdb(input: CreateCmdbInput!): Cmdb!
updateCmdb(id: Int!, input: UpdateCmdbInput!): Cmdb!
deleteCmdb(id: Int!): Cmdb!
}
`
<file_sep>/* eslint-disable no-console */
const { PrismaClient } = require('@prisma/client')
const dotenv = require('dotenv')
dotenv.config()
const db = new PrismaClient()
async function main() {
// https://www.prisma.io/docs/guides/prisma-guides/seed-database
// Seed data is database data that needs to exist for your app to run.
// Ideally this file should be idempotent: running it multiple times
// will result in the same database state (usually by checking for the
// existence of a record before trying to create it). For example:
/*
const result = await db.user.createMany({
data: [
{ email: "<EMAIL>" },
{ email: "<EMAIL>" },
{ email: "<EMAIL>" },
{ email: "<EMAIL>" },
],
skipDuplicates: true, // Supported with Postgres database
})
console.log(`Created ${result.count} users!`)
*/
// Note: createMany creates multiple records in a transaction.
// To enable this feature, add createMany to previewFeatures in your schema.
// See: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#createmany-preview
// Note: createMany is not supported by SQLite.
//
// Example without createMany (supported by all databases):
/*
const existing = await db.user.findMany({ where: { email: '<EMAIL>' }})
if (!existing.length) {
await db.user.create({ data: { name: 'Admin', email: '<EMAIL>' }})
}
*/
//console.info('No data to seed. See api/db/seed.js for info.')
const resultUsers = await db.user.createMany({
data: [
{ id: 1, email: "<EMAIL>", userName: "demotaskdoer", name: "<NAME>"},
{ id: 2, email: "<EMAIL>", userName: "demotaskadmin", name: "<NAME>"},
{ id: 3, email: "<EMAIL>", userName: "demoassetdoer", name: "<NAME>"},
{ id: 4, email: "<EMAIL>", userName: "demoassetadmin", name: "<NAME>"},
{ id: 5, email: "<EMAIL>", userName: "demoadmin", name: "<NAME>"},
{ id: 6, email: "<EMAIL>", userName: "kevin", name: "<NAME>" },
{ id: 7, email: "<EMAIL>", userName: "jacebenson", name: "<NAME>" },
],
skipDuplicates: true, // Supported with Postgres database
})
console.log(`Created ${resultUsers.count} users!`)
const resultTickets = await db.ticket.createMany({
data: [
{ number: "1000", title: "Lost iPhone", userId: 1 },
{ number: "1001", title: "iPhone screen is cracked", userId: 1 },
{ number: "1002", title: "iPhone won't hold a charge", userId: 1 },
{ number: "1003", title: "iPhone only shows a blank screen", userId: 1 },
{ number: "1004", title: "iPhone is overheating", userId: 1 },
{ number: "1005", title: "Samsung Apps won't download", userId: 2 },
{ number: "1006", title: "Samsung bad autocorrect suggestions", userId: 2 },
{ number: "1007", title: "Samsung Google Play not working", userId: 2 },
{ number: "1008", title: "Samsung Google Play doesn't download apps", userId: 2 },
{ number: "1009", title: "Samsung Google Play disappeared", userId: 2 },
],
skipDuplicates: true, // Supported with Postgres database
})
console.log(`Created ${resultTickets.count} tickets!`)
const resultUserRoles = await db.userRole.createMany({
data: [
{ name: "admin", userId: 7 },
{ name: "task_doer", userId: 1 },
{ name: "task_admin", userId: 2 },
{ name: "asset_doer", userId: 3 },
{ name: "asset_admin", userId: 4 },
{ name: "user_admin", userId: 4 },
{ name: "user_doer", userId: 4 }
],
skipDuplicates: true, // Supported with Postgres database
})
console.log(`Created ${resultUserRoles.count} UserRoles!`)
}
main()
.catch((e) => console.error(e))
.finally(async () => {
await db.$disconnect()
})
<file_sep>import { render } from '@redwoodjs/testing'
import TestPage from './TestPage'
describe('TestPage', () => {
it('renders successfully', () => {
expect(() => {
render(<TestPage />)
}).not.toThrow()
})
})
<file_sep>import { db } from 'src/lib/db'
import { requireAuth } from 'src/lib/auth'
import * as util from 'src/lib/util'
import { logger } from 'src/lib/logger'
import { matrix } from 'src/lib/roles'
import rules from 'src/rules/tickets/**.{js,ts}'
let beforeRulesArr = util.loadRules(rules, "before")
let afterRulesArr = util.loadRules(rules, "after")
//requireAuth({ role: READ_TASK_ROLES })
export const tickets = () => {
requireAuth({ role: matrix.ticket.read })
return db.ticket.findMany()
}
export const ticket = async ({ id }) => {
requireAuth({ role: matrix.ticket.read })
let result = await db.ticket.findUnique({
where: { id },
include: {
TicketNote: true,
},
})
logger.info(`read ticket`, result);
return result
}
export const createTicket = async ({ input }) => {
requireAuth({ role: matrix.ticket.create })
var lastTicket = await db.ticket.findFirst({ orderBy: [{ number: 'desc' }], })
if (lastTicket) {
logger.info(`lastTicket`, lastTicket);
input.number = (parseInt(lastTicket.number, 10) + 1).toString()
logger.info(`parseInt ${parseInt(lastTicket.number, 10)}`)
} else {
input.number = '1000'
}
beforeRulesArr.forEach((rule) => {
logger.info(`Starting Before ${rule.title} ${rule.order}`)
let previous = JSON.parse(JSON.stringify(input))
rule.command(input);
if (previous !== input) {
for (var prop in input) {
if (previous[prop] !== input[prop]) {
logger.info(`${prop} "${previous[prop]}"=>"${input[prop]}"`)
}
}
}
logger.info(`Ending Before ${rule.title}`)
})
let update = db.ticket.create({
data: input,
})
afterRulesArr.forEach((rule) => {
logger.info(`Starting After ${rule.title} ${rule.order}`)
let previous = JSON.stringify(input)
previous = JSON.parse(previous)
rule.command(input);
if (previous !== input) {
for (var prop in input) {
if (previous[prop] !== input[prop]) {
logger.info(`${prop} "${previous[prop]}"=>"${input[prop]}"`)
}
}
}
logger.info(`Ending After ${rule.title}`)
})
return update;
}
export const UpdateTicketWithNotes = async ({id, input}) => {
let returnObj = {}
//requireAuth({ role: matrix.ticket.update })
// read record first to get "previous"
let previous = await db.ticket.findUnique({
where: { id },
})
//return result
logger.info('previous', previous)
logger.info('input', input)
if (previous.state === 'solved') {
//requireAuth({ role: UPDATE_TASK_SOLVED_ROLES })
returnObj = db.ticket.update({
data: input,
where: { id },
include: {
TicketNote: [JSON.parse(input.notes)]//expects a array for each journaled field like so
// [{ field, value, ticketId, userId }]
}
})
} else {
returnObj = db.ticket.update({
data: input,
where: { id },
})
}
return returnObj;
}
export const updateTicket = async ({ id, input }) => {
let returnObj = {}
requireAuth({ role: matrix.ticket.update })
// read record first to get "previous"
let previous = await db.ticket.findUnique({
where: { id },
})
//return result
logger.info('previous', previous)
if (previous.state === 'solved') {
//requireAuth({ role: UPDATE_TASK_SOLVED_ROLES })
returnObj = db.ticket.update({
data: input,
where: { id },
})
} else {
returnObj = db.ticket.update({
data: input,
where: { id },
})
}
return returnObj;
}
export const deleteTicket = ({ id }) => {
requireAuth({ role: matrix.ticket.delete })
return db.ticket.delete({
where: { id },
//TODO: add includes to delete TicketNotes
})
}
export const Ticket = {
User: (_obj, { root }) =>
db.ticket.findUnique({ where: { id: root.id } }).User(),
}
<file_sep>import { ticketNotes } from './ticketNotes'
describe('ticketNotes', () => {
scenario('returns all ticketNotes', async (scenario) => {
const result = await ticketNotes()
expect(result.length).toEqual(Object.keys(scenario.ticketNote).length)
})
})
<file_sep>import CmdbsLayout from 'src/layouts/CmdbsLayout'
import EditCmdbCell from 'src/components/EditCmdbCell'
import StandardLayout from 'src/layouts/StandardLayout'
const EditCmdbPage = ({ id }) => {
return (
<>
<CmdbsLayout>
<EditCmdbCell id={id} />
</CmdbsLayout>
</>
)
}
export default EditCmdbPage
<file_sep>import TicketsLayout from 'src/layouts/TicketsLayout'
import TicketsCell from 'src/components/TicketsCell'
const TicketsPage = () => {
return (
<>
<TicketsLayout>
<TicketsCell />
</TicketsLayout>
</>
)
}
export default TicketsPage
<file_sep>export const standard = defineScenario({
ticketNote: {
one: {
field: 'String',
value: 'String',
Ticket: { create: { number: 'String4714460' } },
User: {
create: {
userName: 'String8737864',
email: 'String9626197',
name: 'String',
},
},
},
two: {
field: 'String',
value: 'String',
Ticket: { create: { number: 'String6982996' } },
User: {
create: {
userName: 'String9423703',
email: 'String9996190',
name: 'String',
},
},
},
},
})
<file_sep>import {
tickets,
ticket,
createTicket,
updateTicket,
deleteTicket,
} from './tickets'
describe('tickets', () => {
scenario('returns all tickets', async (scenario) => {
const result = await tickets()
expect(result.length).toEqual(Object.keys(scenario.ticket).length)
})
scenario('returns a single ticket', async (scenario) => {
const result = await ticket({ id: scenario.ticket.one.id })
expect(result).toEqual(scenario.ticket.one)
})
scenario('creates a ticket', async (scenario) => {
const result = await createTicket({
input: { number: 'String2626472' },
})
expect(result.number).toEqual('String2626472')
})
scenario('updates a ticket', async (scenario) => {
const original = await ticket({ id: scenario.ticket.one.id })
const result = await updateTicket({
id: original.id,
input: { number: 'String83903662' },
})
expect(result.number).toEqual('String83903662')
})
scenario('deletes a ticket', async (scenario) => {
const original = await deleteTicket({ id: scenario.ticket.one.id })
const result = await ticket({ id: original.id })
expect(result).toEqual(null)
})
})
<file_sep>import { logger } from 'src/lib/logger'
export const loadRules = (rules, when) => {
let rulesArr = Object.keys(rules).map((k) => rules[k])//from obj to arr of objs
rulesArr.sort((a,b) => a.order-b.order );//order rules asc
rulesArr = rulesArr.filter((rule)=>{
if((//remove inactive rules, and rules missing title, command, order, active
rule.hasOwnProperty('title') &&
rule.hasOwnProperty('order') &&
rule.hasOwnProperty('when') &&
rule.hasOwnProperty('command') &&
rule.hasOwnProperty('active') &&
rule.hasOwnProperty('file')) === false ){
logger.info(`rule ${rule.file||rule.title} removed missing title,order,command,active`,'log');
return false
}
return rule.active === true
})
rulesArr = rulesArr.filter((rule)=>{
if(rule.when == when){
return true;
} else {
return false;
}
})
return rulesArr;
}<file_sep>import { AuthProvider } from '@redwoodjs/auth'
import { UserAgentApplication } from 'msal'
import { FatalErrorBoundary } from '@redwoodjs/web'
import { RedwoodApolloProvider } from '@redwoodjs/web/apollo'
import FatalErrorPage from 'src/pages/FatalErrorPage'
import Routes from 'src/Routes'
import './scaffold.css'
import './index.css'
const azureActiveDirectoryClient = new UserAgentApplication({
auth: {
clientId: process.env.AZURE_ACTIVE_DIRECTORY_CLIENT_ID,
authority: process.env.AZURE_ACTIVE_DIRECTORY_AUTHORITY,
redirectUri: process.env.AZURE_ACTIVE_DIRECTORY_REDIRECT_URI,
postLogoutRedirectUri: process.env.AZURE_ACTIVE_DIRECTORY_LOGOUT_REDIRECT_URI,
}
})
const App = () => (
<FatalErrorBoundary page={FatalErrorPage}>
<AuthProvider client={azureActiveDirectoryClient} type="azureActiveDirectory">
<RedwoodApolloProvider>
<Routes />
</RedwoodApolloProvider>
</AuthProvider>
</FatalErrorBoundary>
)
export default App
<file_sep>import {
Form,
FormError,
FieldError,
Label,
TextField,
SelectField,
Submit,
} from '@redwoodjs/forms'
import UserLookupCell from 'src/components/UserLookupCell'
import { useAuth } from '@redwoodjs/auth'
const TicketForm = (props) => {
const onSubmit = (data) => {
props.onSave(data, props?.ticket?.id)
}
const { hasRole, currentUser } = useAuth()
const canWrite = () => {
//if ticket is not passed, new record.
if(typeof props.ticket === 'undefined'){
return true;
}
//if ticket state is solved... require task_admin or admin
if(props?.ticket?.state === 'solved'){
if(hasRole('task_admin') || hasRole('admin')){
return true;
} else {
return false;
}
} else {
return true;
}
}
console.log(`canWrite ${canWrite()}`)
console.log('currentUser', currentUser)
//console.log(rulesMatrix);
return (
<div className="rw-form-wrapper">
<Form onSubmit={onSubmit} error={props.error}>
<fieldset disabled={canWrite()===false}>
<FormError
error={props.error}
wrapperClassName="rw-form-error-wrapper"
titleClassName="rw-form-error-title"
listClassName="rw-form-error-list"
/>
<Label
name="title"
className="rw-label"
errorClassName="rw-label rw-label-error"
>Title</Label>
<TextField
name="title"
defaultValue={props.ticket?.title}
className="rw-input"
errorClassName="rw-input rw-input-error"
validation={{ required: true }}
autoComplete="off"
/>
<FieldError name="title" className="rw-field-error" />
<Label
name="state"
className="rw-label"
errorClassName="rw-label rw-label-error"
>
STATE
</Label>
<SelectField
name="state"
className="rw-input"
validation={{ required: true }}
defaultValue={props.ticket?.state}
>
<option value="new">New</option>
<option value="open">Open</option>
<option value="pending">Pending</option>
<option value="onhold">On hold</option>
<option value="solved">Solved</option>
</SelectField>
<FieldError name="state" className="rw-field-error" />
<Label
name="impact"
className="rw-label"
errorClassName="rw-label rw-label-error"
>
Impact
</Label>
<SelectField
name="impact"
className="rw-input"
validation={{ required: true }}
defaultValue={props.ticket?.impact}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</SelectField>
<FieldError name="impact" className="rw-field-error" />
<Label
name="urgency"
className="rw-label"
errorClassName="rw-label rw-label-error"
>
Urgency
</Label>
<SelectField
name="urgency"
className="rw-input"
validation={{ required: true }}
defaultValue={props.ticket?.urgency}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</SelectField>
<FieldError name="impact" className="rw-field-error" />
<Label
name="priority"
className="rw-label"
errorClassName="rw-label rw-label-error"
>
Priority
</Label>
<SelectField
name="priority"
className="rw-input"
validation={{ required: true }}
defaultValue={props.ticket?.priority}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</SelectField>
<FieldError name="impact" className="rw-field-error" />
<UserLookupCell defaultValue={props.ticket?.userId} />
<FieldError name="userId" className="rw-field-error" />
<div className="rw-button-group">
<Submit disabled={props.loading} className="rw-button rw-button-blue">
Save
</Submit>
</div>
</fieldset>
</Form>
</div>
)
}
export default TicketForm
<file_sep>import * as util from 'src/lib/util'
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'
module.exports = {
command: async function (current) {
try {
if (current.userId === 2) {
logger.info('Running from an after rule' + current.number + '-' + current.title)
await db.ticket.create({
data: {
number: parseInt(current.number,10) + 1,
title: current.title + '(dup)',
userId: current.userId
},
})
}
} catch (e) {
logger.error(e);
}
},
active: true,
order: 10,
title: "test after rule",
when: "after",
file: __filename
}
<file_sep>import { useMutation, useFlash } from '@redwoodjs/web'
import { Link, routes } from '@redwoodjs/router'
import { QUERY } from 'src/components/TicketsCell'
import { useAuth } from '@redwoodjs/auth'
const DELETE_TICKET_MUTATION = gql`
mutation DeleteTicketMutation($id: Int!) {
deleteTicket(id: $id) {
id
}
}
`
const MAX_STRING_LENGTH = 150
const propercase = (text) =>{
text = text.toLowerCase().split(' ');
for (var i = 0; i < text.length; i++) {
text[i] = text[i].charAt(0).toUpperCase() + text[i].slice(1);
}
return text.join(' ');
}
const truncate = (text) => {
let output = text
if (text && text.length > MAX_STRING_LENGTH) {
output = output.substring(0, MAX_STRING_LENGTH) + '...'
}
return output
}
const jsonTruncate = (obj) => {
return truncate(JSON.stringify(obj, null, 2))
}
const timeTag = (datetime) => {
return (
<time dateTime={datetime} title={datetime}>
{new Date(datetime).toUTCString()}
</time>
)
}
const checkboxInputTag = (checked) => {
return <input type="checkbox" checked={checked} disabled />
}
const TicketsList = ({ tickets }) => {
const { addMessage } = useFlash()
const [deleteTicket] = useMutation(DELETE_TICKET_MUTATION, {
onCompleted: () => {
addMessage('Ticket deleted.', { classes: 'rw-flash-success' })
},
// This refetches the query on the list page. Read more about other ways to
// update the cache over here:
// https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates
refetchQueries: [{ query: QUERY }],
awaitRefetchQueries: true,
})
const onDeleteClick = (id) => {
if (confirm('Are you sure you want to delete ticket ' + id + '?')) {
deleteTicket({ variables: { id } })
}
}
const { logIn, logOut, isAuthenticated, currentUser, hasRole } = useAuth()
return (
<div className="rw-segment rw-table-wrapper-responsive">
<table className="rw-table">
<thead>
<tr>
<th>Number</th>
<th>State</th>
<th>Title</th>
<th>User</th>
<th> </th>
</tr>
</thead>
<tbody>
{tickets.map((ticket) => (
<tr key={ticket.id}>
<td>{truncate(ticket.number)}</td>
<td>{propercase(ticket.state)}</td>
<td>{truncate(ticket.title)}</td>
<td>
{ticket.userId && (
<div title={truncate(ticket.userId)}>
{truncate(ticket.User.name)}
</div>
)}
{!ticket.userId && (
<div title=""></div>
)}
</td>
<td>
<nav className="rw-table-actions">
{hasRole(currentUser?.matrix?.user?.read) &&
<Link
to={routes.ticket({ id: ticket.id })}
title={'Show ticket ' + ticket.id + ' detail'}
className="rw-button rw-button-small"
>
Show
</Link>
}
{hasRole(currentUser?.matrix?.user?.update) &&
<Link
to={routes.editTicket({ id: ticket.id })}
title={'Edit ticket ' + ticket.id}
className="rw-button rw-button-small rw-button-blue"
>
Edit
</Link>
}
{hasRole(currentUser?.matrix?.user?.delete) &&
<a
href="#"
title={'Delete ticket ' + ticket.id}
className="rw-button rw-button-small rw-button-red"
onClick={() => onDeleteClick(ticket.id)}
>
Delete
</a>
}
</nav>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
export default TicketsList
<file_sep>import { db } from 'src/lib/db'
import { requireAuth } from 'src/lib/auth'
import { matrix } from 'src/lib/roles'
export const userRoles = () => {
requireAuth({ role: matrix.userRole.read })
return db.userRole.findMany()
}
export const UserRole = {
User: (_obj, { root }) =>
db.userRole.findUnique({ where: { id: root.id } }).User(),
}
<file_sep>export const schema = gql`
type UserRole {
id: Int!
createdAt: DateTime!
updatedAt: DateTime!
name: String!
User: User
userId: Int
}
type Query {
userRoles: [UserRole!]!
}
input CreateUserRoleInput {
name: String!
userId: Int
}
input UpdateUserRoleInput {
name: String
userId: Int
}
`
<file_sep>import { Link, routes } from '@redwoodjs/router'
import Cmdbs from 'src/components/Cmdbs'
export const QUERY = gql`
query CMDBS {
cmdbs {
id
number
title
}
}
`
export const Loading = () => <div>Loading...</div>
export const Empty = () => {
return (
<div className="rw-text-center">
{'No cmdbs yet. '}
<Link to={routes.newCmdb()} className="rw-link">
{'Create one?'}
</Link>
</div>
)
}
export const Success = ({ cmdbs }) => {
return <Cmdbs cmdbs={cmdbs} />
}
<file_sep>export const standard = defineScenario({
user: {
one: { userName: 'String7013217', email: 'String2114490', name: 'String' },
two: { userName: 'String6143387', email: 'String6983130', name: 'String' },
},
})
<file_sep>module.exports = {
command: function (current) {
try {
console.log(`pre-current: ${JSON.stringify(current)}`)
if (current.title==="jace") {
current.title='Jace';
//current.date = new Date()
}
} catch (e) {
console.log('test.js error', e);
}
console.log(`post-current: ${JSON.stringify(current)}`)
return current;
},
active: true,
order: 10,
title: "user rule"
}<file_sep>import CmdbsLayout from 'src/layouts/CmdbsLayout'
import CmdbsCell from 'src/components/CmdbsCell'
import StandardLayout from 'src/layouts/StandardLayout'
const CmdbsPage = () => {
return (
<>
<CmdbsLayout>
<CmdbsCell />
</CmdbsLayout>
</>
)
}
export default CmdbsPage
<file_sep>-- AlterTable
ALTER TABLE "Cmdb" ADD COLUMN "state" INTEGER DEFAULT 10;
-- AlterTable
ALTER TABLE "Ticket" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "state" INTEGER DEFAULT 10;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
-- CreateTable
CREATE TABLE "Choice" (
"id" SERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"table" TEXT,
"column" TEXT DEFAULT E'state',
"value" INTEGER DEFAULT 10,
"displayValue" TEXT DEFAULT E'New',
PRIMARY KEY ("id")
);
<file_sep>import { cmdbs, cmdb, createCmdb, updateCmdb, deleteCmdb } from './cmdbs'
describe('cmdbs', () => {
scenario('returns all cmdbs', async (scenario) => {
const result = await cmdbs()
expect(result.length).toEqual(Object.keys(scenario.cmdb).length)
})
scenario('returns a single cmdb', async (scenario) => {
const result = await cmdb({ id: scenario.cmdb.one.id })
expect(result).toEqual(scenario.cmdb.one)
})
scenario('creates a cmdb', async (scenario) => {
const result = await createCmdb({
input: { number: 'String8701837' },
})
expect(result.number).toEqual('String8701837')
})
scenario('updates a cmdb', async (scenario) => {
const original = await cmdb({ id: scenario.cmdb.one.id })
const result = await updateCmdb({
id: original.id,
input: { number: 'String79360692' },
})
expect(result.number).toEqual('String79360692')
})
scenario('deletes a cmdb', async (scenario) => {
const original = await deleteCmdb({ id: scenario.cmdb.one.id })
const result = await cmdb({ id: original.id })
expect(result).toEqual(null)
})
})
<file_sep>-- CreateTable
CREATE TABLE "UserRole" (
"id" SERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"name" TEXT NOT NULL,
"userId" INTEGER,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "UserRole.name_userId_unique" ON "UserRole"("name", "userId");
-- AddForeignKey
ALTER TABLE "UserRole" ADD FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
<file_sep>import CmdbsLayout from 'src/layouts/CmdbsLayout'
import CmdbCell from 'src/components/CmdbCell'
const CmdbPage = ({ id }) => {
return (
<>
<CmdbsLayout>
<CmdbCell id={id} />
</CmdbsLayout>
</>
)
}
export default CmdbPage
<file_sep>/*
Warnings:
- You are about to drop the `Choice` table. If the table is not empty, all the data it contains will be lost.
*/
-- AlterTable
ALTER TABLE "Ticket" ALTER COLUMN "state" SET DEFAULT E'new',
ALTER COLUMN "state" SET DATA TYPE TEXT,
ALTER COLUMN "priority" SET DEFAULT E'low',
ALTER COLUMN "priority" SET DATA TYPE TEXT,
ALTER COLUMN "impact" SET DEFAULT E'low',
ALTER COLUMN "impact" SET DATA TYPE TEXT,
ALTER COLUMN "urgency" SET DEFAULT E'low',
ALTER COLUMN "urgency" SET DATA TYPE TEXT;
-- DropTable
DROP TABLE "Choice";
<file_sep>import { db } from 'src/lib/db'
import { requireAuth } from 'src/lib/auth'
import { matrix } from 'src/lib/roles'
export const users = () => {
requireAuth({ role: matrix.user.read })
return db.user.findMany()
}
export const user = ({ id }) => {
requireAuth({ role: matrix.user.read })
return db.user.findUnique({
where: { id },
})
}
export const createUser = ({ input }) => {
requireAuth({ role: matrix.user.create })
return db.user.create({
data: input,
})
}
export const updateUser = ({ id, input }) => {
requireAuth({ role: matrix.user.update })
return db.user.update({
data: input,
where: { id },
})
}
export const deleteUser = ({ id }) => {
requireAuth({ role: matrix.user.delete })
return db.user.delete({
where: { id },
})
}
export const User = {
Ticket: (_obj, { root }) =>
db.user.findUnique({ where: { id: root.id } }).Ticket(),
}
<file_sep># Tskr
Tskr is a open source, task and asset tracking application built on [RedwoodJS](https://redwoodjs.com). Imagine a low-cost task and asset tracking system where you define complex rules to execute the business needs you have — that's **Tskr**.
Because RedwoodJS is the base of this project I'd be remiss if I didn't share the current disclaimer on their project here.
> WARNING: RedwoodJS software has not reached a stable version 1.0 and should not be considered suitable for production use. In the "make it work; make it right; make it fast" paradigm, Redwood is in the later stages of the "make it work" phase. That said, your input can have a huge impact during this period, and we welcome your feedback and ideas! Check out the Redwood Community Forum to join in.
We are an opinionated system. We make the decisions so you don't have to.
This project will use the following features.
- Azure Active Directory for Authentication
- Role Based Access Control within Tskr
- Postgres (at your choice of provider)
## Features
### Users
<details>
<summary>Allow full user management from within the tool</summary>
- Authentication via Azure
- Roles that disctate access
(see ./api/src/lib/roles.js)
```js
export const matrix = {
ticket: {
create: ['task_doer', 'task_admin', 'admin'],
read: ['task_doer', 'task_admin', 'asset_doer', 'asset_admin', 'admin'],
update: ['task_doer', 'task_admin', 'admin'],
delete: [ 'task_admin', 'admin']
},
asset: {
create: [ 'asset_doer', 'asset_admin', 'admin'],
read: [ 'asset_doer', 'asset_admin', 'admin'],
update: [ 'asset_doer', 'asset_admin', 'admin'],
delete: [ 'asset_admin', 'admin']
},
user: {
create: [ 'user_admin', 'admin'],
read: ['task_doer', 'task_admin', 'asset_doer', 'asset_admin', 'user_admin', 'admin'],
update: [ 'user_admin', 'admin'],
delete: [ 'user_admin', 'admin']
},
userRole: {
create: [ 'user_admin', 'admin'],
read: ['task_doer', 'task_admin', 'asset_doer', 'asset_admin', 'user_admin', 'admin'],
update: [ 'user_admin', 'admin'],
delete: [ 'user_admin', 'admin']
}
}
```
Implement the Roles/Personas from the above.
- [Role Based Access from database](https://redwoodjs.com/docs/authentication#roles-from-a-database)
</details>
### Tasks
<details>
<summary>You know, to fill forms in a standard way</summary>
- Links to Assets
- Links to Users
</details>
### Assets
You know, to have things to track against
### Table level rules
<details>
<summary>What is this?</summary>
<span>
Do you ever want to do some server side logic on create/update of a record? Me too.
Do you ever want to keep that logic in it's own file that is easy to track and debug? Me too!
**Introducting Table level rules!**
How does it work? Well, we have a folder in `./api/src/` called rules that has the tables in use.
In the appropriate services we use some magic to pull in these rules and they run in the order defined in their file. Want more logic? Make a new rule. Want less? Delete or deactivate a rule.
</span>
| Status | When | Action | Why (example use case) |
| ------- | ------ | ------ | --------------------------------------------------------------------- |
| Working | Before | Create | Verify duplicate ticket isn't logged |
| | Before | Read | Remove senstive data / Logging someone tried to read sensitve records |
| | Before | Update | Disallow updating of specific fields |
| | Before | Delete | Store deleted record in temporary table to allow restore |
| Working | After | Create | Datalookup, e.g. assigned to availablity or Sending a email |
| | After | Read | Logging someone read a sensitve record |
| | After | Update | Datalookup, e.g. assigned to availablity or Sending a email |
| | After | Delete | Email that data has been purged |
</details>
## Set up
1. Installing the repo
Because this is uses the following you'll need to configure them.
1. Postgres
2. Azure
### Postgres for Data
This should include site that we use, seed command, env variable set up
#### Seeding the database
`yarn rw prisma db seed` will load the 7 users and 10 tasks.
### Azure for Authentication
Because we use Azure for auth you'll need to create or connect to your own.
1. Login to https://portal.azure.com
2. Navigate to *Azure Active Directory*
3. On the left is *App Registrations*
4. Click the *New registration* on this page
1. I named mine RW-POC
2. I picked Single Tenant
3. Set Redirect URI to http://localhost:8910
4. Create it, note the following
- Application (client) ID
- Directory (tenant) ID
5. Update `./env`
```
AZURE_ACTIVE_DIRECTORY_CLIENT_ID=<client>
AZURE_ACTIVE_DIRECTORY_AUTHORITY=https://login.microsoftonline.com/<tenant>
AZURE_ACTIVE_DIRECTORY_REDIRECT_URI=http://localhost:8910
AZURE_ACTIVE_DIRECTORY_LOGOUT_REDIRECT_URI=http://localhost:8910
```
6. Back in Azure on the Azure Active Directory App, there's a *Authentication* link.
1. Goto that and click *Add a platform*
2. Pick Single Page Application
3. Set redirect URI to http://localhost:8910
<file_sep>import { Link, routes } from '@redwoodjs/router'
import { Flash } from '@redwoodjs/web'
import { useAuth } from '@redwoodjs/auth'
const TicketsLayout = (props) => {
const { logIn, logOut, isAuthenticated, currentUser, hasRole } = useAuth()
return (
<div className="rw-scaffold">
<Flash timeout={1000} />
<header className="rw-header">
<h1 className="rw-heading rw-heading-primary">
<Link to={routes.tickets()} className="rw-link">
Tickets
</Link>
</h1>
{hasRole(currentUser?.matrix?.ticket?.create) &&
<Link to={routes.newTicket()} className="rw-button rw-button-green">
<div className="rw-button-icon">+</div> New Ticket
</Link>
}
</header>
<main className="rw-main">{props.children}</main>
</div>
)
}
export default TicketsLayout
<file_sep>-- CreateTable
CREATE TABLE "Post" (
"id" SERIAL NOT NULL,
"title" TEXT NOT NULL,
"body" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Contact" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"message" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"userName" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Ticket" (
"id" SERIAL NOT NULL,
"number" TEXT NOT NULL,
"title" TEXT,
"userId" INTEGER,
"cmdbId" INTEGER,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Cmdb" (
"id" SERIAL NOT NULL,
"number" TEXT NOT NULL,
"title" TEXT,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User.userName_unique" ON "User"("userName");
-- CreateIndex
CREATE UNIQUE INDEX "User.email_unique" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Ticket.number_unique" ON "Ticket"("number");
-- CreateIndex
CREATE UNIQUE INDEX "Cmdb.number_unique" ON "Cmdb"("number");
-- AddForeignKey
ALTER TABLE "Ticket" ADD FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Ticket" ADD FOREIGN KEY ("cmdbId") REFERENCES "Cmdb"("id") ON DELETE SET NULL ON UPDATE CASCADE;
<file_sep>/*
Warnings:
- Added the required column `ticketId` to the `TicketNote` table without a default value. This is not possible if the table is not empty.
- Made the column `field` on table `TicketNote` required. This step will fail if there are existing NULL values in that column.
- Made the column `value` on table `TicketNote` required. This step will fail if there are existing NULL values in that column.
- Made the column `userId` on table `TicketNote` required. This step will fail if there are existing NULL values in that column.
*/
-- AlterTable
ALTER TABLE "TicketNote" ADD COLUMN "ticketId" INTEGER NOT NULL,
ALTER COLUMN "field" SET NOT NULL,
ALTER COLUMN "value" SET NOT NULL,
ALTER COLUMN "userId" SET NOT NULL;
-- AddForeignKey
ALTER TABLE "TicketNote" ADD FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
<file_sep>import { userRoles } from './userRoles'
describe('userRoles', () => {
scenario('returns all userRoles', async (scenario) => {
const result = await userRoles()
expect(result.length).toEqual(Object.keys(scenario.userRole).length)
})
})
<file_sep>import TicketsLayout from 'src/layouts/TicketsLayout'
import EditTicketCell from 'src/components/EditTicketCell'
const EditTicketPage = ({ id }) => {
return (
<>
<TicketsLayout>
<EditTicketCell id={id} />
</TicketsLayout>
</>
)
}
export default EditTicketPage
<file_sep>import TicketsLayout from 'src/layouts/TicketsLayout'
import NewTicket from 'src/components/NewTicket'
const NewTicketPage = () => {
return (
<>
<TicketsLayout>
<NewTicket />
</TicketsLayout>
</>
)
}
export default NewTicketPage
<file_sep>import { db } from 'src/lib/db'
import { requireAuth } from 'src/lib/auth'
import * as util from 'src/lib/util'
import { logger } from 'src/lib/logger'
import { matrix } from 'src/lib/roles'
export const cmdbs = () => {
requireAuth({ role: matrix.asset.read })
return db.cmdb.findMany()
}
export const cmdb = ({ id }) => {
requireAuth({ role: matrix.asset.read })
return db.cmdb.findUnique({
where: { id },
})
}
export const createCmdb = ({ input }) => {
requireAuth({ role: matrix.asset.create })
return db.cmdb.create({
data: input,
})
}
export const updateCmdb = ({ id, input }) => {
requireAuth({ role: matrix.asset.update })
return db.cmdb.update({
data: input,
where: { id },
})
}
export const deleteCmdb = ({ id }) => {
requireAuth({ role: matrix.asset.delete })
return db.cmdb.delete({
where: { id },
})
}
export const Cmdb = {
Ticket: (_obj, { root }) =>
db.cmdb.findUnique({ where: { id: root.id } }).Ticket(),
}
<file_sep>import { useMutation } from '@redwoodjs/web'
import { toast } from '@redwoodjs/web/toast'
import { navigate, routes } from '@redwoodjs/router'
import CmdbForm from 'src/components/CmdbForm'
export const QUERY = gql`
query FIND_CMDB_BY_ID($id: Int!) {
cmdb: cmdb(id: $id) {
id
number
title
}
}
`
const UPDATE_CMDB_MUTATION = gql`
mutation UpdateCmdbMutation($id: Int!, $input: UpdateCmdbInput!) {
updateCmdb(id: $id, input: $input) {
id
number
title
}
}
`
export const Loading = () => <div>Loading...</div>
export const Success = ({ cmdb }) => {
const [updateCmdb, { loading, error }] = useMutation(UPDATE_CMDB_MUTATION, {
onCompleted: () => {
toast.success('Cmdb updated')
navigate(routes.cmdbs())
},
})
const onSave = (input, id) => {
updateCmdb({ variables: { id, input } })
}
return (
<div className="rw-segment">
<header className="rw-segment-header">
<h2 className="rw-heading rw-heading-secondary">Edit Cmdb {cmdb.id}</h2>
</header>
<div className="rw-segment-main">
<CmdbForm cmdb={cmdb} onSave={onSave} error={error} loading={loading} />
</div>
</div>
)
}
<file_sep>/*
Warnings:
- You are about to drop the column `state` on the `Cmdb` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "Cmdb" DROP COLUMN "state";
<file_sep>import CmdbsLayout from 'src/layouts/CmdbsLayout'
import NewCmdb from 'src/components/NewCmdb'
import StandardLayout from 'src/layouts/StandardLayout'
const NewCmdbPage = () => {
return (
<>
<CmdbsLayout>
<NewCmdb />
</CmdbsLayout>
</>
)
}
export default NewCmdbPage
<file_sep>import { Link, routes } from '@redwoodjs/router'
import { useAuth } from '@redwoodjs/auth'
const StandardLayout = ({ children }) => {
const { logIn, logOut, isAuthenticated, currentUser, hasRole } = useAuth()
return (
<>
<header>
<h1>
</h1>
<nav>
<Link to={routes.home()}>Tskr.io</Link>
<ul>
<li><Link to={routes.about()}>About</Link></li>
{hasRole(currentUser?.matrix?.ticket?.read) && <li><Link to={routes.tickets()}>Tickets</Link></li>}
{hasRole(currentUser?.matrix?.asset?.read) && <li><Link to={routes.cmdbs()}>CMDB</Link></li>}
{hasRole(currentUser?.matrix?.user?.read) && <li><Link to={routes.users()}>Users</Link></li>}
<li>
<a alt={JSON.stringify(currentUser)} onClick={isAuthenticated ? logOut : logIn}>
{isAuthenticated && currentUser && (`Log Out ${currentUser.name}`)}
{isAuthenticated && !currentUser && (`Log Out`)}
{!isAuthenticated && `Log In`}
</a>
</li>
</ul>
</nav>
</header>
<main>
<article>
{children}
</article>
</main>
</>
)
}
export default StandardLayout
|
a871299d6f80a9b174201e08a923598ebae5f2d0
|
[
"JavaScript",
"SQL",
"Markdown",
"Shell"
] | 51 |
JavaScript
|
shiningblue7/rw-poc
|
84cddae242597898eb516d65c39613813ddecd9f
|
38b4feaf40c8ecc9dca3c64f9061752639b10dca
|
refs/heads/main
|
<repo_name>Noor-Ansari/Baat-Chat<file_sep>/frontend/src/components/JoinPage/JoinPage.js
import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
function JoinPage() {
const [userName, setUserName] = useState("");
const [roomName, setRoomName] = useState("");
const [isValidated, setIsValidated] = useState(true);
const history = useHistory();
const submitForm = (e) => {
e.preventDefault();
history.push(`/chat-page/?userName=${userName}&roomName=${roomName}`);
};
useEffect(() => {
if (userName && roomName) {
setIsValidated(false);
}
}, [userName, roomName]);
return (
<MainContainer>
<PageTitle>Welcome to Baat-Chat</PageTitle>
<FormContainer>
<form onSubmit={submitForm}>
<FormItem>
<InputLabel>UserName :</InputLabel>
<InputControl
value={userName}
onChange={(e) => setUserName(e.target.value)}
/>
</FormItem>
<FormItem>
<InputLabel>RoomName :</InputLabel>
<InputControl
value={roomName}
onChange={(e) => setRoomName(e.target.value)}
/>
</FormItem>
<SubmitButton type="submit" disabled={isValidated}>
Send
</SubmitButton>
</form>
</FormContainer>
</MainContainer>
);
}
export default JoinPage;
const MainContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
width: 100vw;
font-family: monospace;
`;
const PageTitle = styled.h1`
color: #444;
margin: 2rem 0;
`;
const FormContainer = styled.div`
height: 20rem;
width: 20rem;
background-color: #444;
border-radius: 0.25rem;
padding: 2rem 1rem;
`;
const FormItem = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
margin: 0.5rem 0;
min-height: 5rem;
`;
const InputControl = styled.input`
border: 1px solid #c2c2c2;
padding: 0.5rem;
border-radius: 4px;
font-size: 1.2rem;
`;
const InputLabel = styled.label`
font-size: 1.2rem;
color: #fff;
`;
const SubmitButton = styled.button`
border: none;
padding: 0.5rem;
border-radius: 0.25rem;
margin: 1rem 0;
`;
<file_sep>/frontend/src/components/Messages/Messages.js
import React from "react";
import Message from "../Message/Message";
function Messages({ messages, name }) {
return messages.map((message, idx) => (
<div key={idx}>
<Message message={message} name={name} />
</div>
));
}
export default Messages;
<file_sep>/frontend/src/components/InfoBar/InfoBar.js
import React from "react";
import styled from "styled-components";
import { useHistory } from "react-router-dom";
import { FiX, FiCircle } from "react-icons/fi";
function InfoBar({ roomName, userName }) {
const history = useHistory();
return (
<MainBar>
<LeftPart>
<OnLineIcon />
<Title>{roomName}</Title>
</LeftPart>
<RightPart>
<Title>{userName}</Title>
<CloseButton onClick={() => history.push("/")}>
<FiX />
</CloseButton>
</RightPart>
</MainBar>
);
}
export default InfoBar;
const MainBar = styled.div`
background-color: blue;
color: #fff;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 1rem;
`;
const BarSection = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
`;
const LeftPart = styled(BarSection)`
width: 10rem;
`;
const RightPart = styled(BarSection)`
width: 8rem;
`;
const Title = styled.h1`
font-family: sans-serif;
font-size: 1.2rem;
text-transform: capitalize;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const OnLineIcon = styled(FiCircle)`
background-color: yellow;
border-radius: 50%;
border: none;
`;
const CloseButton = styled.button`
border: none;
background: transparent;
color: #fff;
`;
<file_sep>/frontend/src/components/Message/Message.js
import React from "react";
import styled from "styled-components";
function Message({ message: { user, text }, name }) {
let isSentByCurrentUser = name === user;
return isSentByCurrentUser ? (
<MessageContainerRight>
<UserName>You</UserName>
<MessageBox>
<MessageText>{text}</MessageText>
</MessageBox>
</MessageContainerRight>
) : user === "admin" ? (
<MessageContainerCenter>
<MessageBox>
<MessageText>{text}</MessageText>
</MessageBox>
</MessageContainerCenter>
) : (
<MessageContainerLeft>
<MessageBox>
<MessageText>{text}</MessageText>
</MessageBox>
<UserName>{user}</UserName>
</MessageContainerLeft>
);
}
export default Message;
const MessageContainer = styled.div`
display: flex;
align-items: center;
`;
const MessageContainerCenter = styled(MessageContainer)`
justify-content: center;
div {
border-radius: 1rem;
padding: 0.5rem 1rem;
p {
font-size: 0.8rem;
}
}
`;
const MessageContainerRight = styled(MessageContainer)`
justify-content: flex-end;
div {
border-radius: 1rem 1rem 0 1rem;
}
`;
const MessageContainerLeft = styled(MessageContainer)`
justify-content: flex-start;
div {
border-radius: 1rem 1rem 1rem 0;
}
`;
const UserName = styled.h1`
max-width: 5rem;
font-size: 0.8rem;
font-family: monospace;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
`;
const MessageBox = styled.div`
background-color: #dadbff;
padding: 1rem;
margin: 1rem;
max-width: 50%;
`;
const MessageText = styled.p`
font-family: cursive;
word-wrap: break-word;
`;
|
66dbdacdc5ecfc2b4a5aafa79658680b447dad6d
|
[
"JavaScript"
] | 4 |
JavaScript
|
Noor-Ansari/Baat-Chat
|
e77a54d7af6d52ae957b2463334b84cf229950db
|
014251fd1ddb3de9aea6ec2bdbac906b70864bc1
|
refs/heads/master
|
<file_sep>#include<stdio.h>
#include"node.h"
#include<string.h>
int main(){
link lnk={0};//创建一个链表
link_init(&lnk);//初始化
int size=link_size(&lnk);
printf("this link size is %d\n",size);//查看是否清空链表
link_insert(&lnk,1,"where is father",(float)7.6);
link_insert(&lnk,2,"where is mather",(float)2.5);
link_insert(&lnk,3,"where is brother",(float)4.6);
link_insert(&lnk,4,"where is sister",(float)9.6);
link_insert(&lnk,5,"where is uncle",(float)5.2);
size=link_size(&lnk);
printf("this link size is %d\n",size);//查看是否添加进链表
node *t_node;//声明结构体指针接收查找到的结构体地址
int i;
for(i=1;i<6;i++){
t_node=link_get(&lnk,i);
printf("movie name is %s score is %lg\n",t_node->name,t_node->score);
}
link_remove(&lnk,2);//删除编号为2的节点
t_node=link_get(&lnk,2);//检查是否删除
printf("%d\n",(t_node==NULL));
return 0;
}
<file_sep>#include <stdio.h>
#include <dlfcn.h>
#include"node.h"
int main(){
void *handle=dlopen("movie/libmovie.so",RTLD_NOW);
if(handle==NULL){
perror("dlopen");
return -1;
}
printf("loaded success...\n");
link lnk;
void (*p)(link *);//声明一个初始化链表的函数指针
p=dlsym(handle,"link_init");//在动态库中找到要初始化的函数名字
p(&lnk);//对这个函数进行初始化
int (*p1)(link *);
p1=dlsym(handle,"link_size");
printf("size:%d\n",p1(&lnk));
dlclose(handle);
return 0;
}
<file_sep>#include<stdlib.h>
#include<string.h>
typedef struct node{
int num;
char name[20];
float score;
struct node *p_next;
}node;
typedef struct{
node head,tail;
}link;
//链表的初始化
void link_init(link *p_link){
p_link->head.p_next = &(p_link->tail);
p_link->tail.p_next = NULL;
}
//链表的清理函数
void link_deinit(link *p_link){
while(p_link->head.p_next!=&(p_link->tail)){
node *p_first = &(p_link->head);
node *p_mid = p_first->p_next;
node *p_last = p_mid->p_next;
p_first->p_next = p_last;
free(p_mid);
p_mid = NULL;
}
}
//判断函数是否为空的
int link_empty(const link *p_link){
return(p_link->head.p_next == &(p_link->tail));
}
//判断链表是否为满
int link_full(const link *p_link){
return 0;
}
//统计链表中有效个数的函数
int link_size(const link *p_link){
int cnt = 0 ;
const node *p_node = NULL;
for(p_node = &(p_link->head);p_node!=&(p_link->tail);p_node=p_node->p_next){
const node *p_first = p_node;
const node *p_mid = p_first->p_next;
const node *p_last = p_mid->p_next;
if(p_mid!=&(p_link->tail)){
cnt++;
}
}
return cnt;
}
/* 按照豆瓣评分从小到大的顺序把新电影加入到链表的函数*/
int link_insert(link *p_link,int num,char *name,float score){
node *p_node = NULL;
node *p_tmp = (node *)malloc(sizeof(node));
if(!p_tmp){
return 0;
}
p_tmp->num = num;
p_tmp->score= score;
strcpy(p_tmp->name,name);
p_tmp->p_next = NULL;
for(p_node=&(p_link->head);p_node!=&(p_link->tail);p_node = p_node->p_next){
node *p_first = p_node;
node *p_mid = p_first->p_next;
node *p_last =p_mid->p_next;
if(p_mid==&(p_link->tail)||p_mid->score > p_tmp->score){
p_first->p_next = p_tmp;
p_tmp->p_next = p_mid;
break;
}
}
return 1;
}
/*删除某个编号所在结点的函数*/
int link_remove(link *p_link,int num){
node *p_node = NULL;
for(p_node=&(p_link->head);p_node!=&(p_link->tail);p_node=p_node->p_next){
node *p_first = p_node;
node *p_mid = p_node->p_next;
node *p_last =p_mid->p_next;
if(p_mid!=&(p_link->tail) && p_mid->num == num){
p_first->p_next = p_last;
free(p_mid);
p_mid = NULL;
return 1;
}
}
return 0;
}
/*根据编号找到对应的数字的函数*/
const node *link_get(const link *p_link,int num){
const node *p_node = NULL;
for (p_node = &(p_link->head);p_node != &(p_link->tail);p_node = p_node->p_next) {
const node *p_first = p_node;
const node *p_mid = p_first->p_next;
const node *p_last = p_mid->p_next;
if (p_mid != &(p_link->tail) && p_mid->num == num){
return p_mid;
break;
}
}
return NULL;
}
<file_sep>#ifndef __NODE_H__
#define __NODE_H__
typedef struct node{
int num;
char name[20];
float score;
struct node *p_next;
}node;
typedef struct{
node head,tail;
}link;
//链表的初始化
void link_init(link *p_link);
//链表的清理函数
void link_deinit(link *p_link);
//判断函数是否为空的
int link_empty(const link *p_link);
//判断链表是否为满
int link_full(const link *p_link);
//统计链表中有效个数的函数
int link_size(const link *p_link);
/* 按照豆瓣评分从小到大的顺序把新电影加入到链表的函数*/
int link_insert(link *p_link,int num,char *name,float score);
/*删除某个编号所在结点的函数*/
int link_remove(link *p_link,int num);
/*根据编号找到对应的数字的函数*/
node *link_get(const link *p_link,int num);
#endif
|
11bee471228f03a003d5d4357763797c8d8dedf3
|
[
"C"
] | 4 |
C
|
kakazhangbao/movie-link
|
dcfce720fd803c307878a9848f69c69323494f29
|
21f67c8ddec0c1caca6aeae0a8d1c3509db6eb3b
|
refs/heads/master
|
<file_sep>package main.java.servlets;
import main.java.databasetables.BotUser;
import main.java.datamanage.JSONAuthorizationDataSerializingClass;
import main.java.datamanage.UserDAOImpl;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class BotAuthorizationPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Map < [Session Identifier (generated from JSESSIONID)] , [Telegram's chat identifier (cid)] >
private static HashMap<String, String> authData = new HashMap<String, String>();
// Map < [chat identifier], [Telegram Username] >
private static HashMap<String, String> usernameMap = new HashMap<String, String>();
public BotAuthorizationPageServlet() {
super();
}
@SuppressWarnings("rawtypes")
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getContentType() != null)
if (request.getContentType().equals("application/json"))
doPost(request, response);
response.getWriter().append("All auth info\n");
Iterator iterator = authData.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.print("code: " + mapEntry.getKey() + " & cid: " + mapEntry.getValue());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
try {
JSONAuthorizationDataSerializingClass currentData = mapper.readValue(request.getReader(),
JSONAuthorizationDataSerializingClass.class);
authData.put(currentData.getCode(), currentData.getChatID());
out.println(authData.toString());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
out.close();
}
@SuppressWarnings("rawtypes")
protected static String getChatIdentifierbySessionId(String sessionId) {
Map.Entry<String, String> mapEntry;
Iterator iterator = authData.entrySet().iterator();
while (iterator.hasNext()) {
mapEntry = (Map.Entry<String, String>) iterator.next();
if (mapEntry.getKey().equals(sessionId)) {
return mapEntry.getValue();
}
}
return null;
}
protected static boolean deleteChatIdentifierBySessionId(String sessionId) {
String chatId = authData.get(sessionId);
if(chatId != null)
{
usernameMap.remove(chatId);
}
if (null != authData.remove(sessionId))
return true;
return false;
}
protected static String getUsernameByChatId(Long chatId) {
String username;
username = usernameMap.get(chatId);
if(username == null && chatId != null)
{
try {
UserDAOImpl userDAO = new UserDAOImpl();
BotUser user = userDAO.getUserByChatId(BigInteger.valueOf(chatId));
if(user != null)
{
username = user.getFirstName() + " " + user.getLastName();
if(username != null || username != "")
usernameMap.put(chatId.toString(), username);
}
} catch (NumberFormatException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(username == null) username = "";
return username;
}
}
<file_sep>package main.java.datamanage;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import main.java.databasetables.BotUser;
import main.java.databasetables.RequestToBot;
public class UserDAOImpl implements UserDAO {
public BotUser getUserByChatId(BigInteger chatId) throws SQLException {
Session session = null;
List user = new ArrayList<BotUser>();
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session
.createQuery(" from main.java.databasetables.BotUser r" + " where r.chatId = :cid")
.setParameter("cid", chatId);
user = query.list();
session.getTransaction().commit();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
if(user.isEmpty())
return null;
return (BotUser) user.get(0);
}
}
<file_sep>package main.java.datamanage;
import main.java.databasetables.RequestToBot;
import java.util.Collection;
import java.util.List;
import java.math.BigInteger;
import java.sql.SQLException;
public interface RequestsDAO {
public void addRequest(RequestToBot request) throws SQLException;
public void updateRequest(Long request_id, RequestToBot request) throws SQLException;
public RequestToBot getRequestById(Long request_id) throws SQLException;
public Collection getAllRequests() throws SQLException;
public void deleteRequest(RequestToBot request) throws SQLException;
public List getRequestsByChatId(BigInteger chatId) throws SQLException;
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>vkfilebotwebsite</groupId>
<artifactId>vkfilebotwebsite</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>vkfilebotwebsite</name>
<description>website for VkFiles_Bot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<version>1.1.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>com.github.jsimone</groupId>
<artifactId>webapp-runner</artifactId>
<version>8.5.11.3</version>
<destFileName>webapp-runner.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.spec.javax.transaction/jboss-transaction-api_1.2_spec -->
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/antlr/antlr -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml/classmate -->
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.3.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.common/hibernate-commons-annotations -->
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc4</version>
</dependency>
</dependencies>
</project><file_sep>package main.java.servlets;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import main.java.datamanage.HibernateUtil;
/**
* Servlet implementation class IndexPageServlet
*/
public class IndexPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexPageServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
HttpSession session = request.getSession(true);
boolean isCIDFounded = false;
String sessionId = sessionIdGenerator(session.getId());
Long ChatId = 0l;
if (request.getParameter("logout") != null) {
logoutUserBySessionId(response, sessionId);
return;
}
request.setAttribute("sessionId", sessionId);
if(null != cookies)
for(Cookie currentCookie: cookies)
if(currentCookie.getName().equals("cid")) {
isCIDFounded = true;
ChatId = Long.parseLong(currentCookie.getValue());
}
if (!isCIDFounded)
ChatId = addCIDFromHashMapToCookiesAndSetAttribute(request, response, sessionId);
if (null != ChatId)
isCIDFounded = true;
if (null != cookies)
if (cookies.length <= 1 && !isCIDFounded) {
request.setAttribute("isAuthorized", 0);
request.setAttribute("username", "");
} else {
String username = BotAuthorizationPageServlet.getUsernameByChatId(ChatId);
request.setAttribute("isAuthorized", 1);
request.setAttribute("username", username);
}
response.setContentType("text/html");
RequestDispatcher dispatcher = (RequestDispatcher) request.getRequestDispatcher("/startpage.jsp");
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private Long addCIDFromHashMapToCookiesAndSetAttribute(HttpServletRequest request, HttpServletResponse response,
String sessionId) {
String cid = BotAuthorizationPageServlet.getChatIdentifierbySessionId(sessionId);
if (null != cid) {
Cookie cidCookie = new Cookie("cid", cid);
cidCookie.setMaxAge(60 * 15); // Browser will store this
// cookie for 15 minutes
response.addCookie(cidCookie);
request.setAttribute("userCID", cid);
return Long.parseLong(cid);
}
return null;
}
protected static String sessionIdGenerator(String JSESSIONID) {
String sessionId = "vkf";
return (sessionId + JSESSIONID.substring(JSESSIONID.length() - 7, JSESSIONID.length()));
}
protected static void logoutUserBySessionId(HttpServletResponse response, String sessionId) throws IOException {
Cookie cookie = new Cookie("cid", "");
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);
response.sendRedirect("index");
BotAuthorizationPageServlet.deleteChatIdentifierBySessionId(sessionId);
}
}
<file_sep>package main.java.servlets;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.java.databasetables.RequestToBot;
import main.java.datamanage.RequestsDAOImpl;
/**
* Servlet implementation class IndexPageServlet
*/
public class HistoryPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HistoryPageServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestsDAOImpl requestsDAOImpl = new RequestsDAOImpl();
RequestToBot requestToBot = new RequestToBot();
List requestsFromDB = new ArrayList<RequestToBot>();
Cookie[] cookies = request.getCookies();
Long chatId = 0l;
if (null != cookies)
for (Cookie currentCookie : cookies)
if (currentCookie.getName().equals("cid")) {
chatId = Long.parseLong(currentCookie.getValue());
break;
}
if (chatId == 0l) {
response.sendRedirect("index");
return;
}
String username = BotAuthorizationPageServlet.getUsernameByChatId(chatId);
request.setAttribute("isAuthorized", 1);
request.setAttribute("username", username);
try {
requestsFromDB = requestsDAOImpl.getRequestsByChatId(BigInteger.valueOf(chatId));
} catch (SQLException e) {
e.printStackTrace();
}
Vector<String> requests = new Vector<>();
RequestToBot currentRequest;
int numOfElements;
for (numOfElements = 0; numOfElements < requestsFromDB.size(); numOfElements++) {
currentRequest = (RequestToBot) requestsFromDB.get(numOfElements);
requests.add(Long.toString((currentRequest.getDateTimeOfRequest().getTime())));
requests.add(getFileTypePicture(currentRequest.getFileType()));
requests.add(currentRequest.getSearchRequest());
}
if (numOfElements == 0)
request.setAttribute("numOfElements", 0);
else
request.setAttribute("numOfElements", (numOfElements) * 3);
request.setAttribute("requests", requests);
response.setContentType("text/html");
RequestDispatcher dispatcher = (RequestDispatcher) request.getRequestDispatcher("/history.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private String getFileTypePicture(int fileTypeIndex) {
String result = "";
switch (fileTypeIndex) {
case 1:
result = "images/icons/text.png";
break;
case 2:
result = "images/icons/archive.png";
break;
case 3:
result = "images/icons/gif.png";
break;
case 4:
result = "images/icons/image.png";
break;
case 5:
result = "images/icons/music.png";
break;
case 6:
result = "images/icons/video.png";
break;
case 8:
result = "images/icons/book.png";
break;
case 9:
result = "images/icons/all.png";
break;
default:
result = "";
break;
}
return result;
}
}<file_sep># vkfilebotwebsite
This is my Pet-project i create for learning java web developing.
VkFileBot GitHub project: https://github.com/ddci/vkfilebot
## FAQ
* Is this project comlete?
No, work still in progress
* Where can i see how it looks like?
You can see it by this link: http://vkfiles.herokuapp.com/
<file_sep>package main.java.datamanage;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonAutoDetect
public class JSONAuthorizationDataSerializingClass {
@JsonProperty("code")
private String codeGeneratedOnWebSite;
@JsonProperty("cid")
private String chatID;
@Override
public String toString() {
return (codeGeneratedOnWebSite + " : " + chatID);
}
public String getChatID() {
return chatID;
}
public String getCode() {
return codeGeneratedOnWebSite;
}
}
|
fe47275c376a5c105f7c077549996ebaad0a5120
|
[
"Markdown",
"Java",
"Maven POM"
] | 8 |
Java
|
KhomenkoCode/vkfilebotwebsite
|
af0caa4e2f8055fdd34ae1ec1b401d75b3eb1366
|
50852e301346779e4078fadb6bf98ffc2396efcc
|
refs/heads/master
|
<repo_name>RobReece/sandbox<file_sep>/JUnit4UsingAJUnit3SuperClass/src/test/java/com/rrc/junit/conversion/approach1/JUnit3SuperClass_NowJUnit4.java
package com.rrc.junit.conversion.approach1;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.RuleChain;
import org.junit.rules.TestName;
import org.junit.rules.TestRule;
import com.rrc.junit.utils.BeforeAndAfter;
public class JUnit3SuperClass_NowJUnit4 {
String ctorState;
String setupState;
static String somethingStatic;
static {
somethingStatic = getTestData();
}
private TestName testName = new TestName();
private TestRule junit3Bridge = new BeforeAndAfter() {
@Override
public void before() {
setUp();
};
@Override
public void after() {
tearDown();
};
};
@Rule
public RuleChain superClassInitializer = RuleChain.outerRule(testName).around(junit3Bridge);
public void init() {
ctorState = getTestData();
}
private static String getTestData() {
return Long.toString(System.nanoTime());
}
public void setUp() {
setupState = getTestData();
}
public void tearDown() {
System.out.println("Tearing it down");
}
public void failWithJUnit3Assert() {
assertNotNull("always fails.", null);
}
}
|
c4d96ad2d3f3fc439896849caf971bf7d5426fdf
|
[
"Java"
] | 1 |
Java
|
RobReece/sandbox
|
8ee58fdead5b1e2436e62283b04f5e70a48266a5
|
263211dba6683ea2a3b7eaaf0ddf6b0e0a9a5825
|
refs/heads/master
|
<file_sep># datacleaningproject
This file explains how the script works, line by line, and how the tidy data set is created from the collected raw data
# Step by step description for the data cleaning project and how the uploaded run_analysis.R script works
##Intial steps
Set the working directory for R
Downloaded and unzipped all the avialable raw data files into the working directory
Files used for the analysis are:
*features.txt- Contains the name of variables measured for the respective activities of the subject
*X_train.txt & X_test.txt- Collected data are put into 2 files, train(70% of data) and test(30% of data)
*activity_labels.txt- Has the activity label information
*Y_train.txt, Y_test.txt- Contains the respective activities for train and test data, represented in numbers from 1 to 6
*subject_train.txt & subject_test.txt-Contains the respective subjects performing the activity, represented in mumbers 1 to 30
*Other files are the informational files that explains data, how it is recorded etc.
##Line by Line explanation of run_analysis.R
###Line 1 to 2
*Reads the activity labels and features into R
###Line 4 to 7
*Reads the test and train subject files into R
*combines them to one file, called "subject", using rbind() and assign variable name "Subject"
*dim is [10299 1]
###lines 9 to 12
*Reads the test and train activity files into R
*combines them to one file, called "activity", using rbind() and assign variable name "Activity"
*dim is [10299 1]
###lines 14 to 17
*Reads the test and train files into R
*Combines them into one file, called "join" using rbind()
*Used the data from features.txt and assigned them as variable names for the file "join"
*dim is [10299 561]
###line 18
*From the above file "join", only the measurements containing mean and standard deviation are extracted
*used grep funtion to do this
*only the variables containing mean() & std() are extracted, which resulted in 66 columns
*current file is called "test_train_final and has dim [10299 66]
###line 20
*Acttivity and Subject information stored in files "activity" & "subject" are combined to "test_train_final"
*This is acheived by using cbind()
*Combined file is called "data1" and has dim [10299 68]
###lines 22 to 23
*Current file has the entire raw data that has mean and standard deviation measurements for the subjects and activities. *Activities are still represneted in numbers.
*this for loop replaces all the numbers to the respective activity labels, that is stored in "activity_labels"
### lines 26 to 29 (FInal tidy data set is created in these steps)
*In order to get the final tidy set, we need the aggregate means for each variable for each activity and each subject
*This perfomed using melt and dcast functions. Library reshape2 is loaded.
*Resulted data set is called "dataFinal" and has dimension [180 68]
###Line 31
*using write.table, with row.names as FALSE and text file is called tidy_data is created
*Created file is stored in the work directory
###Final Tidy data set (called "dataFinal")
*Required final tidy data has been created by the script. DIM [180 68]
*This file has subject, their activities and aggregated mean of mean & standard deviation varaibles selected for each activity and each subject
*Each row is a diffrent observation
*There are 68 columns (first column is subject & second column is activity) and each column represent seperate variables.
<file_sep>#CODEBOOK
##Project Description:
* Created a tidy data set from the given raw data. Variables in the final tidy data set are the subject who volunteered, their respective activities and the aggregated mean of the various signals used from the raw data( explained below in detail in the "Creating Tidy Data" section).
* Dimension of the final tidy data is [180 * 68]
##Study design and data processing
###Collection of the raw data
The experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz.
The sensor signals (accelerometer and gyroscope) were pre-processed by applying noise filters and then sampled in fixed-width sliding windows of 2.56 sec and 50% overlap (128 readings/window). The sensor acceleration signal, which has gravitational and body motion components, was separated using a Butterworth low-pass filter into body acceleration and gravity. The gravitational force is assumed to have only low frequency components, therefore a filter with 0.3 Hz cutoff frequency was used. From each window, a vector of features was obtained by calculating variables from the time and frequency domain
##Creating the tidy datafile
*Created a raw data set using all the collected raw data (train data, test data, respective subjects & activities)
*Replaced activities, currently reprensented as number, with the actual activity label
*Added descriptive variables to the created raw data file and named all the variables
*Extracted all the variables that measures the mean and standard deviation
*DImension of the current data avaialable is [10299 * 68]
*Tidy data is derived from this by calculating aggregated means of each varialble for each activity and each subject
*Current tidy data set has dimension [180 * 68]
##Variable names and description
####Subject
*The subject who performed the activity
*Total 30 volunteers performed the acivities and are reporesent by 1 to 30
*Unit- Integer
####Activity
*Contains the activity performed by each subject
*WALKING
, WALKING_UPSTAIRS
, WALKING_DOWNSTAIRS
, SITTING
, STANDING
, LAYING are the six activities performed
*Unit- Character
####tBodyAcc-mean()-X
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####tBodyAcc-mean()-Y
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####tBodyAcc-mean()-Z
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####tBodyAcc-std()-X
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standarad deviation estimated from signals on X axis
*no units
####tBodyAcc-std()-Y
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standarad deviation estimated from signals on Y axis
*no units
####tBodyAcc-std()-Z
*Body acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standarad deviation estimated from signals on Z axis
*no units
####tGravityAcc-mean()-X
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####tGravityAcc-mean()-Y
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####tGravityAcc-mean()-Z
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####tGravityAcc-std()-X
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####tGravityAcc-std()-Y
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####tGravityAcc-std()-Z
*gravity acceralation signal, seperated from the accerelation signal by using another low pass Butterworth filter with a corner frequency of 0.3 Hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####tBodyAccJerk-mean()-X
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####tBodyAccJerk-mean()-Y
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####tBodyAccJerk-mean()-Z
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####tBodyAccJerk-std()-X
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####tBodyAccJerk-std()-Y
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####tBodyAccJerk-std()-Z
*body acceleration jerk signal, obatained by deriving in time the body linear acceleration signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####tBodyGyro-mean()-X
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no unit
####tBodyGyro-mean()-Y
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####tBodyGyro-mean()-Z
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####tBodyGyro-std()-X
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####tBodyGyro-std()-Y
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####tBodyGyro-std()-Z
*body angular velocity signal, captured using embedded gryroscope at a constant rate of 50hz
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####tBodyGyroJerk-mean()-X
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####tBodyGyroJerk-mean()-Y
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####tBodyGyroJerk-mean()-Z
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####tBodyGyroJerk-std()-X
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####tBodyGyroJerk-std()-Y
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####tBodyGyroJerk-std()-Z
*body angular velocity jerk signal, obatained by deriving in time the body angular velocity signal
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####tBodyAccMag-mean()
*body acceleration signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####tBodyAccMag-std()
*body acceleration signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####tGravityAccMag-mean()
*Gravity acceleration signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####tGravityAccMag-std()
*Gravity acceleration signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####tBodyAccJerkMag-mean()
*body acceleration jerk signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####tBodyAccJerkMag-std()
*body acceleration jerk signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####tBodyGyroMag-mean()
*body angualar velocity signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####tBodyGyroMag-std()
*body angualar velocity signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####tBodyGyroJerkMag-mean()
*body angular velocity jerk signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####tBodyGyroJerkMag-std()
*body angular velocity jerk signal magnitude, calculated using Euclidean norm
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####fBodyAcc-mean()-X
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####fBodyAcc-mean()-Y
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####fBodyAcc-mean()-Z
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####fBodyAcc-std()-X
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####fBodyAcc-std()-Y
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####fBodyAcc-std()-Z
*Frequency domain Body acceralation signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####fBodyAccJerk-mean()-X
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####fBodyAccJerk-mean()-Y
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####fBodyAccJerk-mean()-Z
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####fBodyAccJerk-std()-X
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####fBodyAccJerk-std()-Y
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####fBodyAccJerk-std()-Z
*Frequency domain Body acceralation jerk signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####fBodyGyro-mean()-X
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on X axis
*no units
####fBodyGyro-mean()-Y
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Y axis
*no units
####fBodyGyro-mean()-Z
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals on Z axis
*no units
####fBodyGyro-std()-X
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on X axis
*no units
####fBodyGyro-std()-Y
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Y axis
*no units
####fBodyGyro-std()-Z
*Frequency domain Body angular velocity signal, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals on Z axis
*no units
####fBodyAccMag-mean()
*Frequency domain Body acceralation signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####fBodyAccMag-std()
*Frequency domain Body acceralation signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####fBodyBodyAccJerkMag-mean()
*Frequency domain Body acceralation jerk signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####fBodyBodyAccJerkMag-std()
*Frequency domain Body acceralation jerk signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####fBodyBodyGyroMag-mean()
*Frequency domain Body aangular velocity signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####fBodyBodyGyroMag-std()
*Frequency domain Body angular velocity signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
####fBodyBodyGyroJerkMag-mean()
*Frequency domain Body angular velocity jerk signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the mean estimated from signals
*no units
####fBodyBodyGyroJerkMag-std()
*Frequency domain Body anuglar velocity jerk signal magnitude, obtained by applying Fast Fourier Transform
*Column represent the aggreagated mean of the standard deviation estimated from signals
*no units
<file_sep>activity_labels<-read.table("activity_labels.txt")
features<-read.table("features.txt")
subject_test<-read.table("./test/subject_test.txt")
subject_train<-read.table("./train/subject_train.txt")
subject<-rbind(subject_test,subject_train)
names(subject)<-"Subject"
test_activity<-read.table("./test/y_test.txt")
train_activity<-read.table("./train/y_train.txt")
activity<-rbind(test_activity,train_activity)
names(activity)<-"Activity"
test_data<-read.table("./test/X_test.txt")
train_data<-read.table("./train/X_train.txt")
join<-rbind(test_data,train_data)
names(join)<-features[,2]
test_train_final<-join[,sort(c(grep("mean()",colnames(join),fixed=TRUE),grep("std()",colnames(join),fixed=TRUE)))]
data1<-cbind(subject,activity,test_train_final)
for(i in 1:6){
data1[data1$Activity==i,2]<-as.character(activity_labels[i,2])
}
library(reshape2)
names<-names(data1[,3:68])
data1_melt<-melt(data1,id=c("Subject","Activity"),measure.vars=names)
dataFinal<-dcast(data1_melt,Subject+Activity~variable,mean)
write.table(dataFinal,"tidy_data.txt",row.names=FALSE)
|
37954abad964cbeacfab742dacd818dd26ba4daa
|
[
"Markdown",
"R"
] | 3 |
Markdown
|
aks1807/projectdatacleaning
|
b34a3ee771246553203c363aa7b67fdf5960141d
|
c1418ff23ccf977a86ee6f9dfdee8b1282fcff80
|
refs/heads/master
|
<file_sep><?php
// redirect to list.php file
header('Location: list_purchase_order.php');
<file_sep>
<?php
if (isset($_POST['save_purchase_order']) && $_POST['save_purchase_order'] === 'submit') {
header('Location: list.php?message=success');
}
?>
<?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Production Planning & Control
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">PPC</a></li>
<li class="active">Tambah SPP</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST">
<div class="box">
<div class="box-header">
<h3 class="box-title">Tambah Surat Perintah Produksi</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nomor PPDO</label>
<select class="form-control select2" style="width: 100%;">
<?php
for ($i = 1; $i < 10; $i++) {
$ppdoId = "PPDO" . str_pad($i, 5, '0', STR_PAD_LEFT);
echo '<option>' . $ppdoId . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nama Barang</label>
<select class="form-control select2" style="width: 100%;">
<?php
for ($i = 0; $i < 4; $i++) {
echo '<option>' . getNamaBarang($i) . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Deskripsi</label>
<select class="form-control select2" style="width: 100%;">
<?php
for ($i = 0; $i < 3; $i++) {
echo '<option>' . getDeskripsi($i) . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Jumlah</label>
<input type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label>Bahan Baku</label>
<div class="box">
<!-- /.box-header -->
<div class="box-body no-padding">
<table class="table table-striped" id="table_bahan">
<tbody><tr>
<th>Kode Bahan</th>
<th>Nama Bahan</th>
<th>Jumlah</th>
</tr>
<tr>
<td>
<a data-toggle="modal" data-target="#modal_add_bahan" style="cursor: pointer;">
<i class="fa fa-plus" aria-hidden="true"></i> Tambah Bahan Baku
</a>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.form-group -->
</div>
<div class="modal fade" id="modal_add_bahan">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Tambah Bahan Baku</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Kode Bahan</div>
<div class="col-sm-8">
<select class="form-control" name="kode_bahan" style="width: 100%;">
<?php
for ($i = 0; $i < 4; $i++) {
echo '<option>' . getKodeBahan($i) . '</option>';
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Nama Bahan</div>
<div class="col-sm-8">
<select class="form-control" name="nama_bahan" style="width: 100%;">
<?php
for ($i = 0; $i < 4; $i++) {
echo '<option>' . getNamaBahan($i) . '</option>';
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Jumlah</div>
<div class="col-sm-8">
<div class="input-group">
<input name="jumlah_bahan" type="number" class="form-control">
<span class="input-group-addon"> liter</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="button" id="button_add_bahan" class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</div>
<div class="row">
<!-- Date -->
<div class="col-md-6">
<label>Target</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="datepicker">
</div>
<!-- /.input group -->
</div>
<!-- /.form group -->
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="save_purchase_order" value="submit" class="btn btn-primary">Simpan</button>
</div>
</div>
</form>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php
function getRandomCustomer() {
$customerFirstNames = [
'PT. Vanita',
'PT. Nicolasa',
'PT. Illa',
'PT. Nereida',
'PT. Donnette',
'PT. Melita',
'PT. Signe',
'PT. Claretta',
'PT. Jennell',
'PT. Robert'
];
$customerLastNames = [
'Jessenia',
'Luciana',
'Elinore',
'Elizabet',
'Carmelo',
'Kiyoko',
'Leticia',
'Wyatt',
'Imelda',
'Rupert'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)] . ' ' . $customerLastNames[rand(1, 100) % count($customerLastNames)];
}
function getRandomDate($format = 'd F Y') {
return date($format, mt_rand(1511457239, 1514049238));
}
<file_sep><script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
</script>
<!-- Create Function Script -->
<script>
var tempTotal = 0;
$('#button_add_bahan').on('click', function() {
$('#table_bahan tr:last').prev().after(
'<tr>' +
'<td>' + $('[name="kode_bahan"]').val() + '</td>' +
'<td>' + $('[name="nama_bahan"]').val() + '</td>' +
'<td>' + $('[name="jumlah_bahan"]').val() + ' liter</td>' +
'</tr>'
);
$('[name="kode_bahan"]').val('');
$('[name="nama_bahan"]').val('');
$('[name="jumlah_bahan"]').val('');
$('#modal_add_bahan').modal('toggle');
});
</script><file_sep><?php
// redirect to list.php file
header('Location: create.php');
<file_sep><?php
function getRandomCustomer() {
$customerFirstNames = [
'PT. Vanita',
'PT. Nicolasa',
'PT. Illa',
'PT. Nereida',
'PT. Donnette',
'PT. Melita',
'PT. Signe',
'PT. Claretta',
'PT. Jennell',
'PT. Robert'
];
$customerLastNames = [
'Jessenia',
'Luciana',
'Elinore',
'Elizabet',
'Carmelo',
'Kiyoko',
'Leticia',
'Wyatt',
'Imelda',
'Rupert'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)] . ' ' . $customerLastNames[rand(1, 100) % count($customerLastNames)];
}
function getRandomDate($format = 'd F Y') {
return date($format, mt_rand(1511457239, 1514049238));
}
function getRandomAddress() {
$customerAddress = [
'Dk. Kiaracondong No. 555',
'Jln. Yoga No. 892',
'Gg. Bagas Pati No. 595',
'Ki. Ekonomi No. 763',
'Kpg. Yoga No. 916',
'Jln. Baranang Siang Indah No. 103',
'Dk. Bambon No. 409',
'Ki. Muwardi No. 418',
'Ki. Batako No. 136',
'Ds. Wahidin Sudirohusodo No. 627',
'Dk. Abdul Muis No. 661',
'Jln. Muwardi No. 349',
'Gg. Ki Hajar Dewantara No. 317',
'Jln. Yos Sudarso No. 634',
'Kpg. Salatiga No. 852',
'Ki. Kalimalang No. 84',
'Dk. Bak Air No. 37',
'Jr. Ters. Pasir Koja No. 968',
'Ki. Uluwatu No. 934',
'Psr. Siliwangi No. 601'
];
return $customerAddress[rand(1, 100) % count($customerAddress)];
}
function getRandomReason() {
$customerReason = [
'Terlalu banyak piutang.',
'Telat membayar.',
'Tingkah laku tidak etis.',
'Terlalu banyak penyimpangan dalam transaksi-transaksi sebelumnya.',
'Pemalsuan identitas.',
];
return $customerReason[rand(1, 100) % count($customerReason)];
}
function getStatusPO(){
$availableStatuses = [
'Diajukan',
'Ditolak',
'Disetujui Keuangan'
];
for ($i = 3; $i <= 99; $i++){
$availableStatuses[$i] = $availableStatuses[rand(1, 100) % count($availableStatuses)];
}
return $availableStatuses;
}<file_sep><script>
$('.button_set_setujui').on('click', function () {
$(this).parents('tr').css('display', 'none');
$('.callout-info').css('display', 'block');
})
</script><file_sep><script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
</script>
<!-- Create Function Script -->
<script>
var tempTotal = 0;
// tambah order item
$('#button_add_order_item').on('click', function() {
$('#table_order_item tr:last').prev().after(
'<tr>' +
'<td>' + $('[name="order_item_product_name"]').val() + '</td>' +
'<td>' + $('[name="order_item_total_order"]').val() + '</td>' +
'<td>Rp. ' + numberWithCommas($('[name="order_item_price_per_unit"]').val()) + ',00</td>' +
'<td>' + $('[name="order_item_discount"]').val() + '%</td>' +
'<td>' + $('[name="order_item_tax"]').val() + '%</td>' +
'<td>' + $('[name="order_item_description"]').val() + '</td>' +
'</tr>'
);
tempTotal += parseInt($('[name="order_item_price_per_unit"]').val()) * parseInt($('[name="order_item_total_order"]').val());
$('[name="order_item_product_name"]').val('');
$('[name="order_item_total_order"]').val('');
$('[name="order_item_price_per_unit"]').val('');
$('[name="order_item_discount"]').val('');
$('[name="order_item_tax"]').val('');
$('[name="order_item_description"]').val('');
$('#modal_add_order_item').modal('toggle');
});
// hitung total biaya
$('#button_calculate_total_costs').on('click', function() {
var shippingCosts = $('[name="purchase_order_shipping_costs"]').val() ? $('[name="purchase_order_shipping_costs"]').val() : '0';
$('[name="purchase_order_total_costs"]').val('Rp. ' + numberWithCommas(2000000 * 120 + parseInt(shippingCosts) + tempTotal) + ',00');
});
$('#button_add_contact_person').on('click', function() {
$('#table_contact_person tr:last').prev().after(
'<tr>' +
'<td>' + $('[name="cp_nama"]').val() + '</td>' +
'<td>' + $('[name="cp_pekerjaan"]').val() + '</td>' +
'<td>' + $('[name="cp_email"]').val() + '</td>' +
'<td>' + $('[name="cp_phone"]').val() + '</td>' +
'</tr>'
);
$('[name="cp_nama"]').val('');
$('[name="cp_pekerjaan"]').val('');
$('[name="cp_email"]').val('');
$('[name="cp_phone"]').val('');
$('#modal_add_order_item').modal('toggle');
});
</script><file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Modul Production
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Surat Perintah Produksi</a></li>
<li><a href="#">Detail</a></li>
<li class="active"><?php echo isset($_GET['poId']) ? $_GET['poId'] : '00001'; ?></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Detail Surat Perintah Produksi</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-xs-12">
<h4>
SPP #<?php echo isset($_GET['poId']) ? $_GET['poId'] : '00001'; ?>
</h4>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Customer</label>
</div>
<div class="col-xs-4">
PT. Kapal Laut Indonesia
</div>
<div class="col-xs-2">
<label>Tanggal Dibuat</label>
</div>
<div class="col-xs-4">
<?php echo getRandomDate(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Alamat Pengiriman</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
<NAME>, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
<div class="col-xs-2">
<label>Alamat Invoice</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
<NAME>, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Metode Pengiriman</label>
</div>
<div class="col-xs-4">
Normal
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Cara Pembayaran</label>
</div>
<div class="col-xs-4">
Tunai
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Waktu Penyerahan</label>
</div>
<div class="col-xs-4">
<?php echo getRandomDate(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Status</label>
</div>
<div class="col-xs-4">
Diproduksi
</div>
</div>
<!-- /.row -->
<!-- Table row -->
<div class="row">
<div class="col-xs-12">
<label>Order Item</label>
</div>
<div class="col-xs-12 table-responsive">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama Barang</th>
<th>Jumlah</th>
<th>Deskripsi</th>
<th>Target</th>
<th>Status</th>
</tr>
<tr>
<td>Cat Lapisan Kapal</td>
<td>1500</td>
<td>Kualitas A</td>
<td>8 Desember 2017</td>
<td>Dipoduksi</td>
</tr>
</tbody>
</table>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<!-- this row will not appear when printing -->
<button type="button" id="mulaiProduksi" title="Mulai Produksi" class="btn btn-success pull-left" data-dismiss="modal">Mulai Produksi</button>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<?php
if (isset($_POST['save_blacklist']) && $_POST['save_blacklist'] === 'submit') {
header('Location: list_purchase_order.php?message=success');
}
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Modul Keuangan
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Keuangan</a></li>
<li class="active">Tambah ke Blacklist</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST">
<div class="box">
<div class="box-header">
<h3 class="box-title">Tambah ke Blacklist</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Pelanggan</label>
<select class="form-control select2" style="width: 100%;">
<?php
for ($i = 0; $i < 30; $i++) {
echo '<option>' . getRandomCustomer() . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<div class="col-md-2">
<div class="form-group">
<label> </label>
<a href="../customer/create.php">
<button type="button" class="btn btn-block btn-default">Tambah Pelanggan</button>
</a>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Alamat</label>
<input type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>No. Telepon</label>
<input name='phoneNo' type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Piutang</label>
<input type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Alasan</label>
<input type="textarea" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="save_blacklist" value="submit" class="btn btn-primary">Simpan</button>
</div>
</div>
</form>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Modul Marketing
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">PPDO</a></li>
<li><a href="#">Detail</a></li>
<li class="active"><?php echo isset($_GET['poId']) ? $_GET['poId'] : '00001'; ?></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Detail Permintaan Produksi Delivery Order (PPDO)</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-xs-12">
<h4>
PPDO #<?php echo isset($_GET['poId']) ? $_GET['poId'] : '00001'; ?>
</h4>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>No Purchase Order</label>
</div>
<div class="col-xs-4">
00004
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Customer</label>
</div>
<div class="col-xs-4">
PT. Kapal Laut Indonesia
</div>
<div class="col-xs-2">
<label>Tanggal Dibuat</label>
</div>
<div class="col-xs-4">
<?php echo getRandomDate(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Alamat Pengiriman</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
Pasar Minggu, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
<div class="col-xs-2">
<label>Alamat Invoice</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
Pas<NAME>inggu, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Metode Pengiriman</label>
</div>
<div class="col-xs-4">
Normal
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Cara Pembayaran</label>
</div>
<div class="col-xs-4">
Tunai
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Waktu Penyerahan</label>
</div>
<div class="col-xs-4">
<?php echo getRandomDate(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Status</label>
</div>
<div class="col-xs-4">
Direncanakan untuk diproduksi
</div>
</div>
<!-- /.row -->
<!-- Table row -->
<div class="row">
<div class="col-xs-12">
<label>Order Item</label>
</div>
<div class="col-xs-12 table-responsive">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama Produk</th>
<th>Jumlah Order</th>
<th>Harga Per Unit</th>
<th>Diskon</th>
<th>Pajak</th>
<th>Deskripsi</th>
</tr>
<tr>
<td>Cat Lapisan Kapal</td>
<td>100</td>
<td>Rp. 2.000.000,00</td>
<td>5%</td>
<td>2.5%</td>
<td>Kualitas A</td>
</tr>
<tr>
<td>Cat Dekoratif</td>
<td>50</td>
<td>Rp. 1.000.000,00</td>
<td>0%</td>
<td>2.5%</td>
<td>Kualitas A</td>
</tr>
<tr>
<td>Cat Lapisan Pelindung</td>
<td>30</td>
<td>Rp. 5.000.000,00</td>
<td>0%</td>
<td>2.5%</td>
<td>Kualitas B</td>
</tr>
<tr>
<td>Cat Industri</td>
<td>60</td>
<td>Rp. 2.000.000,00</td>
<td>0%</td>
<td>2.5%</td>
<td>Kualitas B</td>
</tr>
</tbody>
</table>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<!-- accepted payments column -->
<div class="col-xs-6">
</div>
<!-- /.col -->
<div class="col-xs-6">
<div class="table-responsive">
<table class="table">
<tr>
<th style="width:50%">Subtotal:</th>
<td>Rp. 520.000.000,00</td>
</tr>
<tr>
<th>Biaya Pengiriman:</th>
<td>Rp. 20.000.000,00</td>
</tr>
<tr>
<th>Total:</th>
<td>Rp. 540.000.000,00</td>
</tr>
<tr>
<th>Harga Penawaran:</th>
<td>Rp. 500.000.000,00</td>
</tr>
</table>
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="box-footer">
<a href="list.php">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Kembali</button>
</a>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="https://placehold.it/160x160/00a65a/ffffff/&text=JD" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p><NAME></p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu" data-widget="tree">
<li class="active treeview">
<a href="#">
<i class="fa fa-line-chart"></i> <span>Marketing</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<?php
$uri = explode('/', $_SERVER['REQUEST_URI']);
$currentFile = $uri[count($uri)-1];
?>
<li class="<?php echo $currentFile === 'list.php' ? 'active' : ''; ?>"><a href="list.php"><i class="fa fa-circle-o"></i> Daftar PPDO</a></li>
<li class="<?php echo $currentFile === 'create.php' ? 'active' : ''; ?>"><a href="create.php"><i class="fa fa-circle-o"></i> Tambah PPDO</a></li>
</ul>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Production Planning & Control
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">PPC</a></li>
<li class="active">Daftar SPP</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<?php
if (isset($_GET['message']) && $_GET['message'] === 'success') {
?>
<div class="callout callout-info">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4>Success</h4>
<span>Berhasil menyimpan Surat Perintah Produksi</span>
</div>
<?php
}
?>
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Daftar Surat Perintah Produksi</h3>
</div>
<div class="box-header">
<a href="create_spp.php">
<button type="button" class="btn btn-primary">Buat Surat Perintah Produksi</button>
</a>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Nomor SPP</th>
<th>Nama Barang</th>
<th>Jumlah</th>
<th>Deskripsi</th>
<th>Target</th>
<th>Status</th>
</tr>
</thead>
<?php
$availableStatuses = [
'Direncanakan untuk Produksi',
'Mulai Produksi',
'Selesai Produksi',
'Terjadwal untuk pengiriman',
'Disetujui QC',
'Terkirim',
'Inovice terbit',
'Terbayar'
];
for ($i = 1; $i <= 100; $i++) {
$date = getRandomDate();
$poId = "SPP" . str_pad($i, 5, '0', STR_PAD_LEFT);
?>
<tr>
<td>
<a href="detail.php?poId=<?php echo $poId; ?>">
<?php echo $poId; ?>
</a>
</td>
<td><?php echo getRandomNamaBarang() ?></td>
<td><?php echo number_format(rand(1000, 10000), 0, ',', '.') . " liter" ; ?></td>
<td><?php echo getRandomDeskripsi() ?></td>
<td><?php echo $date; ?></td>
<td><?php echo $availableStatuses[rand(0, 7)]; ?></td>
</tr>
<?php
}
?>
<tfoot>
<tr>
<th>Nomor SPP</th>
<th>Nama Barang</th>
<th>Jumlah</th>
<th>Deskripsi</th>
<th>Target</th>
<th>Status</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<?php
if (isset($_POST['save_purchase_order']) && $_POST['save_purchase_order'] === 'submit') {
header('Location: list.php?message=success');
}
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Gudang
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Status Produksi</a></li>
<li class="active">Delivery Order</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST">
<div class="box">
<div class="box-header">
<h3 class="box-title">Buat Delivery Order</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Pelanggan</label>
<select class="form-control select2" style="width: 100%;">
<?php
for ($i = 0; $i < 30; $i++) {
echo '<option>' . getRandomCustomer() . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Metode Pengiriman</label>
<input type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label>Order Item</label>
<div class="box">
<!-- /.box-header -->
<div class="box-body no-padding">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama Produk</th>
<th>Jumlah Order</th>
<th>Harga Per Unit</th>
<th>Diskon</th>
<th>Pajak</th>
<th>Deskripsi</th>
</tr>
<tr>
<td>Cat Kapal</td>
<td>120</td>
<td>Rp. 2.000.000,00</td>
<td>5%</td>
<td>2.5%</td>
<td>Cat kapal kualitas A</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.form-group -->
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Biaya Pengiriman</label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input name="purchase_order_shipping_costs" type="number" class="form-control">
<span class="input-group-addon">,00</span>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Total Harga</label>
<input name='purchase_order_total_costs' type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<div class="col-md-2">
<div class="form-group">
<label> </label>
<button type="button" id="button_calculate_total_costs" class="btn btn-block btn-default">Hitung Total Harga</button>
</div>
<!-- /.form-group -->
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Harga Penawaran</label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control">
<span class="input-group-addon">,00</span>
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Metode Pembayaran</label>
<input type="text" class="form-control">
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="save_purchase_order" value="submit" class="btn btn-primary">Simpan</button>
</div>
</div>
</form>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
</script>
<!-- Create Function Script -->
<script>
// Author : <NAME>
$('#setujuKeuangan').on('click', function() {
if (confirm('Apakah anda yakin menyetujui PO ini?')) {
$(location).attr('href', './list.php?message=successSetuju')
}
});
$('#tolakKeuangan').on('click', function() {
if (confirm('Apakah anda yakin menolak PO ini?')) {
$(location).attr('href', './list.php?message=successTolak')
}
});
</script><file_sep><script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
</script>
<!-- Create Function Script -->
<script>
var tempTotal = 0;
// Author : <NAME>
$('#mulaiProduksi').on('click', function() {
if (confirm('Apakah anda yakin akan memulai produksi untuk SPP ini?')) {
$(location).attr('href', './list.php?message=successStart')
}
});
$('#selesaiProduksi').on('click', function() {
if (confirm('Apakah anda yakin akan menyelesaikan status produksi untuk SPP ini?')) {
$(location).attr('href', './list.php?message=successFinish')
}
});
</script><file_sep><?php
// redirect to list.php file
header('Location: list.php');
<file_sep><?php
// redirect to list.php file
// header('Location: status-produksi-list.php');
include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Gudang
</h1>
<h4>
Selamat Datang di Gudang <b>SU</b>PER!
</h4>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
</ol>
</section>
<!-- Main content -->
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php
function getRandomCustomer() {
$customerFirstNames = [
'PT. Vanita',
'PT. Nicolasa',
'PT. Illa',
'PT. Nereida',
'PT. Donnette',
'PT. Melita',
'PT. Signe',
'PT. Claretta',
'PT. Jennell',
'PT. Robert'
];
$customerLastNames = [
'Jessenia',
'Luciana',
'Elinore',
'Elizabet',
'Carmelo',
'Kiyoko',
'Leticia',
'Wyatt',
'Imelda',
'Rupert'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)] . ' ' . $customerLastNames[rand(1, 100) % count($customerLastNames)];
}
function getRandomProvince() {
$province = [
'ACEH',
'SUMATERA UTARA',
'SUMATERA BARAT',
'RIAU',
'JAMBI',
'SUMATERA SELATAN',
'BENGKULU',
'LAMPUNG',
'KEPULAUAN BANGKA BELITUNG',
'KEPULAUAN RIAU'
];
return $province[rand(1, 100) % count($province)];
}
function getRandomKabupaten() {
$customerFirstNames = [
'KOTA JAKARTA SELATAN',
'KOTA JAKARTA TIMUR',
'KOTA JAKARTA PUSAT',
'KOTA JAKARTA BARAT',
'KOTA JAKARTA UTARA',
'SUMATERA SELATAN',
'KABUPATEN BOGOR',
'KABUPATEN SUKABUMI',
'KABUPATEN CIANJUR',
'KABUPATEN BANDUNG'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)];
}
function getRandomDate($format = 'd F Y') {
return date($format, mt_rand(1511457239, 1514049238));
}
function getRandomPhone() {
return "08".rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9).rand(1, 9);
}
function getRandomAddress() {
$addressFirst = [
'Jln. Cempaka',
'Jln. Melati',
'Jln. Pahlawan',
'Jln. Menteng',
'Jln. Pramuka',
'Jln. Perjuangan',
'Jln. Mawar',
'Jln. Sudirman',
'Jln. Imam Bonjol',
'Jln. Salemba',
];
$addressLast = [
'Barat',
'Selatan',
'Timur',
'Utara',
'Harum',
'Tengah',
'Belakang',
'Merdeka',
'Maju',
'Hitam'
];
return $addressFirst[rand(1, 100) % count($addressFirst)] . ' ' . $addressLast[rand(1, 100) % count($addressLast)];
}
function getStatusPO(){
$availableStatuses = [
'Diajukan',
'Ditolak',
'Disetujui Keuangan',
'Direncanakan untuk diproduksi',
'Diproduksi',
'Terjadwal untuk pengiriman',
'Disetujui QC',
'Terkirim',
'Inovice terbit',
'Terbayar'
];
for ($i = 10; $i <= 99; $i++){
$availableStatuses[$i] = $availableStatuses[rand(1, 100) % count($availableStatuses)];
}
return $availableStatuses;
}<file_sep><!-- Create Function Script -->
<script>
$('#button_choose_purchase_order').on('click', function () {
$('#purcase_order_detail').attr('style', 'display: block;');
})
</script>
<file_sep># akpsi-ptsu
## How to install
1. run `cd /path/to/your/htdocs/directory` (`cd C:/xampp/htdocs`)
2. run `git clone <EMAIL>:ffahmii/akpsi-ptsu.git` or extract zip file to your htdocs directory
3. open `localhost/akpsi-ptsu/index.php`
## Demo
Access demo [here](http://env-dev.tk/)
<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Modul Sales
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Pelanggan</a></li>
<li><a href="#">Detail</a></li>
<li class="active"><?php echo isset($_GET['cId']) ? $_GET['cId'] : '00001'; ?></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Detail Pelanggan</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-xs-12">
<h4>
Pelanggan #<?php echo isset($_GET['cId']) ? $_GET['cId'] : '00001'; ?>
</h4>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Nama</label>
</div>
<div class="col-xs-4">
PT. Kapal Laut Indonesia
</div>
<div class="col-xs-2">
<label>Tipe</label>
</div>
<div class="col-xs-4">
Perusahaan
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Alamat Pelanggan</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
<NAME>, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
<div class="col-xs-2">
<label>Alamat Pengiriman</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
<NAME>, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Alamat Invoice</label>
</div>
<div class="col-xs-4">
<address>
PT. Kapal Laut Indonesia<br>
Jalan Kemang Timur No.22, RT.14/RW.8,<br>
<NAME>, Kota Jakarta Selatan,<br>
Daerah Khusus Ibukota Jakarta,<br>
12510
</address>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>Nomor Telepon</label>
</div>
<div class="col-xs-4">
0873289478
</div>
</div>
<div class="row">
<div class="col-xs-2">
<label>email</label>
</div>
<div class="col-xs-4">
<EMAIL>
</div>
</div><br>
<!-- /.row -->
<!-- Table row -->
<div class="row">
<div class="col-xs-12">
<label>Contact Person</label>
</div>
<div class="col-xs-12 table-responsive">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama</th>
<th>Posisi Pekerjaan</th>
<th>Email</th>
<th>Nomor Telepon</th>
</tr>
<tr>
<td>Fransisco</td>
<td>Sales</td>
<td><EMAIL></td>
<td>08583247823</td>
</tr>
<tr>
<td>Iman</td>
<td>Sales</td>
<td><EMAIL></td>
<td>08563287282</td>
</tr>
</tbody>
</table>
</div>
<!-- /.col -->
</div><br>
<div class="row">
<div class="col-xs-12">
<label>Informasi Rekening</label>
</div>
<div class="col-xs-12 table-responsive">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama Rekening</th>
<th>Nomor Rekening</th>
<th>Nama Bank</th>
<th>Cabang Bank</th>
</tr>
<tr>
<td>PT. Kapal Laut Indonesia</td>
<td>324798328492</td>
<td>Bank BCA</td>
<td>KCP Plaza Central</td>
</tr>
</tbody>
</table>
</div>
<!-- /.col -->
</div><br>
<!-- /.row -->
<!-- this row will not appear when printing -->
<a href="list_pelanggan.php">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Kembali</button>
</a>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php
if (isset($_POST['save_pelanggan']) && $_POST['save_pelanggan'] === 'submit') {
header('Location: list_pelanggan.php?message=success');
}
?>
<?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Modul Sales
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Pelanggan</a></li>
<li class="active">Tambah</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST">
<div class="box">
<div class="box-header">
<h3 class="box-title">Tambah Pelanggan</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<div class="radio">
<div class="col-md-6">
<label>
<input type="radio" name="opsi">Individu
</label>
</div>
<div class="col-md-6">
<label>
<input type="radio" name="opsi">Perusahaan
</label>
</div>
</div>
</div>
</div>
</div><br>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Nomor Telepon</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Alamat Pelanggan</label>
<textarea name="alamat" class="form-control" rows="2" ></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Alamat Pengiriman</label>
<textarea name="alamat" class="form-control" rows="2" ></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Alamat Invoice</label>
<textarea name="alamat" class="form-control" rows="2" ></textarea>
</div>
</div>
</div><br>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label>Contact Person</label>
<div class="box">
<!-- /.box-header -->
<div class="box-body no-padding">
<table class="table table-striped" id="table_contact_person">
<tbody><tr>
<th>Nama</th>
<th>Posisi Pekerjaan</th>
<th>Email</th>
<th>Nomor Telepon</th>
</tr>
<tr>
<td>
<a data-toggle="modal" data-target="#modal_add_order_item" style="cursor: pointer;">
<i class="fa fa-plus" aria-hidden="true"></i> Tambah Contact Person
</a>
</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.form-group -->
</div>
<div class="modal fade" id="modal_add_order_item">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Tambah Contact Person</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Nama</div>
<div class="col-sm-8">
<input name="cp_nama" type="text" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Posisi Pekerjaan</div>
<div class="col-sm-8">
<input name="cp_pekerjaan" type="text" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Email</div>
<div class="col-sm-8">
<input name="cp_email" type="text" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="form-group">
<div class="col-sm-4 control-label">Nomor Telepon</div>
<div class="col-sm-8">
<input name="cp_phone" type="text" class="form-control">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="button" id="button_add_contact_person" class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</div><br>
<!-- /.row -->
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label>Informasi Rekening</label>
<div class="box">
<!-- /.box-header -->
<div class="box-body no-padding">
<table class="table table-striped" id="table_contact_person">
<tbody><tr>
<th>Nama Rekening</th>
<th>Nomor Rekening</th>
<th>Nama Bank</th>
<th>Cabang Bank</th>
</tr>
<tr>
<td>
<input name="nama_rekening" type="text" class="form-control">
</td>
<td>
<input name="nomor_rekening" type="text" class="form-control">
</td>
<td>
<input name="nama_bank" type="text" class="form-control">
</td>
<td>
<input name="cabang_bank" type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.form-group -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="save_pelanggan" value="submit" class="btn btn-primary">Simpan</button>
</div>
</div>
</form>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image">
<img src="https://placehold.it/160x160/00a65a/ffffff/&text=JD" class="img-circle" alt="User Image">
</div>
<div class="pull-left info">
<p><NAME></p>
<a href="#"><i class="fa fa-circle text-success"></i> Online</a>
</div>
</div>
<!-- sidebar menu: : style can be found in sidebar.less -->
<ul class="sidebar-menu" data-widget="tree">
<li class="active treeview">
<a href="#">
<i class="fa fa-bar-chart"></i> <span>Production Planning & Control</span>
<span class="pull-right-container">
<i class="fa fa-angle-left pull-right"></i>
</span>
</a>
<ul class="treeview-menu">
<?php
$uri = explode('/', $_SERVER['REQUEST_URI']);
$currentFile = $uri[count($uri)-1];
?>
<li class="<?php echo $currentFile === 'list_ppdo.php' ? 'active' : ''; ?>"><a href="list_ppdo.php"><i class="fa fa-circle-o"></i> Daftar PPDO</a></li>
<li class="<?php echo $currentFile === 'list.php' ? 'active' : ''; ?>"><a href="list.php"><i class="fa fa-circle-o"></i> Daftar SPP</a></li>
<li class="<?php echo $currentFile === 'create_spp.php' ? 'active' : ''; ?>"><a href="create_spp.php"><i class="fa fa-circle-o"></i> Buat SPP</a></li>
<li class="<?php echo $currentFile === 'stok_produk.php' ? 'active' : ''; ?>"><a href="stok_produk.php"><i class="fa fa-circle-o"></i> Stok Produk Jadi</a></li>
<li class="<?php echo $currentFile === 'stok_bahan.php' ? 'active' : ''; ?>"><a href="stok_bahan.php"><i class="fa fa-circle-o"></i> Stok Bahan Baku</a></li>
<li class="<?php echo $currentFile === 'create_pkbb.php' ? 'active' : ''; ?>"><a href="create_pkbb.php"><i class="fa fa-circle-o"></i> Buat PKBB</a></li>
</ul>
</li>
</ul>
</section>
<!-- /.sidebar -->
</aside>
<file_sep><?php
function getRandomNamaBarang() {
$namaBarang = [
'Cat Lapisan Kapal',
'Cat Dekoratif',
'Cat Lapisan Pelindung',
'Cat Industri',
];
return $namaBarang[rand(1, 100) % count($namaBarang)];
}
function getNamaBarang($i) {
$namaBarang = [
'Cat Lapisan Kapal',
'Cat Dekoratif',
'Cat Lapisan Pelindung',
'Cat Industri',
];
return $namaBarang[$i];
}
function getRandomDeskripsi() {
$deskripsi = [
'Kualitas A',
'Kualitas B',
'Kualitas C',
];
return $deskripsi[rand(1, 100) % count($deskripsi)];
}
function getDeskripsi($i) {
$deskripsi = [
'Kualitas A',
'Kualitas B',
'Kualitas C',
];
return $deskripsi[$i];
}
function getRandomNamaBahan() {
$namaBahan = [
'Additive',
'Binder',
'Pigment',
'Solvent',
];
return $namaBahan[rand(1, 100) % count($namaBahan)];
}
function getKodeBahan($i) {
$kodeBahan = [
'BB00001',
'BB00002',
'BB00003',
'BB00004',
];
return $kodeBahan[$i];
}
function getNamaBahan($i) {
$namaBahan = [
'Additive',
'Binder',
'Pigment',
'Solvent',
];
return $namaBahan[$i];
}
function getRandomDate($format = 'd F Y') {
return date($format, mt_rand(1511457239, 1514049238));
}
function getRandomCustomer() {
$customerFirstNames = [
'PT. Vanita',
'PT. Nicolasa',
'PT. Illa',
'PT. Nereida',
'PT. Donnette',
'PT. Melita',
'PT. Signe',
'PT. Claretta',
'PT. Jennell',
'PT. Robert'
];
$customerLastNames = [
'Jessenia',
'Luciana',
'Elinore',
'Elizabet',
'Carmelo',
'Kiyoko',
'Leticia',
'Wyatt',
'Imelda',
'Rupert'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)] . ' ' . $customerLastNames[rand(1, 100) % count($customerLastNames)];
}
<file_sep><?php
function getRandomNamaBarang() {
$namaBarang = [
'Cat Lapisan Kapal',
'Cat Dekoratif',
'Cat Lapisan Pelindung',
'Cat Industri',
];
return $namaBarang[rand(1, 100) % count($namaBarang)];
}
function getNamaBarang($i) {
$namaBarang = [
'Cat Lapisan Kapal',
'Cat Dekoratif',
'Cat Lapisan Pelindung',
'Cat Industri',
];
return $namaBarang[$i];
}
function getRandomDeskripsi() {
$deskripsi = [
'Kualitas A',
'Kualitas B',
'Kualitas C',
];
return $deskripsi[rand(1, 100) % count($deskripsi)];
}
function getDeskripsi($i) {
$deskripsi = [
'Kualitas A',
'Kualitas B',
'Kualitas C',
];
return $deskripsi[$i];
}
function getRandomNamaBahan() {
$namaBahan = [
'Additive',
'Binder',
'Pigment',
'Solvent',
];
return $namaBahan[rand(1, 100) % count($namaBahan)];
}
function getNamaBahan($i) {
$namaBahan = [
'Additive',
'Binder',
'Pigment',
'Solvent',
];
return $namaBahan[$i];
}
function getRandomDate($format = 'd F Y') {
return date($format, mt_rand(1511457239, 1514049238));
}
function getRandomCustomer() {
$customerFirstNames = [
'PT. Vanita',
'PT. Nicolasa',
'PT. Illa',
'PT. Nereida',
'PT. Donnette',
'PT. Melita',
'PT. Signe',
'PT. Claretta',
'PT. Jennell',
'PT. Robert'
];
$customerLastNames = [
'Jessenia',
'Luciana',
'Elinore',
'Elizabet',
'Carmelo',
'Kiyoko',
'Leticia',
'Wyatt',
'Imelda',
'Rupert'
];
return $customerFirstNames[rand(1, 100) % count($customerFirstNames)] . ' ' . $customerLastNames[rand(1, 100) % count($customerLastNames)];
}
function getStatusSPP(){
$availableStatuses = [
'Direncanakan untuk diproduksi',
'Mulai Produksi',
'Terjadwal untuk pengiriman'
];
$other = [
'Direncanakan untuk diproduksi',
'Mulai Produksi',
'Selesai Produksi',
'Disetujui QC',
'Terjadwal untuk pengiriman',
'Terkirim',
'Inovice terbit',
'Terbayar'
];
for ($i = 3; $i <= 99; $i++){
$availableStatuses[$i] = $other[rand(1, 100) % count($other)];
}
return $availableStatuses;
}<file_sep><?php include('../template/header.php'); ?>
<?php include('./sidebar.php'); ?>
<?php include('./functions.php'); ?>
<?php
if (isset($_POST['save_purchase_order']) && $_POST['save_purchase_order'] === 'submit') {
header('Location: list.php?message=success');
}
?>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Gudang
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-bar-chart"></i> Home</a></li>
<li><a href="#">Status Produksi</a></li>
<li class="active">Delivery Order</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST">
<div class="box">
<div class="box-header">
<h2 class="box-title">Buat Delivery Order</h2>
</div>
<!-- /.box-header -->
<?php for ($i = 1; $i <= 36; $i++) {
$poId = str_pad($i, 7, '0', STR_PAD_LEFT);} ?>
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>No: <?php echo $poId; ?></label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Pelanggan</label>
<p>PT. ABC (Joko Widodo)</p>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Tujuan</label>
<textarea id="textarea_address"class="form-control pull-right" disabled>Jl. Djuanda No. 1, Jakarta Pusat</textarea>
</div>
<div style="margin-bottom: 10px;" id="div_change_address">
<a href="#">Ubah</a>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label>Order Item</label>
<div class="box">
<!-- /.box-header -->
<div class="box-body no-padding">
<table class="table table-striped" id="table_order_item">
<tbody><tr>
<th>Nama Produk</th>
<th>Quantity</th>
<!-- <th>Harga Per Unit</th> -->
<!-- <th>Diskon</th>
<th>Pajak</th> -->
<th>Deskripsi</th>
</tr>
<tr>
<td>Cat Kapal</td>
<td>120</td>
<!-- <td>Rp. 2.000.000,00</td> -->
<!-- <td>5%</td>
<td>2.5%</td> -->
<td>Cat kapal kualitas A</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
</div>
<!-- /.form-group -->
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Tanggal Pengiriman</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="datepicker">
</div>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Dikirim dari</label>
<select class="form-control select2" style="width: 100%;" name="order_item_product_supplier" type="text" form="modal_add_order_item">
<?php
$gudangList = [
'Gudang Jakarta',
'Gudang Surabaya',
'Gudang Semarang',
'Gudang Papua',
];
for ($i = 0; $i < 30; $i++) {
echo '<option>' . $gudangList[$i%count($gudangList)] . '</option>';
}
?>
</select>
</div>
<!-- /.form-group -->
</div>
<!-- /.col -->
<!-- /.col -->
</div>
<!-- /.row -->
<!-- /.row -->
<!-- /.row -->
<!-- /.row -->
<!-- /.row -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="save_purchase_order" value="submit" class="btn btn-primary">Buat</button>
</div>
</div>
</form>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<?php include('../template/footer.php'); ?>
<file_sep><?php
// redirect to list.php file
header('Location: list_pelanggan.php');
|
780dd64bd0a9c7cdd8a8e04f5167bac6d182fa57
|
[
"Markdown",
"PHP"
] | 28 |
PHP
|
ffahmii/akpsi-ptsu
|
b6d62960db38faca6254afdb72c72d68668a25cc
|
d42c3a00cf9f90d143a17941b7c4f6f398139cfa
|
refs/heads/master
|
<file_sep>json.extract! principal, :id, :created_at, :updated_at
json.url principal_url(principal, format: :json)
<file_sep># Atletibr
* Projeto para o site em português com informações do Atletico de Madrid
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
d099e647a55de3569e3fc935c96fe8e346f53765
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
axelzito/atletibr
|
ddfcb6d1f48e275171b6ecbd1ff6686bd4c43f6a
|
1b54e9a046b02955113d5c53f54d95bfbed32c17
|
refs/heads/master
|
<file_sep><?php
$subjectPrefix = '[TechMiami Contact]';
$emailTo = '<EMAIL>';
$msg = 'Oops! Something went wrong. Try emailing <EMAIL>';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = stripslashes(trim($_POST['form-name']));
$email = stripslashes(trim($_POST['form-email']));
$subject = stripslashes(trim($_POST['form-assunto']));
$message = stripslashes(trim($_POST['form-mensagem']));
$pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';
if (preg_match($pattern, $name) || preg_match($pattern, $email) || preg_match($pattern, $subject)) {
$msg = "Oops! Something went wrong.";
die("Header injection detected");
}
$emailIsValid = preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email);
if($name && $email && $emailIsValid && $subject && $message){
$subject = "$subjectPrefix $subject";
$body = "Name: $name <br /> Email: $email <br /> Message: $message";
$headers = 'MIME-Version: 1.1' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
$headers .= "From: $name <$email>" . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
mail($emailTo, $subject, $body, $headers);
$msg = 'Success! Email sent.';
}
}
echo $msg;
?>
|
ce8d9aab199d6a970fbe9260a476b1b095ad8b4c
|
[
"PHP"
] | 1 |
PHP
|
mauromadeit/techmiami
|
d20feef4e6d72112e8eccbdbeacb767d506fbe0c
|
5007dc1f9f5b060ca591231d1ee72b188fe6fd36
|
refs/heads/master
|
<file_sep>from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='', max_length=50)<file_sep>from django.shortcuts import render
from credapp import creditCheck
from django.http import HttpResponseRedirect
from .forms import NameForm
def index(request):
form = NameForm()
return render(request, 'checker/home.html', {'form': form})
def get_result(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
cd = form.cleaned_data
redditor=cd['your_name']
resultdictionary = creditCheck(redditor)
else:
resultdictionary = {}
form = NameForm()
return render(request, 'checker/home.html', {'form': form})
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'checker/home.html', {'form': form})
return render(request, 'checker/result.html', resultdictionary)<file_sep># CredditCheck
Currently live at: https://credditcheck.herokuapp.com/
Reddit user credibility checker. Web app version of my Reddit bot. Personal project to get familiar with Django, Bootstrap and Jinja.
Purpose of the bot is to gauge the credibility of a user without having to go through their account history. Your questions on subreddits such as r/LearnProgramming or r/HomeworkHelp might not necessarily gain any traction or votes. At best you might have 3 to 4 comments with one vote each and each reply's solution might be heading in a different direction. CredditCheck can help here to see which user has historically provided popular answers and help you reach the best solution. Higher karma points on an account does not necessarily garner high grades on CredditCheck; users who merely respond in small subreddits may receive excellent grades on the app.
Obviously, it's Reddit, it’s user-voted and more about overall agreeability and not actual credibility but CredditCheck is a much cooler name.
This tool can also used by marketers who buy Reddit accounts to promote their products as a message holds more weight coming from a trusted account. Another example of usage that doesn't involve buying accounts would be: a brand looking to hire a celebrity for endorsement, may use this tool and decide to approach <NAME> instead of <NAME> to promote their product on Reddit. The grades of both of these science-celebs as of 14 Jan 2019 are:
• <NAME>(Reddit username: neiltyson) : A+
• <NAME>(Reddit username: sundialbill) : B
If I had to guess beforehand, I would guess the Neil Degrasse Tyson's grade to be much lower as <NAME> seemingly has been the overall better liked celebrity at Reddit. It was just lately his account has been subject to negative responses by Reddit users due to several reasons explained here by other users(may contain foul language):
https://www.reddit.com/r/OutOfTheLoop/comments/7bqfhm/why_is_bill_nyes_ama_so_heavily_downvoted/
As a marketer, I could skip all of this research by simply using CredditCheck!
Sidenote: I was looking to move from PRAW API to PushShift for quicker, more consistent results but apparently they might not be around for much longer so we'll stay with PRAW for now. Source: https://www.reddit.com/r/pushshift/comments/ad1kz9/thanks_to_all_who_donated_the_minimum_needed_has/
<file_sep>import praw
#import time
from statistics import mean
from credentials import reddit
def creditCheck(name):
redditor = reddit.redditor(name)
comments = redditor.comments.new(limit=50)
scores = []
try:
for comment in comments:
parent = comment.parent()
parentscore = parent.score
if (parentscore>0):
if (parent.author != redditor): #if statement checks if person is replying to own post
myscore = comment.score
scores.append(myscore/parentscore)
if (len(scores)>35): #len() is O(1), so why not. Adds credibility(ayy!) to the tool itself
finalscore = round(mean(scores)*10)
# multiplying score by 10 to have a whole number
else:
return {'finalscore': "Account does not have enough comments/information", 'name': name, 'grade': "N/A"}
grade = getGrade(int(finalscore))
dict = {'finalscore': finalscore, 'name': name, 'grade': grade}
except:
return {'finalscore': "No account/comments found", 'name': name, 'grade': "N/A"}
return (dict)
def getGrade(score):
try:
if (score>=4 and score<8):
return "C"
elif (score>=0 and score<4):
return "D"
elif (score>=8 and score<12):
return "B"
elif (score>=12 and score<16):
return "A"
elif (score>=16):
return "A+"
elif (score>=-4 and score<0):
return "F"
elif (score<-4):
return "Delete Account."
except:
return "No grade available."<file_sep>certifi==2018.11.29
chardet==3.0.4
dj-database-url==0.5.0
Django==1.11.23
django-heroku==0.3.1
gunicorn==19.9.0
idna==2.8
praw==6.0.0
prawcore==1.0.0
psycopg2==2.7.6.1
requests==2.21.0
update-checker==0.16
urllib3==1.24.2
whitenoise==4.1.2
psycopg2-binary
|
d3274c190f3246431f93711a4e9427542d3e875f
|
[
"Markdown",
"Python",
"Text"
] | 5 |
Python
|
jawedib/CredditCheck
|
9b7607b97491d26aab39d6e76aa6a1d1e7fa23ac
|
e82009d7196fc4fd08db089e2581c3571f338f4c
|
refs/heads/master
|
<file_sep>from plyer import notification
from requests import get
import subprocess
import logging
import boto3
import yaml
import json
import os
logging.basicConfig(filename='Log.log', level=logging.INFO, format='%(asctime)s: %(levelname)s: %(message)s', datefmt='%d/%m/%y %H:%M:%S')
logging.FileHandler(filename='Log.log', mode='w', encoding='utf-8', delay=False)
def main():
errors = 0
try:
with open(r'data.yml') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
old_ip = data['Data']['LastKnownIp']
except:
logging.error("Unable to retrieve last known public IP (check permissions)")
errors = errors + 1
else:
logging.info("Last known public IP: " + str(old_ip))
try:
ip = get('https://api.ipify.org').text
except:
logging.error("Unable to retrieve current public IP (check internet connection)")
errors = errors + 1
else:
logging.info("Current public IP: " + str(ip))
if old_ip != ip:
logging.info("Change detected")
results = changeDetected(old_ip, ip, data['Accounts'])
errors = errors + results['errors']
if errors == 0:
try:
data['Data']['LastKnownIp'] = ip
with open(r'data.yml', 'w') as file:
yaml.dump(data, file)
except:
logging.error("Unable to update last known public IP")
errors = errors + 1
else:
logging.info("Last known public IP updated successfully")
if results['changed']:
if data['Data']['Notifications']['Success']:
logging.info("Success notification delivered")
notification.notify(
title='Public IP Detector',
message='All security group ingress rules updated successfully',
app_name='Public IP Detector',
app_icon='wifi-logo.ico',
timeout=5
)
else:
logging.info("No change notification skipped due to config")
else:
if data['Data']['Notifications']['NoRulesToUpdate']:
logging.info("No rules to update notification delivered")
notification.notify(
title='Public IP Detector',
message='Change detected but no related rules to update',
app_name='Public IP Detector',
app_icon='wifi-logo.ico',
timeout=5
)
else:
logging.info("No rules to update notification skipped due to config")
else:
logging.info("Purposely did not update last known public IP (fix errors and retry)")
if data['Data']['Notifications']['Failure']:
logging.info("Failure notification delivered")
notification.notify(
title='Public IP Detector',
message='Failed to update security group.\nView the log: ' + str(os.getcwd()) + '\Log.log',
app_name='Public IP Detector',
app_icon='wifi-logo.ico',
timeout=5
)
else:
logging.info("No change notification skipped due to config")
else:
logging.info("No change detected")
if data['Data']['Notifications']['NoChange']:
logging.info("No change notification delivered")
notification.notify(
title='Public IP Detector',
message='No change detected',
app_name='Public IP Detector',
app_icon='wifi-logo.ico',
timeout=5
)
else:
logging.info("No change notification skipped due to config")
return errors
def changeDetected(old_ip, ip, data):
errors = 0
changed = False
for account in data:
logging.info("Checking account: " + str(account))
try:
client = boto3.client('ec2', aws_access_key_id=data[account]['Credentials']['AccessKey'], aws_secret_access_key=data[account]['Credentials']['Secret'])
security_groups = client.describe_security_groups()
except:
logging.error("Failed to get security groups (check internet connection and IAM permissions - need 'ALLOW' for 'ec2:DescribeSecurityGroups' action)")
errors = errors + 1
else:
logging.info("Security groups gathered successfully")
for security_group_details in security_groups['SecurityGroups']:
ec2 = boto3.resource('ec2', aws_access_key_id=data[account]['Credentials']['AccessKey'], aws_secret_access_key=data[account]['Credentials']['Secret'])
security_group = ec2.SecurityGroup(security_group_details['GroupId'])
logging.info("Checking security group: " + security_group_details['GroupId'])
for ip_address in security_group_details['IpPermissions']:
for ip_range in ip_address['IpRanges']:
if ip_range['CidrIp'] == str(old_ip) + '/32':
if ip_address['IpProtocol'] == '-1':
try:
remove_response = security_group.revoke_ingress(
IpPermissions=[
ip_address
]
)
logging.debug(remove_response)
except Exception as e:
logging.debug(e)
logging.error("Failed to remove old security group rule (check internet connection and IAM permissions - need 'ALLOW' for 'ec2:RevokeSecurityGroupIngress' action)")
errors = errors + 1
else:
logging.info("Old security group rule removed successfully")
try:
add_response = security_group.authorize_ingress(
IpPermissions=[
{
'IpProtocol': ip_address['IpProtocol'],
'IpRanges': [
{
'CidrIp': str(ip) + '/32'
},
],
'UserIdGroupPairs': [
{
'GroupId': security_group_details['GroupId']
},
]
},
]
)
logging.debug(add_response)
except Exception as e:
logging.debug(e)
logging.error("Failed to create new security group rule (check internet connection and IAM permissions - need 'ALLOW' for 'ec2:AuthorizeSecurityGroupIngress' action)")
errors = errors + 1
else:
logging.info("New security group rule created successfully")
else:
try:
remove_response = security_group.revoke_ingress(
IpPermissions=[
ip_address
]
)
logging.debug(remove_response)
except Exception as e:
logging.debug(e)
logging.error("Failed to remove old security group rule (check internet connection and IAM permissions - need 'ALLOW' for 'ec2:RevokeSecurityGroupIngress' action)")
errors = errors + 1
else:
logging.info("Old security group rule removed successfully")
try:
add_response = security_group.authorize_ingress(
IpPermissions=[
{
'IpProtocol': ip_address['IpProtocol'],
'FromPort': ip_address['FromPort'],
'ToPort': ip_address['ToPort'],
'IpRanges': [
{
'CidrIp': str(ip) + '/32'
},
],
'UserIdGroupPairs': [
{
'GroupId': security_group_details['GroupId']
},
]
},
]
)
logging.debug(add_response)
except Exception as e:
logging.debug(e)
logging.error("Failed to create new security group rule (check internet connection and IAM permissions - need 'ALLOW' for 'ec2:AuthorizeSecurityGroupIngress' action)")
errors = errors + 1
else:
logging.info("New security group rule created successfully")
changed = True
else:
logging.info("Security group rule skipped (no match found)")
return {'errors': errors, 'changed': changed}
if __name__ == '__main__':
logging.info("Execution initiated...")
errors = main()
logging.info("Execution finished with " + str(errors) + " error(s)")
<file_sep># Public IP Detector
Python script to periodically and automatically detect a change in your public IP address. If so, all AWS EC2 security groups containing your old public IP will be updated to use your new IP. This tool uses Python and the Boto3 python SDK for AWS.
## Overview
- When executed, this tool will check to see if your public IP address is the same as last time.
- If it is the same, the tool will exit.
- If it has changed, it will:
- Remove the ingress rule for your old public IP address.
- Add a new ingress rule for your new public IP address using the same protocols and ports as the old rule.
## Prerequisites
This application requires the following items to be installed prior to running the installer:
- Python 3 (with user or system environment variable)
- Pip (with user or system environment variable)
The IAM users will also need to have the following permissions allowed on each of the accounts they want checking:
- `ec2:DescribeSecurityGroups`
- `ec2:RevokeSecurityGroupIngress`
- `ec2:AuthorizeSecurityGroupIngress`
## Installation
- Run the following command using the command prompt:
```
pip install boto3 requests pyyaml plyer
```
- Clone the repository:
```
git clone https://github.com/hlacannon/aws-public-ip-detector.git
```
- If you want the tool to run automatically at a given frequency, run the following command:
```
SCHTASKS /CREATE /SC Variable1 /MO Variable2 /TN hlacannon\aws-public-ip-detector /TR Variable3\schedule.bat
```
Where:
- Variable1 is the frequency intenger (i.e. 1, 7, etc.)
- Variable2 is the frequency type (i.e. MINUTE, HOURLY, DAILY, etc.)
- Variable3 is the path where you cloned the repository
For more information on the Windows Task Scheduler, visit https://docs.microsoft.com/en-us/windows/win32/taskschd/using-the-task-scheduler
## Post-Installation
Before this tool is able to run successfully, you will need to provide the programmatic access keys (access keys and secrets) for your different AWS accounts (e.g. Personal, Work, etc.).
These are required as the tool uses the AWS SDK boto3. The programmatic access keys will need to be stored in the `data.yml` file in the following format:
```
# data.yml
Accounts:
Personal:
Credentials:
AccessKey: your-access-key-here
Secret: your-secret-here
Work:
Credentials:
AccessKey: your-access-key-here
Secret: your-secret-here
Data:
LastKnownIp: your-current-public-ip-address
Notifications:
Failure: true
NoChange: true
NoRulesToUpdate: true
Success: true
```
*\* The account names can be customised and more can be added*
## Execution
- If you have set up the Windows Task Scheduler task correctly, the tool should run at the frequency you specified.
- If you haven't set up the Windows Task Scheduler task or would like to run the program directly:
- In the command line navigate to the repository folder and run:
```
python public_ip_detector.py
```
- Or execute the run.vbs file.
## Custom Configuration
Within the `data.yml` file you will notice 4 different notifications (Failure, NoChange, NoRulesToUpdate & Success). The boolean values of these attributes can be customised and will be used to determine whether to notify you of the following:
- Failure:
- Used to determine whether you should be notified when the tool fails to execute completely and further detail will be recorded in the log (`Log.log`)
- Default value: `true`
- NoChange:
- Used to determine whether you should be notified when the tool doesn't recognise a change in your public IP since last time
- Default value: `true`
- NoRulesToUpdate:
- Used to determine whether you should be notified when the tool recognises a change in your public IP but can't find any security group ingress rules associated to your old public IP
- Default value: `true`
- Success:
- Used to determine whether you should be notified when the tool recognises a change in your public IP and successfully updates all security group ingress rules associated to your IP
- Default value: `true`
## Debugging
The results of the AWS API calls are logged each time the tool is executed and are available to view at `your-installation-path\Log.log`.
If you need help debugging or find a bug, please [raise an issue](https://github.com/hlacannon/aws-public-ip-detector/issues/new).
## Contributing
Contributions are welcomed and appreciated. If you have an idea for a new feature, or find a bug, you can [open an issue](https://github.com/hlacannon/aws-public-ip-detector/issues/new) and report it. Or if you are in the developing mood, you can fork this repository, implement the idea or fix the bug and [submit a new pull request](https://github.com/hlacannon/aws-public-ip-detector/compare).
|
f6ba6842c0ceae9271d190d18f4d2f256af76bcd
|
[
"Markdown",
"Python"
] | 2 |
Python
|
HariboDev/aws-public-ip-detector-python
|
71f7adfd702034b5f0f56e2ed77f71efe13fb8aa
|
2c56df03994c76a9959981012a82e697d347b90c
|
refs/heads/master
|
<repo_name>edwardchen40/itinerary-viewer<file_sep>/kml/test_geocodeKML.py
import geocodeKML
def test_parseAddresses():
addressesText = '''
Mozilla HQ; 331 E Evelyn Ave, Mountain View, CA 94041
Mozilla Paris; 16 Boulevard Montmartre, 75009 Paris
'''
assert geocodeKML.parseAddresses(addressesText) == [
{'name':'Mozilla HQ', 'address':'331 E Evelyn Ave, Mountain View, CA 94041'},
{'name':'Mozilla Paris', 'address': '16 Boulevard Montmartre, 75009 Paris'}
]
<file_sep>/README.md
#Itinerary Viewer
#[Production Site](https://shinglyu.github.io/itinerary-viewer)
# How to use locally
```
npm install -g live-server
```
```
ln -s <your yml file> source_files/default.yml
live-server
```
<file_sep>/js/itineary_components.jsx
if (typeof require !== "undefined"){
var React = require('react')
}
//https://www.google.com.tw/maps/dir/University+of+Taipei,+Zhongzheng+District,+Taipei+City,+Taiwan/%E5%8F%B0%E5%8C%97%E5%B8%82%E4%BF%A1%E7%BE%A9%E5%8D%80%E8%87%BA%E5%8C%97101%E8%B3%BC%E7%89%A9%E4%B8%AD%E5%BF%83/@25.0321477,121.5204559,14z/data=!3m1!4b1!4m13!4m12!1m5!1m1!1s0x3442a9a02f53dd45:0x38f05d6edd6d3845!2m2!1d121.5138046!2d25.0366038!1m5!1m1!1s0x3442abb6da80a7ad:0xacc4d11dc963103c!2m2!1d121.56481!2d25.033718
var AutoLinkText = React.createClass({
render: function(){
var re = /(http[s]?:\/\/[^\s]*)/g;
if (typeof this.props.data == "undefined"){
return <div/>
}
var lines = this.props.data.split("\n")
console.log(lines)
lines_w_brs = []
for (var id in lines){
//console.log(line)
lines_w_brs.push(lines[id]);
lines_w_brs.push(<br/>);
}
var text_blocks = lines_w_brs;
//var text_blocks = this.props.data.split(" ")
console.log(this.props.data)
console.log(text_blocks)
var texts = text_blocks.map(function(text){
if (typeof text == "string"){
if (text.match(re)){
return <a href={text} target="_blank">{text}</a>
}
else {
return text + " "
}
}
else {
return text
}
})
return (
<span>{texts}</span>
)
}
});
var NodeIcon = React.createClass({
render: function(){
var icon_name="fa-"
if (typeof this.props.type == "undefined") {
var nodetype = "S";
}
else {
//var nodetype = this.props.type[0];
var nodetype = this.props.type;
}
switch (nodetype){
case "S":
icon_name += "street-view"
break;
case "T":
icon_name += "subway"
break;
case "F":
icon_name += "cutlery"
break;
case "N":
icon_name += "info"
break;
case "D":
icon_name += "calendar"
break;
case "SG-route":
icon_name += "map-signs"
break;
default:
icon_name += "info"
break;
}
return (<div className={"icon " + "icon-" + this.props.type}><i className={"fa " + icon_name}/></div>)
}
});
var Map = React.createClass({
render: function(){
var address = undefined;
var map_img_src="http://maps.googleapis.com/maps/api/staticmap?center=" + encodeURI(address) +
"&size=200x200" +
"&markers=size:small|color:red|label:A|" + encodeURI(address)
"&key=<KEY>";
//var map_img_src="http://placehold.it/200x200";
var external_link ="http://maps.google.com/maps?q=" + encodeURI(address);
if ((this.props.node.type != "S" && typeof this.props.node.type !== "undefined") || typeof address == "undefined"){
return <div/>
}
else {
return (
<div className="map">
<a href={external_link} target="_blank">
<img src={map_img_src}/>
</a>
</div>
)
}
}
})
var DayMap = React.createClass({
getInitialState: function(){
return {"size": "300x300"};
},
handleClick: function(){
// FIXME: what't the upper limit?
this.setState({"size": "1200x1200"});
},
render: function(){
//FIXME: ES6
var map_img_src="https://maps.googleapis.com/maps/api/staticmap?" +
"&size=" + this.state['size']
"&key=<KEY>";
//var mapsrc="http://placehold.it/200x200";
//
this.props.nodes.map(function(node){
//if (typeof qs['no_map'] == "undefined"){
if (typeof node.address !== "undefined" && (node.type == "S" || typeof node.type == "undefined")){
address = node.address;
map_img_src += "&markers=size:small|color:red|label:A|" + encodeURI(address)
}
else {
//if (typeof node.title !== "undefined" && typeof qs['no_auto_map'] == "undefined" && (node.type == "S" || typeof node.type == "undefined")){
//TODO:disable auto infer
if (typeof node.title !== "undefined"){
address = node.title;
map_img_src += "&markers=size:small|color:red|label:A|" + encodeURI(address)
}
}
//}
})
//var map_img_src="http://placehold.it/200x200";
return (
<div className="daymap" onClick={this.handleClick}>
<img src={map_img_src}/>
</div>
)
}
})
var Suggestions = React.createClass({
render: function(){
var suggestions = []
//console.log("Address")
//console.log(this.props.node.address)
if (this.props.node.type == "S" && typeof this.props.node.address !== "undefined"){
suggestions.push(<li><a target="_blank" href={"https://maps.google.com/maps?q=" + encodeURI(this.props.node.address)}>Open map</a></li>)
}
if (typeof this.props.node.address == "undefined" || this.props.node.address == this.props.node.title){
suggestions.push(<li><a target="_blank" href={"https://www.google.com/search?q=" + encodeURI(this.props.node.title) + "+address"}>Find address</a></li>)
//console.log(suggestions)
}
if (typeof this.props.node.description == "undefined" || this.props.node.description == ""){
suggestions.push(<li><a target="_blank" href={"https://www.google.com/search?q=" + encodeURI(this.props.node.title)}>Find detail</a></li>)
//console.log(suggestions)
}
return (
<div className="suggestions">
<ul>
{suggestions}
</ul>
</div>
)
}
})
var Node = React.createClass({
render: function(){
//console.log("config:")
//console.log(this.props.config)
var node = this.props.node;
//console.log(node)
var line;
if (this.props.drawVertLine){
line = <div className="line"/>;
}
//console.log(node.description)
var desc = <AutoLinkText data={node.description}/>
//console.log(desc)
var sg_route_class="";
if (node.type == "SG-route"){
return (
<div className="node suggestions" >
<NodeIcon type={node.type}/>
{line}
<div className="content">
<h4 className="title"><a href={node.description} target="_blank">Find route</a></h4>
</div>
</div>
);
}
var suggestions;
if (typeof this.props.config['planningMode'] !== "undefined"){
suggestions = (<Suggestions node={node}/>)
}
var map = <Map node={node}/>
var map = {};
var time = {};
if (typeof node.time !== "undefined" && node.time !== ""){
time = <p className="time"><i className="fa fa-clock-o"/>{node.time}</p>
}
var address = {};
if (node.address !== node.title){
address = <p className="address"><i className="fa fa-map-marker"/>{node.address}</p>
}
var titleNode = <h4 className="title">{node.title}</h4>
if (node.type == "T"){
titleNode = <p className="title"> {node.title}</p>
}
return (
<div className={"node " + sg_route_class} >
<NodeIcon type={node.type}/>
{line}
<div className="content">
{titleNode}
{map}
<div className="text">
{time}
{address}
<p className="description">{desc}</p>
{suggestions}
</div>
</div>
</div>
);
}
})
var Day = React.createClass({
fillEmptyTypes: function(nodes){
return nodes.map(function(node){
if (typeof node['type'] == "undefined") {
node['type'] = "S";
}
if (typeof node['address'] == "undefined") {
node['address'] = node['title'];
}
return node
});
},
inferAddress: function(nodes){
return nodes.map(function(node){
if (node['type'] !== "S"){
return node;
}
if (typeof node['address'] == "undefined"){
node['address'] = node['title'];
return node
}
})
},
insertTransitSuggestions: function(nodes){
for (var idx =0; idx < nodes.length-1; idx++){
if (nodes[idx]['type'] == "S" && nodes[idx+1]['type'] == "S"){
nodes.splice(idx+1, 0, {
"type": "SG-route",
"title":"Find route",
"address":"Find route",
"description":"http://maps.google.com/maps?saddr=" + encodeURI(nodes[idx]['address']) + "&daddr=" + encodeURI(nodes[idx+1]['address']) + "&dirflg=r"
})
}
}
return nodes;
},
render: function(){
var rawnodes = [{title: this.props.date, type:"D"}]
rawnodes = rawnodes.concat(this.props.nodes)
//console.log(rawnodes)
var nodes = this.fillEmptyTypes(rawnodes);
//console.log(nodes)
if(typeof this.props.config['planningMode'] !== "undefined" && this.props.config['planningMode'][0] == "1"){ //BUG: python server will be "1/"
nodes = this.insertTransitSuggestions(nodes);
}
console.log(nodes)
//console.log(this)
var config = this.props.config;
//console.log(config)
nodes = nodes.map(function(node, index, array){
return (
//<Node node={node} drawVertLine={(index != array.length-1)} />
<Node node={node} config={config} drawVertLine={(index != array.length-1)} />
)
})
return (
<div className="timeline">
{nodes}
</div>
);
}
});
var Days= React.createClass({
render: function(){
//console.log(this.props.config)
days = []
for (var date in this.props.days){
days.push(
<div>
<Day nodes={this.props.days[date]} date={date} config={this.props.config}/>
<DayMap nodes={this.props.days[date]}/>
<hr/>
</div>
)
}
return (
<div className="container">
{days}
</div>
)
}
});
module.exports.Day = Day;
module.exports.NodeIcon = NodeIcon;
module.exports.Node = Node;
module.exports.Suggestions = Suggestions;
<file_sep>/kml/README.md
#Usage
Run
```
python geocodeKML.py <your input txt>
```
or
```
bash geocode.sh <your input txt> #Will open online kml viewer and nemo file manager
```
A file called `google.kml` will be generated. You can import it to apps like MAPS.ME or Google My Map.
#Input file format
```
title; address
title; title
```
If you don't know the address, simply repeat the title again.
e.g.
```
Taipei 101; No.x, Hsin-yi Rd. Taipei, Taiwan
Taipei Main Train Station; Taipei Main Train Station
```
|
08b07de466752b2f5bf18971d3d818c8fe848aa9
|
[
"Markdown",
"Python",
"JavaScript"
] | 4 |
Python
|
edwardchen40/itinerary-viewer
|
45f1bb925144682c4f8a08a994abc9219156a290
|
353d485455d19cb86177bd63964d035173bb7163
|
refs/heads/main
|
<file_sep>/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
#define B1_Pin GPIO_PIN_13
#define B1_GPIO_Port GPIOC
#define B1_EXTI_IRQn EXTI4_15_IRQn
#define RCC_OSC32_IN_Pin GPIO_PIN_14
#define RCC_OSC32_IN_GPIO_Port GPIOC
#define RCC_OSC32_OUT_Pin GPIO_PIN_15
#define RCC_OSC32_OUT_GPIO_Port GPIOC
#define RCC_OSC_IN_Pin GPIO_PIN_0
#define RCC_OSC_IN_GPIO_Port GPIOF
#define RCC_OSC_OUT_Pin GPIO_PIN_1
#define RCC_OSC_OUT_GPIO_Port GPIOF
#define ResetCam_Pin GPIO_PIN_2
#define ResetCam_GPIO_Port GPIOC
#define pwdn_Pin GPIO_PIN_3
#define pwdn_GPIO_Port GPIOC
#define USART_TX_Pin GPIO_PIN_2
#define USART_TX_GPIO_Port GPIOA
#define USART_RX_Pin GPIO_PIN_3
#define USART_RX_GPIO_Port GPIOA
#define pclk_Pin GPIO_PIN_4
#define pclk_GPIO_Port GPIOA
#define D0_Pin GPIO_PIN_0
#define D0_GPIO_Port GPIOB
#define D1_Pin GPIO_PIN_1
#define D1_GPIO_Port GPIOB
#define D2_Pin GPIO_PIN_2
#define D2_GPIO_Port GPIOB
#define vsyncEXTI10_Pin GPIO_PIN_10
#define vsyncEXTI10_GPIO_Port GPIOB
#define vsyncEXTI10_EXTI_IRQn EXTI4_15_IRQn
#define href_Pin GPIO_PIN_11
#define href_GPIO_Port GPIOB
#define pwm_Pin GPIO_PIN_7
#define pwm_GPIO_Port GPIOC
#define CS_Pin GPIO_PIN_9
#define CS_GPIO_Port GPIOC
#define TMS_Pin GPIO_PIN_13
#define TMS_GPIO_Port GPIOA
#define TCK_Pin GPIO_PIN_14
#define TCK_GPIO_Port GPIOA
#define LED_Pin GPIO_PIN_15
#define LED_GPIO_Port GPIOA
#define DC_Pin GPIO_PIN_10
#define DC_GPIO_Port GPIOC
#define RST_Pin GPIO_PIN_12
#define RST_GPIO_Port GPIOC
#define D3_Pin GPIO_PIN_3
#define D3_GPIO_Port GPIOB
#define D4_Pin GPIO_PIN_4
#define D4_GPIO_Port GPIOB
#define D5_Pin GPIO_PIN_5
#define D5_GPIO_Port GPIOB
#define D6_Pin GPIO_PIN_6
#define D6_GPIO_Port GPIOB
#define D7_Pin GPIO_PIN_7
#define D7_GPIO_Port GPIOB
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main goal of this project is using OV7670( without FIFO)
* using STM32F070RB and it consumes very less place in the SRAM. Every peripheral clock speed is set 48MHz.
* Display Rendering Time approximately 2 second.
* If you have using another board please check your System Clock and PWM setting to be 48MHz and (24Mhz for PWM).
*
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <ov7670.h>
#include "string.h"
#include "ILI9341_STM32_Driver.h"
#include "ILI9341_GFX.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
CRC_HandleTypeDef hcrc;
I2C_HandleTypeDef hi2c1;
SPI_HandleTypeDef hspi1;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim6;
TIM_HandleTypeDef htim7;
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_I2C1_Init(void);
static void MX_TIM3_Init(void);
static void MX_SPI1_Init(void);
static void MX_CRC_Init(void);
static void MX_TIM6_Init(void);
static void MX_TIM7_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_I2C1_Init();
MX_TIM3_Init();
MX_SPI1_Init();
MX_CRC_Init();
MX_TIM6_Init();
MX_TIM7_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
HAL_TIM_Base_Start(&htim6);
HAL_TIM_Base_Start(&htim7);
//We wrote 1 the compare counting for being %50 rate of the (Duty Cycle Duty Cycle oranını %50 olmasi icin compare sayimini 1 olarak yazdik).
//Counter Period Index is 1 that means this value divides the clock signal by 2( Counter Period indexi 1 yani Clock sinyalini 2 ye bölüyor.)
//Pwm clock value is = 48 / 2 = 24 MHz (Su anki clock degeri = 48 / 2 = 24MHz osiloskopsuz degeri(para yok olcemedik))
__HAL_TIM_SetCompare(&htim3,TIM_CHANNEL_2,1);
//LED Settings
//Set the PA15 LED pin
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, SET);
//Initialize LED settings
ILI9341_Init();//initial driver setup to drive ili9341
// Give 100 ms delay for initializing
HAL_Delay(100);
//OV Camera Settings
ConfigurePWDNandRESETpins();
//Make little delay for healthy process
HAL_Delay(1);
//Reset all registers
ov7670_init();
//Make little delay for healthy process
HAL_Delay(1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
GetFramesFromOvCam();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV1;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C1;
PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief CRC Initialization Function
* @param None
* @retval None
*/
static void MX_CRC_Init(void)
{
/* USER CODE BEGIN CRC_Init 0 */
/* USER CODE END CRC_Init 0 */
/* USER CODE BEGIN CRC_Init 1 */
/* USER CODE END CRC_Init 1 */
hcrc.Instance = CRC;
hcrc.Init.DefaultInitValueUse = DEFAULT_INIT_VALUE_ENABLE;
hcrc.Init.InputDataInversionMode = CRC_INPUTDATA_INVERSION_NONE;
hcrc.Init.OutputDataInversionMode = CRC_OUTPUTDATA_INVERSION_DISABLE;
hcrc.InputDataFormat = CRC_INPUTDATA_FORMAT_BYTES;
if (HAL_CRC_Init(&hcrc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN CRC_Init 2 */
/* USER CODE END CRC_Init 2 */
}
/**
* @brief I2C1 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C1_Init(void)
{
/* USER CODE BEGIN I2C1_Init 0 */
/* USER CODE END I2C1_Init 0 */
/* USER CODE BEGIN I2C1_Init 1 */
/* USER CODE END I2C1_Init 1 */
hi2c1.Instance = I2C1;
hi2c1.Init.Timing = 0x2000090E;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
Error_Handler();
}
/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C1_Init 2 */
/* USER CODE END I2C1_Init 2 */
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 7;
hspi1.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief TIM3 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM3_Init(void)
{
/* USER CODE BEGIN TIM3_Init 0 */
/* USER CODE END TIM3_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
/* USER CODE BEGIN TIM3_Init 1 */
/* USER CODE END TIM3_Init 1 */
htim3.Instance = TIM3;
htim3.Init.Prescaler = 1;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.Period = 1;
htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM3_Init 2 */
/* USER CODE END TIM3_Init 2 */
HAL_TIM_MspPostInit(&htim3);
}
/**
* @brief TIM6 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM6_Init(void)
{
/* USER CODE BEGIN TIM6_Init 0 */
/* USER CODE END TIM6_Init 0 */
/* USER CODE BEGIN TIM6_Init 1 */
/* USER CODE END TIM6_Init 1 */
htim6.Instance = TIM6;
htim6.Init.Prescaler = 47;
htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
htim6.Init.Period = 65535;
htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM6_Init 2 */
/* USER CODE END TIM6_Init 2 */
}
/**
* @brief TIM7 Initialization Function
* @param None
* @retval None
*/
static void MX_TIM7_Init(void)
{
/* USER CODE BEGIN TIM7_Init 0 */
/* USER CODE END TIM7_Init 0 */
/* USER CODE BEGIN TIM7_Init 1 */
/* USER CODE END TIM7_Init 1 */
htim7.Instance = TIM7;
htim7.Init.Prescaler = 47;
htim7.Init.CounterMode = TIM_COUNTERMODE_UP;
htim7.Init.Period = 65535;
htim7.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim7) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM7_Init 2 */
/* USER CODE END TIM7_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 38400;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, ResetCam_Pin|pwdn_Pin|CS_Pin|DC_Pin
|RST_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : ResetCam_Pin pwdn_Pin CS_Pin DC_Pin
RST_Pin */
GPIO_InitStruct.Pin = ResetCam_Pin|pwdn_Pin|CS_Pin|DC_Pin
|RST_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pins : pclk_Pin PA8 */
GPIO_InitStruct.Pin = pclk_Pin|GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : D0_Pin D1_Pin D2_Pin href_Pin
D3_Pin D4_Pin D5_Pin D6_Pin
D7_Pin */
GPIO_InitStruct.Pin = D0_Pin|D1_Pin|D2_Pin|href_Pin
|D3_Pin|D4_Pin|D5_Pin|D6_Pin
|D7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : vsyncEXTI10_Pin */
GPIO_InitStruct.Pin = vsyncEXTI10_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(vsyncEXTI10_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : LED_Pin */
GPIO_InitStruct.Pin = LED_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI4_15_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI4_15_IRQn);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep># Using OV7670 Camera with(QQVGA format) STM32f070RB(Nucleo Board) and IL9341 LED(With SPI)
Main goal of this project is getting frame syncronuisly and display on the IL9341 LED( without FIFO)
* using STM32F070RB and it consumes very less place in the SRAM. Every peripheral clock speed is set 48MHz.
* Display Rendering Time approximately 2 second.
* If you have using another board please check your System Clock and PWM setting to be 48MHz and (24Mhz for PWM).
For Pin Definitions Please Check main.h class
SPI Pın Definitions :
PA5 : SPI_SCK
PA6 : SPI_MISO
PA7 : SPI_MOSI
PC9 : SPI_NSS (or CS)
I2C Pin Definition :
PB9 : I2C_SDA
PB8 : I2C_SCL
NOTE : I didnt use 5x5 font.h (or function of the IL9341_GFX.h like DrawCircle, DrawRectangle etc..) for this project.
I didn't delete the codes because maybe it can be useful.
<file_sep>/*
* ov7670.c
*
* Created on: 6 Haz 2021
* Author: H3RK3S
*/
/*
* ov7670 camera initializing codes are taken by <NAME>
*
*/
#include "ov7670.h"
#include "stm32f0xx_hal.h"
#include "main.h"
#include "ILI9341_GFX.h"
extern I2C_HandleTypeDef hi2c1;
extern SPI_HandleTypeDef hspi1;
extern TIM_HandleTypeDef htim6;
extern TIM_HandleTypeDef htim7;
//This settings includes RGB565 format,QQVGA format and color optimization settings.
//You can find "OV7670 Implementation " document as pdf by OmniVision Company
const uint8_t OV7670_reg[][2] = {
{REG_COM7, 0x80},
{REG_CLKRC, 0x91},
{REG_COM11, 0x0A},
{REG_TSLB, 0x04},
{REG_TSLB, 0x04},
{REG_COM7, 0x04},
{REG_RGB444, 0x00},
{REG_COM15, 0xD0},
{REG_HSTART, 0x16},
{REG_HSTOP, 0x04},
{REG_HREF, 0x24},
{REG_VSTART, 0x02},
{REG_VSTOP, 0x7a},
{REG_VREF, 0x0a},
{REG_COM10, 0x02},
{REG_COM3, 0x04},
{REG_MVFP, 0x3f},
// 3 consecutive lines of code are QQVGA format settings.
{REG_COM14, 0x1a},
{0x72, 0x22},
{0x73, 0xf2},
{0x4f, 0x80},
{0x50, 0x80},
{0x51, 0x00},
{0x52, 0x22},
{0x53, 0x5e},
{0x54, 0x80},
{0x56, 0x40},
{0x58, 0x9e},
{0x59, 0x88},
{0x5a, 0x88},
{0x5b, 0x44},
{0x5c, 0x67},
{0x5d, 0x49},
{0x5e, 0x0e},
{0x69, 0x00},
{0x6a, 0x40},
{0x6b, 0x0a},
{0x6c, 0x0a},
{0x6d, 0x55},
{0x6e, 0x11},
{0x6f, 0x9f},
{0xb0, 0x84},
{0xFF, 0xFF},
};
const uint8_t needForHalfMicroDelay =0;
const uint16_t hrefPeriod= 9406; //Micro Second
const uint16_t pclkHighPixSynTime = 6; //Micro Second
const uint16_t pclkLowPixSynTime = 4; //Micro Second
const uint16_t vsyncLowTime = 7052; //Micro Second
uint8_t horizArray[320];
uint8_t vsync =0;
char ov7670_init(void)
{
ResetRegisterForOvCam();
HAL_Delay(30);
uint8_t buffer[4];
ReadOperationOVCam(REG_VER, buffer);
if ( buffer[0] != 0x73)
{
return 0;
}
else
{
ov7670_config();
}
return 1;
}
char ov7670_config()
{
ResetRegisterForOvCam();
HAL_Delay(30);
for(int i = 0; OV7670_reg[i][0]!=0xFF; i++) {
WriteOperationOVCam(OV7670_reg[i][0], OV7670_reg[i][1]);
HAL_Delay(1);
}
return 0;
}
void GetFramesFromOvCam()
{
/*
* PB0 = D0 PB1 = D1 PB2 = D2
* PB3 = D3 PB4 = D4 PB5 = D5
* PB6 = D6 PB7 = D7
*
*/
uint16_t microCounter =0;
uint16_t microCountertwo =0;
//This definition also needed for pixel sync or you can define
//unused value instead this value...
uint8_t currentRowHorizantalData =0;
//RGB565 format is 16bit format and OV7670 is supported it.
//In order to obtain 160 horizantel pixel for LCD you need to catch 320 pixel
//(8 bit = 1 pixel for Camera)
const uint16_t horizantelPixel = 320;
const uint8_t verticalPixel = 120;
if(needForHalfMicroDelay == 0)
{
if(vsync == 1)
{
//In order to catch the second Interrupt at the right time
//I added this delay(It is measured with Logic Analyzer with cheap one :)
delayUsec(vsyncLowTime);
while(vsync == 2)
{
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_8) )
{
for(uint16_t verticalCount =0; verticalCount < verticalPixel; verticalCount++)
{
__HAL_TIM_SET_COUNTER(&htim6,0);
__HAL_TIM_SET_COUNTER(&htim7,0);
for(uint16_t horizCount =0; horizCount < horizantelPixel ; horizCount++)
{
if(HAL_GPIO_ReadPin(GPIOA, pclk_Pin) == 0 )
{
/*
* This part when PCLK is
*/
currentRowHorizantalData = ((0x00FF) & (GPIOB->IDR));
horizArray[horizCount] = currentRowHorizantalData;
microCountertwo = pclkHighPixSynTime - __HAL_TIM_GET_COUNTER(&htim7) ;
delayUsecForTimSeven(microCountertwo);
}else
{
currentRowHorizantalData = ((0x00FF) & (GPIOB->IDR));
horizArray[horizCount] = currentRowHorizantalData;
//This unused variable needed for very little pixel spikes
//If you try delete this value, you can understand :)
uint8_t forNanoSecDelay =0;
microCountertwo = pclkLowPixSynTime - __HAL_TIM_GET_COUNTER(&htim7) ;
delayUsecForTimSeven(microCountertwo);
}
__HAL_TIM_SET_COUNTER(&htim7,0);
}
//Elapsed Time for Data sending to led is 1900 - 2800 microSecond
sendImageBufferToLed(&hspi1, horizArray, verticalCount,horizantelPixel);
microCounter = hrefPeriod -__HAL_TIM_GET_COUNTER(&htim6);
//It need to wait to be HIGH of the HREF
delayUsec(microCounter);
}
}
}
}
}
//delayUsec(38155);
}
void ConfigurePWDNandRESETpins()
{
//for pwdn configure as Reset state to PC3
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, RESET);
//for RESET configure as Set state to PC2
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_2, SET);
}
void ResetRegisterForOvCam()
{
uint8_t pData[] = {0x80};
//You need to set of Bit[7] for 0x12 Register Address
if( HAL_I2C_Mem_Write(&hi2c1, writeAddressSCCB, REG_COM7, I2C_MEMADD_SIZE_8BIT, pData, 1, 10) != HAL_OK)
{
return;
}
}
void WriteOperationOVCam(uint16_t memADdress, uint8_t pData)
{
if( HAL_I2C_Mem_Write(&hi2c1, writeAddressSCCB, memADdress, I2C_MEMADD_SIZE_8BIT, &pData, 1, 10) != HAL_OK)
{
return;
}
}
void ReadOperationOVCam(uint16_t memAddress, uint8_t* buffer)
{
if(HAL_I2C_Master_Transmit(&hi2c1, writeAddressSCCB, (uint8_t*)&memAddress, 1, 10) != HAL_OK)
{
return ;
}
if(HAL_I2C_Master_Receive(&hi2c1, readAddressSCCB, buffer, 1, 10) != HAL_OK)
{
return;
}
}
//I defined timers separately for not changing the time sync
void delayUsec(uint16_t time)
{
__HAL_TIM_SET_COUNTER(&htim6,0);
while( __HAL_TIM_GET_COUNTER(&htim6) < time);
}
void delayUsecForTimSeven(uint16_t time)
{
__HAL_TIM_SET_COUNTER(&htim7,0);
while( __HAL_TIM_GET_COUNTER(&htim7) < time);
}
|
264af1e6616fc3d71c0e632734faa16799c04630
|
[
"Markdown",
"C"
] | 4 |
C
|
mmtcoder/OV7670-Stm32F070Rb
|
faacfaa97e80f787f49df6244e96e0f9016fa298
|
4281a801c649a6f52cfa8c47e47119bbf8e03cc9
|
refs/heads/master
|
<file_sep>export interface IFabricUiNestingProps {
description: string;
context:any;
listData: any[];
}
<file_sep>export interface IFormWindowProps {
closeWindow: Function;
userDetails: { Id: number, Title: string, Team: string, Department: string };
nameChangeHandler: (nameChange:string, id:number) => void;
teamChangeHandler: (team:string, id:number) => void;
depChangeHandler: (department:string, id:number) => void;
}
export interface IFormWindowState {
page1: boolean;
page2: boolean;
page3: boolean;
percentComplete: number;
}<file_sep>import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import * as strings from 'FabricUiNestingWebPartStrings';
import FabricUiNesting from './components/FabricUiNesting';
import { IFabricUiNestingProps } from './components/IFabricUiNestingProps';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { mockData } from '../fabricUiNesting/MockData';
export interface IFabricUiNestingWebPartProps {
description: string;
context: any;
listData: any[];
}
export default class FabricUiNestingWebPart extends BaseClientSideWebPart<IFabricUiNestingWebPartProps> {
// Environment Checker
private get _isSharePoint(): boolean {
return (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint);
}
private _getListItems(): Promise<any[]> {
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getByTitle('NewYearsParty')/items", SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
})
.then(jsonResponse => {
return jsonResponse.value;
}) as Promise<any[]>;
}
public render(): void {
// Check if the app is running on local or online environment
if (!this._isSharePoint) {
console.log("LOCAL");
this.checkConditionPassToRender(mockData);
} else {
// If online then grab the list and .THEN once that is done render the component to the DOM.
console.log("ONLINE");
this._getListItems().then(response => {
this.checkConditionPassToRender(response);
});
}
}
private checkConditionPassToRender(listData:any[]) {
const element: React.ReactElement<IFabricUiNestingProps> = React.createElement(
FabricUiNesting,
{
description: this.properties.description,
context: this.context,
listData: listData
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}
<file_sep>export interface IListPageProps {
listData: any[];
}
export interface IListPageState {
listData: any[];
modalOpen: boolean;
modalIndexValue: number;
}
|
f0311db9b6eb871d1ba98881718900b03240a1ca
|
[
"TypeScript"
] | 4 |
TypeScript
|
VB6Hobbyst7/FabricUiNesting
|
b224eabdd6e210f022c774bc74e9791cb720ec1e
|
ef5856b5edb0d14d7780c5eb47f70cda7858ed0e
|
refs/heads/master
|
<file_sep>import java.util.Scanner;
public class QuadraticEquation {
double a,b,c;
double delta;
public QuadraticEquation(){
}
public QuadraticEquation(double a,double b, double c){
this.a=a;
this.b=b;
this.c=c;
this.delta=delta;
}
public double Discriminant(){
this.delta= (this.b*this.b-4*this.a*this.c);
return delta;
}
public double Root1(){
return (-this.b+Math.pow(this.delta,0.5)/(2*this.a));
}
public double Root2(){
return (-this.b-Math.pow(this.delta,0.5)/(2*this.a));
}
}
class Display{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a,b,c:");
double a=sc.nextDouble();
double b=sc.nextDouble();
double c=sc.nextDouble();
QuadraticEquation quadraticequation = new QuadraticEquation(a,b,c);
if (quadraticequation.Discriminant()>0){
System.out.println("Root1= "+quadraticequation.Root1()+", Root2="+ quadraticequation.Root2());
}else if(quadraticequation.Discriminant()==0){
System.out.println("Root= "+quadraticequation.Root1());
}else {
System.out.println("No Root");
}
}
}
|
d21413df8ad0997f92f5ad6c5935f70c55f3714f
|
[
"Java"
] | 1 |
Java
|
Dungqa/session3WBC
|
ed1d0ac1038b664ad31c4fb45aedae91fa70064d
|
3c79a0d138b4d2108d2461cbb1c64080291f414f
|
refs/heads/master
|
<repo_name>Luisdanielmartinez/example-realm<file_sep>/AppRealm/AppRealm/Connection/RealmConnection.cs
using Realms;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AppRealm.Connection
{
public static class RealmConnection
{
public static Realm getConnection()
{
Realm r = null;
try
{
var con = new RealmConfiguration("myappDb.realm");
System.Diagnostics.Debug.WriteLine(con.DatabasePath);
r = Realm.GetInstance(con);
}
catch (Exception ex)
{
App.Current.MainPage.DisplayAlert("Error",$"este es el error{ex.Message}","Ok");
}
return r;
}
}
}
<file_sep>/AppRealm/AppRealm/Views/LoginPage.xaml.cs
using AppRealm.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace AppRealm.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
private LoginViewModel model;
public LoginPage()
{
InitializeComponent();
model = new LoginViewModel();
BindingContext = model;
}
}
}<file_sep>/AppRealm/AppRealm/Models/User.cs
using Realms;
using System;
using System.Collections.Generic;
using System.Text;
namespace AppRealm.Models
{
public class User : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
}
<file_sep>/AppRealm/AppRealm/ViewModels/LoginViewModel.cs
using AppRealm.Views;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
namespace AppRealm.ViewModels
{
public class LoginViewModel : BaseViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public ICommand LoginCommand => new RelayCommand(validaterLogin);
public ICommand RegisterCommand => new RelayCommand(goToRegister);
public LoginViewModel()
{
}
public async void validaterLogin()
{
var user = await DataStoreUser.GetUserByUserName(UserName,Password);
if (user==null)
{
await App.Current.MainPage.DisplayAlert("Info","Usuario o Contraseña estan incorrectas","ok");
return;
}
App.Current.MainPage=new AppShell();
}
public async void goToRegister()
{
await App.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(new RegisterPage()));
}
}
}
<file_sep>/AppRealm/AppRealm/Services/UserRepo.cs
using AppRealm.Connection;
using AppRealm.Models;
using Realms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppRealm.Services
{
public class UserRepo : IDataUser<User>
{
private Realm db;
public UserRepo()
{
db = RealmConnection.getConnection();
}
public async Task<bool> AddItemAsync(User item)
{
if (item==null)
{
return await Task.FromResult(false);
}
db.Write(() =>
{
db.Add(item);
});
return await Task.FromResult(true);
}
public async Task<bool> DeleteItemAsync(string id)
{
var user = db.Find<User>(id);
db.Remove(user);
return await Task.FromResult(true);
}
public async Task<bool> UpdateItemAsync(User item)
{
var user = db.Find<User>(item.Id);
db.Remove(user);
db.Add(item);
return await Task.FromResult(true);
}
public async Task<User> GetUserByUserName(string username,string password)
{
var myPuppy = db.All<User>().First(u => u.UserName == username && u.Password==<PASSWORD>);
return await Task.FromResult(myPuppy);
}
}
}
<file_sep>/AppRealm/AppRealm/Services/IDataUser.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AppRealm.Services
{
public interface IDataUser<T>
{
Task<bool> AddItemAsync(T item);
Task<bool> UpdateItemAsync(T item);
Task<bool> DeleteItemAsync(string id);
Task<T> GetUserByUserName(string userName, string password);
}
}
<file_sep>/AppRealm/AppRealm/ViewModels/RegisterViewModel.cs
using AppRealm.Models;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace AppRealm.ViewModels
{
public class RegisterViewModel:BaseViewModel
{
private User user;
public string UserName { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public ICommand SaveCommand => new RelayCommand(saveData);
public ICommand CancelCommand => new RelayCommand(Cancel);
public RegisterViewModel()
{
}
private async void saveData()
{
user = new User {
UserName = this.UserName,
Name = this.Name,
Password=<PASSWORD>
};
var response = await DataStoreUser.AddItemAsync(user);
if (!response)
{
await App.Current.MainPage.DisplayAlert("Error","Error al insertar los datos","ok");
return;
}
await App.Current.MainPage.DisplayAlert("Info", "Se insertaron los datos correctamente", "ok");
await App.Current.MainPage.Navigation.PopModalAsync();
}
private async void Cancel()
{
await App.Current.MainPage.Navigation.PopModalAsync();
}
}
}
|
93e5cb4eb971f812d6634195f80620c49e01e75b
|
[
"C#"
] | 7 |
C#
|
Luisdanielmartinez/example-realm
|
82ba040a24bcef63b87b674225af78d7edeace67
|
4198a44a5798993912904597a700ba4e36ea5cc7
|
refs/heads/master
|
<repo_name>davemcg3/gilded-rose<file_sep>/README.md
# Gilded Rose
## Task
Implemented code for `Conjured Mana Cake`.
## Running the Specs
To run the specs, you will need the RSpec gem. Open a terminal window,
and run the following command in the exercise directory:
bundle install
You can run the specs from the exercise directory. Execute the
following command:
rspec spec
To use the refactored gilded rose class set the environment variable REFACTORED_GILDED_ROSE to true with the following command:
export REFACTORED_GILDED_ROSE=true
Then you can run the spec as defined above.
When finished, to permanently remove the environment variable simply run:
unset REFACTORED_GILDED_ROSE
<file_sep>/lib/gilded_rose_v2.rb
require 'active_support/inflector'
# More readable version of Gilded Rose class
class GildedRoseV2
attr_reader :name, :lookup, :days_remaining, :quality
ITEM_HASH = {
normal_item: :quality_decreases,
aged_brie: :quality_increases,
sulfuras_hand_of_ragnaros: :quality_stays_the_same,
backstage_passes_to_a_tafkal80etc_concert: :quality_rapidly_increases,
conjured_mana_cake: :quality_rapidly_decreases
}.freeze
TRAITS = {
# logically the first should be a 2 but we use a map and increment each time
quality_rapidly_increases: 1,
quality_increases: 1,
quality_stays_the_same: 0,
quality_decreases: -1,
quality_rapidly_decreases: -2
}.freeze
NO_QUALITY = 0
MAX_QUALITY = 50
NO_DAYS_REMAINING_ON_SELL_DATE = 0
DAYS_WHERE_QUALITY_INCREASES = [11, 6].freeze
DAYS_TO_DECREMENT = 1
def initialize(name:, days_remaining:, quality:)
@name = name
# symbols are faster than strings
@lookup = name.parameterize.underscore.to_sym
@days_remaining = days_remaining
@quality = quality
end
def tick
change_quality
rapidly_increase_quality
decrement_days_remaining
return unless no_days_remaining
if ITEM_HASH[lookup].equal?(:quality_rapidly_increases)
zero_out_quality
else
change_quality
end
end
private
def change_quality
return unless (quality_step.positive? && quality < MAX_QUALITY) ||
(quality_step.negative? && quality > NO_QUALITY)
@quality += quality_step
end
def rapidly_increase_quality
return unless ITEM_HASH[lookup].equal? :quality_rapidly_increases
DAYS_WHERE_QUALITY_INCREASES.map do |day_that_matters|
change_quality if days_remaining < day_that_matters
end
end
def zero_out_quality
@quality = NO_QUALITY
end
def quality_step
TRAITS[ITEM_HASH[lookup]]
end
def decrement_days_remaining
return if ITEM_HASH[lookup].equal? :quality_stays_the_same
@days_remaining -= DAYS_TO_DECREMENT
end
def no_days_remaining
days_remaining < NO_DAYS_REMAINING_ON_SELL_DATE
end
end
<file_sep>/spec/gilded_rose_spec.rb
require 'spec_helper'
require_relative '../lib/gilded_rose'
if ENV['REFACTORED_GILDED_ROSE'] == 'true'
require_relative '../lib/gilded_rose_v2'
end
RSpec.describe GildedRose do
before :each do
if ENV['REFACTORED_GILDED_ROSE'] == 'true'
stub_const('GildedRose', GildedRoseV2)
end
end
subject(:gilded_rose) do
GildedRose.new(name: name, days_remaining: days_remaining, quality: quality)
end
context 'Normal Item' do
let(:name) { 'Normal Item' }
context 'of high quality' do
let(:quality) { 10 }
context 'before sell date' do
let(:days_remaining) { 5 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should diminish in quality by 1' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(9)
end
end
context 'on sell date' do
let(:days_remaining) { 0 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should diminish in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(8)
end
end
context 'after sell date' do
let(:days_remaining) { -10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should diminish in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(8)
end
end
end
context 'of no quality' do
let(:days_remaining) { 5 }
let(:quality) { 0 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should remain of no quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context '<NAME>' do
let(:name) { '<NAME>' }
context 'before sell date' do
let(:days_remaining) { 5 }
context 'with moderate quailty' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should improve in quality by 1' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(11)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'on sell date' do
let(:days_remaining) { 0 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should improve in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(12)
end
end
context 'with near max quality' do
let(:quality) { 49 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should improve quality to max' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(49).to(50)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'after sell date' do
let(:days_remaining) { -10 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should improve in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(12)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
end
context 'Sulfuras, Hand of Ragnaros' do
let(:name) { 'Sulfuras, <NAME>' }
let(:quality) { 80 }
context 'before sell date' do
let(:days_remaining) { 5 }
it 'should remain at the same days remaining' do
expect { gilded_rose.tick }.to_not change { gilded_rose.days_remaining }
end
it 'should remain at the same quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
context 'on sell date' do
let(:days_remaining) { 0 }
it 'should remain at the same days remaining' do
expect { gilded_rose.tick }.to_not change { gilded_rose.days_remaining }
end
it 'should remain at the same quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
context 'after sell date' do
let(:days_remaining) { -10 }
it 'should remain at the same days remaining' do
expect { gilded_rose.tick }.to_not change { gilded_rose.days_remaining }
end
it 'should remain at the same quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'Backstage passes to a TAFKAL80ETC concert' do
let(:name) { 'Backstage passes to a TAFKAL80ETC concert' }
context 'with 11 days to sell date' do
let(:days_remaining) { 11 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(11).to(10)
end
it 'should improve in quality by 1' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(11)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(11).to(10)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'with 10 days to sell date' do
let(:days_remaining) { 10 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(10).to(9)
end
it 'should improve in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(12)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(10).to(9)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'with 6 days to sell date' do
let(:days_remaining) { 6 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(6).to(5)
end
it 'should improve in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(12)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(6).to(5)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'with 5 days to sell date' do
let(:days_remaining) { 5 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should improve in quality by 3' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(13)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'with 1 day to sell date' do
let(:days_remaining) { 1 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(1).to(0)
end
it 'should improve in quality by 3' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(13)
end
end
context 'with max quality' do
let(:quality) { 50 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(1).to(0)
end
it 'should remain at max quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'on sell date' do
let(:days_remaining) { 0 }
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should have no quality' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(0)
end
end
context 'after sell date' do
let(:days_remaining) { -10 }
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should have no quality' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(0)
end
end
end
context 'Conjured Mana Cake' do
let(:name) { '<NAME>' }
context 'before sell date' do
let(:days_remaining) { 5 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should diminish in quality by 2' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(8)
end
end
context 'with no quality' do
let(:quality) { 0 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(5).to(4)
end
it 'should remain at no quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'on sell date' do
let(:days_remaining) { 0 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should diminish in quality by 4' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(6)
end
end
context 'with no quality' do
let(:quality) { 0 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(0).to(-1)
end
it 'should remain at no quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
context 'after sell date' do
let(:days_remaining) { -10 }
context 'with moderate quality' do
let(:quality) { 10 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should diminish in quality by 4' do
expect { gilded_rose.tick }.to change { gilded_rose.quality }
.from(10).to(6)
end
end
context 'with no quality' do
let(:quality) { 0 }
it 'should have one less day remaining' do
expect { gilded_rose.tick }.to change { gilded_rose.days_remaining }
.from(-10).to(-11)
end
it 'should remain at no quality' do
expect { gilded_rose.tick }.to_not change { gilded_rose.quality }
end
end
end
end
end
|
92c07437ada045eae2b2de33858e0363b28f0d17
|
[
"Markdown",
"Ruby"
] | 3 |
Markdown
|
davemcg3/gilded-rose
|
6f859a463ae632f9fe482bcc8fb402bd5978cf1c
|
ca53c5923e17bf1ee4d75430af819b96309bf0b3
|
refs/heads/master
|
<repo_name>Mothrakk/Downvote_Nuke<file_sep>/Downvote Nuke/Program.cs
using System;
using System.Collections.Generic;
using RedditSharp;
using System.IO;
using System.Security.Authentication;
using RedditSharp.Things;
using System.Threading;
using System.Threading.Tasks;
namespace Downvote_Nuke
{
class Program
{
static void Main(string[] args)
{
Reddit reddit = new Reddit();
Dictionary<string, string> accounts = readAccountsFromFile();
Uri uri = getUri();
foreach (var entry in accounts)
{
try
{
Console.WriteLine("Logging in as " + entry.Key.ToString());
AuthenticatedUser user = reddit.LogIn(entry.Key, entry.Value);
Console.WriteLine("Logged in as " + entry.Key.ToString());
Console.WriteLine("Getting post..");
Comment comment = reddit.GetComment(uri);
Console.WriteLine("Downvoting..");
comment.Downvote();
Console.WriteLine("Downvoted!");
}
catch (AuthenticationException e)
{
Console.WriteLine(e.Message);
}
}
Console.WriteLine("Accounts exhausted");
Console.ReadKey();
}
/// <summary>
/// Asks the user to type in a URI
/// </summary>
/// <returns>an Uri instance</returns>
private static Uri getUri()
{
string uriAsString;
bool correctUri = true;
do
{
if (!correctUri)
{
Console.WriteLine("Not a valid URL");
}
Console.WriteLine("Insert full URL");
uriAsString = Console.ReadLine();
correctUri = Uri.IsWellFormedUriString(uriAsString, UriKind.Absolute);
} while (!correctUri);
return new Uri(uriAsString);
}
/// <summary>
/// Reads the account information from a file
/// </summary>
/// <returns>A dictionary containing the username as the key and the password as the value</returns>
private static Dictionary<string, string> readAccountsFromFile()
{
string fileLocation = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "/accountinfo.txt";
string[] lines = File.ReadAllLines(fileLocation);
var accounts = new Dictionary<string, string>();
foreach (string line in lines)
{
string[] accountInfo = line.Split(' ');
accounts.Add(accountInfo[0], accountInfo[1]);
}
return accounts;
}
}
}
<file_sep>/Downvote Forms/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RedditSharp;
using System.IO;
namespace Downvote_Forms
{
public partial class Form1 : Form
{
BackgroundWorker m_oWorker;
public Form1()
{
InitializeComponent();
m_oWorker = new BackgroundWorker();
m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
}
bool isUpvote;
bool isPostVote;
bool isCommentVote;
bool isReplyToComment;
bool isReplyToPost;
bool status = false;
int actioncounter;
string replyText;
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
if (e.Error is System.UriFormatException)
{
textBox.Text = "Invalid URL";
}
else if(e.Error is System.Net.WebException)
{
textBox.Text = "Reddit is currently having problems";
}
else
{
textBox_Reply.Text = e.Error.ToString();
}
}
else if (e.Cancelled)
{
textBox.Text = ("Process cancelled, " + actioncounter + " action(s) applied");
}
else
{
textBox.Text = ("Accounts exhausted, " + actioncounter + " actions applied");
}
statusChange();
reset();
}
private Dictionary<string, string> readAccountsFromFile()
{
string fileLocation = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "/accountinfo.txt";
label_accountsCounter.Text = ("/ " +File.ReadLines(fileLocation).Count());
string[] lines = File.ReadAllLines(fileLocation);
var accounts = new Dictionary<string, string>();
foreach (string line in lines)
{
string[] accountInfo = line.Split(' ');
accounts.Add(accountInfo[0], accountInfo[1]);
Console.WriteLine(accountInfo[0] + " : " + accountInfo[1]);
}
return accounts;
}
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
var reddit = new Reddit();
var accounts = readAccountsFromFile();
actioncounter = 0;
label_actionCounter.Text = 0.ToString();
Uri posturi = new Uri(textBox.Text);
foreach (var entry in accounts)
{
if (m_oWorker.CancellationPending)
{
e.Cancel = true;
button_Pasteenter.Enabled = true;
return;
}
var user = reddit.LogIn(entry.Key, entry.Value);
if (isReplyToComment || isCommentVote)
{
var post = reddit.GetComment(posturi);
if (isCommentVote && isUpvote)
{
post.Upvote();
}
else if (isCommentVote && isUpvote == false)
{
post.Downvote();
}
else
{
post.Reply(replyText);
}
}
else
{
var post = reddit.GetPost(posturi);
if (isPostVote && isUpvote)
{
post.Upvote();
}
else if (isPostVote && isUpvote == false)
{
post.Downvote();
}
else if (isReplyToPost)
{
post.Comment(replyText);
}
}
actioncounter = (actioncounter + 1);
label_actionCounter.Text = actioncounter.ToString();
}
}
private void reset()
{
isUpvote = false;
isReplyToComment = false;
isPostVote = false;
isCommentVote = false;
isReplyToPost = false;
}
private void statusChange()
{
if (status)
{
status = false;
button_Pasteenter.Text = "Paste from Clipboard and Run";
label_status.Text = "Not Running";
label_status.ForeColor = Color.Red;
textBox_Reply.Enabled = true;
}
else
{
status = true;
button_Pasteenter.Text = "Cancel";
label_status.Text = "Running";
label_status.ForeColor = Color.Green;
textBox_Reply.Enabled = false;
}
}
private void button_Pasteenter_Click(object sender, EventArgs e)
{
if (status)
{
m_oWorker.CancelAsync();
label_status.Text = "Cancelling..";
label_status.ForeColor = Color.Blue;
button_Pasteenter.Enabled = false;
}
else
{
textBox.Text = Clipboard.GetText();
if (radioButton_Upvote.Checked)
{
isUpvote = true;
}
else
{
isUpvote = false;
}
if (radioButton_Post.Checked)
{
isPostVote = true;
}
else if (radioButton_Comment.Checked)
{
isCommentVote = true;
}
else if(radioButton_ReplyComment.Checked)
{
isReplyToComment = true;
}
else if (radioButton_ReplyPost.Checked)
{
isReplyToPost = true;
}
replyText = textBox_Reply.Text;
statusChange();
m_oWorker.RunWorkerAsync();
}
}
}
}
|
75394238b6393c17666847f969ba9c11dd58c734
|
[
"C#"
] | 2 |
C#
|
Mothrakk/Downvote_Nuke
|
e9860bb5293c8a59c955a7a857dfa9ef6adc6efd
|
e57789599832388e57d1dc0c1d6866352cded454
|
refs/heads/master
|
<repo_name>apache7140/CBIR-<file_sep>/feature_matching.py
import cv2
import numpy as np
img1=cv2.imread("C:/Users/Rishabh/Pictures/Camera Roll/WIN_20200502_005310.JPG", cv2.IMREAD_GRAYSCALE)
img2=cv2.imread("C:/Users/Rishabh/Pictures/Camera Roll/WIN_20200502_005317.JPG", cv2.IMREAD_GRAYSCALE)
#ORB Detector
'''
cv2.imshow("img",img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
orb= cv2.ORB_create()
kp1,des1 = orb.detectAndCompute(img1,None)
kp2,des2 = orb.detectAndCompute(img2,None)
for d in des1:
print(d)
#Brute Force Matcher
# =============================================================================
#
# bf=cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=True)
# matches = bf.match(des1,des2)
# matches = sorted(matches, key=lambda x:x.distance)
#
# for m in matches:
# print(m.distance)
# matching_result=cv2.drawMatches(img1,kp1,img2,kp2,matches[40:80],None)
#
#
# cv2.imshow("img",img1)
# cv2.imshow("img2",img2)
# cv2.imshow("matching_result",matching_result)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
# =============================================================================
<file_sep>/Feature_Extraction_SIFT.py
import cv2
import numpy as np
import glob
import csv
import uuid
import os as os
from pathlib import Path
import pandas as pd
class Feature_Extraction_SIFT:
def feature_extraction(self, path, index_path):
all_images_to_compare = []
titles = []
print("Block1")
for f in glob.iglob(path):
image = cv2.imread(f)
#query_img_bw = cv2.cvtColor(query_img,cv2.COLOR_BGR2GRAY)
#image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
all_images_to_compare.append(image)
titles.append(f)
print(f)
return all_images_to_compare,titles
def ArrayToFile(self,title, descriptor):
uid=uuid.uuid1()
array_path = desc_path + str(uid) +'.txt'
try:
array_path=Path(array_path)
np.savetxt(array_path,np.array(descriptor), fmt='%.0f',delimiter=",")
except Exception :
print(Exception)
return array_path
def writingDescriptorToCSV(self,all_images_to_compare,titles):
print('Going to Write to the index file')
output = open(index_path, "w")
for all_images_to_compare_temp, title in zip(all_images_to_compare, titles):
print("Reached Here")
#orb = cv2.ORB_create()
sift = cv2.xfeatures2d.SIFT_create()
kp,descriptors = sift.detectAndCompute(all_images_to_compare_temp, None)
#orb.detectAndCompute(all_images_to_compare_temp, None)
self.desc_arr_1=descriptors
number_of_keypoints = str(len(kp))
array_path=self.ArrayToFile(title,descriptors)
output.write("%s,%s,%s,\n" % (title,number_of_keypoints,array_path))
print("Writing done for"+title)
output.close()
def queryImage(self, query_path):
query_image = cv2.imread(query_path)
# query_image=cv2.cvtColor(query_image,cv2.COLOR_BGR2GRAY)
cv2.imshow("query_image", query_image)
cv2.waitKey(0)
# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create()
sift = cv2.xfeatures2d.SIFT_create()
kp, descriptors = sift.d.etectAndCompute(query_image, None)
length_kp_query = len(kp)
print("length_of_query_keypoint:" + str(length_kp_query))
return descriptors, length_kp_query
def fileInput(self,query_image_desc,len_kp_query):
index_params = dict(algorithm=0, trees=5)
search_params = dict()
flann = cv2.FlannBasedMatcher(index_params, search_params)
fileHandle = open('index.csv','r')
list_title=[]
list_percentage = []
for line in fileHandle:
fields = line.split(',')
title = fields[0]
kp_1=int(fields[1])
array_path=Path(fields[2])
arr=np.loadtxt(array_path,delimiter=",")
ex1=np.asarray(arr,np.float32)
ex2=np.asarray(query_image_desc,np.float32)
matches = flann.knnMatch(ex1,ex2,k=2)
good_points = []
for m, n in matches:
if m.distance < 0.7 * n.distance:
good_points.append(m)
number_keypoints = 0
if (kp_1 >= len_kp_query):
number_keypoints = kp_1
else:
number_keypoints = len_kp_query
print("Title : " + title)
print("number_of_keyPoints"+str(number_keypoints))
print('length_of_good_points'+str(len(good_points)))
#calculation of the Rank
percentage_similarity = len(good_points) / number_keypoints * 100
print("similarity : ", str(int(percentage_similarity)) + "%")
list_title.append(title)
list_percentage.append(percentage_similarity)
fileHandle.close()
return self.convertingRawDataIntoDataFrames(list_title, list_percentage)
def convertingRawDataIntoDataFrames(self,list_titles,list_percentage):
d= {'title':list_titles,'percentages':list_percentage}
df = pd.DataFrame(d)
df=df.sort_values(by=['percentages'],ascending=False)
for a in df :
print(a)
print(df)
return "successfull"
def deleteFiles(self, desc_path):
filelist = [f for f in os.listdir(desc_path)]
for f in filelist:
print(f)
os.remove(os.path.join(desc_path, f))
print(f + " deleted!")
#path = "C:/Users/Rishabh/Desktop/CBIR/HOGDescriptor/Images/*.jpg"
print('***************sift Method******************')
desc_path="Descriptor_sift/"
path="Images/*.jpg"
index_path = "index_sift.csv"
query_image_path="Images/100.jpg"
#just remove the comments down below
'''
#initialize the object
f = Feature_Extraction_ORB()
f.deleteFiles(desc_path)
#initialize the object
'''
f = Feature_Extraction_SIFT()
#extracting descriptors from the images
all_images_to_compare,titles=f.feature_extraction(path, index_path)
#putting all of it into a file
f.writingDescriptorToCSV(all_images_to_compare,titles)
#querying image
query_image_desc,len_kp_query=f.queryImage(query_image_path)
abc=f.fileInput(query_image_desc,len_kp_query)
print(abc)
print("Successfull")
<file_sep>/adriansCode.py
import cv2
import numpy as np
import glob
orignal = cv2.imread("Images/orignal.jpg")
# =============================================================================
#for loading only single image
#image_to_compare = cv2.imread("Images/little_darker.jpg")
#
# =============================================================================
#for loading multiple images
#for f in glob.iglob(r"C:\Users\Rishabh\Desktop\Python In One Video\Project(ImageFetureExtraction)\Programs\Images\*") :
all_images_to_compare = []
titles = []
for f in glob.iglob("Images\*"):
image = cv2.imread(f)
all_images_to_compare.append(image)
titles.append(f)
for image_to_compare, title in zip(all_images_to_compare,titles):
image1=orignal.shape
#image2=image_to_compare.shape
# =============================================================================
#
# print(image1)
# print(image2)
#
# =============================================================================
# 1) check if 2 images are equal
if orignal.shape==image_to_compare.shape:
difference = cv2.subtract(orignal,image_to_compare)
b,g,r=cv2.split(difference)
# cv2.imshow("difference",difference)
print(cv2.countNonZero(b))
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) ==0 :
print("images are completely equal")
else:
print("they are different")
# 2)check for similarities between the 2 images
sift=cv2.xfeatures2d.SIFT_create()
orb=cv2.ORB_create()
#kp_1,descriptor_1=sift.detectAndCompute(orignal,None)
#kp_2,descriptor_2=sift.detectAndCompute(image_to_compare,None)
kp_1,descriptor_1=orb.detectAndCompute(orignal,None)
kp_2,descriptor_2=orb.detectAndCompute(image_to_compare,None)
print("Keypoints 1st Image : "+ str(len(kp_1)))
print("Keypoints 2nd Image : "+ str(len(kp_2)))
index_params = dict(algorithm=0,trees=5)
search_params = dict()
descriptor_1=np.asarray(descriptor_1,np.float32)
descriptor_2=np.asarray(descriptor_2,np.float32)
flann=cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(descriptor_1,descriptor_2,k=2)
good_points = []
print("len of matches"+str(len(matches)))
for m,n in matches:
if m.distance < 0.6*n.distance:
good_points.append(m)
print("good points length"+str(len(good_points)))
number_keypoints=0
if(len(kp_1) >= len(kp_2)):
number_keypoints = len(kp_1)
else:
number_keypoints = len(kp_2)
print("Title : "+title)
#print(len(matches))
#print("Good Matches:",len(good_points))
percentage_similarity =len(good_points)/number_keypoints*100
print("similarity : ", str(int(percentage_similarity)) + "%")
#result = cv2.drawMatchesKnn(orignal,kp_1,image_to_compare,kp_2,matches,None)
result=cv2.drawMatches(orignal,kp_1,image_to_compare,kp_2,good_points,None)
# =============================================================================
# cv2.imshow("result",result)
#
# cv2.imshow("orignal",orignal)
# cv2.imshow("image_to_compare",image_to_compare)
# =============================================================================
print("--------------------------------------")
# =============================================================================
# cv2.waitKey(0)
# cv2.destroyAllWindows();
#
# =============================================================================
#for resizing we can use this script
#cv2.resize(image_to_compare,None,fx=0.4,fy=0.4)
|
e201c587449262057c594343e276c7520df3888f
|
[
"Python"
] | 3 |
Python
|
apache7140/CBIR-
|
ef870ee16fc7034185b6010c605c674ceb493db9
|
cfce549b2850f9053e4f072a11c4c1e793c9c5dc
|
refs/heads/master
|
<file_sep>import express from "express";
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Sever started on port : ${port}`);
});
|
57e5e8b95a5d94ab3e0dafcbc5f9396878cd014b
|
[
"TypeScript"
] | 1 |
TypeScript
|
rafaelmennabarreto/ProApplicationApi
|
50703dd34824373fa860592894042d8ccdbd20f6
|
50fda94523e5328f620526ae4d7f68438e7fc091
|
refs/heads/master
|
<file_sep>//
// main.cpp
// ImageAnalysis_Assignment3
//
// Created by <NAME> on 02/04/16.
// Copyright © 2015 <NAME>. All rights reserved.
//
/*
Question 3 and 4 :
Report of comparison attached.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <string>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/objdetect/objdetect.hpp"
#define PI 3.14159265
#define min(i, j) (i <= j ? i : j)
#define INF 10000
using namespace std;
using namespace cv;
void displayImage(Mat , string);
Mat convertVec3bToBinary(Mat );
Mat medianFilter(Mat );
Mat erosion(Mat , int **arr, int);
Mat dilation(Mat , int **arr, int);
void genStructingElement1(int , int **arr);
Mat diff(Mat , Mat );
int countBead(Mat , int **arr, int);
Mat keyPoints(Mat );
vector < vector < float > > HOG(Mat );
float cosine_dis(vector < float > , vector < float > );
Mat lbp(Mat );
int lbpValue(int [][5]);
void faceDivide(Mat , vector < int > [64]);
float chiSquareDiff(vector < int > [64], vector < int > [64]);
Mat GetSkin(Mat );
int main(int argc, const char * argv[])
{
cout << "HOG Loop computation : " << endl;
int accuracy = 0;
int ctr=0;
for (int i1 = 0; i1 < 10; i1++)
{
for (int j1 = 5; j1 <= 10; j1++)
{
ctr+=1;
float MIN = 100000.0;
int imagePos1 = -1;
int imagePos2 = -1;
for (int l1 = 0; l1 < 10; l1++) {
for (int k1 = 1; k1 <= 4; k1++) {
float result = 0.0;
Mat orgImg1, orgImg2;
// char first1[] = "/Users/mridul/Shakespeer/Telegram/Slides/FaceImages/";
char first1[]="/Users/mridul/HGR/Datasets/scaledDataset/";
stringstream f1;
f1 << first1;
stringstream m1, m2, m3;
m1 << i1;
m2 << "_";
m3 << j1;
char end1[] = ".jpg";
stringstream e1;
e1 << end1;
f1 << m1.str();
f1 << m2.str();
f1 << m3.str();
f1 << e1.str();
orgImg1 = imread(f1.str(), 0);
cout <<"Source: "<< f1.str() << endl;
if(orgImg1.empty()) {
cout << "Image not loaded properly." << endl;
return 0;
}
// displayImage(orgImg1, "Original Image 1");
Mat keyImg1 = keyPoints(orgImg1);
vector < vector < float > > des1 = HOG(keyImg1);
// char first2[]="/Users/mridul/Shakespeer/Telegram/Slides/FaceImages/";
char first2[] = "/Users/mridul/HGR/Datasets/scaledDataset/";
stringstream f2;
f2 << first2;
stringstream m11, m12, m13;
m11 << l1;
m12 << "_";
m13 << k1;
char end2[] = ".jpg";
stringstream e2;
e2 << end2;
f2 << m11.str();
f2 << m12.str();
f2 << m13.str();
f2 << e2.str();
orgImg2 = imread(f2.str(), 0);
cout <<"Destination: "<< f2.str() << endl;
// displayImage(orgImg2, "Original Image 2");
if(orgImg2.empty()) {
cout << "Image not loaded properly." << endl;
return 0;
}
Mat keyImg2 = keyPoints(orgImg2);
vector < vector < float > > des2 = HOG(keyImg2);
float answer = 0;
for (int i = 0; i < 16; i++) {
answer += cosine_dis(des1[i], des2[i]);
}
// cout<<"Answer is "<<answer<<endl;
result = (answer/16.0);
// cout<<"prelim result for "<<f1.str()<<" with "<<f2.str()<<" is "<<result<<endl;
if (result < MIN) {
MIN = result;
imagePos1 = l1;
imagePos2 = k1;
}
}
}
cout << endl;
cout << "Image " << i1 << "_" << j1 << ".jpg minimum cosine measure : " << MIN << "." << endl;
cout << "Best match of image " << i1 << "_" << j1 << ".jpg is image " << imagePos1 << "_" << imagePos2 << ".png" << endl;
if (imagePos1 == i1)
accuracy++;
}
}
cout << endl;
cout << "Accuracy : " << (accuracy*100.0)/ctr << "% "<< endl;
// --------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------
// Local Binary Pattern
// --------------------------------------------------------------------------------------------------------
// Mat orgImg1;
// orgImg1 = imread("/Users/lifecodemohit/Documents/IIITD_Sem5/ImageAnalysis/Slides/FaceImages/1_10.jpg", 0);
//
// if(orgImg1.empty()) {
// cout << "Image not loaded properly." << endl;
// return 0;
// }
//
// displayImage(orgImg1, "Original Image 1");
//
// Mat orgImg2;
// orgImg2 = imread("/Users/lifecodemohit/Documents/IIITD_Sem5/ImageAnalysis/Slides/FaceImages/9_2.jpg", 0);
//
// if(orgImg2.empty()) {
// cout << "Image not loaded properly." << endl;
// return 0;
// }
//
// displayImage(orgImg2, "Original Image 2");
//
// Mat lbpImg1 = lbp(orgImg1);
// Mat lbpImg2 = lbp(orgImg2);
//
// vector < int > Reg1[64];
// vector < int > Reg2[64];
//
// for (int i = 0;i < 64; i++) Reg1[i].clear();
// faceDivide(lbpImg1, Reg1);
// for (int i = 0;i < 64; i++) Reg2[i].clear();
// faceDivide(lbpImg2, Reg2);
//
// float result = chiSquareDiff(Reg1, Reg2);
// cout << result << endl;
// --------------------------------------------------------------------------------------------------------
// LBP 3 Loop computation
// --------------------------------------------------------------------------------------------------------
//
// cout << "LBP loop computation : " << endl;
// int accuracy = 0;
// for (int i1 = 0; i1 < 10; i1++) {
// for (int j1 = 5; j1 <= 10; j1++) {
// int MIN = INT_MAX;
// int imagePos1 = -1;
// int imagePos2 = -1;
// for (int l1 = 0; l1 < 10; l1++) {
// for (int k1 = 1; k1 <= 4; k1++) {
// float result = 0.0;
// Mat orgImg1;
//
// char first1[] = "/Users/mridul/HGR/Datasets/scaledDataset/";
// stringstream f1;
// f1 << first1;
//
// stringstream m1, m2, m3;
// m1 << i1;
// m2 << "_";
// m3 << j1;
//
// char end1[] = ".jpg";
// stringstream e1;
// e1 << end1;
//
// f1 << m1.str();
// f1 << m2.str();
// f1 << m3.str();
// f1 << e1.str();
//
// orgImg1 = imread(f1.str(), 0);
//// cout << f1.str() << endl;
//
// if(orgImg1.empty()) {
// cout << f1.str()<<" Image not loaded properly." << endl;
// return 0;
// }
//
// // displayImage(orgImg1, "Original Image 1");
//
// Mat orgImg2;
// char first2[] = "/Users/mridul/HGR/Datasets/scaledDataset/";
// stringstream f2;
// f2 << first2;
//
// stringstream m11, m12, m13;
// m11 << l1;
// m12 << "_";
// m13 << k1;
//
// char end2[] = ".jpg";
// stringstream e2;
// e2 << end2;
//
// f2 << m11.str();
// f2 << m12.str();
// f2 << m13.str();
// f2 << e2.str();
//
// orgImg2 = imread(f2.str(), 0);
//
//// cout << f2.str() << endl;
//
// if(orgImg2.empty()) {
// cout << f2.str()<<" Image not loaded properly." << endl;
// return 0;
// }
//
// // displayImage(orgImg2, "Original Image 2");
//
// Mat lbpImg1 = lbp(orgImg1);
// Mat lbpImg2 = lbp(orgImg2);
//
// vector < int > Reg1[64];
// vector < int > Reg2[64];
//
// for (int i = 0;i < 64; i++) Reg1[i].clear();
// faceDivide(lbpImg1, Reg1);
// for (int i = 0;i < 64; i++) Reg2[i].clear();
// faceDivide(lbpImg2, Reg2);
//
// result = chiSquareDiff(Reg1, Reg2);
// if (result < MIN) {
// MIN = result;
// imagePos1 = l1;
// imagePos2 = k1;
// }
// }
// }
// cout << endl;
// cout << "Image " << i1 << "_" << j1 << ".jpg minimum chi square : " << MIN << "." << endl;
// cout << "Best match of image " << i1 << "_" << j1 << ".jpg is image " << imagePos1 << "_" << imagePos2 << ".jpg" << endl;
// if (imagePos1 == i1)
// accuracy++;
// }
// }
//
// cout << endl;
// cout << "Accuracy : " << (accuracy*100.0)/60.0 << "% "<< endl;
// --------------------------------------------------------------------------------------------------------
return 0;
}
void displayImage(Mat img, string text) {
namedWindow(text, WINDOW_AUTOSIZE );
imshow(text,img);
waitKey(0);
// destroyWindow(text);
}
Mat convertVec3bToBinary(Mat img) {
Mat outputImg = Mat::zeros(img.size(), CV_32F);
for (int i = 6; i < img.rows - 6; i++) {
for (int j = 6; j < img.cols - 6; j++) {
outputImg.at<float>(i, j) = (((img.at<Vec3b>(i, j)[0] >= 0 && img.at<Vec3b>(i, j)[0] <= 170) && (img.at<Vec3b>(i, j)[1] >= 0 && img.at<Vec3b>(i, j)[1] <= 140) && (img.at<Vec3b>(i, j)[2] >= 0 && img.at<Vec3b>(i, j)[2] <= 140)) ? 0.0 : 255.0);
}
}
// outputImg.convertTo(outputImg, CV_THRESH_BINARY);
return outputImg;
}
Mat medianFilter(Mat img) {
Mat outputImg = Mat::zeros(img.rows + 2, img.cols + 2, CV_32F);
Mat foutputImg = Mat::zeros(img.size(), CV_32F);
img.convertTo(img, CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+1, j+1) = img.at<float>(i, j);
}
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
vector < float > v1;
for (int i1 = -1; i1 <= 1; i1++) {
for (int j1 = -1; j1 <= 1; j1++) {
v1.push_back(outputImg.at<float>(i+1-i1, j+1-j1));
}
}
sort(v1.begin(), v1.end());
foutputImg.at<float>(i, j) = v1[5];
}
}
// foutputImg.convertTo(foutputImg, CV_THRESH_BINARY);
return foutputImg;
}
Mat erosion(Mat img, int **filter, int sz) {
Mat outputImg = Mat::zeros(img.rows + sz - 1, img.cols + sz - 1, CV_32F);
Mat foutputImg = Mat::zeros(img.size(), CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+(sz/2), j+(sz/2)) = img.at<float>(i, j);
}
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
float result = 255.0;
for (int i1 = -(sz/2); i1 <= sz/2; i1++) {
for (int j1 = -(sz/2); j1 <= sz/2; j1++) {
if (filter[i1+(sz/2)][j1+(sz/2)] == 255 && outputImg.at<float>(i+(sz/2)-i1, j+(sz/2)-j1) != (float)filter[i1+(sz/2)][j1+(sz/2)])
result = 0.0;
}
}
foutputImg.at<float>(i, j) = result;
}
}
return foutputImg;
}
Mat dilation(Mat img, int **filter, int sz) {
Mat outputImg = Mat::zeros(img.rows + sz - 1, img.cols + sz - 1, CV_32F);
Mat foutputImg = Mat::zeros(img.size(), CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+(sz/2), j+(sz/2)) = img.at<float>(i, j);
}
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
float result = 0.0;
for (int i1 = -(sz/2); i1 <= sz/2; i1++) {
for (int j1 = -(sz/2); j1 <= sz/2; j1++) {
if (filter[i1+(sz/2)][j1+(sz/2)] == 255 && outputImg.at<float>(i+(sz/2)-i1, j+(sz/2)-j1) == (float)filter[i1+(sz/2)][j1+(sz/2)])
result = 255.0;
}
}
foutputImg.at<float>(i, j) = result;
}
}
return foutputImg;
}
void genStructingElement1(int n, int **arr) {
int k = n/2;
for (int i = 0; i <= n/2; i++) {
for (int j = 0; j <= n/2; j++) {
if (j < k) {
arr[i][j] = arr[i][n-1-j] = 0;
arr[n-1-i][j] = arr[n-1-i][n-1-j] = 0;
}
else {
arr[i][j] = arr[i][n-1-j] = 255;
arr[n-1-i][j] = arr[n-1-i][n-1-j] = 255;
}
}
k--;
}
}
Mat diff(Mat img1, Mat img2) {
Mat outputImg = Mat::zeros(img1.rows, img1.cols, CV_32F);
for (int i = 0; i < img1.rows; i++) {
for (int j = 0; j < img1.cols; j++) {
outputImg.at<float>(i, j) = img1.at<float>(i, j) - img2.at<float>(i, j);
}
}
return outputImg;
}
int countBead(Mat img, int **filter, int sz) {
Mat outputImg = Mat::zeros(img.rows + sz - 1, img.cols + sz - 1, CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+(sz/2), j+(sz/2)) = img.at<float>(i, j);
}
}
int cnt = 0;
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int count = 0;
for (int i1 = -(sz/2); i1 <= sz/2; i1++) {
for (int j1 = -(sz/2); j1 <= sz/2; j1++) {
if ((filter[i1+(sz/2)][j1+(sz/2)] == 255) && (outputImg.at<float>(i+(sz/2)-i1, j+(sz/2)-j1) != (float)filter[i1+(sz/2)][j1+(sz/2)]))
count++;
}
}
if (count < 2*sz) {
cnt++;
for (int i1 = -(sz/2); i1 <= sz/2; i1++) {
for (int j1 = -(sz/2); j1 <= sz/2; j1++) {
outputImg.at<float>(i+(sz/2)-i1, j+(sz/2)-j1) = 0;
}
}
}
}
}
// displayImage(outputImg, "Difference 1");
return cnt;
}
Mat keyPoints(Mat img) {
Mat outputImg = Mat::zeros(48, 48, CV_32F);
Mat foutputImg = Mat::zeros(8, 8, CV_32F);
img.convertTo(img, CV_32F);
for (int i = 8; i < img.rows - 8; i++) {
for (int j = 8; j < img.cols - 8; j++) {
outputImg.at<float>(i - 8, j - 8) = img.at<float>(i, j);
}
}
// outputImg.convertTo(outputImg, CV_8U);
// displayImage(outputImg, "Image");
for (int i = 0, i1 = 0; i < 8; i++, i1 += 6) {
for (int j = 0, j1 = 0; j < 8; j++, j1 += 6) {
foutputImg.at<float>(i, j) = outputImg.at<float>(i1, j1);
// cout << outputImg.at<float>(i1, j1) << " ";
}
// cout << endl;
}
// foutputImg.convertTo(foutputImg, CV_8U);
// displayImage(foutputImg, "Image");
return foutputImg;
}
vector < vector < float > > HOG(Mat img) {
Mat outputImg = Mat::zeros(img.rows + 2, img.cols + 2, CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+1, j+1) = img.at<float>(i, j);
// cout << img.at<float>(i, j) << " ";
}
// cout << endl;
}
float v[16][8];
float ang[8][8], mag[8][8];
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
mag[i-1][j-1] = sqrt(pow(outputImg.at<float>(i+1, j) - outputImg.at<float>(i-1, j), 2) + pow(outputImg.at<float>(i, j+1) - outputImg.at<float>(i, j-1), 2));
ang[i-1][j-1] = atan2((outputImg.at<float>(i, j+1) - outputImg.at<float>(i, j-1)), (outputImg.at<float>(i+1, j) - outputImg.at<float>(i-1, j)));
if (ang[i-1][j-1] < 0)
ang[i-1][j-1] += 2*PI;
ang[i-1][j-1] = ang[i-1][j-1]*(180/PI);
// cout << ang[i-1][j-1] << " " ;
}
// cout << endl;
}
for (int i = 0; i < 16; i++) {
for (int j= 0; j < 8; j++) {
v[i][j] = 0;
}
}
for (int i= 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
int oct = (int)(ang[i][j]/45.0);
float magnitude = mag[i][j];
if (i < 2 && j < 2) {
v[0][oct] += magnitude;
}
else if (i < 2 && j < 4) {
v[1][oct] += magnitude;
}
else if (i < 2 && j < 6) {
v[2][oct] += magnitude;
}
else if (i < 2 && j < 8) {
v[3][oct] += magnitude;
}
else if (i < 4 && j < 2) {
v[4][oct] += magnitude;
}
else if (i < 4 && j < 4) {
v[5][oct] += magnitude;
}
else if (i < 4 && j < 6) {
v[6][oct] += magnitude;
}
else if (i < 4 && j < 8) {
v[7][oct] += magnitude;
}
else if (i < 6 && j < 2) {
v[8][oct] += magnitude;
}
else if (i < 6 && j < 4) {
v[9][oct] += magnitude;
}
else if (i < 6 && j < 6) {
v[10][oct] += magnitude;
}
else if (i < 6 && j < 8) {
v[11][oct] += magnitude;
}
else if (i < 8 && j < 2) {
v[12][oct] += magnitude;
}
else if (i < 8 && j < 4) {
v[13][oct] += magnitude;
}
else if (i < 8 && j < 6) {
v[14][oct] += magnitude;
}
else if (i < 8 && j < 8) {
v[15][oct] += magnitude;
}
}
}
vector < vector < float > > bin;
for (int i = 0; i < 16; i++) {
vector < float > reg;
for (int j= 0; j < 8; j++) {
reg.push_back(v[i][j]);
}
bin.push_back(reg);
}
return bin;
}
float cosine_dis(vector < float > d1, vector < float > d2) {
float dotp = 0.0, dend1 = 0.0, dend2 = 0.0;
for (int i = 0; i < (int)d1.size(); i++) {
dotp += d1[i]*d2[i];
dend1 += d1[i]*d1[i];
dend2 += d2[i]*d2[i];
}
float result = 1.0 - (dotp/(sqrt(dend1)*sqrt(dend2)));
// cout<<"cos: "<<result<<endl;
return result;
}
Mat lbp(Mat img) {
img.convertTo(img, CV_32F);
Mat outputImg = Mat::zeros(img.rows + 4, img.cols + 4, CV_32F);
Mat foutputImg = Mat::zeros(img.rows, img.cols, CV_32F);
Mat disoutputImg = Mat::zeros(img.rows, img.cols, CV_32F);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
outputImg.at<float>(i+2, j+2) = img.at<float>(i, j);
}
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int arr[5][5];
for (int i1 = -2; i1 <= 2; i1++) {
for (int j1 = -2; j1 <= 2; j1++) {
if (outputImg.at<float>(i + 2 - i1, j + 2 - j1) >= img.at<float>(i, j)) {
arr[i1+2][j1+2] = 1;
}
else {
arr[i1+2][j1+2] = 0;
}
}
}
foutputImg.at<float>(i, j) = (float)lbpValue(arr);
disoutputImg.at<float>(i, j) = (foutputImg.at<float>(i, j)/pow(2, 16))*255.0;
foutputImg.at<float>(i, j) = (foutputImg.at<float>(i, j)/pow(2, 16))*255.0; // change
}
}
disoutputImg.convertTo(disoutputImg, CV_8U);
// displayImage(disoutputImg, "LBP Image");
return foutputImg;
}
int lbpValue(int arr[][5]) {
vector < pair < int, int > > filter;
filter.push_back(make_pair(2, 0));
filter.push_back(make_pair(3, 0));
filter.push_back(make_pair(3, 1));
filter.push_back(make_pair(4, 1));
filter.push_back(make_pair(4, 2));
filter.push_back(make_pair(4, 3));
filter.push_back(make_pair(3, 3));
filter.push_back(make_pair(3, 4));
filter.push_back(make_pair(2, 4));
filter.push_back(make_pair(1, 4));
filter.push_back(make_pair(1, 3));
filter.push_back(make_pair(0, 3));
filter.push_back(make_pair(0, 2));
filter.push_back(make_pair(0, 1));
filter.push_back(make_pair(1, 1));
filter.push_back(make_pair(1, 0));
int power = 1;
int result = 0;
for (int i = (int)filter.size() - 1; i >= 0; i--) {
result = result + arr[filter[i].first][filter[i].second]*power;
power *= 2;
}
return result;
}
void faceDivide(Mat img, vector < int > Reg[64]) {
int reg = -1;
for (int i = 0; i < 64; i++) {
for (int j = 0; j < pow(2, 8); j++) { // 2^16 change
Reg[i].push_back(0);
}
}
for (int i = 0; i < img.rows; i += 8) {
for (int j = 0; j < img.cols; j += 8) {
reg++;
for (int i1 = 0; i1 < 8; i1++) {
for (int j1 = 0; j1 < 8; j1++) {
Reg[reg][(int)img.at<float>(i + i1, j + j1)] += 1;
}
}
}
}
}
float chiSquareDiff(vector < int > Reg1[64], vector < int > Reg2[64]) {
float result = 0.0;
for (int i = 0; i < 64; i++) {
for (int j = 0; j < pow(2, 8); j++) { // 2^16 change
if (Reg1[i][j] + Reg2[i][j] != 0)
result = result + (pow(Reg1[i][j] - Reg2[i][j], 2) / (float)(Reg1[i][j] + Reg2[i][j]));
}
}
return result;
}
Mat GetSkin(Mat img) {
Mat outImg = img.clone();
Mat imgYCRCB, imgHSV;
bool rgb;
Vec3b black = Vec3b::all(0);
// bool b,c ;
// Vec3b white = Vec3b::all(255);
img.convertTo(imgHSV, CV_32FC3);
cvtColor(imgHSV,imgHSV, CV_BGR2HSV);
normalize(imgHSV,imgHSV, 0.0, 255.0, NORM_MINMAX, CV_32FC3);
cvtColor(img, imgYCRCB, CV_BGR2YCrCb);
for(int i = 0; i < img.rows; i++) {
for(int j = 0; j < img.cols; j++) {
Vec3f hsv = imgHSV.ptr<Vec3f>(i)[j];
Vec3b bgr = img.ptr<Vec3b>(i)[j];
Vec3b ycrcb = imgYCRCB.ptr<Vec3b>(i)[j];
//
// int Y = ycrcb.val[0];
// int Cr = ycrcb.val[1];
// int Cb = ycrcb.val[2];
// if ((135 < Cr <180) && (85 < Cb <135) && (Y > 80))
// b = true;
// else
// b = false;
//
// float H = hsv.val[0];
// float S = hsv.val[1];
// float V = hsv.val[2];
// if ((0 < H < 50) && (0.23 < S < 0.68))
// c = true;
// else
// c = false;
//
int B = bgr.val[0];
int G = bgr.val[1];
int R = bgr.val[2];
if ((R > 95) && (G > 40) && (B > 20) && ((max(R, max(G,B)) - min(R, min(G,B))) > 15) && (abs(R - G) > 15) && (R > G) && (R > B))
rgb = true;
else
rgb=false;
if(!rgb)
outImg.ptr<Vec3b>(i)[j] = black;
// else
// img3.ptr<Vec3b>(i)[j] = white;
}
}
return outImg;
}
<file_sep>
# Hand-Gesture-Recognition
Using Microsoft Kinect depth stream to create a tool to read and identify American Sign Language as a part of Engineering Design course in Winter 2016.
For abstract and code zip, please visit http://mridulg.github.io/Hand-Gesture-Recognition/
Blog - http://iedprojects2016.blogspot.com/2016/05/hand-gesture-recognition-using-kinect.html
<file_sep>##Source
Dataset was obtained from the Gesture Dataset of [__Massey University__] (http://www.massey.ac.nz/~albarcza/gesture_dataset2012.html)
<file_sep>//
// temp.cpp
// testSegmentation
//
// Created by <NAME> on 4/1/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
//
// References : http://paulbourke.net/geometry/circlesphere/
// http://s-ln.in/2013/04/18/hand-tracking-and-gesture-detection-opencv/
// http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html
// http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/hull/hull.html
//
//
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;
using namespace cv;
void displayImage(Mat , string);
void ASL_Detection(Mat );
double distPoints(Point , Point);
pair < Point, double > ThreePointsCircle(Point, Point, Point);
Mat GetSkin(Mat);
Mat spatialFilterGaussian(Mat );
double mask3(Mat , Mat , int , int);
Mat averageFilter3x3(Mat );
double mask5(Mat , Mat , int , int);
Mat averageFilter5x5(Mat );
int main(int argc, const char * argv[])
{
Mat orgImg;
orgImg=imread("../Dataset/Original_Dataset/0_1.png",CV_LOAD_IMAGE_ANYCOLOR);
int i=0,j=1;
while(i<10)
{
j=1;
while(j<56)
{
int x=0;
char first1[] = "/Users/mridul/HGR/Datasets/originalDataset/"; //Add your own source path here
stringstream src, uscore,png,dest;
src << first1;
src<<i;
uscore<<"_";
src<<uscore.str();
src<<j;
png<<".png";
src<<png.str();
char first2[] = "/Users/mridul/HGR/Datasets/myDataset/"; //Add your own destination path
dest << first2;
dest<<i;
dest<<uscore.str();
dest<<j;
dest<<png.str();
orgImg=imread(src.str(),CV_LOAD_IMAGE_ANYCOLOR);
if(orgImg.empty())
{
cout << "Image not loaded properly." << endl;
j++;
continue;
}
if (orgImg.type() != 0)
orgImg = GetSkin(orgImg);
while(x<orgImg.cols)
{
orgImg.at<uchar>(orgImg.rows-1, x) = 0;
orgImg.at<uchar>(orgImg.rows-2, x) = 0;
orgImg.at<uchar>(orgImg.rows-3, x) = 0;
orgImg.at<uchar>(orgImg.rows-4, x) = 0;
orgImg.at<uchar>(orgImg.rows-5, x) = 0;
x++;
}
erode(orgImg,orgImg,Mat());
dilate(orgImg,orgImg,Mat());
imwrite(dest.str(), orgImg);
cout<<dest.str()<<endl;
j++;
}
i++;
}
i='a';j=1;
while(i<='z')
{
// cout<<"I is "<<i<<endl;
j=1;
while(j<56)
{
int x=0;
char first1[] = "/Users/mridul/HGR/Datasets/originalDataset/";
stringstream src, uscore,png,dest;
src << first1;
src<<(char)i;
uscore<<"_";
src<<uscore.str();
src<<j;
png<<".png";
src<<png.str();
char first2[] = "/Users/mridul/HGR/Datasets/myDataset/";
dest << first2;
dest<<(char)i;
dest<<uscore.str();
dest<<j;
dest<<png.str();
orgImg=imread(src.str(),CV_LOAD_IMAGE_ANYCOLOR);
if(orgImg.empty())
{
cout << "Image not loaded properly." << endl;
j++;
continue;
}
if (orgImg.type() != 0)
orgImg = GetSkin(orgImg);
while(x<orgImg.cols)
{
orgImg.at<uchar>(orgImg.rows-1, x) = 0;
orgImg.at<uchar>(orgImg.rows-2, x) = 0;
orgImg.at<uchar>(orgImg.rows-3, x) = 0;
orgImg.at<uchar>(orgImg.rows-4, x) = 0;
orgImg.at<uchar>(orgImg.rows-5, x) = 0;
x++;
}
erode(orgImg,orgImg,Mat());
dilate(orgImg,orgImg,Mat());
imwrite(dest.str(), orgImg);
j++;
cout<<dest.str()<<endl;;
}
i++;
}
return 0;
}
void displayImage(Mat img, string text)
{
namedWindow(text, WINDOW_AUTOSIZE );
imshow(text,img);
waitKey(0);
}
void ASL_Detection(Mat frame) {
Mat canny_output;
vector < vector < Point > > contours;
vector<Vec4i> hierarchy;
vector < pair < Point, double > > avg_center_of_palm;
vector < Point > all_palm_point;
vector < Point > st_point;
vector < Point > en_point;
vector < Point > fa_point;
// Find contours
Canny(frame, canny_output, 100, 200, 3);
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Find the convex hull object for each contour
vector < vector < int > > hullI(contours.size());
vector < vector < Point > > hull(contours.size());
vector < vector < Point > > defect_points(contours.size());
Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3);
int loc_max_defects = 0;
for(int i = 0; i < (int)contours.size(); i++) {
vector < Vec4i > defects;
convexHull( Mat(contours[i]), hullI[i], false);
convexHull( Mat(contours[i]), hull[i], false);
convexityDefects(contours[i], hullI[i], defects);
cout << "Size of Defects : " << defects.size() << endl;
Point palm_center_all;
vector < Point > palm_point;
if ((int)defects.size() >= 3) {
bool flag = false;
if ((int)defects.size() > loc_max_defects) {
loc_max_defects = (int)defects.size();
flag = true;
all_palm_point.clear();
st_point.clear();
en_point.clear();
fa_point.clear();
}
for (int j = 0; j < (int)defects.size(); j++) {
int index = defects[j][2];
defect_points[i].push_back(contours[i][index]);
circle(drawing, contours[i][index], 5, Scalar(243, 2, 243), -1);
drawContours(drawing, contours, i, Scalar(243, 2, 58), 2, 8, vector<Vec4i>(), 0, Point());
drawContours(drawing, hull, i, Scalar(9, 9, 227), 2, 8, vector<Vec4i>(), 0, Point());
int start_index = defects[j][0];
int end_index = defects[j][1];
int far_index = defects[j][2];
Point start_point(contours[i][start_index]);
Point end_point(contours[i][end_index]);
Point far_point(contours[i][far_index]);
palm_center_all += start_point + end_point + far_point;
palm_point.push_back(start_point);
palm_point.push_back(end_point);
palm_point.push_back(far_point);
if (flag) {
all_palm_point.push_back(start_point);
all_palm_point.push_back(end_point);
all_palm_point.push_back(far_point);
st_point.push_back(start_point);
en_point.push_back(end_point);
fa_point.push_back(far_point);
}
}
palm_center_all.x = (palm_center_all.x)/((int)defects.size()*3);
palm_center_all.y = (palm_center_all.y)/((int)defects.size()*3);
// cout << "Palm center all : (" << palm_center_all.x << ", " << palm_center_all.y << ")" << endl;
vector < pair < double, int > > distance_vector;
for (int j = 0; j < (int)palm_point.size(); j++) {
distance_vector.push_back(make_pair(distPoints(palm_center_all, palm_point[j]), j));
}
sort(distance_vector.begin(), distance_vector.end());
pair < Point, double > find_circle;
for (int j = 0; j < (int)distance_vector.size() - 2; j++) {
Point pt1 = palm_point[distance_vector[j+0].second];
Point pt2 = palm_point[distance_vector[j+1].second];
Point pt3 = palm_point[distance_vector[j+2].second];
find_circle = ThreePointsCircle(pt1, pt2, pt3);
// cout << pt1.x << " " << pt1.y << endl;
// cout << pt2.x << " " << pt2.y << endl;
// cout << pt3.x << " " << pt3.y << endl;
// cout << endl;
if(find_circle.second != 0)
break;
}
// cout << "What " << find_circle.second << endl;
avg_center_of_palm.push_back(find_circle);
Point center_of_palm = find_circle.first;
}
}
Point all_palm_center_all;
for (int j = 0; j < (int)all_palm_point.size(); j++) {
all_palm_center_all.x += all_palm_point[j].x;
all_palm_center_all.y += all_palm_point[j].y;
}
all_palm_center_all.x = all_palm_center_all.x/(int)(all_palm_point.size());
all_palm_center_all.y = all_palm_center_all.y/(int)(all_palm_point.size());
cout << "Palm center average : (" << all_palm_center_all.x << ", " << all_palm_center_all.y << ")" << endl;
vector < pair < double, int > > all_distance_vector;
for (int j = 0; j < (int)all_palm_point.size(); j++) {
all_distance_vector.push_back(make_pair(distPoints(all_palm_center_all, all_palm_point[j]), j));
}
sort(all_distance_vector.begin(), all_distance_vector.end());
pair < Point, double > all_find_circle;
vector < pair < Point, double > > all_circle;
for (int j = 0; j < (int)all_distance_vector.size() - 2; j++) {
Point pt1 = all_palm_point[all_distance_vector[j + 0].second];
Point pt2 = all_palm_point[all_distance_vector[j + 1].second];
Point pt3 = all_palm_point[all_distance_vector[j + 2].second];
all_find_circle = ThreePointsCircle(pt1, pt2, pt3);
if(all_find_circle.second != 0)
break;
}
// cout << all_circle.size() << " " << frame.rows << " " << frame.cols << endl;
Point center_of_palm = all_find_circle.first;
double radius = all_find_circle.second;
cout << "Radius : " << radius << endl;
circle(drawing, center_of_palm, 5, Scalar(34, 245, 10), 3);
circle(drawing, center_of_palm, radius, Scalar(34, 245, 10), 3);
int finger_count = 0;
for (int j = 0; j < (int)st_point.size(); j++) {
double xlength = sqrt(distPoints(st_point[j], center_of_palm));
double ylength = sqrt(distPoints(fa_point[j], center_of_palm));
double hlength = sqrt(distPoints(fa_point[j], st_point[j]));
double zlength = sqrt(distPoints(en_point[j], fa_point[j]));
// Reference for selecting center of palm: http://s-ln.in/2013/04/18/hand-tracking-and-gesture-detection-opencv/
if((hlength <= 3*radius) && (ylength >= 0.4*radius) && (hlength >= 10) && (zlength >= 10) && max(hlength,zlength)/min(hlength,zlength) >= 0.8)
if(min(xlength, ylength)/max(xlength,ylength) <= 0.8) {
if(((xlength >= 0.1*radius) && (xlength <= 1.3*radius) && (xlength < ylength))||((ylength >= 0.1*radius) && (ylength <= 1.3*radius) && (xlength > ylength)))
line(drawing, en_point[j], fa_point[j], Scalar(0,255,0), 1);
finger_count++;
}
}
cout << "Finger count : " << min(5, finger_count + 1) << endl;
displayImage(drawing, "Contour + Hull Image.");
}
double distPoints(Point x,Point y) {
return ((x.x - y.x) * (x.x - y.x)) + ((x.y - y.y) * (x.y - y.y));
}
// Reference : http://paulbourke.net/geometry/circlesphere/
pair < Point, double > ThreePointsCircle(Point pt1, Point pt2, Point pt3) {
int ma_num = pt2.y - pt1.y;
int ma_den = pt2.x - pt1.x;
int mb_num = pt3.y - pt2.y;
int mb_den = pt3.x - pt2.x;
double eps = 0.00000001;
if (abs((mb_num * ma_den) - (mb_den * ma_num)) < eps)
return make_pair(Point(-1, -1), 0);
double x = ((ma_num*mb_num*(pt1.y - pt3.y)) + (mb_num*ma_den*(pt1.x + pt2.x)) - (ma_num*mb_den*(pt2.x + pt3.x)))/(2*(mb_num*ma_den - ma_num*mb_den));
double y = ((pt1.y + pt2.y)/2) -((ma_den*(x - (pt1.x + pt2.x)/2))/ma_num);
double rad = hypot(pt1.x - x, pt1.y - y);
return make_pair(Point(x, y), rad);
}
Mat GetSkin(Mat img) {
Mat outImg = img.clone();
Mat imgYCRCB, imgHSV;
bool rgb;
Vec3b black = Vec3b::all(0);
// bool b,c ;
Vec3b white = Vec3b::all(255);
img.convertTo(imgHSV, CV_32FC3);
cvtColor(imgHSV,imgHSV, CV_BGR2HSV);
normalize(imgHSV,imgHSV, 0.0, 255.0, NORM_MINMAX, CV_32FC3);
cvtColor(img, imgYCRCB, CV_BGR2YCrCb);
for(int i = 0; i < img.rows; i++) {
for(int j = 0; j < img.cols; j++) {
Vec3f hsv = imgHSV.ptr<Vec3f>(i)[j];
Vec3b bgr = img.ptr<Vec3b>(i)[j];
Vec3b ycrcb = imgYCRCB.ptr<Vec3b>(i)[j];
int B = bgr.val[0];
int G = bgr.val[1];
int R = bgr.val[2];
if ((R > 95) && (G > 40) && (B > 20) && ((max(R, max(G,B)) - min(R, min(G,B))) > 15) && (abs(R - G) > 15) && (R > G) && (R > B))
rgb = true;
else
rgb=false;
if(!rgb)
outImg.ptr<Vec3b>(i)[j] = black;
else
outImg.ptr<Vec3b>(i)[j] = white;
}
}
return outImg;
}
Mat spatialFilterGaussian(Mat img) {
Mat G = Mat::zeros(img.rows + 6, img.cols + 6, CV_8UC1);
Mat F = Mat::zeros(img.rows, img.cols, CV_8UC1);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
G.at<uchar>(i+3, j+3) = img.at<uchar>(i, j);
}
}
int filter[][7] = {{1, 1, 2, 2, 2, 1, 1}, {1, 2, 2, 4, 2, 2, 1}, {2, 2, 4, 8, 4, 2, 2}, {2, 4, 8, 16, 8, 4, 2}, {2, 2, 4, 8, 4, 2, 2}, {1, 2, 2, 4, 2, 2, 1}, {1, 1, 2, 2, 2, 1, 1}};
for (int i = 3; i < img.rows + 3; i++) {
for (int j = 3; j < img.cols + 3; j++) {
double res = 0.0, sum = 0.0;
for (int i1 = 0; i1 < 7; i1++) {
for (int j1 = 0; j1 < 7; j1++) {
res += (G.at<uchar>(i - 3 + i1, j - 3 + j1)*filter[i1][j1]);
sum += filter[i1][j1];
}
}
res = res/sum;
F.at<uchar>(i - 3, j - 3) = (255 < res ? 255 : res);
}
}
return F;
}
double mask3(Mat filter, Mat img, int x, int y) {
double res = 0.0;
for (int i = 0; i < filter.rows; i++) {
for (int j = 0; j < filter.cols; j++) {
res = res + ((int)filter.at<uchar>(i, j)*(int)img.at<uchar>(y - 1 + i, x - 1 + j)) / 9.0;
}
}
return res;
}
double mask5(Mat filter, Mat img, int x, int y) {
double res = 0.0;
for (int i = 0; i < filter.rows; i++) {
for (int j = 0; j < filter.cols; j++) {
res = res + ((int)filter.at<uchar>(i, j)*(int)img.at<uchar>(y - 2 + i, x - 2 + j)) / 25.0;
}
}
return res;
}
Mat averageFilter3x3(Mat img) {
Mat tmpImg = Mat(img.rows + 2, img.cols + 2, CV_8UC1); // Zero padding
Mat finalImg = Mat(img.rows, img.cols, CV_8UC1);
int x,y;
for(x=0;x<tmpImg.rows;x++)
for(y=0;y<tmpImg.cols;y++)
tmpImg.at<uchar>(x,y) = 0;
for(x=1;x<=img.rows;x++)
for (y=1;y<=img.cols;y++)
tmpImg.at<uchar>(x,y) = img.at<uchar>(x-1,y-1);
Mat avFilter3X3 = Mat::ones(3, 3, CV_8UC1);
for(x=1;x<tmpImg.rows-1;x++)
for(y=1;y<tmpImg.cols-1;y++)
finalImg.at<uchar>(x-1,y-1) = mask5(avFilter3X3,tmpImg,y,x);
return finalImg;
}
Mat averageFilter5x5(Mat img) {
Mat tmpImg = Mat(img.rows + 4, img.cols + 4, CV_8UC1); // Zero padding
Mat finalImg = Mat(img.rows, img.cols, CV_8UC1);
int y,x;
for(x=0;x<tmpImg.rows;x++)
for(y=0;y<tmpImg.cols;y++)
tmpImg.at<uchar>(x,y) = 0;
for(x=2; x<=img.rows+1;x++)
for (y=2;y<=img.cols+1;y++)
tmpImg.at<uchar>(x,y) = img.at<uchar>(x-2,y-2);
Mat avFilter5X5 = Mat::ones(5, 5, CV_8UC1);
for(x=2;x<tmpImg.rows-2;x++)
for(y=2;y<tmpImg.cols-2;y++)
finalImg.at<uchar>(x-2,y-2) = mask5(avFilter5X5, tmpImg, y,x);
return finalImg;
}
<file_sep>//
// main.cpp
// videoCapture
//
// Created by <NAME> on 5/3/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame, rgb;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, COLOR_BGR2GRAY);
// cvtColor(edges,rgb, CV_GRAY2RGB);
GaussianBlur(edges,edges, Size(7,7), 1.5, 1.5);
Canny(edges,edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}<file_sep>import os
filenames = next(os.walk("/Users/mridul/Downloads/handgesturedataset_part3/"))[2]
for i in filenames:
bleh=i
x=i.split("_")
y=[]
num=0
# print len(x)
for j in range(len(x)):
# print x[j]
y.append(x[j])
# print y
# print "Y1 is "+str(y[1])
name=str(y[1])+"_"
if str(y[2])=="dif":
num=int(y[4])+50
elif str(y[2])=="bot":
num=int(y[4])+55
elif str(y[2])=="left":
num=int(y[4])+60
elif str(y[2])=="right":
num=int(y[4])+65
elif str(y[2])=="top":
num=int(y[4])+70
name=name+str(num)+".png"
print name
os.rename("/Users/mridul/Downloads/handgesturedataset_part3/"+i,"/Users/mridul/Downloads/handgesturedataset_part1/"+name)
|
03db3d9153e38ca6613b5e74d61c95400c718299
|
[
"Markdown",
"Python",
"C++"
] | 6 |
C++
|
mridulg/Hand-Gesture-Recognition-using-Kinect
|
4489575c7cda337226e1d33a72df61f76ebd5b35
|
c722d9638b7553fac8f7824c5852209b1e00c305
|
refs/heads/master
|
<file_sep>print("p3 fileeee")
print("chnages in p3")
print ("new push changes")
|
2e20042368039fb11ce866dd935ed38d5e07875f
|
[
"Python"
] | 1 |
Python
|
sindhujadasari/projectdemo3
|
745059b21b240968f18ec25ae29852e7d01c2c1a
|
82493ebc040845a988a3a39a6e1c16827b22dd6f
|
refs/heads/master
|
<repo_name>crossatom/UniCommons<file_sep>/src/main/java/ru/unicorn/storm/unicommons/commands/CommandHome.java
package ru.unicorn.storm.unicommons.commands;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import ru.unicorn.storm.unicommons.utils.Title;
public class CommandHome implements CommandExecutor {
private FileConfiguration players;
public CommandHome(FileConfiguration Players) {
players = Players;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length < 2) return false;
if(args[0] == "tp") {
if(players.getString(((Player)sender).getDisplayName() + ".home." + args[1]) == null) {
sender.sendMessage("§eУ Вас нет дома с названием §c" + args[1]);
} else {
double x = players.getInt(((Player) sender).getDisplayName() + ".home." + args[1] + ".x"),
y = players.getInt(((Player) sender).getDisplayName() + ".home." + args[1] + ".y"),
z = players.getInt(((Player) sender).getDisplayName() + ".home." + args[1] + ".z");
Location point = new Location(((Player) sender).getWorld(), x, y, z);
new Title().send((Player) sender, "Перемещение", "Немного подождите", 1, 2, 1);
((Player) sender).teleport(point);
}
} else if(args[0] == "set") {
if(players.getString(((Player) sender).getDisplayName() + ".home." + args[1]) != null) {
sender.sendMessage("§eУ Вас уже есть дом с названием §c" + args[1]);
} else {
double x = ((Player) sender).getLocation().getX(),
y = ((Player) sender).getLocation().getY(),
z = ((Player) sender).getLocation().getZ();
players.set(((Player) sender).getDisplayName() + ".home." + args[1] + ".x", x);
players.set(((Player) sender).getDisplayName() + ".home." + args[1] + ".y", y);
players.set(((Player) sender).getDisplayName() + ".home." + args[1] + ".z", z);
}
} else if(args[0] == "del") {
if(players.getString(((Player) sender).getDisplayName() + ".home." + args[1]) == null) {
sender.sendMessage("§eУ Вас нет дома с названием §c" + args[1]);
} else {
players.set(((Player) sender).getDisplayName() + ".home." + args[1], null);
}
} else {
return false;
}
return true;
}
}
<file_sep>/src/main/java/ru/unicorn/storm/unicommons/UniCommons.java
package ru.unicorn.storm.unicommons;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import ru.unicorn.storm.unicommons.commands.CommandHome;
import ru.unicorn.storm.unicommons.commands.CommandKit;
import ru.unicorn.storm.unicommons.commands.CommandSave;
import ru.unicorn.storm.unicommons.commands.CommandSpawn;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public final class UniCommons extends JavaPlugin implements Listener {
private FileConfiguration config;
private FileConfiguration players;
@Override
public void onEnable() {
// Plugin startup logic
if(!(new File(getDataFolder(), "config.yml").exists()))
saveDefaultConfig();
config = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml"));
if(!(new File(getDataFolder(), "players.yml").exists()))
saveResource("players.yml", false);
players = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "players.yml"));
// Register commands
getCommand("spawn").setExecutor(new CommandSpawn(config));
getCommand("home").setExecutor(new CommandHome(players));
getCommand("save").setExecutor(new CommandSave(config, players, this));
getCommand("kit").setExecutor(new CommandKit(this));
// Register events
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onJoin(PlayerJoinEvent evt) {
if(players.getString(evt.getPlayer().getDisplayName()) == null) {
players.set(evt.getPlayer().getDisplayName() + ".online", true);
}
if(players.getBoolean(evt.getPlayer().getDisplayName() + ".banned")) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy-HH:mm");
Date now;
Date exp;
try {
now = sdf.parse(sdf.format(new Date()));
exp = sdf.parse(players.getString(evt.getPlayer().getDisplayName() + ".ban-expire"));
} catch (ParseException ex) {
ex.printStackTrace();
return;
}
if(exp.compareTo(now) < 0) {
players.set(evt.getPlayer().getDisplayName() + ".banned", false);
players.set(evt.getPlayer().getDisplayName() + ".ban-expire", false);
evt.setJoinMessage(ChatColor.translateAlternateColorCodes('&', config.getString("connection.join").replace("{NICKNAME}", evt.getPlayer().getDisplayName())));
} else {
evt.setJoinMessage(null);
long time = now.getTime() - exp.getTime();
long days = time / (24 * 60 * 60 * 1000);
long hours = time / (60 * 60 * 1000) % 24;
long minutes = time / (60 * 1000) % 60;
evt.getPlayer().kickPlayer("Вы забанены на этом сервере. Бан истекает через " + days + "д " +
hours + "ч " + minutes + "м");
}
} else {
evt.setJoinMessage(ChatColor.translateAlternateColorCodes('&', config.getString("connection.join").replace("{NICKNAME}", evt.getPlayer().getDisplayName())));
}
}
@EventHandler
public void onQuit(PlayerQuitEvent evt) {
evt.setQuitMessage(ChatColor.translateAlternateColorCodes('&', config.getString("connection.quit").replace("{NICKNAME}", evt.getPlayer().getDisplayName())));
}
@Override
public void onDisable() {
// Plugin shutdown logic
try {
config.save(new File(getDataFolder(), "config.yml"));
players.save(new File(getDataFolder(), "players.yml"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
<file_sep>/src/main/java/ru/unicorn/storm/unicommons/utils/Reflection.java
package ru.unicorn.storm.unicommons.utils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Reflection {
public void sendPacket(Player p, Object packet) {
try {
Object handle = p.getClass().getMethod("getHandle").invoke(p);
Object playerConnection = handle.getClass().getField("playerConnection").get(handle);
playerConnection.getClass().getMethod("sendPacket", getNMClass("Packet")).invoke(playerConnection, packet);
} catch (Exception ex) {}
}
public Class<?> getNMClass(String name) {
try {
return Class.forName("net.minecraft.server." +
Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "." + name);
} catch (ClassNotFoundException ex) {}
return null;
}
}
<file_sep>/src/main/java/ru/unicorn/storm/unicommons/utils/Title.java
package ru.unicorn.storm.unicommons.utils;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
public class Title extends Reflection {
public void send(Player p, String title, String subtitle, int fadeIn, int stay, int fadeOut) {
try {
Object chatTitle = getNMClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class)
.invoke(null, "{\"text\": \"" + title + "\"}");
Constructor<?> titleConstructor = getNMClass("PacketPlayOutTitle").getConstructor(
getNMClass("PacketPlayOutTitle").getDeclaredClasses()[0],
getNMClass("IChatBaseComponent"),
int.class,
int.class,
int.class
);
Object packet = titleConstructor.newInstance(
getNMClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("TITLE").get(null),
chatTitle,
fadeIn,
stay,
fadeOut
);
Object chatsTitle = getNMClass("IChatBaseComponent").getDeclaredClasses()[0].getMethod("a", String.class)
.invoke(null, "{\"text\": \"" + subtitle + "\"}");
Constructor<?> stitleConstructor = getNMClass("PacketPlayOutTitle").getConstructor(
getNMClass("PacketPlayOutTitle").getDeclaredClasses()[0],
getNMClass("IChatBaseComponent"),
int.class,
int.class,
int.class
);
Object spacket = stitleConstructor.newInstance(
getNMClass("PacketPlayOutTitle").getDeclaredClasses()[0].getField("SUBTITLE").get(null),
chatsTitle,
fadeIn,
stay,
fadeOut
);
sendPacket(p, packet);
sendPacket(p, spacket);
} catch (Exception ex) {}
}
}
|
0d0fc252770e4cd98134760a9ac024eb0bd5486b
|
[
"Java"
] | 4 |
Java
|
crossatom/UniCommons
|
698a773a3c06a44bafadbc2bd273ef133e496773
|
b9a20a1bb39766ad17ccb1d2c1e26044ac6ea76b
|
refs/heads/master
|
<file_sep><?php
if (!defined('BASEPATH'))
{
exit('No direct script access allowed');
}
class User_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function profile_update($table, $where, $data)
{
return $this->db->where($where)->update($table, $data);
}
public function get_user($email)
{
$user_details = [];
$user_details = $this->db->limit(1)->get_where('users', ['email' => $email])->result();
if (count($user_details) == 1 && !empty($user_details) && is_array($user_details))
{
return $user_details;
}
return NULL;
}
public function update_password($userDetails)
{
return $this->db->where(['email' => $userDetails['email']])->update('users', ['password' => $userDetails['password']]);
}
public function create_user($user_details)
{
return $this->db->insert('users', $user_details);
}
public function clean_password_input($details)
{
$this->$details = htmlspecialchars(stripslashes(trim($details)));
return $this->$details;
}
public function verify_password($email, $old_password)
{
$hash = $this->get_hashed_password($email);
$old_password = $this->clean_password_input($old_password);
if (!empty($hash))
{
if (password_verify($old_password, $hash))
{
return TRUE;
}
}
return FALSE;
}
public function validate_email($email)
{
$check_user_tbl = $this->db->limit(1)->get_where('users', ['email' => $email])->result();
if (!empty($check_user_tbl) && count($check_user_tbl) == 1)
{
return TRUE;
}
return FALSE;
}
public function get_hashed_password($email)
{
$password = $this->db->limit(1)->get_where('users', ['email' => $email])->row()->password;
if (empty($password)) {
return NULL;
}
return $password;
}
}<file_sep><?php
if (!defined('BASEPATH'))
{
exit('No direct script access allowed');
}
class Auth_model extends CI_Model
{
var $details;
public function __construct()
{
parent::__construct();
}
public function clean_login_input($details)
{
$this->$details = htmlspecialchars(stripslashes(trim($details)));
return $this->$details;
}
public function validate_user_login($user)
{
$email = $this->clean_login_input(strtolower($user['email']));
$password = $this->clean_login_input($user['password']);
$hash = $this->get_hashed_password($email);
if (!empty($hash))
{
if (password_verify($password, $hash))
{
$result = $this->db->get_where('users', ['email' => $email])->result();
if (is_array($result) && count($result) > 0 && !empty($result))
{
$this->details = $result[0];
$this->set_session();
return TRUE;
}
else
{
return FALSE;
}
}
return FALSE;
}
return FALSE;
}
public function set_session()
{
$this->session->set_userdata(
[
'fullname' => $this->details->first_name . ' ' . $this->details->last_name,
'email' => $this->details->email,
'first_name' => $this->details->first_name,
'last_name' => $this->details->last_name,
'isLoggedIn' => TRUE,
]
);
}
public function get_hashed_password($email)
{
$password = $this->db->limit(1)->get_where('users', ['email' => $email])->row()->password;
if (empty($password)) {
return NULL;
}
return $password;
}
}<file_sep> <!-- /#wrapper -->
<!-- jQuery -->
<script src="<?php echo base_url('plugins/bower_components/jquery/dist/jquery.min.js'); ?>"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url('bootstrap/dist/js/bootstrap.min.js'); ?>"></script>
<!-- Menu Plugin JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js'); ?>"></script>
<!--Counter js -->
<script src="<?php echo base_url('plugins/bower_components/waypoints/lib/jquery.waypoints.js'
);?>"></script>
<script src="<?php echo base_url('plugins/bower_components/counterup/jquery.counterup.min.js');?>"></script>
<!--slimscroll JavaScript -->
<script src="<?php echo base_url('js/jquery.slimscroll.js');?>"></script>
<!--Wave Effects -->
<script src="<?php echo base_url('js/waves.js');?>"></script>
<!-- Vector map JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-2.0.2.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-world-mill-en.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-in-mill.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-us-aea-en.js');?>"></script>
<!-- chartist chart -->
<script src="<?php echo base_url('plugins/bower_components/chartist-js/dist/chartist.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/chartist-plugin-tooltip-master/dist/chartist-plugin-tooltip.min.js');?>"></script>
<!-- sparkline chart JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/jquery-sparkline/jquery.sparkline.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/jquery-sparkline/jquery.charts-sparkline.js');?>"></script>
<!-- Custom Theme JavaScript -->
<script src="<?php echo base_url('js/custom.min.js');?>"></script>
<script src="<?php echo base_url('js/dashboard3.');?>'"></script>
<!--Style Switcher -->
<script src="<?php echo base_url('plugins/bower_components/styleswitcher/jQuery.style.switcher.js');?>"></script>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.866, lng: 151.196},
zoom: 15
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
}
</script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Signup extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function clean_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
public function load_page()
{
$data['title'] = 'Delta State Tourism Board | Sign Up';
$this->load->view('includes/header', $data);
$this->load->view('register');
$this->load->view('includes/footer');
}
public function create_account()
{
$password = "";
$this->session->set_userdata('isLoggedIn', '');
$login_status = $this->session->userdata('isLoggedIn');
$registration_start = $this->session->userdata('registration_start');
$registration_finished = $this->session->userdata('registration_finished');
if ($_SERVER['REQUEST_METHOD'] != 'POST')
{
redirect(site_url('register'));
}
$userDetails['email'] = $accountDetails['email'] = $this->clean_data(strtolower($this->input->post('email')));
$userDetails['last_name'] = $this->clean_data(ucwords($this->input->post('last_name')));
$userDetails['first_name'] = $this->clean_data(ucwords($this->input->post('first_name')));
$userDetails['password'] = $this->input->post('password');
$password = password_hash($this->clean_data($userDetails['password']), PASSWORD_DEFAULT);
$email_error_msg = [
'is_unique' => 'The email account address you provided already exists in our database. Please use another email account!',
];
$this->form_validation->set_rules('last_name', 'Last Name', 'required|min_length[2]');
$this->form_validation->set_rules('email', 'Email', 'required|min_length[5]|is_unique[users.email]', $email_error_msg);
$this->form_validation->set_rules('first_name', 'First Name', 'required|min_length[2]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]|max_length[255]');
$this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|min_length[5]|max_length[255]|matches[password]');
if ($this->form_validation->run())
{
$userDetails['password'] = $<PASSWORD>;
$user = $this->user_model->create_user($userDetails);
if ($user)
{
$this->session->set_userdata('registration_start', 0);
$this->session->set_userdata('registration_finished', 1);
$message = "<div class='alert alert-success'><center>You have successfully signed up. Please login!</center></div>";
$this->session->set_flashdata('error_message', $message);
redirect(site_url('login'));
}
else
{
$message = "<div class='alert alert-danger'><center>You could not be signed up successfully. Try again! </center></div>";
$this->session->set_flashdata('error_message', $message);
redirect(base_url('login'));
}
}
else if (!$this->form_validation->run())
{
$data['message'] = "<div class='alert alert-danger'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><center>". validation_errors() ."</center></div>";
$this->session->set_flashdata('error_message', $data['message']);
$this->load_page();
}
}
}
<file_sep><!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo base_url('plugins/images/logo.png') ?>">
<title><?php echo $title; ?></title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script src="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/d004434a5ff76e7b97c8b07c01f34ca69e635d97/src/js/bootstrap-datetimepicker.js"></script>
<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/d004434a5ff76e7b97c8b07c01f34ca69e635d97/build/css/bootstrap-datetimepicker.css" rel="stylesheet">
<!-- Bootstrap Core CSS -->
<link href="<?php echo base_url('bootstrap/dist/css/bootstrap.min.css'); ?>" rel="stylesheet">
<!-- Menu CSS -->
<link href="<?php echo base_url('plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.css'); ?>" rel="stylesheet">
<!-- chartist CSS -->
<link href="<?php echo base_url('plugins/bower_components/chartist-js/dist/chartist.min.css'); ?>" rel="stylesheet">
<link href="<?php echo base_url('plugins/bower_components/chartist-plugin-tooltip-master/dist/chartist-plugin-tooltip.css'); ?>" rel="stylesheet">
<!-- Vector CSS -->
<link href="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-2.0.2.css'); ?>" rel="stylesheet" />
<!-- animation CSS -->
<link href="<?php echo base_url('css/animate.css'); ?>" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?php echo base_url('css/style.css'); ?>" rel="stylesheet">
<!-- color CSS -->
<link href="<?php echo base_url('css/colors/blue-dark.css'); ?>" id="theme" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
#map-canvas {
width:700px;
height: 600px;
margin: 0px;
padding: 10px;
float: left;
background: #FFF !important;
}
#target {
width: 345px;
}
.map-box{
background: #FFF !important;
padding: 25px;
height:600px;
}
#target {
width: 345px;
}
.trip_loopn{margin-top: 10px; margin-bottom:10px;}
.title{
margin-bottom:10px;
}
.title input,textarea{
margin-top:10px;
}
.title h4{
margin-top:10px;
}
.custom_footer {
width:100%;
display:inline-block;
background:burlywood;
color:#fff;
text-align:center;
font-size:20px;
}
</style>
<script>
var map;
var markers = [];
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos,box_no) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
if(box_no == '1'){
updateMarkerAddress1(responses[0].formatted_address);
}
else{
updateMarkerAddress2(responses[0].formatted_address);
}
} else {
if(box_no == '1'){
updateMarkerAddress1('Cannot determine address at this location.');
}
else{
updateMarkerAddress2('Cannot determine address at this location.');
}
}
});
}
function updateMarkerPosition(latLng) {
var str = latLng.lat() +" "+ latLng.lng();
$('#info').val(str);
}
function updateMarkerAddress1(str) {
$('#address1').val(str);
}
function updateMarkerAddress2(str) {
$('#address2').val(str);
}
// drag end
var mj;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var rendererOptions = {
draggable: true
};
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var asaba = new google.maps.LatLng(6.2219387,6.6612933);
var mapOptions = {
zoom: 6,
center: asaba
}
map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 6,
center: asaba
});
// direction service code
directionsDisplay.setMap(map);
// search box defined here
var input1 = $('.pac-input')[0];
var input2 = $('.pac-input')[1];
// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox1 = new google.maps.places.SearchBox((input1));
var searchBox2 = new google.maps.places.SearchBox((input2));
// search function start here
google.maps.event.addListener(searchBox1, 'places_changed', function() {
console.log("searchbox 1");
var places = searchBox1.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
// Create a marker for each place.
marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
draggable: true
});
$(".latitude").val(place.geometry.location.lat());
$(".longitude").val(place.geometry.location.lng());
updateMarkerPosition(marker.getPosition());
geocodePosition(marker.getPosition(),'1');
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition(),'1');
$(".latitude").val(marker.getPosition().lat());
$(".longitude").val(marker.getPosition().lat());
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
if($('#address2').val().length > 0 && $('#address2').val() != 'undefined')
{
console.log("searchbox 1 make route");
setTimeout(function() {
calcRoute();
}, 500);
}
else{
map.fitBounds(bounds);
map.setZoom(9);
}
});
google.maps.event.addListener(searchBox2, 'places_changed', function() {
console.log("searchbox 2");
var places1 = searchBox2.getPlaces();
if (places1.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places1[i]; i++) {
// Create a marker for each place.
marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
draggable: true
});
$(".latitude2").val(place.geometry.location.lat());
$(".longitude2").val(place.geometry.location.lng());
updateMarkerPosition(marker.getPosition());
geocodePosition(marker.getPosition(),'2');
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition(),'2');
$(".latitude2").val(marker.getPosition().lat());
$(".longitude2").val(marker.getPosition().lat());
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
if($('#address1').val().length > 0 && $('#address1').val() != 'undefined')
{
console.log("searchbox 2 make route");
setTimeout(function() {
calcRoute();
}, 500);
}
else{
map.fitBounds(bounds);
map.setZoom(9);
}
});
// google.maps.event.addListener(map, 'bounds_changed', function() {
// var bounds = map.getBounds();
// searchBox2.setBounds(bounds);
// map.setZoom(10);
// });
}
//initial function close here
// calculate route function
function calcRoute() {
var start = $('#address1').val();
var end = $('#address2').val();
var request = {
origin: start,
destination: end,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
console.log("Done");
var route = response.routes[0];
}
});
}
//to compute total distance function
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body class="fix-header">
<!-- ============================================================== -->
<!-- Preloader -->
<!-- ============================================================== -->
<div class="preloader">
<svg class="circular" viewBox="25 25 50 50">
<circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" />
</svg>
</div>
<!-- ============================================================== -->
<!-- Wrapper -->
<!-- ============================================================== -->
<div id="wrapper">
<!-- ============================================================== -->
<!-- Topbar header - style you can find in pages.scss -->
<!-- ============================================================== -->
<nav class="navbar navbar-default navbar-static-top m-b-0">
<div class="navbar-header">
<div class="top-left-part">
<center> <h2 style="color:white; font-weight: bold;">DSTB GIRS</h2></center>
</div>
<ul class="nav navbar-top-links navbar-right pull-right">
<li class="dropdown">
<a class="dropdown-toggle profile-pic" data-toggle="dropdown" href="#">
<b class="hidden-xs"><span class="glyphicon glyphicon-user"></span> <?php echo $this->session->userdata('fullname'); ?></b>
<span class="caret"></span>
</a>
<ul class="dropdown-menu dropdown-user animated flipInY">
<li>
<div class="dw-user-box">
<div class="u-text">
<h4><?php echo $this->session->userdata('fullname'); ?></h4>
<p class="text-muted"><?php echo $this->session->userdata('email'); ?></p>
</div>
</div>
</li>
<li role="separator" class="divider"></li>
<li><a href="<?php echo site_url('logout'); ?>"><span class="glyphicon glyphicon-off"></span> Logout</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav slimscrollsidebar">
<div class="sidebar-head">
<h3><img src="<?php echo base_url('plugins/images/logo.png'); ?>" width="30px" heigth="30px" /> <span class="hide-menu">GIRS System</span></h3>
</div>
<ul class="nav" id="side-menu">
<li class="user-pro">
<a href="#" class="waves-effect"><span class="hide-menu"> <?php echo $this->session->userdata('fullname'); ?> <span class="glyphicon glyphicon-user"></span></span>
</a>
<ul class="nav nav-second-level collapse" aria-expanded="false" style="height: 0px;">
<li><a href="<?php echo site_url('logout'); ?>"><span class="glyphicon glyphicon-user"></span> <span class="hide-menu">Logout</span></a></li>
</ul>
</li>
<li> <a href="<?php echo site_url('dashboard'); ?>" class="waves-effect active"><i class="mdi mdi-av-timer fa-fw" data-icon="v"></i> <span class="hide-menu"> Dashboard <span class="glyphicon glyphicon-home"></span></span></a>
</li>
<li> <a href="<?php echo site_url('location'); ?>" class="waves-effect active"><i class="mdi mdi-av-timer fa-fw" data-icon="v"></i> <span class="hide-menu"> Search for a Location </span></a>
</li>
</ul>
</div>
</div>
<!-- ============================================================== -->
<!-- End Left Sidebar -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Page Content -->
<!-- ============================================================== -->
<div id="page-wrapper">
<div class="container-fluid">
<center>
<br />
<br />
<h1 style="font-weight: bold;">DELTA STATE TOURISM BOARD, ASABA</h1>
<h3><a href="<?php echo site_url('dashboard'); ?>">Dashboard</a></h3>
</center>
<div class="row">
<div class="col-md-4 start_route">
<!-- <div class="add_new_route"> <button class="btn btn-primary"> Add New Route </div> -->
<div class="trip_loop1">
<h4>Search Location: </h4>
<input class="controls form-control pac-input" type="text" placeholder="Search Box"><br />
<input id="address1" class="controls form-control" type="text" placeholder="Nearest address">
<input TYPE="hidden" name="latitude" class="latitude form-control" value="" />
<input TYPE="hidden" name="longitude" class="longitude form-control" value="" />
<input type="hidden" name="marker_status" class="form-control" id="info"/>
</div>
</div>
<div class="col-md-8">
<div id="map-canvas"></div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="<?php echo base_url('plugins/bower_components/jquery/dist/jquery.min.js'); ?>"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url('bootstrap/dist/js/bootstrap.min.js'); ?>"></script>
<!-- Menu Plugin JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js'); ?>"></script>
<!--Counter js -->
<script src="<?php echo base_url('plugins/bower_components/waypoints/lib/jquery.waypoints.js'
);?>"></script>
<script src="<?php echo base_url('plugins/bower_components/counterup/jquery.counterup.min.js');?>"></script>
<!--slimscroll JavaScript -->
<script src="<?php echo base_url('js/jquery.slimscroll.js');?>"></script>
<!--Wave Effects -->
<script src="<?php echo base_url('js/waves.js');?>"></script>
<!-- Vector map JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-2.0.2.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-world-mill-en.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-in-mill.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-us-aea-en.js');?>"></script>
<!-- chartist chart -->
<script src="<?php echo base_url('plugins/bower_components/chartist-js/dist/chartist.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/chartist-plugin-tooltip-master/dist/chartist-plugin-tooltip.min.js');?>"></script>
<!-- sparkline chart JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/jquery-sparkline/jquery.sparkline.min.js');?>"></script>
<script src="<?php echo base_url('plugins/bower_components/jquery-sparkline/jquery.charts-sparkline.js');?>"></script>
<!-- Custom Theme JavaScript -->
<script src="<?php echo base_url('js/custom.min.js');?>"></script>
<script src="<?php echo base_url('js/dashboard3.');?>'"></script>
<!--Style Switcher -->
<script src="<?php echo base_url('plugins/bower_components/styleswitcher/jQuery.style.switcher.js');?>"></script>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.866, lng: 151.196},
zoom: 15
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
}
</script>
</body>
</html><file_sep>A tourism management system application in PHP
<file_sep><!-- Preloader -->
<div class="preloader">
<div class="cssload-speeding-wheel"></div>
</div>
<section id="wrapper" class="new-login-register">
<div class="lg-info-panel">
<div class="inner-panel" style="background-image: <?php echo base_url('plugins/images/wallpaper.jpg'); ?>">
<a href="javascript:void(0)" class="p-20 di"><img src="<?php echo base_url('plugins/images/logo.png') ?>" width="90px" height="90px"></a>
<div class="lg-content">
<h2>DELTA STATE TOURISM BOARD GEOGRAPHICAL INFORMATION RETRIEVAL SYSTEM</h2>
<p class="text-muted">with this App you can get information about locations to thousands of cities, towns, etc. in Delta State and many more... </p>
<a href="<?php echo site_url('register'); ?>" class="btn btn-danger p-l-20 p-r-20"> Sign Up Now</a>
</div>
</div>
</div>
<div class="new-login-box">
<div class="white-box">
<h3 class="box-title m-b-0">Sign In to the App</h3>
<small>Enter your details below</small>
<form class="form-horizontal new-lg-form" id="loginform" method="POST" action="<?php echo site_url('login'); ?>">
<?php if (!empty($this->session->flashdata('error_message'))): ?>
<div class="row">
<div class="col-md-12">
<?php
echo $this->session->flashdata('error_message');
$this->session->set_flashdata('error_message', '');
?>
</div>
</div>
<?php endif; ?>
<div class="form-group m-t-20">
<div class="col-xs-12">
<label>Email</label>
<input class="form-control" type="email" name="email" required placeholder="Email" autofocus required value="<?php echo set_value('email'); ?>" />
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<label>Password</label>
<input id="password" type="password" class="form-control" name="password" placeholder="<PASSWORD>" required value="<?php echo set_value('password'); ?>" />
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Log In</button>
</div>
</div>
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
<p>Don't have an account? <a href="<?php echo site_url('register'); ?>" class="text-primary m-l-5"><b>Sign Up</b></a></p>
</div>
</div>
</form>
<form class="form-horizontal" id="recoverform" action="<?php echo site_url('password/request'); ?>">
<div class="form-group ">
<div class="col-xs-12">
<h3>Recover Password</h3>
<p class="text-muted">Enter your Email and instructions will be sent to you! </p>
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" placeholder="Email">
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-primary btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Reset</button>
</div>
</div>
</form>
</div>
</div>
</section><file_sep> <!-- jQuery -->
<script src="<?php echo base_url('plugins/bower_components/jquery/dist/jquery.min.js'); ?>"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url('bootstrap/dist/js/bootstrap.min.js'); ?>"></script>
<!-- Menu Plugin JavaScript -->
<script src="<?php echo base_url('plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js'); ?>"></script>
<!--slimscroll JavaScript -->
<script src="<?php echo base_url('js/jquery.slimscroll.js'); ?>"></script>
<!--Wave Effects -->
<script src="<?php echo base_url('js/waves.js'); ?>"></script>
<!-- Custom Theme JavaScript -->
<script src="<?php echo base_url('js/custom.min.js'); ?>"></script>
<script src="<?php echo base_url('js/validator.js'); ?>"></script>
<!--Style Switcher -->
<script src="<?php echo base_url('plugins/bower_components/styleswitcher/jQuery.style.switcher.js'); ?>"></script>
</body>
</html>
<file_sep><!-- ============================================================== -->
<!-- Preloader -->
<!-- ============================================================== -->
<div class="preloader">
<svg class="circular" viewBox="25 25 50 50">
<circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" />
</svg>
</div>
<!-- ============================================================== -->
<!-- Wrapper -->
<!-- ============================================================== -->
<div id="wrapper">
<!-- ============================================================== -->
<!-- Topbar header - style you can find in pages.scss -->
<!-- ============================================================== -->
<nav class="navbar navbar-default navbar-static-top m-b-0">
<div class="navbar-header">
<div class="top-left-part">
<center> <h2 style="color:white; font-weight: bold;">DSTB GIRS</h2></center>
</div>
<ul class="nav navbar-top-links navbar-right pull-right">
<li class="dropdown">
<a class="dropdown-toggle profile-pic" data-toggle="dropdown" href="#">
<b class="hidden-xs"><span class="glyphicon glyphicon-user"></span> <?php echo $this->session->userdata('fullname'); ?></b>
<span class="caret"></span>
</a>
<ul class="dropdown-menu dropdown-user animated flipInY">
<li>
<div class="dw-user-box">
<div class="u-text">
<h4><?php echo $this->session->userdata('fullname'); ?></h4>
<p class="text-muted"><?php echo $this->session->userdata('email'); ?></p>
</div>
</div>
</li>
<li role="separator" class="divider"></li>
<li><a href="<?php echo site_url('logout'); ?>"><span class="glyphicon glyphicon-off"></span> Logout</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav slimscrollsidebar">
<div class="sidebar-head">
<h3><img src="<?php echo base_url('plugins/images/logo.png'); ?>" width="30px" heigth="30px" /> <span class="hide-menu">GIRS System</span></h3>
</div>
<ul class="nav" id="side-menu">
<li class="user-pro">
<a href="#" class="waves-effect"><span class="hide-menu"> <?php echo $this->session->userdata('fullname'); ?> <span class="glyphicon glyphicon-user"></span></span>
</a>
<ul class="nav nav-second-level collapse" aria-expanded="false" style="height: 0px;">
<li><a href="<?php echo site_url('logout'); ?>"><span class="glyphicon glyphicon-user"></span> <span class="hide-menu">Logout</span></a></li>
</ul>
</li>
<li> <a href="<?php echo site_url('dashboard'); ?>" class="waves-effect active"><i class="mdi mdi-av-timer fa-fw" data-icon="v"></i> <span class="hide-menu"> Dashboard <span class="glyphicon glyphicon-home"></span></span></a>
</li>
<li> <a href="<?php echo base_url('map.html');?>" class="waves-effect active"><i class="mdi mdi-av-timer fa-fw" data-icon="v"></i> <span class="hide-menu"> Search for a Location</span></a>
</li>
</ul>
</div>
</div>
<!-- ============================================================== -->
<!-- End Left Sidebar -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Page Content -->
<!-- ============================================================== -->
<div id="page-wrapper">
<div class="container-fluid">
<center>
<br />
<br />
<h1 style="font-weight: bold;">DELTA STATE TOURISM BOARD, ASABA</h1>
<h3><a href="<?php echo base_url('map.html'); ?>">Search for a Location</a></h3>
</center>
<div class="vtabs">
<ul class="nav tabs-vertical">
<li class="tab active">
<a data-toggle="tab" href="#home3" aria-expanded="true"> <span class="visible-xs"><span class="glyphicon glyphicon-home"></span></span> <span class="hidden-xs">Find Information</span> </a>
</li>
<li class="tab">
<a data-toggle="tab" href="#profile3" aria-expanded="false"> <span class="visible-xs"><span class="glyphicon glyphicon-user"></span></span> <span class="hidden-xs">Get Directions</span> </a>
</li>
</ul>
<div class="tab-content">
<div id="home3" class="tab-pane active">
<div class="col-md-4 text-justify">
<h3>Tourism Development in Delta State.</h3>
<p>
<img src="<?php echo base_url('plugins/images/elias.png'); ?>" width="100%" />
<br />
<br />
Delta State, the “Big Heart” is one of the thirty–six (36) states that make up Nigeria. It has 25 local Tourism in Delta State
government areas with Asaba as the capital and Warri as major commercial city, Sapele, Agbor, Ughelli, Abraka, wale, Oleh, Ozoro, Koko, Oghara, and Burutu are other major towns.</p>
<p>To promote tourism in the state, the state government established the Delta State Tourism Board and the Ministry of culture and Tourism. The board has a compendium of tourism resources in the state in the form of rochure, bulletin, posters and post cards. There is also a website to that effect. The goal of the Government of Delta tate is to mobilize and encourage private sector participation in the development of tourism. The function of overnment is to create an enabling environment for private initiative to flourish. It is expected that this would generate mployment and improve the general well being of the people.
</p>
</div>
<div class="col-md-8 pull-right">
<div class="row">
<div class="col-md-12">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3966.327187948717!2d6.702666614901781!3d6.2205152954970355!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1043f25f3c36c9d7%3A0xcd8a775334c96b72!2sDelta+State+Tourism+Board!5e0!3m2!1sen!2sng!4v1531383363559" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div id="profile3" class="tab-pane">
<div class="col-md-4 text-justify">
<h3>Tourism Resources in the State.</h3>
<p>
<img src="<?php echo base_url('plugins/images/asaba.png'); ?>" width="100%" />
<br />
<br />
In Delta State there are numerous tourism resources located in different parts of the state. These resources are rouped under the following headings according to Delta State Ministry of Culture and Tourism (2003):
<ul>
<li>Slave trade relic, Aboh Ndokwa East Local Government Area (L.G.A).</li>
<li>Mongo Park Building/Asaba Museum Oshimili South L.G.A.</li>
<li>Bible site at Araya Isoko South L.G.A.</li>
<li>Nwoko Villa, Idumuje Ugboko Aniocha North L.G.A.</li>
<li>Obi palace, Idumuje Ugboko Aniocha North L.G.A.</li>
<li>Nana living History (National Monument) Koko Warri-North L.G.A.</li>
<li>Expatriates grave yard, Asaba Oshimili South L.G.A.</li>
<li>Adane-Okpe, Orerokpe Okpe L.G.A.</li>
<li>Ozomona – Manor House, Onicha-Olona Aniocha North L.G.A.</li>
</ul>
</p>
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<div class="col-md-8 pull-right">
<div class="row">
<div class="col-md-12">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3966.327187948717!2d6.702666614901781!3d6.2205152954970355!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x1043f25f3c36c9d7%3A0xcd8a775334c96b72!2sDelta+State+Tourism+Board!5e0!3m2!1sen!2sng!4v1531383363559" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#page-wrapper -->
<file_sep><!-- Preloader -->
<div class="preloader">
<div class="cssload-speeding-wheel"></div>
</div>
<section id="wrapper" class="new-login-register">
<div class="lg-info-panel">
<div class="inner-panel" style="background-image: <?php echo base_url('plugins/images/wallpaper.jpg'); ?>">
<a href="javascript:void(0)" class="p-20 di"><img src="<?php echo base_url('plugins/images/logo.png') ?>" width="90px" height="90px"></a>
<div class="lg-content">
<h2>DELTA STATE TOURISM BOARD GEOGRAPHICAL INFORMATION RETRIEVAL SYSTEM</h2>
<p class="text-muted">with this App you can get information about locations to thousands of cities, towns, etc. in Delta State and many more... </p>
<a href="<?php echo site_url('login'); ?>" class="btn btn-default p-l-20 p-r-20"> Sign In Now</a>
</div>
</div>
</div>
<div class="new-login-box">
<div class="white-box">
<h3 class="box-title m-b-0">Sign Up to Use the App</h3>
<small>Enter your details below</small>
<form class="form-horizontal new-lg-form" method="post" id="loginform" action="<?php echo site_url('register'); ?>">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" placeholder="<NAME>" name="first_name" value="<?php echo set_value('first_name') ?>">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" placeholder="<NAME>" name="last_name" value="<?php echo set_value('last_name') ?>">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="email" required="" placeholder="Email" name="email" value="<?php echo set_value('email') ?>">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="password" required="" placeholder="<PASSWORD>" name="password" value="<?php echo set_value('password') ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" id="password-confirmed" type="password" required="" placeholder="Confirm Password" name="cpassword"> </div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Sign Up</button>
</div>
</div>
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
<p>Already have an account? <a href="<?php echo site_url('login') ?>" class="text-danger m-l-5"><b>Sign In</b></a></p>
</div>
</div>
</form>
</div>
</div>
</section><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function logout()
{
$this->session->sess_destroy();
redirect(site_url('login'));
}
public function load_page()
{
$login_status = $this->session->userdata('isLoggedIn');
if ($login_status)
{
redirect(site_url('dashboard'));
}
$data['title'] = 'Delta State Tourism Board | GIRS App';
$this->load->view('includes/header', $data);
$this->load->view('login');
$this->load->view('includes/footer');
}
public function index()
{
$this->load_page();
}
public function login()
{
$login_status = $this->session->userdata('isLoggedIn');
if ($login_status)
{
redirect(site_url('dashboard'));
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$user['email'] = $this->input->post('email');
$user['password'] = $this->input->post('password');
$email_error_msg = [
'required' => 'Email is required',
'min_length' => 'Minimum email length is 5',
'max_length' => 'Maximum email length is 255',
'email' => 'Enter a valid email',
];
$password_error_msg = [
'required' => 'Password is required',
'min_length' => 'Minimum password length is 5',
'max_length' => 'Maximum password length is 255'
];
$this->form_validation->set_rules('email', 'Email', 'required|min_length[5]|max_length[255]', $email_error_msg);
$this->form_validation->set_rules('password', '<PASSWORD>', 'required|min_length[5]|max_length[255]', $password_error_msg);
if (!$this->form_validation->run())
{
$message = "<div class='alert alert-danger'><center>". validation_errors() ."</center></div>";
$this->session->set_flashdata('error_message', $message);
$this->load_page();
}
else
{
$valid_login = $this->auth_model->validate_user_login($user);
if ($valid_login)
{
redirect(site_url('dashboard'));
}
else
{
$this->session->set_flashdata('error_message', '<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><center>You cannot login because you provided an invalid email or password!</center></div>');
$this->load_page();
}
}
}
else
{
redirect(base_url());
}
}
}
<file_sep><!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo base_url('plugins/images/logo.png') ?>">
<title><?php echo $title; ?></title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<!-- Bootstrap Core CSS -->
<link href="<?php echo base_url('bootstrap/dist/css/bootstrap.min.css'); ?>" rel="stylesheet">
<!-- Menu CSS -->
<link href="<?php echo base_url('plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.css'); ?>" rel="stylesheet">
<!-- chartist CSS -->
<link href="<?php echo base_url('plugins/bower_components/chartist-js/dist/chartist.min.css'); ?>" rel="stylesheet">
<link href="<?php echo base_url('plugins/bower_components/chartist-plugin-tooltip-master/dist/chartist-plugin-tooltip.css'); ?>" rel="stylesheet">
<!-- Vector CSS -->
<link href="<?php echo base_url('plugins/bower_components/vectormap/jquery-jvectormap-2.0.2.css'); ?>" rel="stylesheet" />
<!-- animation CSS -->
<link href="<?php echo base_url('css/animate.css'); ?>" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?php echo base_url('css/style.css'); ?>" rel="stylesheet">
<!-- color CSS -->
<link href="<?php echo base_url('css/colors/blue-dark.css'); ?>" id="theme" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="fix-header">
|
093cef2b60652a8deed3beb5484b2d8e4f28f052
|
[
"Markdown",
"PHP"
] | 12 |
PHP
|
hackdaemon2/tourism_management_system
|
08ab28b7df344467a37dea2f6ee6ee4f0adc4b16
|
c8a0371e507ec10b380a0935f9fb758e2d79d8f7
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SchoolManager.Generation_utils;
using SchoolManager.School_Models;
namespace SchoolManager
{
class Program
{
static void Main(string[] args)
{
List <string> filenames = new List<string>()
{
"Programa-2019-2020-I-srok",
"Programa-2019-2020-II-srok",
"Programa-2018-2019-I-srok",
"Programa-2018-2019-II-srok",
};
PerformanceTestPMGHaskovo.test(filenames[3]);
//PerformanceTest1.test();
}
}
}<file_sep>using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using SchoolManager.School_Models;
using SchoolManager.School_Models.Higharchy;
namespace SchoolManager
{
static class PerformanceTestPMGHaskovo
{
private static int workDays = 5;
private static int groupsCnt = 28;
class SuperGroupExcell : IEquatable<SuperGroupExcell>
{
public List<string> teachers;
public List<Tuple<string, string>> groups;
public List<Tuple<int, int, int>> positions;
public SuperGroupExcell() { }
public SuperGroupExcell(List <string> teachers, List <Tuple<string, string>> groups, List <Tuple <int, int, int>> positions)
{
this.positions = positions;
this.teachers = teachers;
this.groups = groups;
}
public SuperGroupExcell(string group, string subject, List <string> teachers, Tuple <int, int, int> pos)
{
this.teachers = teachers;
this.positions = new List<Tuple<int, int, int>>() { pos };
this.groups = new List<Tuple<string, string>>() { Tuple.Create(group, subject) };
}
public bool isIntersecting(SuperGroupExcell other)
{
if (groups.Any(g => other.groups.Any(x => x.Item1.Equals(g.Item1)==true) == true) == true) return true;
if (teachers.Any(t => other.teachers.Contains(t) == true) == true) return true;
return false;
}
public bool isSuper()
{
return (teachers.Count > 1 || groups.Count > 1);
}
public override string ToString()
{
return string.Join("|", groups) + " ## " + string.Join("|", teachers);
}
public SuperGroupExcell Clone()
{
return new SuperGroupExcell(teachers.Select(x => x.Clone().ToString()).ToList(), groups.Select(x => Tuple.Create(x.Item1, x.Item2)).ToList(),
positions.Select(t => Tuple.Create(t.Item1, t.Item2, t.Item3)).ToList());
}
public bool Equals([AllowNull] SuperGroupExcell other)
{
return this.ToString().Equals(other.ToString());
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
}
private static SuperGroupExcell merge(SuperGroupExcell A, SuperGroupExcell B)
{
return new SuperGroupExcell(A.teachers.Concat(B.teachers).Distinct().ToList(),
A.groups.Concat(B.groups).Distinct().ToList(),
A.positions.Concat(B.positions).Distinct().ToList());
}
private static List<SuperGroupExcell> getSuperGroups(string filename)
{
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @$"{filename}.xlsm");
using (var package = new ExcelPackage(new FileInfo(path)))
{
var sheetTeacher = package.Workbook.Worksheets["По класове"];
var sheetSubject = package.Workbook.Worksheets["ХЕИ"];
Dictionary<SuperGroupExcell, List<SuperGroupExcell>> superGroups = new Dictionary<SuperGroupExcell, List<SuperGroupExcell>>();
for (int l = 1; l <= 7; l++)
{
for (int day = 1; day <= workDays; day++)
{
List<SuperGroupExcell> currSuperGroups = new List<SuperGroupExcell>();
for (int g = 0; g < groupsCnt; g++)
{
string subject = sheetSubject.Cells[20 + g * 9 + l - 1, 3 + day - 1].Text;
List<string> teachers = sheetTeacher.Cells[2 + g * 9 + l, 3 * day].Text.Split('/').ToList();
if (subject == "") continue;
if(subject=="0") continue;
if(subject=="ИТ") subject = "ИТ/ИТ";
SuperGroupExcell sg = new SuperGroupExcell(sheetTeacher.Cells[2 + g * 9, 1].Text, subject, teachers, Tuple.Create(g, l, day));
int ind = currSuperGroups.FindIndex(x => x.isIntersecting(sg) == true);
if (ind == -1) currSuperGroups.Add(sg);
else currSuperGroups[ind] = merge(currSuperGroups[ind], sg);
}
foreach(var x in currSuperGroups.Where(x => x.isSuper() == true))
{
if (superGroups.ContainsKey(x) == false) superGroups.Add(x, new List<SuperGroupExcell>());
superGroups[x].Add(x);
}
}
}
List<SuperGroupExcell> output = new List<SuperGroupExcell>();
foreach(var item in superGroups)
{
SuperGroupExcell x = item.Value[0];
for (int i = 1; i < item.Value.Count; i++) x = merge(x, item.Value[i]);
output.Add(x);
}
return output;
}
}
private static List<string> getSubjects(string filename)
{
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @$"{filename}.xlsm");
List<string> subjects = new List<string>();
using (var package = new ExcelPackage(new FileInfo(path)))
{
var sheetSubject = package.Workbook.Worksheets["ХЕИ"];
for (int l = 1; l <= 7; l++)
{
for (int day = 1; day <= workDays; day++)
{
for (int g = 0; g < groupsCnt; g++)
{
subjects.Add(sheetSubject.Cells[20 + g * 9 + l - 1, 3 + day - 1].Text);
}
}
}
}
return subjects.Where(x => x!="" && x!="0" && x!="ИТ").Distinct().ToList();
}
private static List <string> getTeachers(string filename)
{
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @$"{filename}.xlsm");
List<string> teachers = new List<string>();
using (var package = new ExcelPackage(new FileInfo(path)))
{
var sheetTeacher = package.Workbook.Worksheets["По класове"];
for (int l = 1; l <= 7; l++)
{
for (int day = 1; day <= workDays; day++)
{
for (int g = 0; g < groupsCnt; g++)
{
sheetTeacher.Cells[2 + g * 9 + l, 3 * day].Text.Split('/').ToList().ForEach(t => teachers.Add(t));
}
}
}
}
return teachers.Distinct().ToList();
}
private static List <Group> getGroups(string filename, List <SuperGroupExcell> superGroupExcells,
List <Subject> subjects, List <Teacher> teachers,
List <LimitationGroup> limitationGroups, List <string> subjectNames)
{
List<Group> groups = new List<Group>();
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @$"{filename}.xlsm");
using (var package = new ExcelPackage(new FileInfo(path)))
{
var sheetTeacher = package.Workbook.Worksheets["По класове"];
var sheetSubject = package.Workbook.Worksheets["ХЕИ"];
for (int g = 0; g < groupsCnt; g++)
{
string gName = sheetTeacher.Cells[2 + g * 9, 1].Text;
List<string> allSubjects = new List<string>();
List<Tuple<string, string>> subject2TeacherName = new List<Tuple<string, string>>();
System.Console.WriteLine($"Group {gName}");
for (int l = 1; l <= 7; l++)
{
for (int day = 1; day <= workDays; day++)
{
string subject = sheetSubject.Cells[20 + g * 9 + l - 1, 3 + day - 1].Text;
List<string> teacherNames = sheetTeacher.Cells[2 + g * 9 + l, 3 * day].Text.Split('/').ToList();
//System.Console.WriteLine($"lesson {l} day {day} => {subject}");
if (subject == "") continue;
if(subject=="0") continue;
if(subject=="ИТ") subject = "ИТ/ИТ";
allSubjects.Add(subject);
if (superGroupExcells.Any(x => x.positions.Any(p => p.Item1 == g && p.Item2 == l && p.Item3 == day) == true) == true)
{
continue;
}
string tName = teacherNames[0];
if(tName=="<NAME>") tName = "Петров";
subject2TeacherName.Add(Tuple.Create(subject, tName));
}
}
var subject2Teacher = subjects.Select(s => Tuple.Create(s,
((subject2TeacherName.Any(x => x.Item1 == s.name) == false) ? null
: teachers.First(t => t.name== subject2TeacherName.First(x => x.Item1 == s.name).Item2)))).ToList();
//var weekLims = limitationGroups.Select(lg => Tuple.Create(lg, allSubjects.Count(x => x==lg.name))).ToList();
System.Console.WriteLine(string.Join("|", allSubjects));
List <Tuple <LimitationGroup, int>> weekLims = new List<Tuple<LimitationGroup, int>>();
foreach(LimitationGroup lg in limitationGroups)
{
if(subjectNames.Any(s => s==lg.name)==false)
{
System.Console.WriteLine($"am ai sq de {lg.name}");
weekLims.Add(Tuple.Create(lg, 6969));
}
else weekLims.Add(Tuple.Create(lg, allSubjects.Count(x => x==lg.name)));
}
List <Tuple<LimitationGroup, int>> dayLims;
if(gName.Length<=3 && gName[0]!='8' && gName.Last()!='д')
{
dayLims = dayLimsGeneral;
System.Console.WriteLine($"{gName} sa generali");
}
else if(gName.Length<=3 && gName.Last()=='д' && gName[0]!='8')
{
dayLims = dayLimsBiology;
System.Console.WriteLine($"{gName} sa biolozi");
}
else if(gName[0]=='8')
{
dayLims = dayLims8Grade;
System.Console.WriteLine($"{gName} sa osmi");
}
else
{
dayLims = dayLimsClashers;
System.Console.WriteLine($"{gName} sa clashari");
}
//else dayLims = weekLims.Select(t => Tuple.Create(t.Item1, Math.Min(t.Item2, 5))).ToList();
//Console.WriteLine($"{gName} -> {string.Join(", ", subject2TeacherName)}");
// Console.WriteLine(string.Join("\n", weekLims.Select(t => $"{t.Item1.name} -> {t.Item2}")));
//subject2Teacher.ForEach(x => Console.WriteLine($"{x.Item1.name} - {((x.Item2 is null)?"null":x.Item2.name)}"));
//Console.WriteLine();
groups.Add(new Group(6, gName, dayLims, weekLims, subject2Teacher));
}
}
return groups;
}
private static List<SuperGroup> superGroups;
private static List<Teacher> teachers;
private static List<LimitationGroup> limitationGroups;
private static List<Subject> subjects;
private static List<Group> groups;
private static LimitationTreeNode higharchy = new LimitationTreeNode("root", null);
private static List <Tuple <LimitationGroup, int>> dayLimsGeneral, dayLimsBiology, dayLims8Grade, dayLimsClashers;
private static void loadDayLimsGeneral()
{
dayLimsGeneral = new List<Tuple<LimitationGroup, int>>();
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("to4ni"), 4));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("razkazvatelni"), 3));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("ezici"), 4));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("математика"), 2));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("бълг. език"), 2));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("информатика"), 2));
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup("II - ри чужд език"), 2));
foreach(Subject s in subjects.Where(x => !(x is null)).Where(x => dayLimsGeneral.Any(t => t.Item1.name==x.name)==false))
dayLimsGeneral.Add(Tuple.Create(new LimitationGroup(s.name), 2));
}
private static void loadDayLimsBiology()
{
dayLimsBiology = new List<Tuple<LimitationGroup, int>>();
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("to4ni"), 3));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("razkazvatelni"), 4));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("ezici"), 4));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("математика"), 2));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("бълг. език"), 2));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("информатика"), 2));
dayLimsBiology.Add(Tuple.Create(new LimitationGroup("II - ри чужд език"), 2));
foreach(Subject s in subjects.Where(x => !(x is null)).Where(x => dayLimsBiology.Any(t => t.Item1.name==x.name)==false))
dayLimsBiology.Add(Tuple.Create(new LimitationGroup(s.name), 2));
}
private static void loadDayLims8Grade()
{
dayLims8Grade = new List<Tuple<LimitationGroup, int>>();
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("to4ni"), 2));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("razkazvatelni"), 4));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("ezici"), 4));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("математика"), 2));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("бълг. език"), 2));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("информатика"), 2));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("II - ри чужд език"), 2));
dayLims8Grade.Add(Tuple.Create(new LimitationGroup("английски език"), 4));
foreach(Subject s in subjects.Where(x => !(x is null)).Where(x => dayLims8Grade.Any(t => t.Item1.name==x.name)==false))
dayLims8Grade.Add(Tuple.Create(new LimitationGroup(s.name), 2));
}
private static void loadDayLimsClashers()
{
dayLimsClashers = new List<Tuple<LimitationGroup, int>>();
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("to4ni"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("razkazvatelni"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("ezici"), 4));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("математика"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("бълг. език"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("информатика"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("II - ри чужд език"), 2));
dayLimsClashers.Add(Tuple.Create(new LimitationGroup("английски език"), 4));
foreach(Subject s in subjects.Where(x => !(x is null)).Where(x => dayLimsClashers.Any(t => t.Item1.name==x.name)==false))
dayLimsClashers.Add(Tuple.Create(new LimitationGroup(s.name), 2));
}
private static void loadDayLims()
{
loadDayLimsGeneral();
loadDayLimsBiology();
loadDayLims8Grade();
loadDayLimsClashers();
}
private static void loadHigharcy()
{
limitationGroups.Where(lg => subjects.Any(s => s.name==lg.name)==false).ToList().ForEach(lg => higharchy.addChild(new LimitationTreeNode(lg)));
Dictionary <string, string> subject2LimGroup = new Dictionary<string, string>();
subject2LimGroup.Add("математика", "tochni");
subject2LimGroup.Add("география", "razkazvatelni");
subject2LimGroup.Add("история", "razkazvatelni");
subject2LimGroup.Add("физика", "razkazvatelni");
subject2LimGroup.Add("биология", "razkazvatelni");
subject2LimGroup.Add("химия", "razkazvatelni");
subject2LimGroup.Add("английски език", "ezici");
foreach(Subject s in subjects)
{
TreeNode dfs(TreeNode x, string name)
{
if(x.GetType()==typeof(LimitationTreeNode) && (x as LimitationTreeNode).name==name) return x;
TreeNode res = null;
foreach(TreeNode y in x.children)
{
TreeNode curr = dfs(y, name);
if(!(curr is null))
{
res = curr;
break;
}
}
return res;
}
TreeNode node = null;
if(subject2LimGroup.ContainsKey(s.name)==true) node = dfs(higharchy, subject2LimGroup[s.name]);
if(node==null) node = higharchy;
else s.limGroups.Add((node as LimitationTreeNode).lg);
System.Console.WriteLine($"{s.name} --> {node.name}");
(node as LimitationTreeNode).addChild(new SubjectTreeNode(s));
}
}
private static void loadSchedule(string filename)
{
List<SuperGroupExcell> excellSuperGroups = getSuperGroups(filename).ToList();
Console.WriteLine($"superGroupsCnt = {excellSuperGroups.Count}");
//Console.WriteLine(string.Join("\n", excellSuperGroups));
for(int i = 0;i<excellSuperGroups.Count;i++) System.Console.WriteLine($"{i} -> {excellSuperGroups[i].ToString()}");
Console.WriteLine();
List<string> subjectNames = getSubjects(filename);
Console.WriteLine($"subjectsCnt = {subjectNames.Count}");
Console.WriteLine(string.Join("\n", subjectNames));
Console.WriteLine();
List<string> teacherNames = getTeachers(filename);
Console.WriteLine($"teachersCnt = {teacherNames.Count}");
Console.WriteLine(string.Join(", ", teacherNames));
Console.WriteLine();
limitationGroups = subjectNames.Select(s => new LimitationGroup(s)).ToList();
limitationGroups.Add(new LimitationGroup("tochni"));
limitationGroups.Add(new LimitationGroup("razkazvatelni"));
limitationGroups.Add(new LimitationGroup("ezici"));
teachers = teacherNames.Select(t => new Teacher(t, new List<Subject>() { })).ToList();
subjects = subjectNames.Select(s => new Subject(s, new List<LimitationGroup>() { limitationGroups.First(lg => lg.name==s)})).ToList();
loadHigharcy();
loadDayLims();
groups = getGroups(filename, excellSuperGroups, subjects, teachers, limitationGroups, subjectNames);
foreach(Group g in groups)
{
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, g.subject2Teacher.First(t => t.Item1.name=="<NAME>").Item2,
g.subject2Teacher.First(t => t.Item1.name=="<NAME>").Item1,
new Generation_utils.IntInInterval(2, 2)));
if(g.name.Last()!='д')
{
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, g.subject2Teacher.First(t => t.Item1.name=="математика").Item2,
g.subject2Teacher.First(t => t.Item1.name=="математика").Item1,
new Generation_utils.IntInInterval(2, 2)));
}
if(g.name.Length<=3 && g.name[0]!='8')
{
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, g.subject2Teacher.First(t => t.Item1.name=="<NAME>").Item2,
g.subject2Teacher.First(t => t.Item1.name=="<NAME>").Item1,
new Generation_utils.IntInInterval(2, 2)));
}
}
superGroups = new List<SuperGroup>();
for(int i = 0;i<excellSuperGroups.Count;i++)
{
List <int> multilessons = new List<int>();
System.Console.WriteLine($"---------- {excellSuperGroups[i].groups[0].Item2}");
if(excellSuperGroups[i].groups[0].Item2=="II - <NAME>")
{
System.Console.WriteLine("ima go");
multilessons.Add(2);
}
SuperGroup sg = new SuperGroup(i.ToString(), excellSuperGroups[i].groups.Select(t => Tuple.Create(groups.First(g => g.name == t.Item1), subjects.First(s => s.name == t.Item2))).ToList(),
excellSuperGroups[i].teachers.Select(t => teachers.First(x => x.name==t)).ToList(), excellSuperGroups[i].positions.Count/excellSuperGroups[i].groups.Count, multilessons);
superGroups.Add(sg);
//Console.WriteLine($"{string.Join(", ", excellSuperGroups[i].groups)} -> {sg.weekLessons}");
}
}
public static void test(string filename)
{
loadSchedule(filename);
List<Generation_utils.Multilesson>[] multilessons = new List<Generation_utils.Multilesson>[5 + 1];
for (int day = 1; day <= 5; day++)
multilessons[day] = new List<Generation_utils.Multilesson>();
Generation_utils.ScheduleGenerator4 sg = new Generation_utils.ScheduleGenerator4(groups, teachers, subjects,
higharchy, multilessons, superGroups);
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
SchoolManager.ScheduleUtils.WeekSchedule res = sg.gen();
if(!(res is null))
{
res.print();
res.exportToExcell($"{filename}_myVersion");
}
System.Console.WriteLine($"Total ellapsed time = {sw.ElapsedMilliseconds}");
sw.Stop();
}
}
}
<file_sep>using SchoolManager.ScheduleUtils;
using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SchoolManager.Generation_utils.ScheduleCompleters.GeneticAlgorithm
{
class ScheduleCompleter
{
private int maxLessons;
private List<Group> state;
private List<Teacher> teachers;
private List<Tuple<SuperGroup, int>> supergroupMultilessons;
private ConfigurationState baseConfig;
public ScheduleCompleter() { }
public ScheduleCompleter(List<Group> state, List<Teacher> teachers, List<Tuple<SuperGroup, int>> supergroupMultilessons, int maxLessons)
{
this.state = state;
this.teachers = teachers;
this.maxLessons = maxLessons;
this.supergroupMultilessons = compressSGMultilesons(supergroupMultilessons.Select(x => Tuple.Create(x.Item1.Clone(), x.Item2)).ToList());
this.baseConfig = new ConfigurationState(this.state, this.teachers, this.supergroupMultilessons, true, this.maxLessons);
}
private List<Tuple<SuperGroup, int>> compressSGMultilesons(List<Tuple<SuperGroup, int>> l)
{
//redo later when we can differenciate better between SuperGroups
l = l.OrderBy(x => x.Item1.name).ToList();
List<Tuple<SuperGroup, int>> output = new List<Tuple<SuperGroup, int>>();
for (int i = 0; i < l.Count;)
{
int startInd = i, sum = 0;
for (; i < l.Count && l[startInd].Equals(l[i]); i++) sum += l[i].Item2;
output.Add(Tuple.Create(l[startInd].Item1, sum));
}
return output;
}
public DaySchedule geneticAlgorithm(bool onlyConsequtive)
{
if (supergroupMultilessons.Count == 3)
{
}
List<ConfigurationState> generation = new List<ConfigurationState>() { baseConfig };
for (int g = 0; g < state.Count; g++)
{
//var watch = System.Diagnostics.Stopwatch.StartNew();
List<ConfigurationState> newGeneration = new List<ConfigurationState>();
foreach (ConfigurationState cs in generation)
{
cs.prepareForMutations(g);
for (int iter = 0; iter < Math.Min(50, cs.options.Count*1.5); iter++)
{
var newElement = cs.Clone();
if(newElement.mutate(g)==true) newGeneration.Add(newElement);
}
}
//watch.Stop(); Console.WriteLine($"New gen time = {watch.ElapsedMilliseconds}");
newGeneration = newGeneration.GroupBy(cs => cs.getState(g)).Select(x => x.First()).ToList();
Console.WriteLine($"Group {g} -> {newGeneration.Count}");
//watch.Restart();
generation = newGeneration.OrderByDescending(cs => cs.fitness(g)).Where(cs => cs.fitness(g)!=double.MinValue).Take(50).ToList();
//watch.Stop(); Console.WriteLine($"Nz i az kvo vreme = {watch.ElapsedMilliseconds}");
//Console.WriteLine(string.Join(" ", generation.Select(cs => cs.fitness(g))));
}
if (generation.Count == 0) return null;
var output = new DaySchedule(generation[0].solution, state, teachers, supergroupMultilessons, generation[0], maxLessons);
return output;
}
private static Dictionary<string, DaySchedule> calculated = new Dictionary<string, DaySchedule>();
public DaySchedule gen(bool onlyConsequtive)
{
string str = string.Join("|", Enumerable.Range(0, state.Count).Select(gInd => string.Join(" ", baseConfig.teacherList[gInd].Select(x => x.Item2.name))));
if (calculated.ContainsKey(str) == true) return calculated[str];
var output = geneticAlgorithm(onlyConsequtive);
calculated[str] = output;
return output;
}
}
}
<file_sep>using SchoolManager.ScheduleUtils;
using SchoolManager.School_Models;
using SchoolManager.School_Models.Higharchy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SchoolManager.Generation_utils
{
class ScheduleGenerator4
{
const int workDays = 5;
const int minLessons = 6, maxLessons = 7;
private TreeNode higharchy;
private List<Group> groups;
private List<Subject> subjects;
private List<Teacher> teachers;
private List<SuperGroup> superGroups;
private List<Multilesson>[] multilessons;
public ScheduleGenerator4() { }
public ScheduleGenerator4(List<Group> groups, List<Teacher> teachers,
List<Subject> subjects, TreeNode higharchy,
List <SuperGroup> superGroups)
{
this.groups = groups;
this.teachers = teachers;
this.subjects = subjects;
this.higharchy = higharchy;
this.superGroups = superGroups;
this.multilessons = new List<Multilesson>[workDays + 1];
for (int day = 1; day <= workDays; day++)
this.multilessons[day] = new List<Multilesson>();
}
public ScheduleGenerator4(List<Group> groups, List<Teacher> teachers,
List<Subject> subjects, TreeNode higharchy, List<Multilesson>[] multilessons,
List <SuperGroup> superGroups) : this(groups, teachers, subjects, higharchy, superGroups)
{
this.multilessons = multilessons;
}
private List<Multilesson> allMultilessons;
private bool[] usedMultilessons;
private WeekSchedule ans = null;
private ScheduleDayState[] dayState;
private int[] teacherDemand;
private List <int>[] supergroup2TeacherInds;
private List <Tuple<int, int>>[] supergroup2GroupSubjetInds;
bool [][] supergroupMultilessonsAdded;
List<Tuple<SuperGroup, int>>[] supergroupMultilessons = new List<Tuple<SuperGroup, int>>[workDays + 1];
private bool arrangeMultilessons(int day, int ind)
{
while(day!=workDays+1 && ind==allMultilessons.Count)
{
ind = 0;
day++;
}
if (day == workDays + 1)
{
int cnt = 0;
for(int i = 0;i<usedMultilessons.Length;i++)
{
if (usedMultilessons[i] == true) cnt++;
}
System.Console.WriteLine($"---------------------------------------------------managed to achieve: {cnt}");
if(cnt!=usedMultilessons.Length) return false;
ScheduleGenerator3 sg = new ScheduleGenerator3(groups, teachers, subjects, higharchy, multilessons, supergroupMultilessons);
WeekSchedule sgRes = sg.gen(workDays, true);
if (sgRes is null) return false;
ans = sgRes;
return true;
}
for(int i = 0;i<allMultilessons.Count;i++)
{
if(usedMultilessons[i]==true) continue;
bool fitted = false;
for(int d = day;d<=workDays;d++)
{
fitted |= applyMultilesson(d, i, allMultilessons[i].val.l, +1);
applyMultilesson(d, i, allMultilessons[i].val.l, -1);
}
if(fitted==false) return false;
}
for(int t = 0;t<teachers.Count;t++)
{
int demand = Enumerable.Range(0, allMultilessons.Count).Where(ind => usedMultilessons[ind]==false)
.Where(ind => allMultilessons[ind].t.Equals(teachers[t])==true)
.Sum(ind => allMultilessons[ind].val.l);
for(int d = day;d<=workDays;d++) demand -= dayState[d].teacherLeftLessons[t];
if(demand>0) return false;
}
bool res = false;
if (usedMultilessons[ind] == false)
{
usedMultilessons[ind] = true;
multilessons[day].Add(allMultilessons[ind]);
bool successful = applyMultilesson(day, ind, allMultilessons[ind].val.l, +1);
if(successful==true)
{
ScheduleGenerator3 sg = new ScheduleGenerator3(groups, teachers, subjects, higharchy, multilessons, supergroupMultilessons);
if (sg.gen(workDays, true) != null)
{
res |= arrangeMultilessons(day, ind + 1);
}
}
applyMultilesson(day, ind, allMultilessons[ind].val.l, -1);
multilessons[day].RemoveAt(multilessons[day].Count - 1);
usedMultilessons[ind] = false;
if(res==true) return true;
}
if((usedMultilessons[ind]==true || day!=workDays) && arrangeMultilessons(day, ind+1)==true)
{
res = true;
return true;
}
System.Console.WriteLine($"em pone {usedMultilessons.Count(x => x==true)}");
return false;
}
bool applySupergroupMultilesson(int day, int sgInd, int lessonsCnt, int sign)
{
bool successful = true;
if(sign==+1)
{
superGroups[sgInd].weekLessons -= lessonsCnt;
supergroupMultilessons[day].Add(Tuple.Create(superGroups[sgInd], lessonsCnt));
}
else
{
superGroups[sgInd].weekLessons += lessonsCnt;
supergroupMultilessons[day].RemoveAt(supergroupMultilessons[day].Count - 1);
}
successful &= (superGroups[sgInd].weekLessons>=0);
for(int iter = 0;iter<lessonsCnt;iter++)
{
foreach(var item in supergroup2GroupSubjetInds[sgInd])
{
successful &= dayState[day].updateLimitsNoTeacher(item.Item1, item.Item2, sign);
}
foreach(int tInd in supergroup2TeacherInds[sgInd])
{
successful &= dayState[day].updateTeacherLimits(tInd, sign);
teacherDemand[tInd] -= sign*lessonsCnt;
}
}
return successful;
}
private bool applyMultilesson(int day, int ind, int lessonsCnt, int sign)
{
bool successful = true;
int gInd = groups.FindIndex(g => g.Equals(allMultilessons[ind].g));
int tInd = teachers.FindIndex(t => t.Equals(allMultilessons[ind].t));
int sInd = allMultilessons[ind].g.findSubject(allMultilessons[ind].s);
for(int iter = 0;iter<lessonsCnt;iter++)
{
successful &= dayState[day].updateLimits(gInd, sInd, tInd, sign);
}
return successful;
}
bool solveSuperGroup(int day, int sgInd, int mInd)
{
if (superGroups[sgInd].weekLessons == 0)
{
return arrangeSuperGroups(sgInd + 1, day);
}
bool res = false;
//using required multilessons
for(int i = 0;i<superGroups[sgInd].requiredMultilessons.Count;i++)
{
if(supergroupMultilessonsAdded[sgInd][i]==true) continue;
supergroupMultilessonsAdded[sgInd][i] = true;
bool succ = applySupergroupMultilesson(day, sgInd, superGroups[sgInd].requiredMultilessons[i], +1);
if(succ==true && arrangeSuperGroups(sgInd+1, day)==true) res = true;
supergroupMultilessonsAdded[sgInd][i] = false;
applySupergroupMultilesson(day, sgInd, superGroups[sgInd].requiredMultilessons[i], -1);
if(res==true) return true;
}
int requiredLeft = Enumerable.Range(0, superGroups[sgInd].requiredMultilessons.Count)
.Sum(ind => ((supergroupMultilessonsAdded[sgInd][ind]==false)?superGroups[sgInd].requiredMultilessons[ind]:0));
//using free multilessons
for(int lessons = superGroups[sgInd].weekLessons - requiredLeft;lessons>=((day != workDays) ? 0 : superGroups[sgInd].weekLessons);lessons--)
{
bool succ = applySupergroupMultilesson(day, sgInd, lessons, +1);
if(succ==true && arrangeSuperGroups(sgInd+1, day)==true) res = true;
applySupergroupMultilesson(day, sgInd, lessons, -1);
if(res==true) return true;
}
return false;
}
private bool arrangeSuperGroups(int sgInd, int day)
{
ScheduleGenerator3 sg = null;
if (sgInd==superGroups.Count)
{
/*
for (int t = 0; t < teachers.Count; t++)
{
int demand = teacherDemand[t];
int today = minLessons - dayState[day].teacherLeftLessons[t];
if (demand > (workDays - day) * minLessons) return false;
}
*/
sg = new ScheduleGenerator3(groups, teachers, subjects, higharchy, multilessons, supergroupMultilessons);
if (sg.gen(day, (day==workDays)) == null) return false;
Console.WriteLine($"--------------> {day} {sgInd}");
if (day == workDays) return arrangeMultilessons(1, 0);
return arrangeSuperGroups(0, day + 1);
}
for (int t = 0; t < teachers.Count; t++)
{
int demand = teacherDemand[t];
int today = minLessons - dayState[day].teacherLeftLessons[t];
if (demand > (workDays - day+1) * minLessons - today) return false;
}
if(day!=workDays)
{
sg = new ScheduleGenerator3(groups, teachers, subjects, higharchy, multilessons, supergroupMultilessons);
if (sg.gen(day, false) == null) return false;
}
return solveSuperGroup(day, sgInd, 0);
}
void init()
{
allMultilessons = new List<Multilesson>();
foreach(Group g in groups)
{
foreach (Multilesson m in g.requiredMultilessons)
allMultilessons.Add(m);
}
usedMultilessons = new bool[allMultilessons.Count];
for (int i = 0; i < usedMultilessons.Length; i++) usedMultilessons[i] = false;
dayState = new ScheduleDayState[workDays + 1];
List<Group> refList = groups.Select(g => g.CloneFull()).ToList();
for (int day = 1; day <= workDays; day++)
{
dayState[day] = new ScheduleDayState(refList.Select(g => g.ClonePartial(g.weekLims)).ToList(), teachers, maxLessons);
}
for (int day = 1; day <= workDays; day++)
{
supergroupMultilessons[day] = new List<Tuple<SuperGroup, int>>(100);
}
teacherDemand = new int[teachers.Count];
for(int t = 0;t<teachers.Count;t++)
{
teacherDemand[t] = superGroups.Where(sg => sg.teachers.Any(x => x.Equals(teachers[t]) == true) == true).Sum(sg => sg.weekLessons);
}
supergroup2TeacherInds = new List<int>[superGroups.Count];
supergroup2GroupSubjetInds = new List<Tuple<int, int>>[superGroups.Count];
for(int i = 0;i<superGroups.Count;i++)
{
supergroup2TeacherInds[i] = new List<int>();
foreach(Teacher t in superGroups[i].teachers) supergroup2TeacherInds[i].Add(teachers.FindIndex(x => x.Equals(t)));
supergroup2GroupSubjetInds[i] = new List<Tuple<int, int>>();
foreach(var g in superGroups[i].groups)
supergroup2GroupSubjetInds[i].Add(Tuple.Create(groups.FindIndex(x => x.Equals(g.Item1)==true),
g.Item1.findSubject(g.Item2)));
}
supergroupMultilessonsAdded = new bool[superGroups.Count][];
for(int i = 0;i<supergroupMultilessonsAdded.Length;i++)
{
supergroupMultilessonsAdded[i] = new bool[superGroups[i].requiredMultilessons.Count];
for(int j = 0;j<supergroupMultilessonsAdded[i].Length;j++) supergroupMultilessonsAdded[i][j] = false;
}
}
public WeekSchedule gen()
{
init();
Console.WriteLine($"allMultilessons = {allMultilessons.Count}");
bool res = arrangeSuperGroups(0, 1);
/*
if(res==true)
{
ans.print();
ans.exportToExcell("programa1");
}
*/
return ans;
}
}
}
<file_sep>using SchoolManager.Generation_utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace SchoolManager.School_Models
{
class LimitationGroupPair
{
public LimitationGroup g;
public int cnt;
public LimitationGroupPair() { }
public LimitationGroupPair(LimitationGroup g, int cnt)
{
this.g = g;
this.cnt = cnt;
}
public LimitationGroupPair(Tuple<LimitationGroup, int> x)
{
this.g = x.Item1;
this.cnt = x.Item2;
}
public LimitationGroupPair Clone()
{
return new LimitationGroupPair(g, cnt);
}
}
class Group
{
public int minLessons;
public string name;
private List<LimitationGroupPair> dayLims;
public List<LimitationGroupPair> weekLims { get; private set; }
public List<Tuple<Subject, Teacher>> subject2Teacher;
public List<Multilesson> requiredMultilessons;
private List<int>[] subjectDayDependees, subjectWeekDependees;
private int[] subjectDaySelf, subjectWeekSelf;
public List<Subject> curriculum;
public Group() { }
public Group(int minLessons, string name, List<Tuple<LimitationGroup, int>> dayLims,
List<Tuple<LimitationGroup, int>> weekLims,
List<Tuple<Subject, Teacher>> subject2Teacher)
{
this.name = name;
this.minLessons = minLessons;
this.curriculum = new List<Subject>();
this.dayLims = dayLims.Select(x => new LimitationGroupPair(x)).ToList();
this.weekLims = weekLims.Select(x => new LimitationGroupPair(x)).ToList();
this.subject2Teacher = subject2Teacher;
this.subjectDayDependees = new List<int>[this.subject2Teacher.Count];
this.subjectWeekDependees = new List<int>[this.subject2Teacher.Count];
this.subjectDaySelf = new int[this.subject2Teacher.Count];
this.subjectWeekSelf = new int[this.subject2Teacher.Count];
for (int i = 0; i < subject2Teacher.Count; i++)
{
subjectDayDependees[i] = new List<int>();
subjectWeekDependees[i] = new List<int>();
foreach (LimitationGroup lg in subject2Teacher[i].Item1.limGroups)
{
for (int j = 0; j < dayLims.Count; j++)
{
if (dayLims[j].Item1.Equals(lg) == true)
{
subjectDayDependees[i].Add(j);
if (dayLims[j].Item1.name == subject2Teacher[i].Item1.name)
{
subjectDaySelf[i] = j;
}
}
}
for (int j = 0; j < weekLims.Count; j++)
{
if (weekLims[j].Item1.Equals(lg)==true)
{
subjectWeekDependees[i].Add(j);
if (weekLims[j].Item1.name == subject2Teacher[i].Item1.name) subjectWeekSelf[i] = j;
}
}
}
}
this.requiredMultilessons = new List<Multilesson>();
}
public Group(int minLessons, string name, List<Tuple<LimitationGroup, int>> dayLims,
List<Tuple<LimitationGroup, int>> weekLims,
List<Tuple<Subject, Teacher>> subject2Teacher,
List <Multilesson> requiredMultilessons) : this(minLessons, name, dayLims, weekLims, subject2Teacher)
{
this.requiredMultilessons = requiredMultilessons;
}
public int getSubjectDayLim(int s)
{
return dayLims[subjectDaySelf[s]].cnt;
}
public int getSubjectWeekLim(int s)
{
return weekLims[subjectWeekSelf[s]].cnt;
}
public int getLimGroupDayLim(LimitationGroup lg)
{
var x = dayLims.FirstOrDefault(item => item.g.Equals(lg)==true);
if (x == null) return int.MaxValue;
return x.cnt;
}
public int findSubject(Subject s)
{
for(int i = 0;i<subject2Teacher.Count;i++)
{
if (subject2Teacher[i].Item1.Equals(s) == true)
return i;
}
return -1;
}
public Group CloneFull()
{
Group output = new Group();
output.name = name;
output.minLessons = minLessons;
output.subject2Teacher = subject2Teacher;
output.curriculum = curriculum.Select(x => x).ToList();
output.dayLims = dayLims.Select(x => x.Clone()).ToList();
output.weekLims = weekLims.Select(x => x.Clone()).ToList();
output.subjectDayDependees = subjectDayDependees;
output.subjectWeekDependees = subjectWeekDependees;
output.subjectDaySelf = subjectDaySelf;
output.subjectWeekSelf = subjectWeekSelf;
output.requiredMultilessons = requiredMultilessons;
return output;
}
public Group ClonePartial(List <LimitationGroupPair> weekLimsKeep)
{
Group output = new Group();
output.name = name;
output.minLessons = minLessons;
output.subject2Teacher = subject2Teacher;
output.dayLims = dayLims.Select(x => x.Clone()).ToList();
output.curriculum = curriculum.Select(x => x).ToList();
output.weekLims = weekLimsKeep;
output.subjectDayDependees = subjectDayDependees;
output.subjectWeekDependees = subjectWeekDependees;
output.subjectDaySelf = subjectDaySelf;
output.subjectWeekSelf = subjectWeekSelf;
output.requiredMultilessons = requiredMultilessons;
return output;
}
public override bool Equals(object obj)
{
if (obj.GetType()==typeof(Group))
{
return name.Equals((obj as Group).name);
}
return false;
}
public int getDayBottleneck(int s)
{
int bottleneck = int.MaxValue;
foreach (int ind in subjectDayDependees[s])
{
bottleneck = Math.Min(bottleneck, dayLims[ind].cnt);
}
return bottleneck;
}
public int getWeekBottleneck(int s)
{
int bottleneck = int.MaxValue;
foreach (int ind in subjectWeekDependees[s])
{
bottleneck = Math.Min(bottleneck, weekLims[ind].cnt);
}
return bottleneck;
}
public bool checkSubject(int s, int cnt = 1)
{
foreach(int ind in subjectDayDependees[s])
{
if (dayLims[ind].cnt < cnt) return false;
}
foreach (int ind in subjectWeekDependees[s])
{
if (weekLims[ind].cnt < cnt) return false;
}
return true;
}
public bool applySubject(int s, int sign)
{
if (sign == +1) curriculum.Add(subject2Teacher[s].Item1);
else curriculum.Remove(subject2Teacher[s].Item1);
//Console.WriteLine(subjectDayDependees[s].Count);
foreach (int ind in subjectDayDependees[s])
{
dayLims[ind].cnt -= sign;
if (dayLims[ind].cnt < 0) return false;
}
foreach (int ind in subjectWeekDependees[s])
{
weekLims[ind].cnt -= sign;
if (weekLims[ind].cnt < 0) return false;
}
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.School_Models
{
class Subject
{
public string name { get; set; }
public List <LimitationGroup> limGroups { get; set; }
public Subject() { }
public Subject(string name, List<LimitationGroup> limGroups)
{
this.name = name;
this.limGroups = limGroups;
}
public override bool Equals(object obj)
{
if (obj is null) return false;
if (obj.GetType() == typeof(Subject))
{
return name.Equals((obj as Subject).name);
}
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Linq;
namespace SchoolManager.MaxFlow
{
class MinCostMaxFlowGraph : FlowGraph
{
const int inf = (int)1e9 + 5;
const long infLL = (long)1e18 + 5;
int n;
int source, sink;
List<Edge> edges;
List<List<int>> adj;
int[] lastEdge;
long[] dist;
public MinCostMaxFlowGraph()
{
this.edges = new List<Edge>();
this.adj = new List<List<int>>();
}
public MinCostMaxFlowGraph(int n, int s, int t) : this()
{
this.n = n;
this.sink = t;
this.source = s;
this.dist = new long[n + 5];
this.lastEdge = new int[n + 5];
for (int i = 0; i <= n + 5; i++)
{
this.adj.Add(new List<int>());
}
}
public override int addEdge(int u, int v, int cap)
{
return addEdge(u, v, cap, 0);
}
class DijkstraNodeState : IComparable<DijkstraNodeState>
{
public int node;
public long dist;
public DijkstraNodeState() { }
public DijkstraNodeState(int node, long dist)
{
this.node = node;
this.dist = dist;
}
public int CompareTo([AllowNull] DijkstraNodeState other)
{
if(dist!=other.dist) return dist.CompareTo(other.dist);
return node.CompareTo(other.node);
}
}
private void useNode(int x, SortedSet <DijkstraNodeState> pq)
{
foreach(int e in adj[x])
{
if(dist[edges[e].v] > dist[x] + edges[e].cost && edges[e].cap>0)
{
dist[edges[e].v] = dist[x] + edges[e].cost;
lastEdge[edges[e].v] = e^1;
pq.Add(new DijkstraNodeState(edges[e].v, dist[edges[e].v]));
}
}
}
private long Dijkstra()
{
for(int x = 0;x<dist.Length;x++)
{
dist[x] = infLL;
}
lastEdge[source] = -1;
dist[source] = 0;
SortedSet<DijkstraNodeState> pq = new SortedSet<DijkstraNodeState>();
pq.Add(new DijkstraNodeState(source, dist[source]));
while(pq.Count>0)
{
DijkstraNodeState x = pq.Min;
pq.Remove(x);
if (x.dist != dist[x.node]) continue;
useNode(x.node, pq);
}
return dist[sink];
}
public void test()
{
SortedSet<DijkstraNodeState> pq = new SortedSet<DijkstraNodeState>();
pq.Add(new DijkstraNodeState(1, 1));
pq.Add(new DijkstraNodeState(4, 4));
pq.Add(new DijkstraNodeState(3, 3));
pq.Add(new DijkstraNodeState(3, 3));
pq.Add(new DijkstraNodeState(2, 2));
Console.WriteLine(pq.Min.dist);
pq.Remove(pq.Min);
Console.WriteLine(pq.Min.dist);
}
public override long findFlow()
{
long flow = 0;
long flowCost = 0;
while(true)
{
long d = Dijkstra();
if (d == infLL) break;
int bottleneck = inf;
int x = sink;
while(x!=source)
{
bottleneck = Math.Min(bottleneck, edges[lastEdge[x]^1].cap);
x = edges[lastEdge[x]].v;
}
x = sink;
while(x!=source)
{
edges[lastEdge[x]].cap += bottleneck;
edges[lastEdge[x]^1].cap -= bottleneck;
x = edges[lastEdge[x]].v;
}
flow += bottleneck;
flowCost += bottleneck*d;
}
return flow;
}
public override int getEdge(int ind)
{
return edges[ind ^ 1].cap;
}
public override int addEdge(int u, int v, int cap, long cost)
{
edges.Add(new Edge(u, v, cap, cost));
adj[u].Add(edges.Count - 1);
edges.Add(new Edge(v, u, 0, cost));
adj[v].Add(edges.Count - 1);
return edges.Count - 2;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.School_Models
{
class SuperGroup
{
public string name;
public List<Tuple<Group, Subject>> groups;
public List<Teacher> teachers;
public int weekLessons;
public List<int> requiredMultilessons;
public SuperGroup() { }
public SuperGroup(string name, List <Tuple <Group, Subject>> groups, List <Teacher> teachers, int weekLessons, List <int> requiredMultilessons)
{
this.name = name;
this.groups = groups;
this.teachers = teachers;
this.weekLessons = weekLessons;
this.requiredMultilessons = requiredMultilessons;
}
public SuperGroup Clone()
{
return new SuperGroup(name, groups, teachers, weekLessons, requiredMultilessons);
}
public override bool Equals(object obj)
{
if (obj is null) return false;
if (obj.GetType() != typeof(SuperGroup)) return false;
return name.Equals((obj as SuperGroup).name);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace SchoolManager.School_Models.Higharchy
{
class TreeNode
{
public string name;
public int nodeCode;
public TreeNode parent;
public List<TreeNode> children;
protected TreeNode()
{
this.name = "";
this.nodeCode = -1;
this.parent = null;
this.children = new List<TreeNode>();
}
protected TreeNode(TreeNode other)
{
this.name = other.name;
this.parent = other.parent;
this.nodeCode = other.nodeCode;
this.children = new List<TreeNode>();
foreach(TreeNode x in other.children)
{
this.children.Add(x.Clone());
this.children[this.children.Count - 1].parent = this;
}
}
public void encodeTree(ref int nodeCnt)
{
nodeCode = nodeCnt;
nodeCnt++;
foreach (TreeNode x in children)
x.encodeTree(ref nodeCnt);
}
public void printTree(int depth = 0)
{
for (int i = 0; i < depth; i++) Console.Write(" ");
Console.WriteLine($"{name} {nodeCode}");
foreach (TreeNode x in children)
x.printTree(depth+1);
}
public virtual TreeNode Clone()
{
return new TreeNode(this);
}
}
class LimitationTreeNode : TreeNode
{
public LimitationGroup lg;
public LimitationTreeNode() : base()
{
}
public LimitationTreeNode(LimitationGroup lg) : this()
{
this.name = lg.name;
this.lg = lg;
}
public LimitationTreeNode(string name, LimitationGroup lg) : this()
{
this.name = name;
this.lg = lg;
}
public LimitationTreeNode(LimitationTreeNode other) : base(other)
{
this.lg = other.lg;
}
public void addChild(TreeNode x)
{
children.Add(x);
x.parent = this;
}
public override TreeNode Clone()
{
return new LimitationTreeNode(this);
}
}
class SubjectTreeNode : TreeNode
{
public Subject s;
public SubjectTreeNode() : base()
{
}
public SubjectTreeNode(Subject s) : this()
{
this.name = s.name;
this.s = s;
}
public SubjectTreeNode(string name, Subject s) : this()
{
this.name = name;
this.s = s;
}
public SubjectTreeNode(SubjectTreeNode other) : base(other)
{
this.s = other.s;
}
public override TreeNode Clone()
{
return new SubjectTreeNode(this);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.School_Models
{
class Teacher
{
public string name { get; set; }
public List<Subject> subjects { get; set; }
public Teacher() { }
public Teacher(string name, List<Subject> subjects)
{
this.name = name;
this.subjects = subjects;
}
public Teacher Clone()
{
Teacher output = new Teacher(name, subjects);
return output;
}
public override bool Equals(object obj)
{
if (obj is null) return false;
if (obj.GetType() == typeof(Teacher))
{
return name.Equals((obj as Teacher).name);
}
return false;
}
}
}
<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using SchoolManager.School_Models;
namespace SchoolManager.Generation_utils.ScheduleCompleters.GeneticAlgorithm
{
class ConfigurationState : ConfigurationStateBase
{
private int[] teacherLeftLessons;
private static Random rnd = new Random(22);
public List<Tuple<int, Subject>>[] solution;
public List<TeacherList> options;
public ConfigurationState(ConfigurationState other) : base(other)
{
this.teacherLeftLessons = new int[other.teacherLeftLessons.GetLength(0)];
Array.Copy(other.teacherLeftLessons, this.teacherLeftLessons, other.teacherLeftLessons.Length);
this.options = other.options;
this.solution = new List<Tuple<int, Subject>>[other.solution.GetLength(0)];
Array.Copy(other.solution, this.solution, other.solution.Length);
}
public ConfigurationState(List<Group> state, List<Teacher> teachers, List<Tuple<SuperGroup, int>> supergroupMultilessons,
bool onlyConsequtive, int maxLessons)
: base(state, teachers, supergroupMultilessons, onlyConsequtive, maxLessons)
{
solution = new List<Tuple<int, Subject>>[state.Count];
teacherLeftLessons = new int[teachers.Count];
Array.Fill(teacherLeftLessons, 0);
for(int g = 0;g<state.Count;g++)
{
updateTeacherLessons(teacherList[g], +1);
}
}
public long getState(int g)
{
long stateVal = 0;
const long key = 1019;
const long mod = 67772998972500529;
const long emptySymbol = key - 1;
const long separatingSymbol = key - 2;
stateVal = (stateVal * key + g + 1) % mod;
for (int lesson = 0; lesson < maxLessons; lesson++)
{
for (int t = 0; t < teachers.Count + supergroupMultilessons.Count; t++)
{
if(lastPosSeen[t]<g)
stateVal = (stateVal * key + emptySymbol + 1) % mod;
else
stateVal = (stateVal * key + Convert.ToInt64(lessonTeacher[lesson, t] != 0) + 1) % mod;
}
}
return stateVal;
}
private void updateTeacherLessons(List<Tuple<int, Subject>> l, int change)
{
foreach (var item in l)
{
if (item.Item1 < teachers.Count) teacherLeftLessons[item.Item1] += change;
else
{
foreach (var t in teacherDependees[item.Item1])
teacherLeftLessons[t] += change;
}
}
}
public void prepareForMutations(int g)
{
options = teacherPermList[g].Where(tl => checkSuitable(tl, onlyConsequtive) == true).ToList();
}
private double? fitnessCache = null;
public bool mutate(int g)
{
List<TeacherList> options = teacherPermList[g].Where(tl => checkSuitable(tl, onlyConsequtive) == true).ToList();
if (options.Count == 0)
return false;
fitnessCache = null;
TeacherList tl = options[rnd.Next(options.Count)];
solution[g] = tl.l;
applyPermution(tl);
return true;
}
public new ConfigurationState Clone()
{
return new ConfigurationState(this);
}
public double fitness(int g)
{
if (fitnessCache != null)
return fitnessCache.Value;
double lessonGapSum = 0;
for (int t = 0; t < teachers.Count; t++)
{
int cnt = 0;
for (int l = 1; l <= maxLessons; l++)
{
if (lessonTeacher[l, t] > 0)
{
lessonGapSum += Math.Pow(cnt, 3)*teacherLeftLessons[t];
}
else
cnt++;
}
lessonGapSum += Math.Pow(cnt, 3)*teacherLeftLessons[t];
}
double furtherOptionsProduct = 1;
for (int gInd = g + 1; gInd < state.Count; gInd++)
{
furtherOptionsProduct *= teacherPermList[gInd].Count(tl => checkSuitable(tl, onlyConsequtive) == true);
if (furtherOptionsProduct == 0) return double.MinValue;
}
fitnessCache = furtherOptionsProduct + lessonGapSum;
return fitnessCache.Value;
}
public override void applyPermution(TeacherList tl)
{
base.applyPermution(tl);
updateTeacherLessons(tl.l, -1);
}
public override void undoPermutation(TeacherList tl)
{
base.undoPermutation(tl);
updateTeacherLessons(tl.l, +1);
}
}
}
<file_sep>using SchoolManager.MaxFlow;
using SchoolManager.ScheduleUtils;
using SchoolManager.School_Models;
using SchoolManager.School_Models.Higharchy;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SchoolManager.Generation_utils
{
class ScheduleGenerator3
{
const int workDays = 5;
const int minLessons = 6, maxLessons = 7;
private List<Group> groups;
private List<Teacher> teachers;
private List<Subject> subjects;
private TreeNode higharchy;
private List<Tuple<SuperGroup, int>>[] supergroupMultilessons;
private List<Multilesson>[] multilessons;
public ScheduleGenerator3() { }
public ScheduleGenerator3(List<Group> groups, List<Teacher> teachers,
List<Subject> subjects, TreeNode higharchy)
{
this.groups = groups;
this.teachers = teachers;
this.subjects = subjects;
this.higharchy = higharchy;
groupNode = new int[groups.Count];
groupHigharchy = new TreeNode[groups.Count];
teacherNode = new int[teachers.Count];
groupSubjectNode = new int[groups.Count, subjects.Count];
this.multilessons = new List<Multilesson>[workDays + 1];
this.supergroupMultilessons = new List<Tuple<SuperGroup, int>>[workDays + 1];
for (int day = 1; day <= workDays; day++)
{
this.multilessons[day] = new List<Multilesson>();
this.supergroupMultilessons[day] = new List<Tuple<SuperGroup, int>>();
}
}
public ScheduleGenerator3(List<Group> groups, List<Teacher> teachers,
List<Subject> subjects, TreeNode higharchy, List<Multilesson>[] multilessons) : this(groups, teachers, subjects, higharchy)
{
this.multilessons = multilessons;
}
public ScheduleGenerator3(List<Group> groups, List<Teacher> teachers,
List<Subject> subjects, TreeNode higharchy,
List<Multilesson>[] multilessons,
List<Tuple<SuperGroup, int>>[] supergroupMultilessons) : this(groups, teachers, subjects, higharchy, multilessons)
{
this.supergroupMultilessons = supergroupMultilessons;
}
private ScheduleDayState[] dayState;
private int[] teacherNode;
private int allTeachersNode;
private int[,] groupSubjectNode;
private int[] groupNode;
private TreeNode[] groupHigharchy;
private CirculationFlowGraph G;
private List<int>[,] teacherGroup2Subjects;
private int[,] groupSubject2Teacher;
private int[,] groupSubjectEdge;
private static List <Tuple <int, int>>[][] lastConfig = null;
private static DaySchedule[] lastConfigSolution = null;
private void initNodes()
{
int node = 1;
//initializing nodes
for (int g = 0;g<groups.Count;g++)
{
groupNode[g] = node;
node++;
}
for(int t = 0;t<teachers.Count;t++)
{
teacherNode[t] = node;
node++;
}
for(int g = 0;g<groups.Count;g++)
{
groupHigharchy[g] = higharchy.Clone();
groupHigharchy[g].encodeTree(ref node);
}
for(int g = 0;g<groups.Count;g++)
{
void findSubjects(TreeNode x)
{
if(x.GetType()==typeof(SubjectTreeNode))
{
int sInd = groups[g].findSubject((x as SubjectTreeNode).s);
if(sInd!=-1) groupSubjectNode[g, sInd] = x.nodeCode;
return;
}
foreach (TreeNode y in x.children)
findSubjects(y);
}
findSubjects(groupHigharchy[g]);
}
allTeachersNode = node;
node++;
G = new CirculationFlowGraph(node*2);
}
void initArrays()
{
groupSubjectEdge = new int[groups.Count, subjects.Count];
dayState = new ScheduleDayState[workDays + 1];
List <Group> refList = groups.Select(g => g.CloneFull()).ToList();
for(int day = 1;day<=workDays;day++)
{
dayState[day] = new ScheduleDayState(refList.Select(g => g.ClonePartial(g.weekLims)).ToList(), teachers, maxLessons);
}
groupSubject2Teacher = new int[groups.Count, subjects.Count];
for (int g = 0; g < groups.Count; g++)
{
for (int s = 0; s < groups[g].subject2Teacher.Count; s++)
{
if (groups[g].subject2Teacher[s].Item2 == null)
{
continue;
}
groupSubject2Teacher[g, s] = teachers.FindIndex(t => t.name == groups[g].subject2Teacher[s].Item2.name);
}
}
teacherGroup2Subjects = new List<int>[teachers.Count, groups.Count];
for (int t = 0; t < teachers.Count; t++)
{
for (int g = 0; g < groups.Count; g++)
{
teacherGroup2Subjects[t, g] = new List<int>();
for (int s = 0; s < groups[g].subject2Teacher.Count; s++)
{
if (groups[g].subject2Teacher[s].Item2 == null) continue;
if (groups[g].subject2Teacher[s].Item2.name == teachers[t].name)
{
teacherGroup2Subjects[t, g].Add(s);
}
}
}
}
if(lastConfig is null)
{
lastConfigSolution = new DaySchedule[workDays+1];
lastConfig = new List<Tuple<int, int>>[workDays+1][];
for(int day = 1;day<=workDays;day++) lastConfig[day] = null;
}
}
private bool tryConfig(List <Tuple <int, int>>[] config, int day)
{
bool succ = true;
for(int g = 0;g<config.Length;g++)
{
foreach(var tup in config[g]) succ &= dayState[day].updateLimits(g, tup.Item1, tup.Item2, +1);
if (dayState[day].groups[g].curriculum.Count < dayState[day].groups[g].minLessons
|| dayState[day].groups[g].curriculum.Count > maxLessons)
{
succ = false;
}
}
for(int g = 0;g<groups.Count;g++)
{
foreach(Multilesson m in multilessons[day].Where(x => (x.g.Equals(groups[g])==true)))
{
//System.Console.WriteLine($"for group {groups[g].name} multilesson: {m.s.name} {m.val.l} -> cnt = {cnt}");
int cnt = dayState[day].groups[g].curriculum.Count(s => s.Equals(m.s)==true);
if (cnt < m.val.l || cnt > m.val.r) succ = false;
}
}
succ &= checkPossible(day+1);
for(int g = 0;g<config.Length;g++)
{
foreach(var tup in config[g]) dayState[day].updateLimits(g, tup.Item1, tup.Item2, -1);
}
return succ;
}
private DaySchedule useConfig(List <Tuple <int, int>>[] config, int day)
{
for(int g = 0;g<config.Length;g++)
{
foreach(var tup in config[g]) dayState[day].updateLimits(g, tup.Item1, tup.Item2, +1);
}
return lastConfigSolution[day];
}
private DaySchedule generateDay(int day, bool isFinal)
{
/*
if(isFinal==true && (!(lastConfig[day] is null)) && tryConfig(lastConfig[day], day)==true)
{
System.Console.WriteLine("SKIPPPPP");
return useConfig(lastConfig[day], day);
}
*/
G.reset();
// ----- setting node demands -----
G.setDemand(allTeachersNode, -(Enumerable.Range(0, groups.Count).Sum(ind => dayState[day].groupLeftLessons[ind])));
for (int g = 0; g < groups.Count; g++) G.setDemand(groupNode[g], dayState[day].groupLeftLessons[g]);
// ----- adding edges -----
//connecting teachers to allTeachersNode
for(int t = 0;t<teachers.Count;t++)
{
int requested = 0;
for (int g = 0; g < groups.Count; g++)
{
foreach (int s in teacherGroup2Subjects[t, g])
{
if (groups[g].subject2Teacher[s].Item2.Equals(teachers[t])==true)
{
requested += dayState[day].groups[g].getSubjectWeekLim(s);
}
}
}
for (int d = day+1; d <= workDays; d++)
requested -= dayState[d].teacherLeftLessons[t];
int u = allTeachersNode;
int v = teacherNode[t];
int l = Math.Max(requested, 0);
int c = dayState[day].teacherLeftLessons[t];
//Console.WriteLine($"{teachers[t].name} -> {l} {c}");
G.addEdge(u, v, l, Math.Min(c, minLessons), true);
}
//connecting teachers to possible lessons
for(int t = 0;t<teachers.Count;t++)
{
for (int g = 0; g < groups.Count; g++)
{
foreach (int s in teacherGroup2Subjects[t, g])
{
IntInInterval scheduledLessons = new IntInInterval(0);
List<Multilesson> important = multilessons[day].Where(m => m.t.Equals(teachers[t]) == true
&& m.g.Equals(groups[g]) == true && m.s.Equals(groups[g].subject2Teacher[s].Item1)).ToList();
foreach (Multilesson r in important)
scheduledLessons = scheduledLessons + r.val;
if(important.Count>0) G.addEdge(teacherNode[t], groupSubjectNode[g, s], scheduledLessons.l, scheduledLessons.r, true);
else G.addEdge(teacherNode[t], groupSubjectNode[g, s], 0, minLessons, true);
}
}
}
//connecting the actual higharcy structures
for(int g = 0;g<groups.Count;g++)
{
void dfs(TreeNode x)
{
if(x.GetType()==typeof(SubjectTreeNode))
{
int s = dayState[day].groups[g].findSubject((x as SubjectTreeNode).s);
if (s == -1) return;
if (dayState[day].groups[g].subject2Teacher[s].Item2 == null) return;
int teacherInd = groupSubject2Teacher[g, s];
int lessonsLeft = dayState[day].groups[g].getSubjectWeekLim(s);
for (int d = day+1; d <= workDays; d++)
{
IEnumerable <Multilesson> important = multilessons[d].Where(m => m.g.Equals(groups[g])==true
&& m.s.Equals((x as SubjectTreeNode).s) == true);
int rm = 0;
if(important.Any()==false)
{
rm = Math.Min(dayState[d].groups[g].getDayBottleneck(s), dayState[d].teacherLeftLessons[teacherInd]);
rm = Math.Min(rm, dayState[d].groupLeftLessons[g]);
}
else
{
rm = important.Sum(m => m.val.r);
}
lessonsLeft -= rm;
}
int subjectLim = Math.Min(dayState[day].groups[g].getDayBottleneck(s),
dayState[day].groups[g].getSubjectWeekLim(s));
int subjectDemand = 0;
for(int d = day+1;d<=workDays;d++)
{
subjectDemand += multilessons[d].Where(r => r.g.Equals(groups[g]) == true && r.s.Equals((x as SubjectTreeNode).s))
.Sum(r => r.val.l);
}
int fixatedLessons = multilessons[day].Where(r => r.g.Equals(groups[g]) == true && r.s.Equals((x as SubjectTreeNode).s))
.Sum(r => r.val.l);
groupSubjectEdge[g, s] = G.addEdge(x.nodeCode, x.parent.nodeCode,
Math.Max(fixatedLessons, Math.Max(0, lessonsLeft)),
Math.Min(subjectLim, dayState[day].groups[g].getSubjectWeekLim(s) - subjectDemand));
return;
}
if (x.parent != null)
{
int lim = maxLessons;
if(x.GetType() == typeof(LimitationTreeNode))
lim = Math.Min(lim, dayState[day].groups[g].getLimGroupDayLim((x as LimitationTreeNode).lg));
int lessonsLeft = groups[g].subject2Teacher.Where(t => t.Item1.limGroups.Contains((x as LimitationTreeNode).lg)==true)
.Sum(t => dayState[1].groups[g].getSubjectWeekLim(groups[g].findSubject(t.Item1)));
for(int d = day+1;d<=workDays;d++)
{
IEnumerable<Multilesson> important = multilessons[d].Where(m => m.g.Equals(groups[g]) == true
&& m.s.limGroups.Contains((x as LimitationTreeNode).lg)==true);
int rm = 0;
if (important.Any() == false)
{
rm = Math.Min(dayState[d].groups[g].getLimGroupDayLim((x as LimitationTreeNode).lg), dayState[d].groupLeftLessons[g]);
}
else
{
rm = important.Sum(m => m.val.r);
}
lessonsLeft -= rm;
}
G.addEdge(x.nodeCode, x.parent.nodeCode, Math.Max(0, lessonsLeft), lim);
}
foreach (TreeNode y in x.children)
dfs(y);
}
dfs(groupHigharchy[g]);
}
//connecting groups to their higharchy trees
for(int g = 0;g<groups.Count;g++)
{
int allLeft = dayState[day].groups[g].subject2Teacher.Sum(t => dayState[day].groups[g].getSubjectWeekLim(dayState[day].groups[g].findSubject(t.Item1)));
for (int d = day + 1; d <= workDays; d++) allLeft -= dayState[d].groupLeftLessons[g];
int fixatedLessons = multilessons[day].Where(r => r.g.Equals(groups[g])==true).Sum(r => r.val.l);
int upperBound = dayState[day].groups[g].subject2Teacher.Sum(t => dayState[day].groups[g].getSubjectWeekLim(dayState[day].groups[g].findSubject(t.Item1)));
for (int d = day + 1; d <= workDays; d++) upperBound -= Math.Min(dayState[d].groupLeftLessons[g], groups[g].minLessons);
G.addEdge(groupHigharchy[g].nodeCode, groupNode[g],
Math.Max(Math.Max(groups[g].minLessons - dayState[day].groups[g].curriculum.Count, allLeft), fixatedLessons),
Math.Min(dayState[day].groupLeftLessons[g], upperBound));
}
//connecting groups to allTeachersNode
for (int g = 0; g < groups.Count; g++)
{
G.addEdge(allTeachersNode, groupNode[g], 0, Math.Min(maxLessons-minLessons, maxLessons-dayState[day].groups[g].curriculum.Count));
}
G.eval();
List <Tuple<int, int>>[] currConfig = new List<Tuple <int, int>>[groups.Count];
for(int g = 0;g<groups.Count;g++)
{
//Console.WriteLine($"---- {groups[g].name} - {g} ---");
int expectedCnt = dayState[day].groupLeftLessons[g];
List<int> teacherInds = new List<int>();
currConfig[g] = new List<Tuple <int, int>>();
for (int s = 0; s < groups[g].subject2Teacher.Count; s++)
{
if (groups[g].subject2Teacher[s].Item2 is null) continue;
for (int i = 0; i < G.getEdge(groupSubjectEdge[g, s]); i++)
{
currConfig[g].Add(Tuple.Create(s, groupSubject2Teacher[g, s]));
teacherInds.Add(groupSubject2Teacher[g, s]);
//Console.WriteLine(teachers[groupSubject2Teacher[g, s]].name);
if (dayState[day].updateLimits(g, s, groupSubject2Teacher[g, s], +1) == false)
{
Console.WriteLine($"ebalo si maikata {g}");
return null;
}
}
}
if (dayState[day].groups[g].curriculum.Count < dayState[day].groups[g].minLessons
|| dayState[day].groups[g].curriculum.Count > maxLessons)
{
Console.WriteLine($"e de {dayState[day].groups[g].curriculum.Count} {g} || {day}");
return null;
}
}
Console.WriteLine("pak faida e ");
DaySchedule ds = null;
if(ds is null)
{
ScheduleCompleters.DFS.ScheduleCompleter sc = new ScheduleCompleters.DFS.ScheduleCompleter(dayState[day].groups, teachers, supergroupMultilessons[day], maxLessons);
ds = sc.gen(true);
if (!(ds is null))
{
lastConfigSolution[day] = ds;
lastConfig[day] = currConfig;
}
}
if(ds is null)
{
ScheduleCompleters.GeneticAlgorithm.ScheduleCompleter sc = new ScheduleCompleters.GeneticAlgorithm.ScheduleCompleter(dayState[day].groups, teachers, supergroupMultilessons[day], maxLessons);
ds = sc.gen(true);
if (!(ds is null))
{
lastConfigSolution[day] = ds;
lastConfig[day] = currConfig;
}
}
return ds;
}
public bool runDiagnostics()
{
for(int day = 1;day<=workDays;day++)
{
for (int t = 0; t < teachers.Count; t++)
if (dayState[day].teacherLeftLessons[t] < 0)
return false;
}
for (int g = 0; g < groups.Count; g++)
{
for(int s = 0;s<dayState[1].groups[g].subject2Teacher.Count;s++)
{
if (dayState[1].groups[g].getWeekBottleneck(s) != 0)
return false;
}
for (int s = 0; s < dayState[1].groups[g].subject2Teacher.Count; s++)
{
for(int day = 1;day<=workDays;day++)
{
if (dayState[day].groups[g].getDayBottleneck(s) < 0)
return false;
}
}
}
for(int g = 0;g<groups.Count;g++)
{
for(int day = 1;day<=workDays;day++)
{
foreach(Multilesson m in multilessons[day].Where(x => (x.g.Equals(groups[g])==true)))
{
int cnt = dayState[day].groups[g].curriculum.Count(s => s.Equals(m.s)==true);
if (cnt < m.val.l || cnt > m.val.r) return false;
}
}
}
return true;
}
private bool checkPossible(int day)
{
for(int t = 0;t<teachers.Count;t++)
{
int demand = 0;
for(int g = 0;g<dayState[1].groups.Count;g++)
{
demand += dayState[1].groups[g].subject2Teacher.Where(tup => (!(tup.Item2 is null)) && tup.Item2.Equals(teachers[t])==true)
.Sum(x => dayState[1].groups[g].getSubjectWeekLim(dayState[1].groups[g].findSubject(x.Item1)));
}
for(int d = day;d<=workDays;d++) demand -= dayState[d].teacherLeftLessons[t];
if(demand>0) return false;
}
System.Console.WriteLine("do tuka");
for(int g = 0;g<dayState[1].groups.Count;g++)
{
for(int s = 0;s<dayState[1].groups[g].subject2Teacher.Count;s++)
{
if(dayState[1].groups[g].subject2Teacher[s].Item2 is null) continue;
int tInd = groupSubject2Teacher[g, s];
int demand = dayState[1].groups[g].getSubjectWeekLim(s);
for (int d = day; d <= workDays; d++)
{
IEnumerable <Multilesson> important = multilessons[d].Where(m => m.g.Equals(groups[g])==true
&& m.s.Equals(dayState[1].groups[g].subject2Teacher[s].Item1) == true);
int rm = 0;
if(important.Any()==false)
{
rm = Math.Min(dayState[d].groups[g].getDayBottleneck(s), dayState[d].teacherLeftLessons[tInd]);
rm = Math.Min(rm, dayState[d].groupLeftLessons[g]);
}
else
{
rm = important.Sum(m => m.val.r);
}
demand -= rm;
}
if(demand>0)
{
System.Console.WriteLine("nqma da mozhem da gi vzemem");
return false;
}
}
for(int s = 0;s<dayState[1].groups[g].subject2Teacher.Count;s++)
{
int demand = dayState[1].groups[g].getSubjectWeekLim(s);
for(int d = day;d<=workDays;d++)
{
demand -= multilessons[d].Where(m => m.g.Equals(groups[g])==true && m.s.Equals(groups[g].subject2Teacher[s])==true).Sum(m => m.val.l);
}
if(demand<0)
{
System.Console.WriteLine("oldqhte se");
return false;
}
}
}
for(int g = 0;g<groups.Count;g++)
{
bool fail = false;
void dfs(TreeNode x)
{
if(x.GetType()==typeof(SubjectTreeNode)) return;
LimitationGroup lg = (x as LimitationTreeNode).lg;
if(!(lg is null))
{
int demand = dayState[1].groups[g].subject2Teacher.Where(tup => tup.Item1.limGroups.Any(x => x.Equals(lg)==true)==true)
.Sum(tup => dayState[1].groups[g].getSubjectWeekLim(dayState[1].groups[g].findSubject(tup.Item1)));
for(int d = day;d<=workDays;d++)
{
IEnumerable<Multilesson> important = multilessons[d].Where(m => m.g.Equals(groups[g]) == true
&& m.s.limGroups.Contains((x as LimitationTreeNode).lg)==true);
int rm = 0;
if (important.Any() == false)
{
rm = Math.Min(dayState[d].groups[g].getLimGroupDayLim((x as LimitationTreeNode).lg), dayState[d].groupLeftLessons[g]);
}
else
{
rm = important.Sum(m => m.val.r);
}
demand -= rm;
}
if(demand>0) fail = true;
}
foreach(TreeNode y in x.children) dfs(y);
}
dfs(higharchy);
if(fail==true) return false;
}
for(int g = 0;g<groups.Count;g++)
{
int lessonsLeft = dayState[1].groups[g].subject2Teacher.Sum(tup => dayState[1].groups[g].getSubjectWeekLim(dayState[1].groups[g].findSubject(tup.Item1)));
for(int d = day;d<=workDays;d++) lessonsLeft += dayState[d].groups[g].curriculum.Count;
if(!((workDays-day+1)*minLessons<=lessonsLeft && lessonsLeft<=(workDays-day+1)*maxLessons)) return false;
}
return true;
}
static int callNum = 0, succsefullCallNum = 0;
public WeekSchedule gen(int limDay, bool isFinal)
{
if (limDay == -1) limDay = workDays;
WeekSchedule ws = new WeekSchedule(workDays);
initNodes();
initArrays();
callNum++;
Console.WriteLine($"callNum: {callNum} || {(double)succsefullCallNum/(double)callNum}");
for (int day = 1; day <= limDay; day++)
{
foreach (var item in supergroupMultilessons[day])
{
for(int iter = 0;iter<item.Item2;iter++)
{
foreach (Tuple<Group, Subject> tup in item.Item1.groups)
{
int g = groups.FindIndex(g => g.Equals(tup.Item1));
int s = groups[g].findSubject(tup.Item2);
if (dayState[day].updateLimitsNoTeacher(g, s, +1) == false)
{
return null;
}
}
foreach (Teacher t in item.Item1.teachers)
{
int tInd = teachers.FindIndex(x => x.Equals(t) == true);
if (dayState[day].updateTeacherLimits(tInd, +1) == false)
{
//Console.WriteLine("s tichar");
return null;
}
}
}
}
}
for (int day = 1;day<=limDay;day++)
{
if(isFinal==true && checkPossible(day)==false)
{
System.Console.WriteLine("FAKKKKKKKKKKKK");
//return null;
}
DaySchedule dayRes = generateDay(day, isFinal);
if (dayRes == null) return null;
ws.days[day] = dayRes;
}
bool diagnosticsRes = runDiagnostics();
if (diagnosticsRes == false && limDay==workDays && isFinal==true) return null;
Console.WriteLine("davai volene");
succsefullCallNum++;
return ws;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.MaxFlow
{
abstract class FlowGraph
{
public abstract int getEdge(int ind);
public abstract int addEdge(int u, int v, int cap);
public abstract int addEdge(int u, int v, int cap, long cost);
public abstract long findFlow();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using OfficeOpenXml;
using System.IO;
using System.Reflection;
using System.Drawing;
namespace SchoolManager.ScheduleUtils
{
class WeekSchedule
{
private int workDays;
public DaySchedule[] days;
public WeekSchedule() { }
public WeekSchedule(int workDays)
{
this.workDays = workDays;
this.days = new DaySchedule[workDays+1];
}
public void exportToExcell(string filename)
{
ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @$"{filename}.xlsx");
ExcelPackage excel = new ExcelPackage(new FileInfo(path));
if(File.Exists(path)==false)
{
excel.Workbook.Worksheets.Add("sheet1");
excel.SaveAs(new FileInfo(path));
}
else
{
excel.Workbook.Worksheets.Delete("sheet1");
excel.Workbook.Worksheets.Add("sheet1");
}
excel.Workbook.Worksheets["sheet1"].Column(1).Width = 2;
for(int t = 0;t<days[1].teachers.Count;t++)
{
excel.Workbook.Worksheets["sheet1"].Column(2+t).Width = 4;
excel.Workbook.Worksheets["sheet1"].Cells[1, 2+t].Value = days[1].teachers[t].name;
excel.Workbook.Worksheets["sheet1"].Cells[1, 2+t].Style.TextRotation = 180;
}
for(int day = 1;day<=workDays;day++)
{
for(int lesson = 1;lesson<=days[day].maxLessons;lesson++)
{
excel.Workbook.Worksheets["sheet1"].Cells[2+(day-1)*(days[day].maxLessons+1)+lesson-1, 1].Value = lesson;
Color colFromHex = Color.FromArgb(0, 255, 0);
excel.Workbook.Worksheets["sheet1"].Cells[2+(day-1)*(days[day].maxLessons+1)+lesson-1, 1].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
excel.Workbook.Worksheets["sheet1"].Cells[2+(day-1)*(days[day].maxLessons+1)+lesson-1, 1].Style.Fill.BackgroundColor.SetColor(colFromHex);
}
for(int lesson = 1;lesson<=days[day].maxLessons;lesson++)
{
for(int t = 0;t<days[day].teachers.Count;t++)
{
object val = null;
if(days[day].lessonTeacher2Group[lesson, t]!=null) val = days[day].lessonTeacher2Group[lesson, t].name;
else if(days[day].lessonTeacher2SuperGroup[lesson, t]!=null) val = days[day].lessonTeacher2SuperGroup[lesson, t].name;
excel.Workbook.Worksheets["sheet1"].Cells[2+(day-1)*(days[day].maxLessons+1)+lesson-1, 2+t].Value = val;
}
}
}
excel.Save();
}
public void print()
{
for(int day = 1;day<=days.Length-1;day++)
days[day].print();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace SchoolManager.School_Models
{
class GroupUnion
{
public List<Group> groups;
public List<int> groupSubject;
public List<Teacher> teachers;
public GroupUnion() { }
public GroupUnion(List <Group> groups, List <int> groupSubject, List <Teacher> teachers)
{
this.groups = groups;
this.groupSubject = groupSubject;
this.teachers = teachers;
}
}
}
<file_sep>using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.Generation_utils
{
class ScheduleDayState
{
public List<Group> groups { get; }
public int[] groupLeftLessons { get; }
public int[] teacherLeftLessons { get; }
public ScheduleDayState() { }
public ScheduleDayState(List <Group> groups, List <Teacher> teachers, int maxLessons)
{
this.groups = groups;
this.groupLeftLessons = new int[groups.Count];
this.teacherLeftLessons = new int[teachers.Count];
for (int i = 0; i < groups.Count; i++) this.groupLeftLessons[i] = maxLessons;
for (int i = 0; i < teachers.Count; i++) this.teacherLeftLessons[i] = 6;
}
public bool check(int g, int s, int t, int change)
{
if (groupLeftLessons[g] + change < 0 || teacherLeftLessons[t] + change < 0 || groups[g].checkSubject(s, change)==false) return false;
return true;
}
public bool updateLimits(int g, int s, int t, int sign)
{
groupLeftLessons[g] -= sign;
teacherLeftLessons[t] -= sign;
bool updateRes = groups[g].applySubject(s, sign);
//Console.WriteLine($"{groupLeftLessons[g]} || {teacherLeftLessons[t]} || {updateRes}");
if (groupLeftLessons[g] < 0 || teacherLeftLessons[t] < 0 || updateRes==false) return false;
return true;
}
public bool updateLimitsNoTeacher(int g, int s, int sign)
{
groupLeftLessons[g] -= sign;
bool updateRes = groups[g].applySubject(s, sign);
if (groupLeftLessons[g] < 0 || updateRes==false) return false;
return true;
}
public bool updateTeacherLimits(int t, int sign)
{
teacherLeftLessons[t] -= sign;
if (teacherLeftLessons[t] < 0) return false;
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.Generation_utils
{
class IntInInterval
{
public int l, r;
public IntInInterval() { }
public IntInInterval(int x)
{
this.l = x;
this.r = x;
}
public IntInInterval(int l, int r)
{
this.l = l;
this.r = r;
}
public static IntInInterval operator +(IntInInterval A, IntInInterval B)
{
return new IntInInterval(A.l + B.l, A.r + B.r);
}
public static IntInInterval operator -(IntInInterval A, IntInInterval B)
{
return new IntInInterval(A.l - B.r, A.r - B.l);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.School_Models
{
class LimitationGroup
{
public string name { get; set; }
public LimitationGroup() { }
public LimitationGroup(string name)
{
this.name = name;
}
public override bool Equals(object obj)
{
if(obj is null) return false;
if (obj.GetType() != typeof(LimitationGroup)) return false;
return name.Equals((obj as LimitationGroup).name);
}
}
}
<file_sep>using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using OfficeOpenXml;
using System.Reflection;
using System.IO;
namespace SchoolManager.ScheduleUtils
{
class DaySchedule
{
public int maxLessons;
public List<Teacher> teachers;
public Subject[,] lessonTeacher2Subject;
public Subject[,] lessonGroup2Subject;
public Group[,] lessonTeacher2Group;
public SuperGroup[,] lessonTeacher2SuperGroup;
public DaySchedule(List<Tuple<int, Subject>>[] solution, List<Group> state, List <Teacher> teachers,
List<Tuple<SuperGroup, int>> supergroupMultilessons,
Generation_utils.ScheduleCompleters.ConfigurationStateBase config,
int maxLessons)
: this(solution.Where(x => (!(x is null))).Select(x => x.Select(y => ((y is null) ? null : y.Item2)).ToList()).ToList(),
teachers, state,
solution.Where(x => (!(x is null))).Select(x => x.Select(y => ((y is null || y.Item1 < teachers.Count) ? null
: supergroupMultilessons[Enumerable.Range(0, supergroupMultilessons.Count)
.First(ind => config.superTeacherInd[ind] == y.Item1)].Item1)).ToList()).ToList()
, maxLessons)
{
}
public DaySchedule(List <List<Subject>> orderedCurriculums, List <Teacher> teachers, List <Group> groups,
List <List<SuperGroup>> orderedSuperGroupCurriculums, int maxLessons)
{
this.teachers = teachers;
this.maxLessons = maxLessons;
this.lessonGroup2Subject = new Subject[maxLessons+1, groups.Count];
this.lessonTeacher2Subject = new Subject[maxLessons + 1, teachers.Count];
this.lessonTeacher2Group = new Group[maxLessons + 1, teachers.Count];
this.lessonTeacher2SuperGroup = new SuperGroup[maxLessons + 1, teachers.Count];
for(int g = 0;g<orderedCurriculums.Count;g++)
{
for(int l = 0;l<orderedCurriculums[g].Count;l++)
{
Subject s = orderedCurriculums[g][l];
Teacher t = groups[g].subject2Teacher[groups[g].findSubject(s)].Item2;
int tInd = teachers.FindIndex(x => x.Equals(t));
lessonGroup2Subject[l+1, g] = orderedCurriculums[g][l];
if (tInd != -1)
{
lessonTeacher2Group[l + 1, tInd] = groups[g];
lessonTeacher2Subject[l + 1, tInd] = s;
}
else
{
foreach (Teacher item in orderedSuperGroupCurriculums[g][l].teachers)
lessonTeacher2SuperGroup[l+1, teachers.FindIndex(x => x.Equals(item))] = orderedSuperGroupCurriculums[g][l];
}
}
}
}
public void print()
{
Console.Write(" ");
Console.WriteLine(string.Join(" ", teachers.Select(t => String.Format("{0, -12}", $"|{t.name}")).ToList()));
for(int l = 1;l<=maxLessons;l++)
{
Console.Write(String.Format("{0, -3}", $"{l}: "));
for (int t = 0; t < teachers.Count; t++)
{
if(lessonTeacher2Group[l, t]!=null) Console.Write(String.Format("{0, -13}", $"|{lessonTeacher2Group[l, t].name}"));
else if(lessonTeacher2SuperGroup[l, t]!= null) Console.Write(String.Format("{0, -13}", $"|{lessonTeacher2SuperGroup[l, t].name}"));
else Console.Write(String.Format("{0, -13}", "|"));
}
Console.WriteLine();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.Generation_utils
{
class TeacherSelection
{
public bool[] isSelected;
public HashSet<long> failedStates;
public Dictionary <long, HashSet <long>> branchesLeft;
public TeacherSelection(int allTeachersCnt, List <int> selectedTeacherInds)
{
this.failedStates = new HashSet<long>();
this.isSelected = new bool[allTeachersCnt];
this.branchesLeft = new Dictionary<long, HashSet<long>>();
for (int i = 0; i < this.isSelected.Length; i++) isSelected[i] = false;
foreach (int ind in selectedTeacherInds)
isSelected[ind] = true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace SchoolManager.MaxFlow
{
class CirculationFlowGraph
{
class CirculationEdge
{
public int u, v;
public int l, c;
public bool progressiveCost;
public CirculationEdge()
{
this.progressiveCost = false;
}
public CirculationEdge(int u, int v, int l, int c) : this()
{
this.u = u;
this.v = v;
this.l = l;
this.c = c;
}
public CirculationEdge(int u, int v, int l, int c, bool progressiveCost) : this(u, v, l, c)
{
this.progressiveCost = progressiveCost;
}
}
private List<int> edgeInd = new List<int>();
private FlowGraph G;
private List<CirculationEdge> edges;
private int[] demand;
private int s, t;
private int auxNode;
public CirculationFlowGraph()
{
this.edgeInd = new List<int>();
this.edges = new List<CirculationEdge>();
}
public CirculationFlowGraph(int n) : this()
{
this.demand = new int[n + 15];
for (int x = 0; x < demand.Length; x++) demand[x] = 0;
s = demand.Length - 2;
t = demand.Length - 1;
this.auxNode = demand.Length - 3;
}
public void reset()
{
this.edges = new List<CirculationEdge>();
this.edgeInd = new List<int>();
for (int x = 0; x < demand.Length; x++) demand[x] = 0;
auxNode = demand.Length - 3;
}
public void setDemand(int x, int newDemand)
{
demand[x] = newDemand;
}
public int addEdge(int u, int v, int l, int c)
{
edges.Add(new CirculationEdge(u, v, l, c));
return edges.Count - 1;
}
public int addEdge(int u, int v, int l, int c, bool progressiveCost)
{
if(l==c) progressiveCost = false;
//if (l > c) throw new Exception();
edges.Add(new CirculationEdge(u, v, l, c, progressiveCost));
return edges.Count - 1;
}
public int getEdge(int ind)
{
return G.getEdge(edgeInd[ind]) + edges[ind].l;
}
public int eval()
{
bool hasProgessiveCost = edges.Any(e => e.progressiveCost==true);
//getting rid of the lower bounds
foreach(CirculationEdge e in edges)
{
demand[e.v] -= e.l;
demand[e.u] += e.l;
}
//building the MaxFlowGraph
if (hasProgessiveCost == true) G = new MinCostMaxFlowGraph(demand.Length, s, t);
else G = new DinicMaxFlowGraph(demand.Length, s, t);
//connecting demand/supply nodes
for(int x = 0;x<demand.Length;x++)
{
if (s == x) continue;
if (t == x) continue;
if (demand[x] < 0) G.addEdge(s, x, -demand[x]);
else if (demand[x] > 0) G.addEdge(x, t, demand[x]);
}
//doing the actual edges
foreach (CirculationEdge e in edges)
{
if (e.progressiveCost == false)
edgeInd.Add(G.addEdge(e.u, e.v, e.c - e.l));
else
{
edgeInd.Add(G.addEdge(auxNode, e.v, e.c - e.l));
for(int f = 1;f<=e.c-e.l;f++)
G.addEdge(e.u, auxNode, 1, (((long)1)<<f));
auxNode--;
}
}
int maxFlow = (int)G.findFlow();
return maxFlow;
}
}
}
<file_sep>using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.Generation_utils
{
class TeacherList : IEquatable<TeacherList>
{
public int id { get; set; }
public bool isGood { get; set; }
public List<Tuple<int, Subject>> l { get; set; }
public TeacherList() { }
public TeacherList(int id, List<Tuple<int, Subject>> l)
{
this.id = id;
this.l = l;
this.isGood = checkGood();
}
public TeacherList(int id, List<Tuple<int, Subject>> l, bool isGood)
{
this.isGood = isGood;
this.id = id;
this.l = l;
}
public override int GetHashCode()
{
long h = 0;
long key = 1009, mod = (long)1e9 + 7;
foreach (var x in l)
{
h = (h * key + x.Item1) % mod;
}
return (int)h;
}
public bool Equals(TeacherList other)
{
if (other.l.Count != l.Count) return false;
for (int i = 0; i < l.Count; i++)
if (l[i].Item1 != other.l[i].Item1)
return false;
return true;
}
private bool checkGood()
{
Dictionary<int, int> mp = new Dictionary<int, int>();
foreach (var x in l)
{
if (mp.ContainsKey(x.Item1) == false) mp.Add(x.Item1, 0);
mp[x.Item1]++;
}
foreach (var item in mp)
{
int blocks = 0;
for (int i = 0; i < l.Count;)
{
if (l[i].Item1 != item.Key)
{
i++;
continue;
}
blocks++;
while (i < l.Count && l[i].Item1 == item.Key) i++;
}
if (item.Value <= 2 && blocks > 1) return false;
if (blocks > 2) return false;
}
return true;
}
}
}
<file_sep>using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SchoolManager.Generation_utils.ScheduleCompleters.DFS
{
class ConfigurationState : ConfigurationStateBase
{
public TeacherSelection allTeachersSelected;
public List<TeacherSelection> teacherSelections;
public ConfigurationState(List<Group> state, List<Teacher> teachers, List<Tuple<SuperGroup, int>> supergroupMultilessons,
bool onlyConsequtive, int maxLessons)
: base(state, teachers, supergroupMultilessons, onlyConsequtive, maxLessons)
{
this.teacherSelections = new List<TeacherSelection>();
List<int> sortedTeachers = Enumerable.Range(0, teachers.Count).OrderByDescending(ind => teacherList
.Sum(tl => tl.Count(x => ((x.Item1 < teachers.Count && x.Item1 == ind) ||
(x.Item1 >= teachers.Count))))).ToList();
const int blocksSz = 15;
for (int i = 0; i < teachers.Count; i += blocksSz)
{
List<int> l = new List<int>();
for (int j = i; j < Math.Min(i + blocksSz, sortedTeachers.Count); j++) l.Add(sortedTeachers[j]);
this.teacherSelections.Add(new TeacherSelection(teachers.Count, l));
}
this.allTeachersSelected = new TeacherSelection(teachers.Count, Enumerable.Range(0, teachers.Count).ToList());
}
public bool checkSuitable(TeacherList tl, bool onlyConsequtive, TeacherSelection ts = null)
{
if (onlyConsequtive == true && tl.isGood == false) return false;
for (int lesson = 0; lesson < tl.l.Count; lesson++)
{
if (ts != null)
{
if (tl.l[lesson].Item1 < teachers.Count)
{
if (ts.isSelected[tl.l[lesson].Item1] == false) continue;
}
}
if (isTeacherLocked[tl.l[lesson].Item1] == true && teacherPosLocked[lesson, tl.l[lesson].Item1] == false)
{
return false;
}
if (tl.l[lesson].Item1 < teachers.Count)
{
if (lessonTeacher[lesson, tl.l[lesson].Item1] > 0)
{
return false;
}
}
else
{
if (isTeacherLocked[tl.l[lesson].Item1] == false)
{
foreach (int tInd in teacherDependees[tl.l[lesson].Item1])
{
if (lessonTeacher[lesson, tInd] > 0)
{
return false;
}
}
}
}
}
return true;
}
public long getState(TeacherSelection ts, int g)
{
long stateVal = 0;
const long key = 1019;
const long mod = 67772998972500529;
const long emptySymbol = key - 1;
const long separatingSymbol = key - 2;
stateVal = (stateVal * key + g + 1) % mod;
for (int i = 0; i < ts.isSelected.Length; i++)
stateVal = (stateVal * key + Convert.ToInt64(ts.isSelected[i]) + 1);
stateVal = (stateVal * key + separatingSymbol) % mod;
for (int lesson = 0; lesson < maxLessons; lesson++)
{
for (int t = 0; t < teachers.Count + supergroupMultilessons.Count; t++)
{
if (lastPosSeen[t] < g || (t < teachers.Count && ts.isSelected[t] == false))
stateVal = (stateVal * key + emptySymbol) % mod;
else
stateVal = (stateVal * key + Convert.ToInt64(lessonTeacher[lesson, t] != 0) + 1) % mod;
}
}
return stateVal;
}
public bool checkFailByTeacherSelections(int g, bool onlyConsequtive, long[] skeletonStates)
{
bool failsFound = false;
for (int i = 0; i < teacherSelections.Count; i++)
{
skeletonStates[i] = getState(teacherSelections[i], g);
if (teacherSelections[i].failedStates.Contains(skeletonStates[i]) == true)
{
failsFound = true;
break;
}
bool fail = false;
for (int gInd = g; gInd < state.Count; gInd++)
{
if (teacherPermList[gInd].Any(tl => checkSuitable(tl, onlyConsequtive, teacherSelections[i]) == true) == false)
{
fail = true;
break;
}
}
if (fail == true)
{
failsFound = true;
teacherSelections[i].failedStates.Add(skeletonStates[i]);
break;
}
}
return failsFound;
}
public void loadTeacherSeletionBranches(int g, bool onlyConsequtive, long[] skeletonStates, HashSet<long>[] currSelectionBraches)
{
for (int i = 0; i < teacherSelections.Count; i++)
{
long stateVal = skeletonStates[i];
TeacherSelection ts = teacherSelections[i];
if (ts.branchesLeft.ContainsKey(stateVal) == false)
{
ts.branchesLeft.Add(stateVal, new HashSet<long>());
currSelectionBraches[i] = ts.branchesLeft[stateVal];
IEnumerable<TeacherList> curr = teacherPermList[g].Where(tl => checkSuitable(tl, onlyConsequtive, ts) == true);
foreach (TeacherList tl in curr)
{
applyPermution(tl);
long branchState = getState(ts, g + 1);
currSelectionBraches[i].Add(branchState);
undoPermutation(tl);
}
}
else
{
currSelectionBraches[i] = ts.branchesLeft[stateVal];
}
}
}
public void updateTeacherSelectionBranches(int g, bool[] failed, HashSet<long>[] currSelectionBraches)
{
for (int i = 0; i < teacherSelections.Count; i++)
{
if (failed[i] == true) continue;
if (currSelectionBraches[i].Count == 0) continue;
long branchState = getState(teacherSelections[i], g + 1);
if (teacherSelections[i].failedStates.Contains(branchState) == true)
{
currSelectionBraches[i].Remove(branchState);
}
else
{
failed[i] = true;
}
}
}
}
}
<file_sep>using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.Generation_utils
{
class Multilesson
{
public Group g;
public Teacher t;
public Subject s;
public IntInInterval val;
public Multilesson() { }
public Multilesson(Group g, Teacher t, Subject s, IntInInterval val)
{
this.g = g;
this.t = t;
this.s = s;
this.val = val;
}
}
}
<file_sep>using SchoolManager.School_Models;
using SchoolManager.School_Models.Higharchy;
using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager
{
static class PerformanceTest2
{
private static List<Subject> subjects;
private static List<LimitationGroup> limitationGroups;
private static List<Teacher> teachers;
private static LimitationTreeNode higharchy = new LimitationTreeNode("root", null);
private static void init()
{
limitationGroups = new List<LimitationGroup>()
{
new LimitationGroup("to4ni"),//0
new LimitationGroup("razkazvatelni"),//1
new LimitationGroup("matematika"),//2
new LimitationGroup("istoriq"),//3
new LimitationGroup("geografiq"),//4
new LimitationGroup("balgarski"),//5
new LimitationGroup("angliiski"),//6
new LimitationGroup("svqt i lichnost"),//7
new LimitationGroup("fizika"),//8
new LimitationGroup("fizichesko"),//9
new LimitationGroup("rosski/nemski"),//10
};
subjects = new List<Subject>()
{
new Subject("matematika", new List<LimitationGroup>(){ limitationGroups[0], limitationGroups[2] }),//0
new Subject("istoriq", new List<LimitationGroup>(){ limitationGroups[1], limitationGroups[3] }),//1
new Subject("geografiq", new List<LimitationGroup>(){ limitationGroups[1], limitationGroups[4] }),//2
new Subject("balgarski", new List<LimitationGroup>(){ limitationGroups[5]}),//3
new Subject("angliiski", new List<LimitationGroup>(){ limitationGroups[6]}),//4
new Subject("svqt i lichnost", new List<LimitationGroup>(){ limitationGroups[1], limitationGroups[7]}),//5
new Subject("fizika", new List<LimitationGroup>(){ limitationGroups[0], limitationGroups[8]}),//6
new Subject("fizichesko", new List<LimitationGroup>(){ limitationGroups[9] }),//7
new Subject("rosski/nemski", new List<LimitationGroup>(){ limitationGroups[10] }),//8
};
teachers = new List<Teacher>()
{
new Teacher("batimkata", new List<Subject>(){ }),//0
new Teacher("kireto", new List<Subject>(){ }),//1
new Teacher("valcheto", new List<Subject>(){ }),//2
new Teacher("slav4eto", new List<Subject>(){ }),//3
new Teacher("gabarcheto", new List<Subject>(){ }),//4
new Teacher("krusteva", new List<Subject>(){ }),//5
new Teacher("dancheto", new List<Subject>(){ }),//6
new Teacher("balieva", new List<Subject>(){ }),//7
new Teacher("lateva", new List<Subject>(){ }),//8
new Teacher("klisarova", new List<Subject>(){ }),//9
new Teacher("ivanova", new List<Subject>(){ }),//10
new Teacher("vlashka", new List<Subject>(){ }),//11
new Teacher("tisheto", new List<Subject>(){ }),//12
new Teacher("kongalov", new List<Subject>(){ }),//13
new Teacher("daskalova", new List<Subject>(){ }),//14
new Teacher("ruskinqta", new List<Subject>(){ }),//15
};
higharchy.addChild(new LimitationTreeNode(limitationGroups[0]));
higharchy.addChild(new LimitationTreeNode(limitationGroups[1]));
higharchy.addChild(new SubjectTreeNode(subjects[3]));
higharchy.addChild(new SubjectTreeNode(subjects[4]));
higharchy.addChild(new SubjectTreeNode(subjects[7]));
higharchy.addChild(new SubjectTreeNode(subjects[8]));
(higharchy.children[0] as LimitationTreeNode).addChild(new SubjectTreeNode(subjects[0]));
(higharchy.children[1] as LimitationTreeNode).addChild(new SubjectTreeNode(subjects[1]));
(higharchy.children[1] as LimitationTreeNode).addChild(new SubjectTreeNode(subjects[2]));
(higharchy.children[1] as LimitationTreeNode).addChild(new SubjectTreeNode(subjects[5]));
(higharchy.children[0] as LimitationTreeNode).addChild(new SubjectTreeNode(subjects[6]));
//higharchy.printTree();
}
private static Group _12b()
{
var dayLims = new List<Tuple<LimitationGroup, int>>()
{
Tuple.Create(limitationGroups[0], 2),
Tuple.Create(limitationGroups[1], 2),
Tuple.Create(limitationGroups[2], 2),
Tuple.Create(limitationGroups[3], 1),
Tuple.Create(limitationGroups[4], 1),
Tuple.Create(limitationGroups[5], 2),
Tuple.Create(limitationGroups[6], 2),
Tuple.Create(limitationGroups[7], 1),
Tuple.Create(limitationGroups[8], 1),
Tuple.Create(limitationGroups[9], 2),
Tuple.Create(limitationGroups[10], 2),
};
var weekLims = new List<Tuple<LimitationGroup, int>>()
{
Tuple.Create(limitationGroups[0], 6969),
Tuple.Create(limitationGroups[1], 6969),
Tuple.Create(limitationGroups[2], 5),
Tuple.Create(limitationGroups[3], 2),
Tuple.Create(limitationGroups[4], 2),
Tuple.Create(limitationGroups[5], 3),
Tuple.Create(limitationGroups[6], 4),
Tuple.Create(limitationGroups[7], 2),
Tuple.Create(limitationGroups[8], 2),
Tuple.Create(limitationGroups[9], 2),
Tuple.Create(limitationGroups[10], 2),
};
var subject2Teacher = new List<Tuple<Subject, Teacher>>()
{
Tuple.Create(subjects[0], teachers[0]),
Tuple.Create(subjects[1], teachers[3]),
Tuple.Create(subjects[2], teachers[1]),
Tuple.Create(subjects[3], teachers[2]),
Tuple.Create(subjects[4], teachers[4]),
Tuple.Create(subjects[5], teachers[10]),
Tuple.Create(subjects[6], teachers[11]),
Tuple.Create(subjects[7], teachers[12]),
Tuple.Create(subjects[8], (Teacher)null),
};
Group g = new Group(4, "12a", dayLims, weekLims, subject2Teacher);
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, teachers[0], subjects[0], new Generation_utils.IntInInterval(1, 1)));
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, teachers[2], subjects[3], new Generation_utils.IntInInterval(2, 2)));
g.requiredMultilessons.Add(new Generation_utils.Multilesson(g, teachers[4], subjects[4], new Generation_utils.IntInInterval(2, 2)));
return g;
}
private static SuperGroup _vtoriEzik12BV()
{
List<Tuple<Group, Subject>> currGroups = new List<Tuple<Group, Subject>>()
{
Tuple.Create(_12b(), subjects[8]),
};
List<Teacher> currTeachers = new List<Teacher>()
{
teachers[14],
teachers[15],
};
List<int> requiredMultilessons = new List<int>() { 2 };
SuperGroup sg = new SuperGroup("vtori12A", currGroups, currTeachers, 2, requiredMultilessons);
return sg;
}
public static void test()
{
init();
List<Group> groups = new List<Group>();
List<SuperGroup> superGroups = new List<SuperGroup>();
groups.Add(_12b());
superGroups.Add(_vtoriEzik12BV());
List<Generation_utils.Multilesson>[] multilessons = new List<Generation_utils.Multilesson>[5 + 1];
for (int day = 1; day <= 5; day++)
multilessons[day] = new List<Generation_utils.Multilesson>();
//multilessons[5].Add(new Multilesson(groups[0], PerformanceTest1.teachers[4], PerformanceTest1.subjects[4], new IntInInterval(2, 2)));
//multilessons[5].Add(new Multilesson(groups[7], PerformanceTest1.teachers[4], PerformanceTest1.subjects[4], new IntInInterval(2, 2)));
//multilessons[5].Add(new Multilesson(groups[0], PerformanceTest1.teachers[0], PerformanceTest1.subjects[0], new IntInInterval(1, 2)));
//multilessons[5].Add(new Multilesson(groups[0], PerformanceTest1.teachers[2], PerformanceTest1.subjects[3], new IntInInterval(1, 1)));
//multilessons[3].Add(new Multilesson(groups[2], PerformanceTest1.teachers[5], PerformanceTest1.subjects[0], new IntInInterval(2, 3)));
Generation_utils.ScheduleGenerator4 sg = new Generation_utils.ScheduleGenerator4(groups, teachers, subjects,
higharchy, multilessons, superGroups);//за общи проблеми
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
sg.gen();
sw.Stop();
Console.WriteLine($"Ellapsed total time = {sw.ElapsedMilliseconds}");
}
}
}
<file_sep>using SchoolManager.ScheduleUtils;
using SchoolManager.School_Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SchoolManager.Generation_utils
{
class ScheduleCompleter1
{
private int maxLessons;
private List<Group> state;
private List<Teacher> teachers;
private DaySchedule output = null;
private bool[] teacherUsed;
private int[] teacherDemand, lastTeacher, newTeacher;
private List<Tuple<int, Subject>>[] teacherList;
private List<List<Subject>> solution;
public ScheduleCompleter1() { }
public ScheduleCompleter1(List<Group> state, List<Teacher> teachers, int maxLessons)
{
this.maxLessons = maxLessons;
this.teachers = teachers;
this.state = state;
}
private void init()
{
teacherList = new List<Tuple<int, Subject>>[state.Count];
for (int g = 0; g < state.Count; g++)
{
teacherList[g] = new List<Tuple<int, Subject>>();
for (int s = 0; s < state[g].subject2Teacher.Count; s++)
{
int cnt = state[g].curriculum.Count(x => x.Equals(state[g].subject2Teacher[s].Item1));
if (cnt == 0) continue;
int t = -1;
for (int i = 0; i < teachers.Count; i++)
{
if (teachers[i].name == state[g].subject2Teacher[s].Item2.name)
{
t = i;
break;
}
}
for (int iter = 0; iter < cnt; iter++)
teacherList[g].Add(Tuple.Create(t, state[g].subject2Teacher[s].Item1));
}
}
teacherDemand = new int[teachers.Count];
for (int i = 0; i < teachers.Count; i++) teacherDemand[i] = 0;
for (int g = 0; g < state.Count; g++)
foreach (var item in teacherList[g])
teacherDemand[item.Item1]++;
lastTeacher = new int[state.Count];
for (int g = 0; g < state.Count; g++) lastTeacher[g] = -1;
teacherUsed = new bool[teachers.Count];
newTeacher = new int[state.Count];
solution = new List<List<Subject>>();
for (int g = 0; g < state.Count; g++)
{
solution.Add(new List<Subject>());
}
for (int g = 0; g < state.Count; g++)
{
//teacherList[g] = teacherList[g].OrderBy(x => teacherList[g].Count(y => y.Item1 == x.Item1)).ToList();
}
}
public DaySchedule gen()
{
bool check(int t, int g)
{
return (t != -1 && teacherUsed[t] == false && teacherDemand[t]>0
&& teacherList[g].Any(x => x.Item1 == t)==true);
}
init();
for(int lesson = 1;lesson<=maxLessons;lesson++)
{
for (int t = 0; t < teachers.Count; t++)
{
teacherUsed[t] = false;
}
for(int g = 0;g<state.Count;g++)
{
newTeacher[g] = -1;
}
for (int g = 0; g < state.Count; g++)
{
continue;
if (newTeacher[g] == -1 && check(lastTeacher[g], g) == true)
{
newTeacher[g] = lastTeacher[g];
teacherDemand[newTeacher[g]]--;
teacherUsed[newTeacher[g]] = true;
}
}
List<int> groupInds = new List<int>();
for (int g = 0; g < state.Count; g++) groupInds.Add(g);
groupInds = groupInds.OrderByDescending(ind => (teacherList[ind].Min(x => teacherDemand[x.Item1]))).ToList();
foreach (int g in groupInds)
{
if (newTeacher[g] != -1) continue;
if (teacherList[g].Count == 0) continue;
var res = teacherList[g].Where(x => check(x.Item1, g)==true).OrderByDescending(x => teacherDemand[x.Item1]).FirstOrDefault();
if(!(res is null))
{
newTeacher[g] = res.Item1;
teacherDemand[newTeacher[g]]--;
teacherUsed[newTeacher[g]] = true;
}
if (newTeacher[g] == -1) throw new Exception();
}
Console.WriteLine(string.Join(" ", newTeacher));
for(int g = 0;g<state.Count;g++)
{
Subject s = null;
Subject lastSubject = ((solution[g].Count == 0) ? null : solution[g][solution[g].Count - 1]);
var res = teacherList[g].FirstOrDefault(x => x.Item1 == newTeacher[g] && x.Item2 == lastSubject);
if (!(res is null)) s = res.Item2;
else
{
res = teacherList[g].FirstOrDefault(x => x.Item1 == newTeacher[g]);
if (!(res is null)) s = res.Item2;
}
if (!(s is null))
{
solution[g].Add(s);
lastTeacher[g] = newTeacher[g];
teacherList[g].Remove(Tuple.Create(newTeacher[g], s));
}
}
//output = new DaySchedule(solution, teachers, state, maxLessons);
}
return output;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace SchoolManager.MaxFlow
{
class DinicMaxFlowGraph : FlowGraph
{
int source, sink;
List<Edge> edges;
List<List<int>> adj;
List<int> startInd;
public List<int> dist { get; set; }
public DinicMaxFlowGraph()
{
this.dist = new List<int>();
this.edges = new List<Edge>();
this.startInd = new List<int>();
this.adj = new List<List<int>>();
}
public DinicMaxFlowGraph(int n, int s, int t) : this()
{
this.sink = t;
this.source = s;
for (int i = 0; i <= n+5; i++)
{
this.adj.Add(new List<int>());
this.startInd.Add(0);
this.dist.Add(0);
}
}
public void setSourceSink(int s, int t)
{
source = s;
sink = t;
}
public override int addEdge(int u, int v, int cap)
{
edges.Add(new Edge(u, v, cap));
adj[u].Add(edges.Count - 1);
edges.Add(new Edge(v, u, 0));
adj[v].Add(edges.Count - 1);
return edges.Count - 2;
}
public override int getEdge(int ind)
{
return edges[ind^1].cap;
}
public void bfs(int x)
{
for (int i = 0; i < dist.Count; i++) dist[i] = -1;
Queue<int> q = new Queue<int>();
q.Enqueue(x);
dist[x] = 0;
while (q.Count > 0)
{
x = q.Peek();
q.Dequeue();
foreach (int eInd in adj[x])
{
Edge e = edges[eInd];
if (dist[e.v] == -1 && e.cap > 0)
{
dist[e.v] = dist[x] + 1;
q.Enqueue(e.v);
}
}
}
}
public int dfs(int x, int minVal)
{
if (x == sink) return minVal;
for (int i = startInd[x]; i < adj[x].Count; i++)
{
int eInd = adj[x][i];
Edge e = edges[eInd];
if (dist[e.v] == dist[x] + 1 && e.cap > 0)
{
int flow = dfs(e.v, Math.Min(minVal, e.cap));
if (flow != -1)
{
edges[eInd].cap -= flow;
edges[eInd ^ 1].cap += flow;
return flow;
}
}
startInd[x]++;
}
return -1;
}
public override long findFlow()
{
long maxFlow = 0;
while (true)
{
for (int i = 0; i < startInd.Count; i++) startInd[i] = 0;
bfs(source);
if (dist[sink] == -1) break;
while (true)
{
int add = dfs(source, 1);
if (add == -1) break;
maxFlow += add;
}
}
return maxFlow;
}
public override int addEdge(int u, int v, int cap, long cost)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using SchoolManager.School_Models;
namespace SchoolManager.Generation_utils.ScheduleCompleters
{
class ConfigurationStateBase
{
protected int maxLessons;
public readonly List<Group> state;
public readonly bool onlyConsequtive;
public readonly List<Teacher> teachers;
public readonly List<Tuple<SuperGroup, int>> supergroupMultilessons;
protected readonly int[] lastPosSeen;
protected int[,] lessonTeacher;
protected bool[] isTeacherLocked;
protected bool[,] teacherPosLocked;
public int[] superTeacherInd;
protected List<int>[] teacherDependees;
public readonly List<Tuple<int, Subject>>[] teacherList;
public readonly IEnumerable<TeacherList>[] teacherPermList;
public ConfigurationStateBase() { }
public ConfigurationStateBase(ConfigurationStateBase other)
{
this.state = other.state;
this.teachers = other.teachers;
this.maxLessons = other.maxLessons;
this.onlyConsequtive = other.onlyConsequtive;
this.supergroupMultilessons = other.supergroupMultilessons;
this.superTeacherInd = other.superTeacherInd;
this.teacherDependees = other.teacherDependees;
this.teacherList = other.teacherList;
this.teacherPermList = other.teacherPermList;
this.lastPosSeen = other.lastPosSeen;
this.lessonTeacher = new int[other.lessonTeacher.GetLength(0), other.lessonTeacher.GetLength(1)];
Array.Copy(other.lessonTeacher, lessonTeacher, other.lessonTeacher.Length);
this.isTeacherLocked = new bool[other.isTeacherLocked.GetLength(0)];
Array.Copy(other.isTeacherLocked, isTeacherLocked, other.isTeacherLocked.Length);
this.teacherPosLocked = new bool[other.teacherPosLocked.GetLength(0), other.teacherPosLocked.GetLength(1)];
Array.Copy(other.teacherPosLocked, this.teacherPosLocked, other.teacherPosLocked.Length);
}
public ConfigurationStateBase(List<Group> state, List<Teacher> teachers, List<Tuple<SuperGroup, int>> supergroupMultilessons, bool onlyConsequtive, int maxLessons)
{
this.maxLessons = maxLessons;
this.onlyConsequtive = onlyConsequtive;
this.state = state;
this.teachers = teachers;
this.supergroupMultilessons = supergroupMultilessons;
teacherList = new List<Tuple<int, Subject>>[state.Count];
teacherPermList = new IEnumerable<TeacherList>[state.Count];
lessonTeacher = new int[maxLessons + 1, teachers.Count + supergroupMultilessons.Count + 1];
superTeacherInd = new int[supergroupMultilessons.Count];
teacherDependees = new List<int>[teachers.Count + supergroupMultilessons.Count + 1];
for (int l = 1; l <= maxLessons; l++)
for (int t = 0; t < teachers.Count + supergroupMultilessons.Count + 1; t++)
lessonTeacher[l, t] = 0;
teacherPosLocked = new bool[maxLessons + 1, teachers.Count + supergroupMultilessons.Count + 1];
for (int l = 0; l < maxLessons + 1; l++)
for (int t = 0; t < teachers.Count + supergroupMultilessons.Count + 1; t++)
teacherPosLocked[l, t] = false;
isTeacherLocked = new bool[teachers.Count + supergroupMultilessons.Count + 1];
for (int t = 0; t < isTeacherLocked.Length; t++)
isTeacherLocked[t] = false;
for (int g = 0; g < state.Count; g++)
teacherList[g] = new List<Tuple<int, Subject>>();
for (int i = 0; i < supergroupMultilessons.Count; i++)
{
superTeacherInd[i] = teachers.Count + i;
teacherDependees[superTeacherInd[i]] = supergroupMultilessons[i].Item1.teachers.Select(x => teachers.FindIndex(t => t.Equals(x))).ToList();
for (int iter = 0; iter < supergroupMultilessons[i].Item2; iter++)
foreach (var item in supergroupMultilessons[i].Item1.groups)
teacherList[state.FindIndex(g => g.Equals(item.Item1) == true)].Add(Tuple.Create(superTeacherInd[i], item.Item2));
}
for (int g = 0; g < state.Count; g++)
{
for (int s = 0; s < state[g].subject2Teacher.Count; s++)
{
if (state[g].subject2Teacher[s].Item2 is null) continue;
int cnt = state[g].curriculum.Count(x => x.Equals(state[g].subject2Teacher[s].Item1));
if (cnt == 0) continue;
int t = -1;
for (int i = 0; i < teachers.Count; i++)
{
if (teachers[i].name == state[g].subject2Teacher[s].Item2.name)
{
t = i;
break;
}
}
for (int iter = 0; iter < cnt; iter++)
teacherList[g].Add(Tuple.Create(t, state[g].subject2Teacher[s].Item1));
}
}
lastPosSeen = new int[teachers.Count + supergroupMultilessons.Count];
for (int t = 0; t < lastPosSeen.Length; t++)
{
lastPosSeen[t] = -1;
for (int g = state.Count - 1; g >= 0; g--)
{
if (teacherList[g].Any(x => x.Item1 == t) == true)
{
lastPosSeen[t] = g;
break;
}
if (t < teachers.Count && teacherList[g].Where(x => x.Item1 >= teachers.Count).Any(x => teacherDependees[x.Item1].Contains(t) == true))
{
lastPosSeen[t] = g;
break;
}
}
if (t >= teachers.Count)
lastPosSeen[t] = Math.Max(lastPosSeen[t], teacherDependees[t].Max(x => lastPosSeen[x]));
}
for (int g = 0; g < state.Count; g++)
{
teacherPermList[g] = genPerms(teacherList[g]).Where(t => t.isGood == true || onlyConsequtive == false).ToList();
}
}
private List<TeacherList> genPerms(List<Tuple<int, Subject>> l)
{
List<Tuple<int, Subject>> curr = new List<Tuple<int, Subject>>();
HashSet<TeacherList> ans = new HashSet<TeacherList>();
bool[] used = new bool[l.Count];
for (int i = 0; i < used.Length; i++) used[i] = false;
int cnt = 0;
void rec(int ind)
{
if (ind == l.Count)
{
cnt++;
List<Tuple<int, Subject>> cpy = curr.Select(x => x).ToList();
ans.Add(new TeacherList(cnt, cpy));
return;
}
for (int i = 0; i < l.Count; i++)
{
if (used[i] == false)
{
used[i] = true;
curr.Add(l[i]);
rec(ind + 1);
used[i] = false;
curr.RemoveAt(curr.Count - 1);
}
}
}
rec(0);
return ans.ToList();
}
public bool checkSuitable(TeacherList tl, bool onlyConsequtive)
{
if (onlyConsequtive == true && tl.isGood == false) return false;
for (int lesson = 0; lesson < tl.l.Count; lesson++)
{
if (isTeacherLocked[tl.l[lesson].Item1] == true && teacherPosLocked[lesson, tl.l[lesson].Item1] == false)
{
return false;
}
if (tl.l[lesson].Item1 < teachers.Count)
{
if (lessonTeacher[lesson, tl.l[lesson].Item1] > 0)
{
return false;
}
}
else
{
if (isTeacherLocked[tl.l[lesson].Item1] == false)
{
foreach (int tInd in teacherDependees[tl.l[lesson].Item1])
{
if (lessonTeacher[lesson, tInd] > 0)
{
return false;
}
}
}
}
}
return true;
}
public virtual void applyPermution(TeacherList tl)
{
for (int lesson = 0; lesson < tl.l.Count; lesson++)
{
if (tl.l[lesson].Item1 >= teachers.Count)
{
if (lessonTeacher[lesson, tl.l[lesson].Item1] == 0)
{
teacherPosLocked[lesson, tl.l[lesson].Item1] = true;
isTeacherLocked[tl.l[lesson].Item1] = true;
foreach (int t in teacherDependees[tl.l[lesson].Item1])
lessonTeacher[lesson, t]++;
}
}
lessonTeacher[lesson, tl.l[lesson].Item1]++;
}
}
public virtual void undoPermutation(TeacherList tl)
{
for (int lesson = 0; lesson < tl.l.Count; lesson++)
{
if (tl.l[lesson].Item1 >= teachers.Count)
{
if (lessonTeacher[lesson, tl.l[lesson].Item1] == 1)
{
teacherPosLocked[lesson, tl.l[lesson].Item1] = false;
isTeacherLocked[tl.l[lesson].Item1] = false;
foreach (int t in teacherDependees[tl.l[lesson].Item1])
lessonTeacher[lesson, t]--;
}
}
lessonTeacher[lesson, tl.l[lesson].Item1]--;
}
}
public ConfigurationStateBase Clone()
{
return new ConfigurationStateBase(this);
}
}
}
<file_sep>using System;
using System.Linq;
using System.Collections.Generic;
using SchoolManager.ScheduleUtils;
using SchoolManager.School_Models;
namespace SchoolManager.Generation_utils.ScheduleCompleters.DFS
{
class ScheduleCompleter
{
private int maxLessons;
private List<Group> state;
private List<Teacher> teachers;
private List<Tuple<SuperGroup, int>> supergroupMultilessons;
public ScheduleCompleter() { }
public ScheduleCompleter(List<Group> state, List<Teacher> teachers, List <Tuple <SuperGroup, int>> supergroupMultilessons, int maxLessons)
{
this.state = state;
this.teachers = teachers;
this.maxLessons = maxLessons;
this.supergroupMultilessons = compressSGMultilesons(supergroupMultilessons.Select(x => Tuple.Create(x.Item1.Clone(), x.Item2)).ToList());
}
private List<Tuple<SuperGroup, int>> compressSGMultilesons(List <Tuple <SuperGroup, int>> l)
{
//redo later when we can differenciate better between SuperGroups
l = l.OrderBy(x => x.Item1.name).ToList();
List<Tuple<SuperGroup, int>> output = new List<Tuple<SuperGroup, int>>();
for(int i = 0;i<l.Count;)
{
int startInd = i, sum = 0;
for (; i < l.Count && l[startInd].Equals(l[i]); i++) sum += l[i].Item2;
output.Add(Tuple.Create(l[startInd].Item1, sum));
}
return output;
}
private DaySchedule output = null;
private List<Tuple<int, Subject>>[] solution;
private HashSet <long> reachedStates = new HashSet<long>();
private void rec(int g, bool onlyConsequtive)
{
if (output != null) return;
if (g == state.Count)
{
output = new DaySchedule(solution, state, teachers, supergroupMultilessons, config, maxLessons);
return;
}
if (sw.ElapsedMilliseconds > 2 * 1000) return;
long currState = config.getState(config.allTeachersSelected, g);
if(reachedStates.Contains(currState)==true) return;
reachedStates.Add(currState);
long[] skeletonStates = new long[config.teacherSelections.Count];
bool failsFound = config.checkFailByTeacherSelections(g, onlyConsequtive, skeletonStates);
if(failsFound==true) return;
for(int gInd = g+1;gInd<state.Count;gInd++)
{
if (config.teacherPermList[gInd].Any(tl => config.checkSuitable(tl, onlyConsequtive)==true)==false) return;
}
HashSet<long>[] currSelectionBraches = new HashSet<long>[config.teacherSelections.Count];
List <TeacherList> teacherLists = config.teacherPermList[g].Where(tl => config.checkSuitable(tl, onlyConsequtive)==true).ToList();
config.loadTeacherSeletionBranches(g, onlyConsequtive, skeletonStates, currSelectionBraches);
bool[] failed = new bool[config.teacherSelections.Count];
for(int i = 0;i<config.teacherSelections.Count;i++) failed[i] = false;
foreach (TeacherList tl in teacherLists)
{
solution[g] = tl.l;
config.applyPermution(tl);
rec(g + 1, onlyConsequtive);
config.updateTeacherSelectionBranches(g, failed, currSelectionBraches);
config.undoPermutation(tl);
solution[g] = null;
}
for(int i = 0;i<config.teacherSelections.Count;i++)
{
if(currSelectionBraches[i].Count==0)
{
config.teacherSelections[i].failedStates.Add(skeletonStates[i]);
}
}
}
private ConfigurationState config;
private void init(bool onlyConsequtive)
{
solution = new List<Tuple<int, Subject>>[teachers.Count];
config = new ConfigurationState(state, teachers, supergroupMultilessons, onlyConsequtive, maxLessons);
sw = new System.Diagnostics.Stopwatch();
}
private static Dictionary<string, DaySchedule> calculated = new Dictionary<string, DaySchedule>();
System.Diagnostics.Stopwatch sw;
public DaySchedule gen(bool onlyConsequtive)
{
init(onlyConsequtive);
Console.WriteLine(calculated.Count);
string str = string.Join("|", Enumerable.Range(0, state.Count).Select(gInd => string.Join(" ", config.teacherList[gInd].Select(x => x.Item2.name))));
if (calculated.ContainsKey(str) == true) return calculated[str];
sw.Start();
rec(0, onlyConsequtive);
Console.WriteLine($"Generation time = {sw.ElapsedMilliseconds}");
sw.Stop();
calculated[str] = output;
return output;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SchoolManager.MaxFlow
{
class Edge
{
public int u;
public int v;
public int cap;
public long cost;
public Edge() { }
public Edge(int u, int v, int cap)
{
this.u = u;
this.v = v;
this.cap = cap;
}
public Edge(int u, int v, int cap, long cost) : this(u, v, cap)
{
this.cost = cost;
}
}
}
|
56ec760524dcb2004ac8f5c84e245676d9bbb95e
|
[
"C#"
] | 30 |
C#
|
StoyanMalinin/SchoolManager
|
5bb5fcb89fb4960ede1139cd9cb5dfc627292cc4
|
b2648335e9f80e062c23c19734890e4eff9f0b85
|
refs/heads/master
|
<repo_name>nnxiaod/DataStructure<file_sep>/DataStructure/src/com/liufei/collection/testHashMap.java
package com.liufei.collection;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
public class testHashMap {
public static void main(String[] args) {
Map<String, Integer> m1 = new HashMap<String, Integer>();
m1.put("Orange", 10);
m1.put("apple", 2);
m1.put("banana", 6);
Map<String, Integer> m2 = new HashMap<String, Integer>();
m2.put("dog", 9);
m2.put("cat", 3);
m1.putAll(m2);
//遍历元素1,通过keySet
Iterator<String> keyIterator = m1.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
System.out.println(key + ":" + m1.get(key));
}
//遍历元素2,通过entrySet
Iterator<Map.Entry<String, Integer>> entryInterator = m1.entrySet().iterator();
while (entryInterator.hasNext()) {
Entry<String, Integer> entry = entryInterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println(m1.containsValue(4));
System.out.println(m1.containsValue(6));
//遍历值
Iterator<Integer> valueIterator = m1.values().iterator();
while (valueIterator.hasNext()) {
System.out.println(valueIterator.next());
}
}
}
<file_sep>/DataStructure/src/com/liufei/ds/sorting/SelectSort.java
package com.liufei.ds.sorting;
import java.util.Arrays;
public class SelectSort {
public static void sort(int[] a) {
for (int i = 0; i < a.length; i++) {
boolean exchange = false;
int k = i;
for (int j = i + 1; j < a.length; j++) {
if (a[k] > a[j]) {
k = j;
exchange = true;
}
}
if (exchange) {
int temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
}
public static void main(String[] args) {
int[] a = { 5, 2, 8, 3, 0, 9, 1, 7, 6, 4 };
System.out.println("Before sorting: " + Arrays.toString(a));
SelectSort.sort(a);
System.out.println("After sorting: " + Arrays.toString(a));
}
}
<file_sep>/DataStructure/src/com/liufei/collection/testTreeMap.java
package com.liufei.collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
public class testTreeMap {
public static void main(String[] args) {
Map<String, Integer> m1 = new TreeMap<String, Integer>();
m1.put("Orange", 10);
m1.put("apple", 2);
m1.put("banana", 6);
Map<String, Integer> m2 = new HashMap<String, Integer>();
m2.put("dog", 9);
m2.put("cat", 3);
m2.put("mouse", 20);
m1.putAll(m2);
Iterator<Map.Entry<String, Integer>> entryInterator = m1.entrySet().iterator();
while (entryInterator.hasNext()) {
Entry<String, Integer> entry = entryInterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
<file_sep>/README.md
DataStructure
=============
Basic Data Structure & Algorithms. Implemented by Java
|
a7b2a69414b216af02e7872930eea74ffc33f543
|
[
"Markdown",
"Java"
] | 4 |
Java
|
nnxiaod/DataStructure
|
f1dd662c6e4ed697013e01f650273fd06a7b1444
|
97d0863bfc9b558e957a618b33564394fc586419
|
refs/heads/master
|
<repo_name>nicolasmeunier/cdn<file_sep>/Gemfile
source 'http://rubygems.org'
gem 'rails', '3.0.8'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'mysql2', '0.2.6'
gem 'sqlite3'
# Use unicorn as the web server
# gem 'unicorn'
# Deploy with Capistrano
gem 'capistrano'
gem 'jrails'
gem 'haml'
#Using forked jammit to allow not to rewrite the css relative paths.
gem 'jammit', :git => 'git://github.com/dblock/jammit.git'
group :development, :test do
gem "rspec-rails"
gem "cucumber-rails"
gem "capybara"
gem "factory_girl_rails"
gem "sass"
gem "compass"
gem "rb-fsevent" # for mac development machines
end
gem 'aws-s3'
gem 'right_aws'
#gem 'aproxacs-s3sync'
# To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+)
# gem 'ruby-debug'
# gem 'ruby-debug19', :require => 'ruby-debug'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
# group :development, :test do
# gem 'webrat'
# end
<file_sep>/lib/tasks/assets.rake
###################################################################################################
# RAKE tasks for the asset management ,
# - Compass compiler --> assets:compile
# - Jammit bundler --> assets:bundle
# - Clean all --> assets:clean
# - Compile and bundle --> assets (runs assets:compile and assets:bundle)
####################################################################################################
require 'securerandom'
desc "Compiles SASS using Compass"
task 'sass:compile' do
system 'compass compile'
end
namespace :assets do
desc "Compiles all CSS assets"
task :compile => ['sass:compile']
desc "Bundles all assets with Jammit"
task :bundle => :environment do
system "cd #{Rails.root} && jammit"
end
desc "Copy css images from stylesheets/images to assets/images"
task :copy_css_images => :environment do
#Cleaning public/assets/images and copying fresh css images from stylesheets/images
system "cd #{Rails.root} && rm -r public/assets/images/ && cp -r public/stylesheets/images public/assets"
end
desc "Generating asset_hash used for S3 deployment"
task :generate_hash => [ :environment ] do
rdm = SecureRandom.hex(16)
file = open('config/asset_hash.yml', 'wb')
file.write("hash: " + rdm)
file.close
end
desc "Removes all compiled and bundled assets"
task :clean => :environment do
files = []
files << ['assets']
files << ['javascripts', 'compiled']
files << ['stylesheets', 'compiled']
files = files.map { |path| Dir[Rails.root.join('public', *path, '*.*')] }.flatten
puts "Removing:"
files.each do |file|
puts " #{file.gsub(Rails.root.to_s + '/', '')}"
end
File.delete *files
end
end
desc "Compiles and bundles all assets"
task :assets => ['assets:compile', 'assets:bundle', 'assets:generate_hash', 'assets:copy_css_images']
namespace :server_env do
namespace :hash do
task :to_production => [ :environment, :assets ] do
Rake::Task["server_env:hash:addHashToEnvironment"].execute({ app: 'example-production' })
end
task :to_staging => [ :environment ] do
Rake::Task["server_env:hash:addHashToEnvironment"].execute({ app: 'example-staging' })
end
task :addHashToEnvironment, [ :app ] => [ :environment ] do |t, args|
hash = (`git rev-parse HEAD` || "").chomp
Rake::Task["heroku:config:add"].execute({ app: args[:app], value: "ASSET_HASH=#{hash}" })
end
end
namespace :config do
desc "Set a configuration parameter on Heroku"
task :add, [ :app, :value ] => :environment do |t, args|
app = "--app #{args[:app]}" if args[:app]
value = args[:value]
logger.debug("[#{Time.now}] running 'heroku config:add #{app} #{value}'")
`heroku config:add #{app} #{value}`
end
end
end<file_sep>/app/controllers/photos_controller.rb
class PhotosController < ActionController::Base
layout "photo.haml"
def index
@photos = Photo.find :all
end
end
<file_sep>/config/deploy.rb
#---
# Excerpted from "Agile Web Development with Rails, 3rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails3 for more book information.
#---
# be sure to change these
# deploy
# |-- deploy:update
# |---- deploy:update_code
# |------ Code update based on the :deploy_via
# |------ deploy:finalize_update
# |---- deploy:symlink
# |-- deploy:restart
set :user, 'ubuntu'
set :domain, 'ec2-204-236-177-181.us-west-1.compute.amazonaws.com'
set :application, 'cdn'
set :rails_env, 'production'
# file paths
set :repository, "<EMAIL>:nicolasmeunier/cdn.git" # Your clone URL
set :deploy_to, "/home/#{user}/www/cabinguru"
# distribute your applications across servers (the instructions below put them
# all on the same server, defined above as 'domain', adjust as necessary)
role :app, domain
role :web, domain, :asset_host_syncher => true
role :db, domain, :primary => true
# you might need to set this if you aren't seeing password prompts
# default_run_options[:pty] = true
# As Capistrano executes in a non-interactive mode and therefore doesn't cause
# any of your shell profile scripts to be run, the following might be needed
# if (for example) you have locally installed gems or applications. Note:
# this needs to contain the full values for the variables set, not simply
# the deltas.
# default_environment['PATH']='<your paths>:/usr/local/bin:/usr/bin:/bin'
# default_environment['GEM_PATH']='<your paths>:/usr/lib/ruby/gems/1.8'
# miscellaneous options
# Might be needed to turn off remote_cache http://groups.google.com/group/capistrano/browse_thread/thread/b14635454d40087b/8bbc4d7d286fccc8?pli=1
#set :deploy_via, :remote_cache
set :git_shallow_clone, 1 # As a remote cache alternative
set :scm, 'git'
set :branch, 'master'
set :scm_verbose, true
set :use_sudo, false
# Per http://help.github.com/capistrano/
default_run_options[:pty] = true # Must be set for the password prompt from git to work
ssh_options[:forward_agent] = true
# task which causes Passenger to initiate a restart
namespace :deploy do
task :restart do
run "touch #{current_path}/tmp/restart.txt"
end
end
# # optional task to reconfigure databases
after "deploy:update_code", :configure_database
after"deploy:update_code", :configure_asset_hash
#before "deploy:symlink", "s3_asset_host:synch_public"
# Removed for first deployment
# TODO: Uncomment
#after "configure_database", :start_delayed_job_workers
desc "copy database.yml into the current release path"
task :configure_database, :roles => :app do
db_config = "#{deploy_to}/config/database.yml"
run "cp #{db_config} #{release_path}/config/database.yml"
end
task :configure_asset_hash, :roles => :app do
hash = (`git rev-parse HEAD` || "").chomp
asset_yml = "hash: " + hash
#on local machine
`echo '#{asset_yml}' > config/asset_hash.yml`
#on remote machine
asset_config = "#{release_path}/config/asset_hash.yml"
run "echo '#{asset_yml}' > #{asset_config}"
end
<file_sep>/lib/tasks/s3.rake
###################################################################################################
# RAKE tasks for the deployment to S3
# - sync assets to staging --> s3:push:to_staging (copy files from public/assets to s3
# to cwcdn0/assets/GitRandHash/ )
#
#
# USES:
# - upload to S3 --> s3:uploadToS3
####################################################################################################
require 'logger'
namespace :s3 do
#Helper function
def s3i
@@s3 ||= s3i_open
end
#Config data for s3 are in config/s3.yml.
def s3i_open
s3_config = YAML.load_file(Rails.root.join("config/s3.yml")).symbolize_keys
s3_key_id = s3_config[:production]['config']['S3_ACCESS_KEY_ID']
s3_access_key = s3_config[:production]['config']['S3_SECRET_ACCESS_KEY']
RightAws::S3Interface.new(s3_key_id, s3_access_key, { logger: Rails.logger })
end
# uploads assets to s3 under assets/githash, deletes stale assets
task :uploadToS3, [:to] => :environment do |t, args|
from = File.join(Rails.root, 'public/assets')
to = args[:to]
#hash_config = YAML.load_file(Rails.root.join("config/asset_hash.yml")).symbolize_keys
#hash = hash_config[:hash]
hash = (`git rev-parse HEAD` || "").chomp
#logger.info("[#{Time.now}] fetching keys from #{to}")
existing_objects_hash = {}
s3i.incrementally_list_bucket(to) do |response|
response[:contents].each do |existing_object|
next unless existing_object[:key].start_with?("assets/")
existing_objects_hash[existing_object[:key]] = existing_object
end
end
#logger.info("[#{Time.now}] copying from #{from} to s3:#{to} @ #{hash}")
Dir.glob(from + "/**/*").each do |entry|
next if File::directory?(entry)
key = 'assets/'
key += (hash + '/') if hash
key += entry.slice(from.length + 1, entry.length - from.length - 1)
existing_objects_hash.delete(key)
#logger.info("[#{Time.now}] uploading #{key}")
s3i.put(to, key, File.open(entry), { 'x-amz-acl' => 'public-read' })
end
existing_objects_hash.keys.each do |key|
puts "deleting #{key}"
s3i.delete(to, key)
end
end
namespace :push do
task :to_staging => [:environment] do
Rake::Task["s3:uploadToS3"].execute({ to: 'cwcdn0' })
end
end
end
|
8628ccca95a8f991a8abea473dcd2b9d5f41c5a2
|
[
"Ruby"
] | 5 |
Ruby
|
nicolasmeunier/cdn
|
28ac03cba7bce472c0fc3d1aa12f33b97059279c
|
c0650de681d513dc9f1a4b2bfa374539e2b23c2a
|
refs/heads/master
|
<repo_name>teispir/java-exercises<file_sep>/servlet/ex1_helloworld/src/main/java/org/example/HelloWorld.java
package org.example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//response.setContentType("text/html");
//response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">");
response.getWriter().println("<title>Servlet Hello World</title>");
response.getWriter().println("</head>");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Servlet Hello World</h1>");
response.getWriter().println("</body></html>");
}
}<file_sep>/README.md
# java-exercises
A collection of useful Java Exercises
# subfolder jsp
A collection of JSP Exercises
# subfolder servlet
A collection of Servlet Exercises
<file_sep>/servlet/ex1_helloworld/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>servlet-helloworld</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>Hello World Servlet</name>
<description>Hello World Servlet</description>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<!-- Set the name of the WAR, used as the context root when the app
is deployed -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
|
1abd903fc068a4d2527d04025b375aa021597832
|
[
"Markdown",
"Java",
"Maven POM"
] | 3 |
Java
|
teispir/java-exercises
|
8f768019e8a2774ad3e55db93deb30f7edbbe4fa
|
f0bc34e30ee605289e2f2372e7c118a7d05d9b8b
|
refs/heads/master
|
<repo_name>AntoineAugusti/goodtables-py<file_sep>/frictionless/program/api.py
from typer import Option as Opt
from ..system import system
from .main import program
from .. import settings
@program.command(name="api")
def program_api(
port: int = Opt(settings.DEFAULT_SERVER_PORT, help="Specify server port"),
):
"""
Start API server
"""
server = system.create_server("api")
server.start(port=port)
<file_sep>/docs/tutorials/formats/ckan-tutorial.md
---
title: CKAN Tutorial
sidebar_label: CKAN
---
> This functionality requires an experimental `ckan` plugin. [Read More](../../references/plugins-reference.md)
Frictionless supports reading and writing CKAN datasets.
```bash title="CLI"
pip install frictionless[ckan]
```
## Reading Data
You can read a CKAN dataset:
```python
from pprint import pprint
from frictionless import Package
package = Package.from_ckan('<base_url>', dataset_id='<dataset_id>', api_key='<api_key>')
pprint(package)
for resource in package.resources:
pprint(resource.read_rows())
```
## Writing Data
> **[NOTE]** Timezone information is ignored for `datetime` and `time` types.
You can write a dataset to CKAN:
```python
from frictionless import Package
package = Package('path/to/datapackage.json')
package.to_ckan('<base_url>', dataset_id='<dataset_id>', api_key='<api_key>')
```
## Configuring Data
There is a dialect to configure how Frictionless read and write files in this format. For example:
```python
from frictionless import Resource
from frictionless.plugins.ckan import CkanDialect
dialect = CkanDialect(resource='resource', dataset='dataset', apikey='apikey')
resource = Resource('https://ckan-portal.com', format='ckan', dialect=dialect)
```
For more control on the CKAN query you can use `fields`, `limit`, `sort` and `filter` in the dialect. For example:
```python
from frictionless import Resource
from frictionless.plugins.ckan import CkanDialect
dialect = CkanDialect(
resource='resource',
dataset='dataset',
apikey='apikey',
fields=['date','key','value'],
limit=10,
sort='date desc',
filter={'key': 'value'}
)
resource = Resource('https://ckan-portal.com', format='ckan', dialect=dialect)
```
References:
- [Ckan Dialect](../../references/formats-reference.md#ckan)
<file_sep>/tests/checks/test_regulation.py
from frictionless import validate, checks
# Forbidden Value
def test_validate_forbidden_value():
report = validate(
"data/table.csv",
checks=[checks.forbidden_value(field_name="id", values=[2])],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[3, 1, "forbidden-value"],
]
def test_validate_forbidden_value_task_error():
report = validate(
"data/table.csv",
checks=[{"code": "forbidden-value", "fieldName": "bad", "forbidden": [2]}],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[None, None, "task-error"],
]
def test_validate_forbidden_value_many_rules():
source = [
["row", "name"],
[2, "Alex"],
[3, "John"],
[4, "mistake"],
[5, "error"],
[6],
]
report = validate(
source,
checks=[
{"code": "forbidden-value", "fieldName": "row", "values": [10]},
{"code": "forbidden-value", "fieldName": "name", "values": ["mistake"]},
{"code": "forbidden-value", "fieldName": "row", "values": [10]},
{"code": "forbidden-value", "fieldName": "name", "values": ["error"]},
],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[4, 2, "forbidden-value"],
[5, 2, "forbidden-value"],
[6, 2, "missing-cell"],
]
def test_validate_forbidden_value_many_rules_with_non_existent_field():
source = [
["row", "name"],
[2, "Alex"],
]
report = validate(
source,
checks=[
{"code": "forbidden-value", "fieldName": "row", "values": [10]},
{"code": "forbidden-value", "fieldName": "bad", "values": ["mistake"]},
],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[None, None, "check-error"],
]
# Sequential Value
def test_validate_sequential_value():
source = [
["row", "index2", "index3"],
[2, 1, 1],
[3, 2, 3],
[4, 3, 5],
[5, 5, 6],
[6],
]
report = validate(
source,
checks=[
checks.sequential_value(field_name="index2"),
checks.sequential_value(field_name="index3"),
],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[3, 3, "sequential-value"],
[5, 2, "sequential-value"],
[6, 2, "missing-cell"],
[6, 3, "missing-cell"],
]
def test_validate_sequential_value_non_existent_field():
source = [
["row", "name"],
[2, "Alex"],
[3, "Brad"],
]
report = validate(
source,
checks=[
{"code": "sequential-value", "fieldName": "row"},
{"code": "sequential-value", "fieldName": "bad"},
],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[None, None, "check-error"],
]
# Row constraint
def test_validate_row_constraint():
source = [
["row", "salary", "bonus"],
[2, 1000, 200],
[3, 2500, 500],
[4, 1300, 500],
[5, 5000, 1000],
[6],
]
report = validate(
source, checks=[checks.row_constraint(formula="salary == bonus * 5")]
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[4, None, "row-constraint"],
[6, 2, "missing-cell"],
[6, 3, "missing-cell"],
[6, None, "row-constraint"],
]
def test_validate_row_constraint_incorrect_constraint():
source = [
["row", "name"],
[2, "Alex"],
]
report = validate(
source,
checks=[
{"code": "row-constraint", "formula": "vars()"},
{"code": "row-constraint", "formula": "import(os)"},
{"code": "row-constraint", "formula": "non_existent > 0"},
],
)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[2, None, "row-constraint"],
[2, None, "row-constraint"],
[2, None, "row-constraint"],
]
def test_validate_row_constraint_list_in_formula_issue_817():
data = [["val"], ["one"], ["two"]]
report = validate(
data,
checks=[
checks.duplicate_row(),
checks.row_constraint(formula="val in ['one', 'two']"),
],
)
assert report.valid
def test_validate_table_dimensions_num_rows():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(num_rows=42)],
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumRows": 42, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_num_rows_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "numRows": 42}],
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumRows": 42, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_min_rows():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(min_rows=42)],
)
assert report.flatten(["limits", "code"]) == [
[{"minRows": 42, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_min_rows_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "minRows": 42}],
)
assert report.flatten(["limits", "code"]) == [
[{"minRows": 42, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_max_rows():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(max_rows=2)],
)
assert report.flatten(["limits", "code"]) == [
[{"maxRows": 2, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_max_rows_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "maxRows": 2}],
)
assert report.flatten(["limits", "code"]) == [
[{"maxRows": 2, "numberRows": 3}, "table-dimensions-error"]
]
def test_validate_table_dimensions_num_fields():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(num_fields=42)],
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumFields": 42, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_num_fields_declarative():
report = validate(
"data/table-limits.csv", checks=[{"code": "table-dimensions", "numFields": 42}]
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumFields": 42, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_min_fields():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(min_fields=42)],
)
assert report.flatten(["limits", "code"]) == [
[{"minFields": 42, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_min_fields_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "minFields": 42}],
)
assert report.flatten(["limits", "code"]) == [
[{"minFields": 42, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_max_fields():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(max_fields=2)],
)
assert report.flatten(["limits", "code"]) == [
[{"maxFields": 2, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_max_fields_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "maxFields": 2}],
)
assert report.flatten(["limits", "code"]) == [
[{"maxFields": 2, "numberFields": 4}, "table-dimensions-error"]
]
def test_validate_table_dimensions_no_limits():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions()],
)
assert report.flatten(["limits", "code"]) == []
def test_validate_table_dimensions_no_limits_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions"}],
)
assert report.flatten(["limits", "code"]) == []
def test_validate_table_dimensions_num_fields_num_rows_wrong():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(num_fields=3, num_rows=2)],
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumFields": 3, "numberFields": 4}, "table-dimensions-error"],
[{"requiredNumRows": 2, "numberRows": 3}, "table-dimensions-error"],
]
def test_validate_table_dimensions_num_fields_num_rows_wrong_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "numFields": 3, "numRows": 2}],
)
assert report.flatten(["limits", "code"]) == [
[{"requiredNumFields": 3, "numberFields": 4}, "table-dimensions-error"],
[{"requiredNumRows": 2, "numberRows": 3}, "table-dimensions-error"],
]
def test_validate_table_dimensions_num_fields_num_rows_correct():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(num_fields=4, num_rows=3)],
)
assert report.flatten(["limits", "code"]) == []
def test_validate_table_dimensions_num_fields_num_rows_correct_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "numFields": 4, "numRows": 3}],
)
assert report.flatten(["limits", "code"]) == []
def test_validate_table_dimensions_min_fields_max_rows_wrong():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(min_fields=5, max_rows=2)],
)
assert report.flatten(["limits", "code"]) == [
[{"minFields": 5, "numberFields": 4}, "table-dimensions-error"],
[{"maxRows": 2, "numberRows": 3}, "table-dimensions-error"],
]
def test_validate_table_dimensions_min_fields_max_rows_wrong_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "minFields": 5, "maxRows": 2}],
)
assert report.flatten(["limits", "code"]) == [
[{"minFields": 5, "numberFields": 4}, "table-dimensions-error"],
[{"maxRows": 2, "numberRows": 3}, "table-dimensions-error"],
]
def test_validate_table_dimensions_min_fields_max_rows_correct():
report = validate(
"data/table-limits.csv",
checks=[checks.regulation.table_dimensions(min_fields=4, max_rows=3)],
)
assert report.flatten(["limits", "code"]) == []
def test_validate_table_dimensions_min_fields_max_rows_correct_declarative():
report = validate(
"data/table-limits.csv",
checks=[{"code": "table-dimensions", "minFields": 4, "maxRows": 3}],
)
assert report.flatten(["limits", "code"]) == []
<file_sep>/frictionless/checks/regulation.py
import simpleeval
from .. import errors
from ..check import Check
class forbidden_value(Check):
"""Check for forbidden values in a field
API | Usage
-------- | --------
Public | `from frictionless import checks`
Implicit | `validate(checks=[{"code": "backlisted-value", **descriptor}])`
This check can be enabled using the `checks` parameter
for the `validate` function.
Parameters:
descriptor (dict): check's descriptor
field_name (str): a field name to look into
forbidden (any[]): a list of forbidden values
"""
code = "forbidden-value"
Errors = [errors.ForbiddenValueError]
def __init__(self, descriptor=None, *, field_name=None, values=None):
self.setinitial("fieldName", field_name)
self.setinitial("values", values)
super().__init__(descriptor)
self.__field_name = self["fieldName"]
self.__values = self["values"]
# Validate
def validate_start(self):
if self.__field_name not in self.resource.schema.field_names:
note = 'forbidden value check requires field "%s"' % self.__field_name
yield errors.CheckError(note=note)
def validate_row(self, row):
cell = row[self.__field_name]
if cell in self.__values:
yield errors.ForbiddenValueError.from_row(
row,
note='forbiddened values are "%s"' % self.__values,
field_name=self.__field_name,
)
# Metadata
metadata_profile = { # type: ignore
"type": "object",
"requred": ["fieldName", "values"],
"properties": {
"fieldName": {"type": "string"},
"values": {"type": "array"},
},
}
class table_dimensions(Check):
"""Check for minimum and maximum table dimensions
API | Usage
-------- | --------
Public | `from frictionless import checks`
Implicit | `validate(checks=[{"code": "table-dimensions", numRows, minRows, maxRows, numFields, minFields, maxFields}])`
Parameters:
descriptor (dict): check's descriptor
"""
code = "table-dimensions"
Errors = [errors.TableDimensionsError]
def __init__(
self,
descriptor=None,
*,
num_rows=None,
num_fields=None,
min_rows=None,
max_rows=None,
min_fields=None,
max_fields=None
):
self.setinitial("numRows", num_rows)
self.setinitial("numFields", num_fields)
self.setinitial("minRows", min_rows)
self.setinitial("maxRows", max_rows)
self.setinitial("minFields", min_fields)
self.setinitial("maxFields", max_fields)
super().__init__(descriptor)
self.__num_rows = self["numRows"] if "numRows" in self else -1
self.__num_fields = self["numFields"] if "numFields" in self else -1
self.__min_rows = self["minRows"] if "minRows" in self else -1
self.__max_rows = self["maxRows"] if "maxRows" in self else -1
self.__min_fields = self["minFields"] if "minFields" in self else -1
self.__max_fields = self["maxFields"] if "maxFields" in self else -1
# Validate
def validate_start(self):
number_fields = len(self.resource.schema.fields)
# Check if there is a different number of fields as required
if self.__num_fields > 0 and number_fields != self.__num_fields:
yield errors.TableDimensionsError(
note="Current number of fields is %s, the required number is %s"
% (number_fields, self.__num_fields),
limits={
"requiredNumFields": self.__num_fields,
"numberFields": number_fields,
},
)
# Check if there is less field than the minimum
if self.__min_fields > 0 and number_fields < self.__min_fields:
yield errors.TableDimensionsError(
note="Current number of fields is %s, the minimum is %s"
% (number_fields, self.__min_fields),
limits={"minFields": self.__min_fields, "numberFields": number_fields},
)
# Check if there is more field than the maximum
if self.__max_fields > 0 and number_fields > self.__max_fields:
yield errors.TableDimensionsError(
note="Current number of fields is %s, the maximum is %s"
% (number_fields, self.__max_fields),
limits={"maxFields": self.__max_fields, "numberFields": number_fields},
)
def validate_row(self, row):
self.__last_row = row
number_rows = self.__last_row.row_number
# Check if exceed the max number of rows
if self.__max_rows > 0 and self.__last_row.row_number > self.__max_rows:
yield errors.TableDimensionsError(
note="Current number of rows is %s, the maximum is %s"
% (number_rows, self.__max_rows),
limits={"maxRows": self.__max_rows, "numberRows": number_rows},
)
def validate_end(self):
number_rows = self.__last_row.row_number
# Check if doesn't have the exact number of rows
if self.__num_rows > 0 and number_rows != self.__num_rows:
yield errors.TableDimensionsError(
note="Current number of rows is %s, the required is %s"
% (number_rows, self.__num_rows),
limits={"requiredNumRows": self.__num_rows, "numberRows": number_rows},
)
# Check if has less rows than the required
if self.__min_rows > 0 and number_rows < self.__min_rows:
yield errors.TableDimensionsError(
note="Current number of rows is %s, the minimum is %s"
% (number_rows, self.__min_rows),
limits={"minRows": self.__min_rows, "numberRows": number_rows},
)
# Metadata
metadata_profile = { # type: ignore
"type": "object",
"requred": {
"oneOf": [
"numRows",
"minRows",
"maxRows",
"numFields",
"minFields",
"maxFields",
]
},
"properties": {
"numRows": {"type": "number"},
"minRows": {"type": "number"},
"maxRows": {"type": "number"},
"numFields": {"type": "number"},
"minFields": {"type": "number"},
"maxFields": {"type": "number"},
},
}
class sequential_value(Check):
"""Check that a column having sequential values
API | Usage
-------- | --------
Public | `from frictionless import checks`
Implicit | `validate(checks=[{"code": "sequential-value", **descriptor}])`
This check can be enabled using the `checks` parameter
for the `validate` function.
Parameters:
descriptor (dict): check's descriptor
field_name (str): a field name to check
"""
code = "sequential-value"
Errors = [errors.SequentialValueError]
def __init__(self, descriptor=None, *, field_name=None):
self.setinitial("fieldName", field_name)
super().__init__(descriptor)
self.__field_name = self.get("fieldName")
self.__cursor = None
self.__exited = False
# Validate
def validate_start(self):
if self.__field_name not in self.resource.schema.field_names:
note = 'sequential value check requires field "%s"' % self.__field_name
yield errors.CheckError(note=note)
def validate_row(self, row):
if not self.__exited:
cell = row[self.__field_name]
try:
self.__cursor = self.__cursor or cell
assert self.__cursor == cell
self.__cursor += 1
except Exception:
self.__exited = True
yield errors.SequentialValueError.from_row(
row,
note="the value is not sequential",
field_name=self.__field_name,
)
# Metadata
metadata_profile = { # type: ignore
"type": "object",
"requred": ["fieldName"],
"properties": {"fieldName": {"type": "string"}},
}
class row_constraint(Check):
"""Check that every row satisfies a provided Python expression
API | Usage
-------- | --------
Public | `from frictionless import checks`
Implicit | `validate(checks=([{"code": "row-constraint", **descriptor}])`
This check can be enabled using the `checks` parameter
for the `validate` function. The syntax for the row constraint
check can be found here - https://github.com/danthedeckie/simpleeval
Parameters:
descriptor (dict): check's descriptor
formula (str): a python expression to evaluate against a row
"""
code = "row-constraint"
Errors = [errors.RowConstraintError]
def __init__(self, descriptor=None, *, formula=None):
self.setinitial("formula", formula)
super().__init__(descriptor)
self.__formula = self["formula"]
# Validate
def validate_row(self, row):
try:
# This call should be considered as a safe expression evaluation
# https://github.com/danthedeckie/simpleeval
# NOTE: review EvalWithCompoundTypes/sync with steps
evalclass = simpleeval.EvalWithCompoundTypes
assert evalclass(names=row).eval(self.__formula)
except Exception:
yield errors.RowConstraintError.from_row(
row,
note='the row constraint to conform is "%s"' % self.__formula,
)
# Metadata
metadata_profile = { # type: ignore
"type": "object",
"requred": ["formula"],
"properties": {"formula": {"type": "string"}},
}
<file_sep>/tests/validate/test_main.py
from frictionless import Resource, Field, validate, describe
# Table
def test_validate():
report = validate("data/table.csv")
assert report.valid
def test_validate_invalid():
report = validate("data/invalid.csv")
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[None, 3, "blank-label"],
[None, 4, "duplicate-label"],
[2, 3, "missing-cell"],
[2, 4, "missing-cell"],
[3, 3, "missing-cell"],
[3, 4, "missing-cell"],
[4, None, "blank-row"],
[5, 5, "extra-cell"],
]
def test_validate_from_resource_instance():
resource = Resource("data/table.csv")
report = validate(resource)
assert report.valid
# Issues
def test_validate_multiple_files_issue_850():
report = validate("data/package/*.csv")
assert report.stats["tasks"] == 2
def test_validate_less_actual_fields_with_required_constraint_issue_950():
schema = describe("data/table.csv", type="schema")
schema.add_field(Field(name="bad", constraints={"required": True}))
report = validate("data/table.csv", schema=schema)
assert report.flatten(["rowPosition", "fieldPosition", "code"]) == [
[None, 3, "missing-label"],
[2, 3, "missing-cell"],
[3, 3, "missing-cell"],
]
<file_sep>/frictionless/checks/__init__.py
from .baseline import baseline
from .heuristic import duplicate_row, deviated_value, truncated_value
from .regulation import (
forbidden_value,
sequential_value,
row_constraint,
table_dimensions,
)
<file_sep>/frictionless/plugin.py
# NOTE: implement create_resource so plugins can validate it (see #991)?
class Plugin:
"""Plugin representation
API | Usage
-------- | --------
Public | `from frictionless import Plugin`
It's an interface for writing Frictionless plugins.
You can implement one or more methods to hook into Frictionless system.
"""
code = "plugin"
status = "stable"
def create_candidates(self, candidates):
"""Create candidates
Returns:
dict[]: an ordered by priority list of type descriptors for type detection
"""
pass
def create_check(self, name, *, descriptor=None):
"""Create check
Parameters:
name (str): check name
descriptor (dict): check descriptor
Returns:
Check: check
"""
pass
def create_control(self, file, *, descriptor):
"""Create control
Parameters:
file (File): control file
descriptor (dict): control descriptor
Returns:
Control: control
"""
pass
def create_dialect(self, file, *, descriptor):
"""Create dialect
Parameters:
file (File): dialect file
descriptor (dict): dialect descriptor
Returns:
Dialect: dialect
"""
pass
def create_error(self, descriptor):
"""Create error
Parameters:
descriptor (dict): error descriptor
Returns:
Error: error
"""
pass
def create_file(self, source, **options):
"""Create file
Parameters:
source (any): file source
options (dict): file options
Returns:
File: file
"""
pass
def create_loader(self, file):
"""Create loader
Parameters:
file (File): loader file
Returns:
Loader: loader
"""
pass
def create_parser(self, file):
"""Create parser
Parameters:
file (File): parser file
Returns:
Parser: parser
"""
pass
def create_server(self, name):
"""Create server
Parameters:
name (str): server name
Returns:
Server: server
"""
pass
def create_step(self, descriptor):
"""Create step
Parameters:
descriptor (dict): step descriptor
Returns:
Step: step
"""
pass
def create_storage(self, name, source, **options):
"""Create storage
Parameters:
name (str): storage name
options (str): storage options
Returns:
Storage: storage
"""
pass
def create_type(self, field):
"""Create type
Parameters:
field (Field): corresponding field
Returns:
Type: type
"""
pass
<file_sep>/tests/test_type.py
import pytest
from frictionless import system, Plugin, Type, Resource, Schema, Field, describe
# General
def test_type_custom(custom_plugin):
schema = Schema(
fields=[
Field(name="integer", type="integer"),
Field(name="custom", type="custom"),
]
)
with Resource(path="data/table.csv", schema=schema) as resource:
assert resource.read_rows() == [
{"integer": 1, "custom": ["english"]},
{"integer": 2, "custom": ["中国人"]},
]
def test_type_custom_detect(custom_plugin):
resource = describe("data/table.csv")
assert resource.schema.fields[0].type == "custom"
assert resource.schema.fields[1].type == "custom"
# Fixtures
@pytest.fixture
def custom_plugin():
# Type
class CustomType(Type):
def read_cell(self, cell):
return [cell]
# Plugin
class CustomPlugin(Plugin):
def create_candidates(self, candidates):
candidates.insert(0, {"type": "custom"})
def create_type(self, field):
if field.type == "custom":
return CustomType(field)
# System
plugin = CustomPlugin()
system.register("custom", plugin)
yield plugin
system.deregister("custom")
<file_sep>/tests/test_system.py
import pytest
import requests
from frictionless import Resource, system
BASEURL = "https://raw.githubusercontent.com/frictionlessdata/frictionless-py/master/%s"
# General
@pytest.mark.vcr
def test_system_use_http_session():
session = requests.Session()
with system.use_http_session(session):
assert system.get_http_session() is session
with Resource(BASEURL % "data/table.csv") as resource:
assert resource.control.http_session is session
assert resource.header == ["id", "name"]
assert system.get_http_session() is not session
|
120eae0b365594d392045e0d3e0c09768c1c15bf
|
[
"Markdown",
"Python"
] | 9 |
Python
|
AntoineAugusti/goodtables-py
|
164f611b3a1454893e35c4c70101c2678728818d
|
475a1e37ffe8c87fed1669151d05a345135a411b
|
refs/heads/master
|
<file_sep>// produce same output for the same input
// no side effects
// the computation only depends on the input
// pure fns => self contained
const hello = () => 'worlds';
const hello2 = (name: string) => `hello ${ name }`;
const compute3 = (a: number, b: number) => a + b;
// not pure => output changes but input does not
const now = () => new Date();
// built in fns in JS
// slice => pure
const arr1 = [ 1, 2, 3, 4, 5 ];
const res1 = arr1.slice(0, 1);
console.log(res1); // 1
console.log(arr1); // no change in original data
// splice => not pure
const arr2 = [ 1, 2, 3, 4, 5 ];
const res2 = arr1.splice(0, 1); // changes the original one
console.log(res1); // 1
console.log(arr1); // no change in original data
// mathematical fns => pure => introverts
// pure fns => benefits
// - No side effects
// - output is deterministic
// - self contained, independent
// - may inc performance
// - ref transparent
// explicit like values
// no outside interaction but => not ref transparent => not pure => output changes but input does not
const now2 = () => new Date();<file_sep>// console.log(computeAdd(2, 2)); // error
// not hoisted as its a func expression
const computeAdd = (a: number, b: number) => {
return a + b;
};
// anonymous func expression
const computeAdd2 = function (a: number, b: number) {
return a + b;
};
// IIFE => Also Anonymous Funcs
let count = 0;
(function () {
count += 1;
})();
console.log(count); // 1
let count2 = 0;
const res = (function () {
count2 += 1;
return count;
})();
console.log(res); // 1
// Recursive funcs need to be named ofc
// named func expression
const computeAdd23 = function adding2 (a: number, b: number) {
return a + b;
};
console.log(computeAdd(2, 2));<file_sep>// An expression is ref transparent if it can be replaced with its value without changing the program's behaviour
// Expression is a combo of consts, vars, operations and funcs that is interpreted and COMPUTED to produce another value
// Value => numerical entity
<file_sep>// Memoization it is an optimization technique. It consists of storing function result instead of recomputing it each time. In other words, it is a « cache » for function invocations. Since function results are cached, they can be returned immediately when given function is invoked with the same arguments. A function can only be memoized if it is referentially transparent.
interface MyCache {
arithmeticOperation: MyOperations;
args: number[];
result: number;
}
const Operations = [ 'sum', 'subtract', 'divide', 'multiply' ] as const;
type MyOperations = typeof Operations[ number ];
const cache: MyCache = { args: null, arithmeticOperation: null, result: null };
const areSimilarArray = (arr1: number[], arr2: number[]) => {
const len1 = arr1.length;
const len2 = arr2.length;
let areSimilar = false;
if (len1 !== len2) {
areSimilar = false;
return areSimilar;
}
areSimilar = arr1.every((v, i) => v === arr2[ i ]);
return areSimilar;
};
const computeSumAndFillCache = (a: number, b: number) => {
console.log('filling cache...');
const sum = a + b;
cache.args = [ a, b ];
cache.arithmeticOperation = 'sum';
cache.result = sum;
return sum;
};
const cachedSum = (a: number, b: number) => {
if (!cache.arithmeticOperation || cache.arithmeticOperation !== 'sum') {
const res = computeSumAndFillCache(a, b);
return res;
} else {
const areSimilar = areSimilarArray([ a, b ], cache.args);
if (areSimilar) {
console.log('cache won');
return cache.result;
} else {
const res = computeSumAndFillCache(a, b);
return res;
}
}
};
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));
console.log(cachedSum(1, 2));<file_sep>// Side Effect => Change of original data or observable interaction with the outside world during the pure fns runtime
const compute1 = (a: number, b: number) => {
const sum = a + b;
console.log(sum); // outside interaction
return sum;
};
console.log(compute1(1, 2));
class Person {
age: number;
name: string;
constructor (age: number, name: string) {
this.age = age;
this.name = name;
}
setName (name: string) {
this.name = name; // changing the original state
}
getName (): string {
return this.name;
}
}
const p1 = new Person(23, 'Aman');
p1.setName('<NAME>');
console.log(p1.getName());
// other side effects => db queries, http req (Post?) etc.
// Controlling Side Effects<file_sep>
function addMe (x: number, y: number) {
return x + y;
}
function voidAdd (_: number, __: number) {
}
const addResult = addMe(2, 2);
console.log(addResult);
// only void funcs can be invocked by new keyword
const addResult2 = new voidAdd(2, 2);
console.log(addResult2);
const addResult3 = addMe.call(null, 2, 2);
console.log(addResult3);
const addResult4 = addMe.apply(null, [ 2, 2 ]);
console.log(addResult4);<file_sep>const dev = {
skills: [ 'js', 'ts', 'go', 'c', 'c++' ],
jobTitle: 'SDE'
};
function displaySkills () {
return this.skills;
}
const displayJobTitle = function () {
return this.jobTitle;
};
// undefined => no this of their own in arrow funcs
// const displayJobTitle = () => {
// return this.jobTitle;
// };
const skillset = displaySkills.apply(dev);
console.log(skillset);
const job = displayJobTitle.apply(dev);
console.log(job);<file_sep>// Functions and variables (with var keyword) are hoisted
console.log(adding(2, 2));
// Function Declaration => hoisted => compiler remembers func name => adding
function adding (x: number, y: number) {
return x + y;
}
console.log(adding(2, 2));<file_sep>// Dont have their own this => they inherit
const arrowAdd = (a: number, b: number) => a + b; // implicit return
console.log(arrowAdd(2, 2));
|
2010df157327cc511ead0a6a055b9b59910c6f65
|
[
"TypeScript"
] | 9 |
TypeScript
|
inblack67/Functional-Programming
|
e7f9c27a51fcb7e509afd5c295969219bb3825c2
|
af061eb0526895c6dec67e4928000226e47caf6e
|
refs/heads/master
|
<repo_name>isllyend/RNLearnDemo<file_sep>/js/page/FetchDemoPage.js
import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, SafeAreaView, Text, View, Button} from 'react-native';
export default class FetchDemoPage extends Component {
constructor(props) {
super(props);
this.state = {
result: '',
}
}
loadData() {
let url = `https://api.github.com/search/repositories?q=${this.searchKey}`;
fetch(url)
.then(response => response.text())
.then(responseText => {
this.setState({
result: responseText,
})
})
}
loadData2() {
let url = `https://api.github.com/search/q=${this.searchKey}`;
fetch(url)
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Network response is not ok.');
}
})
.then(responseText => {
this.setState({
result: responseText,
})
})
.catch(e => {
this.setState({
result: e.toString(),
})
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.homePage}>Fetch 基本使用</Text>
<View style={styles.textInputContainer}>
<TextInput style={styles.textInput} onChangeText={text => {
this.searchKey = text;
}}/>
<Button title={'search'} onPress={() => {
this.loadData();
// this.loadData2();
}}/>
</View>
<Text>{this.state.result}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
homePage: {
justifyContent: 'center',
fontSize: 20,
},
textInputContainer: {
flexDirection: 'row',
alignItems: 'center',
height: 50,
},
textInput: {
flex: 1,
height: 40,
borderWidth: 1,
borderColor: 'black',
margin: 10,
},
});
<file_sep>/js/expand/dao/ThemeDao.js
import {AsyncStorage} from 'react-native'
import ThemeFactory, {ThemeFlags} from '../../../res/styles/ThemeFactory'
const THEME_KEY = 'theme_key';
export default class ThemeDao {
/**
* 保存主题标识
* @param themeFlag
*/
saveTheme(themeFlag) {
AsyncStorage.setItem(THEME_KEY, themeFlag);
}
/**
* 获取当前主题
* @returns {Promise<any> | Promise<*>}
*/
getTheme() {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(THEME_KEY, (error, themeFlag) => {
if (error) {
reject(error);
return;
}
if (!themeFlag) {
themeFlag = ThemeFlags.Default;
this.saveTheme(themeFlag);
}
resolve(ThemeFactory.createTheme(themeFlag));
});
});
};
}<file_sep>/ios/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'RNLearnDemo' do
# 友盟公共基础库
pod 'UMCCommon'
pod 'UMCSecurityPlugins'
pod 'UMCCommonLog'
# 友盟统计库
pod 'UMCAnalytics'
pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen'
end
<file_sep>/js/page/CustomKeyPage.js
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
DeviceInfo,
TouchableOpacity,
ScrollView,
Alert
} from 'react-native';
import {connect} from 'react-redux'
import actions from '../action/index'
import NavigationBar from '../common/NavigationBar'
import NavigationUtil from "../navigator/NavigationUtil";
import {FLAG_LANGUAGE} from '../expand/dao/LanguageDao'
import BackPressComponent from "../common/BackPressComponent";
import LanguageDao from "../expand/dao/LanguageDao";
import ViewUtil from "../util/ViewUtil";
import CheckBox from 'react-native-check-box'
import Ionicons from 'react-native-vector-icons/Ionicons'
import ArrayUtil from "../util/ArrayUtil";
import SafeAreaViewPlus from "../common/SafeAreaViewPlus";
type Props = {};
export class CustomKeyPage extends Component<Props> {
constructor(props) {
super(props);
this.params = this.props.navigation.state.params; // 取出上级界面传过来的参数
this.backPress = new BackPressComponent({backPress: this.onBackPress}); //设置安卓物理返回键
this.changeValues = []; // 改变后的标签数组
this.isRemoveKey = !!this.params.isRemoveKey; // 是否是移除标签页面 !!a 等同于 a!=null&&typeof(a)!=undefined&&a!='' 作用是将a强制转换为布尔型
this.languageDao = new LanguageDao(this.params.flag); // flag 代表是自定义标签还是自定义语言
this.state = {
keys: [] // 初始化默认标签数组
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.keys !== CustomKeyPage._keys(nextProps, null, prevState)) {
return {
keys: CustomKeyPage._keys(nextProps, null, prevState),
}
}
return null;
}
componentDidMount() {
this.backPress.componentDidMount();
// 1. 如果props中标签为空则从本地存储中获取标签
if (CustomKeyPage._keys(this.props).length === 0) {
let {onLoadLanguageData} = this.props;
onLoadLanguageData(this.params.flag);
}
// 2. 通过设置state以及来getDerivedStateFromProps赋值render
this.setState({
keys: CustomKeyPage._keys(this.props),
});
}
componentWillUnmount() {
this.backPress.componentWillUnmount();
}
/**
* 获取标签
* @param props
* @param original 移除标签时使用,是否从props获取原始对的标签
* @param state 移除标签时使用
* @returns {*}
* @private
*/
static _keys(props, original, state) {
const {flag, isRemoveKey} = props.navigation.state.params;
let key = flag === FLAG_LANGUAGE.flag_key ? 'keys' : 'languages';
if (isRemoveKey && !original) {
//如果state中的keys为空则从props中取出数组,并且修改checked为false
return state && state.keys && state.keys.length !== 0 && state.keys || props.language[key].map(value => {
return {
...value,
checked: false,
};
})
} else if (isRemoveKey) {
return props.language[key];
} else {
return state && state.keys && state.keys.length !== 0 && state.keys || props.language[key].map(value => {
return {
...value,
};
});
}
}
onBackPress = () => {
this.onBack();
return true;
};
onBack() {
if (this.changeValues.length > 0) {
Alert.alert('提示', '要保存修改吗?', [
{
text: '否',
onPress: () => {
NavigationUtil.goBack(this.props.navigation);
}
},
{
text: '是',
onPress: () => {
this.onSave();
}
}
])
} else {
NavigationUtil.goBack(this.props.navigation);
}
}
onSave() {
if (this.changeValues.length === 0) {
NavigationUtil.goBack(this.props.navigation);
return;
}
let keys;
if (this.isRemoveKey) {
for (let i = 0, len = this.changeValues.length; i < len; i++) {
ArrayUtil.remove(keys = CustomKeyPage._keys(this.props, true), this.changeValues[i], 'name')
}
}
//更新本地数据
this.languageDao.save(keys || this.state.keys);
const {onLoadLanguageData} = this.props;
//更新store
onLoadLanguageData(this.params.flag);
NavigationUtil.goBack(this.props.navigation);
}
renderRightButton() {
return <TouchableOpacity
style={{alignItems: 'center',}}
onPress={() => this.onSave()}>
<Text style={{fontSize: 20, color: '#FFFFFF', marginRight: 10}}>完成</Text>
</TouchableOpacity>
}
onClick(data, index) {
data.checked = !data.checked;
// 更新 changeValues 数组
ArrayUtil.updateArray(this.changeValues, data);
//更新state以便显示选中状态
this.state.keys[index] = data;
this.setState({
keys: this.state.keys,
})
}
_checkedImage(checked) {
const {theme} = this.params;
return <Ionicons
name={checked ? 'ios-checkbox' : 'md-square-outline'}
size={20}
style={{
color: theme.themeColor,
}}
/>
}
renderCheckBox(data, index) {
return <CheckBox
style={{flex: 1, padding: 10}}
onClick={() => this.onClick(data, index)}
isChecked={data.checked}
leftText={data.name}
checkedImage={this._checkedImage(true)}
unCheckedImage={this._checkedImage(false)}
/>
}
renderView() {
let dataArray = this.state.keys;
if (!dataArray || dataArray.length === 0) return;
let views = [];
for (let i = 0, len = dataArray.length; i < len; i += 2) {
views.push(
<View key={i}>
<View style={styles.item}>
{this.renderCheckBox(dataArray[i], i)}
{i + 1 < len && this.renderCheckBox(dataArray[i + 1], i + 1)}
</View>
<View style={styles.line}/>
</View>
)
}
return views;
}
render() {
const {theme} = this.params;
let title = this.isRemoveKey ? '标签移除' : '自定义标签';
title = this.params.flag === FLAG_LANGUAGE.flag_language ? '自定义语言' : title;
let statusBar = {
backgroundColor: theme.themeColor,
barStyle: 'light-content'
};
let navigationBar = <NavigationBar
title={title}
statusBar={statusBar}
style={theme.styles.navBar}
rightButton={this.renderRightButton()}
leftButton={ViewUtil.getLeftBackButton(() => this.onBack())}
/>;
return (<SafeAreaViewPlus style={{flex: 1}} topColor={theme.themeColor}>
{navigationBar}
<ScrollView>
{this.renderView()}
</ScrollView>
</SafeAreaViewPlus>
);
}
}
const mapCustomKeyStateToProps = state => ({
language: state.language,
});
const mapCustomKeyDispatchToProps = dispatch => ({
onLoadLanguageData: (flagKey) => dispatch(actions.onLoadLanguageData(flagKey)),
});
export default connect(mapCustomKeyStateToProps, mapCustomKeyDispatchToProps)(CustomKeyPage);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
line: {
flex: 1,
height: 0.3,
backgroundColor: 'darkgray',
},
item: {
flexDirection: 'row',
},
});
<file_sep>/js/page/WelcomePage.js
import React, {Component} from 'react';
import { Platform, StyleSheet, Image, SafeAreaView, Text, View} from 'react-native';
import NavigationUtil from '../navigator/NavigationUtil'
import SplashScreen from 'react-native-splash-screen'
import actions from "../action";
import {connect} from "react-redux";
type Props = {};
export class WelcomePage extends Component<Props> {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount(): void {
const {onThemeInit} = this.props;
onThemeInit();
this.timer = setTimeout(() => {
SplashScreen.hide()
NavigationUtil.resetToHomePage(this.props)
}, 200)
}
componentWillMount(): void {
this.timer && clearTimeout(this.timer);
}
render() {
return null;
}
}
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
onThemeInit: () => dispatch(actions.onThemeInit())
});
export default connect(mapStateToProps, mapDispatchToProps)(WelcomePage);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
alignItems: 'center',
justifyContent: 'center',
},
welcome: {
justifyContent: 'center',
fontSize: 20,
},
});
<file_sep>/md/以 PopularPage 请求数据为例描述Redux+Flatlist页面开发流程.md
以 PopularPage 请求数据为例描述Redux+Flatlist页面开发流程
1、在`action`文件夹中的`types.js`中添加新的类型 `POPULAR_REFRESH` `LOAD_POPULAR_FAIL` `LOAD_POPULAR_SUCCESS`。
2、 在`action`文件夹中创建`popular`文件夹,并且在`popular`文件夹中创建`index.js`文件,在`index.js`文件中写入`onLoadPopularData`以及`handleData`实现方法。
```javascript
import Types from '../types'
import DataStore from DataStore
/**
* DataStorection
* @param storeName // 指的是具体的某种编程语言,例如iOS, Android
* @returns {Function}
*/
export function onLoadPopularData(storeName) {
// 返回一个异步acton
return dispatch => {
// 下拉时做一些操作,比如loading控件显示之类
dispatch({
type: Types.POPULAR_REFRESH,
storeName: storeName,
});
let dataStore = new DataStoreA();
DataStoree.fetchData(url) // 异步action与数据流
.then(data => {
handleData(dispatch, storeName, data)
})
.catch(error => {
error && console.log(error.toString());
dispatch({
type:Types.LOAD_POPULAR_FAIL,
storeName, // 等价于 storeName: storeName,
error,
})
})
}
}
/* 请求数据成功,进行数据处理 */
function handleData(dispatch, storeName, data) {
dispatch({
type: Types.LOAD_POPULAR_SUCCESS,
items: data && data.data && data.data.items,
storeName: storeName,
})
}
```
并且在`action`目录下的`index.js`文件中聚合`onLoadPopularData`方法。
```javascript
import {onThemeChange} from './theme';
import {onLoadPopularData} from "./popular";
export default {
onThemeChange,
onLoadPopularData,
}
```
3、在`reducer`文件夹中创建`popular`文件夹,并且在`popular`文件夹中创建`index.js`文件,在`index.js`文件中写入第二步设置的`action`的`reducer`方法。
```javascript
import Types from '../../action/types'
const defaultState = {};
/**
* popular:{
* java:{
* items:[],
* isLoading:false,
* },
* ios:{
* items:[],ios
* isLoading:false,
* }
* }
* 0.state树,横向扩展
* 1.如何动态的设置store,和动态获取store(难点:store key 设置为 [action.storeName] 为不固定);
* @param state
* @param action
* @returns {{}}
*/
export default function onAction(state = defaultState, action) {
switch (action.type) {
case Types.LOAD_POPULAR_SUCCESS: {
return {
...state,
[action.storeName]:{
...[action.storeName],
items:action.items,
isLoading:false,
},
};
}
case Types.POPULAR_REFRESH: {
return {
...state,
[action.storeName]:{
...[action.storeName],
isLoading:true,
},
}
}
case Types.LOAD_POPULAR_FAIL: {
return {
...state,
[action.storeName]:{
...[action.storeName],
isLoading:false,
},
}
}
default:
return state;
}
}
```
在reducer目录下的index.js文件中聚合popular的reducer方法。
```javascript
import { combineReducers } from 'redux'
import theme from './theme'
import popular from './popular'
import {rootCom, RootNavigator} from "../navigator/AppNavigator";
/**
* 1.指定默认state
*/
// console.log(RootNavigator);
// const { router } = RootNavigator;
const navState = RootNavigator.router.getStateForAction(RootNavigator.router.getActionForPathAndParams(rootCom));
// debugger;
// console.log(navState);
/**
* 2.创建自己的 navigation reducer,
*/
const navReducer = (state = navState, action) => {
const nextState = RootNavigator.router.getStateForAction(action, state);
// 如果`nextState`为null或未定义,只需返回原始`state`
return nextState || state;
};
/**
* 3.合并reducer
* @type {Reducer<any> | Reducer<any, AnyAction>}
*/
const index = combineReducers({
nav: navReducer,
theme: theme,
popular: popular,
});
export default index;
```
4、在`page`文件夹下对`PopularPage.js`文件进行绑定`state`以及`action`, 通过对this.props中的绑定`state (popular)`以及绑定`action (onLoadPopularData)`来对界面进行数据请求处理以及UI渲染。
```javascript
const mapStateToProps = state => ({
popular: state.popular,
});
const mapDispatchToProps = dispatch => ({
onLoadPopularData: (storeName, url) => dispatch(actions.onLoadPopularData(storeName, url)),
});
const PopularTabPage = connect(mapStateToProps, mapDispatchToProps)(PopularTab);
```<file_sep>/js/action/popular/index.js
import Types from '../types'
import DataStore, {FLAG_STORAGE} from '../../expand/dao/DataStore'
import {_projectModels, handleData} from '../ActionUtil'
/**
* 获取最热数据的异步action
* @param storeName // 指的是具体的某种编程语言,例如iOS, Android
* @returns {Function}
*/
export function onRefreshPopular(storeName, url, pageSize, favoriteDao) {
// 返回一个异步acton
return dispatch => {
// 下拉时做一些操作,比如loading控件显示之类
dispatch({
type: Types.POPULAR_REFRESH,
storeName: storeName,
});
let dataStore = new DataStore();
dataStore.fetchData(url, FLAG_STORAGE.flag_popular) // 异步action与数据流
.then(data => {
handleData(Types.POPULAR_REFRESH_SUCCESS, dispatch, storeName, data, pageSize, favoriteDao)
})
.catch(error => {
error && console.log(error.toString());
dispatch({
type: Types.POPULAR_REFRESH_FAIL,
storeName, // 等价于 storeName: storeName,
error,
})
})
}
}
/**
* 上拉加载更多
* @param storeName
* @param pageIndex 第几页
* @param pageSize 每页展示条数
* @param dataArray 原始数据
* @param favoriteDao
* @param callBack 回调函数,可以通过回调函数来向调用页面通信:比如异常信息的展示,没有更多等待
* @returns {Function}
*/
export function onLoadMorePopular(storeName, pageIndex, pageSize, dataArray = [], favoriteDao, callBack) {
// 返回一个异步acton
return dispatch => {
setTimeout(() => { // 模拟网络请求
if ((pageIndex - 1) * pageSize >= dataArray.length) { // 比较上次已经加载完的数据和源数组的大小来判断是否全部加载完成, 全部加载完成在这里等于加载更多失败
if (typeof callBack === 'function') { // 判断 callBack 是否是一个function
callBack('no more data');
}
dispatch({
type: Types.POPULAR_LOAD_MORE_FAIL,
storeName,
pageIndex: --pageIndex, // 模拟请求的时候做了+1操作,现在让他做-1操作复位到最大的pageIndex
error: 'no more data',
})
} else { // 请求成功返回当前Index的子数组
let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex; //本次和载入的最大数量, 假如是最大数量则展示最大数量的子数组
_projectModels(dataArray.slice(0, max), favoriteDao, projectModels => {
dispatch({
type: Types.POPULAR_LOAD_MORE_SUCCESS,
storeName,
pageIndex,
projectModels: projectModels,
})
})
}
}, 500)
}
}
/**
* 刷新收藏状态
* @param storeName
* @param pageIndex 第几页
* @param pageSize 每页展示条数
* @param dataArray 原始数据
* @param favoriteDao
* @returns {Function}
*/
export function onFlushPopularFavorite(storeName, pageIndex, pageSize, dataArray = [], favoriteDao) {
// 返回一个异步acton
return dispatch => {
let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex; //本次和载入的最大数量, 假如是最大数量则展示最大数量的子数组
_projectModels(dataArray.slice(0, max), favoriteDao, projectModels => {
dispatch({
type: Types.FLUSH_POPULAR_FAVORITE,
storeName,
pageIndex,
projectModels: projectModels,
})
})
}
}
// /* 请求数据成功,进行数据处理 */
// /**
// *
// * @param dispatch
// * @param storeName
// * @param data
// * @param pageSize
// */
// function handleData(dispatch, storeName, data, pageSize) {
// let fixItems = [];
// if (data && data.data && data.data.items) {
// fixItems = data.data.items;
// }
// dispatch({
// type: Types.POPULAR_REFRESH_SUCCESS,
// projectModels: pageSize > fixItems.length ? fixItems : fixItems.slice(0, pageSize), // 第一次要加载的数据,根据设置的pageSize来判断,不能超过fixItems的长度
// items: fixItems,
// storeName: storeName,
// pageIndex: 1, // 初始的时候Index为1
// })
// }
// 数据样例
/*
* {
"total_count": 987198,
"incomplete_results": false,
"items": [
{
"id": 63477660,
"node_id": "MDEwOlJlcG9zaXRvcnk2MzQ3NzY2MA==",
"name": "Java",
"full_name": "TheAlgorithms/Java",
"private": false,
"owner": {
"login": "TheAlgorithms",
"id": 20487725,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjIwNDg3NzI1",
"avatar_url": "https://avatars1.githubusercontent.com/u/20487725?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/TheAlgorithms",
"html_url": "https://github.com/TheAlgorithms",
"followers_url": "https://api.github.com/users/TheAlgorithms/followers",
"following_url": "https://api.github.com/users/TheAlgorithms/following{/other_user}",
"gists_url": "https://api.github.com/users/TheAlgorithms/gists{/gist_id}",
"starred_url": "https://api.github.com/users/TheAlgorithms/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/TheAlgorithms/subscriptions",
"organizations_url": "https://api.github.com/users/TheAlgorithms/orgs",
"repos_url": "https://api.github.com/users/TheAlgorithms/repos",
"events_url": "https://api.github.com/users/TheAlgorithms/events{/privacy}",
"received_events_url": "https://api.github.com/users/TheAlgorithms/received_events",
"type": "Organization",
"site_admin": false
},
"html_url": "https://github.com/TheAlgorithms/Java",
"description": "All Algorithms implemented in Java",
"fork": false,
"url": "https://api.github.com/repos/TheAlgorithms/Java",
"forks_url": "https://api.github.com/repos/TheAlgorithms/Java/forks",
"keys_url": "https://api.github.com/repos/TheAlgorithms/Java/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/TheAlgorithms/Java/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/TheAlgorithms/Java/teams",
"hooks_url": "https://api.github.com/repos/TheAlgorithms/Java/hooks",
"issue_events_url": "https://api.github.com/repos/TheAlgorithms/Java/issues/events{/number}",
"events_url": "https://api.github.com/repos/TheAlgorithms/Java/events",
"assignees_url": "https://api.github.com/repos/TheAlgorithms/Java/assignees{/user}",
"branches_url": "https://api.github.com/repos/TheAlgorithms/Java/branches{/branch}",
"tags_url": "https://api.github.com/repos/TheAlgorithms/Java/tags",
"blobs_url": "https://api.github.com/repos/TheAlgorithms/Java/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/TheAlgorithms/Java/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/TheAlgorithms/Java/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/TheAlgorithms/Java/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/TheAlgorithms/Java/statuses/{sha}",
"languages_url": "https://api.github.com/repos/TheAlgorithms/Java/languages",
"stargazers_url": "https://api.github.com/repos/TheAlgorithms/Java/stargazers",
"contributors_url": "https://api.github.com/repos/TheAlgorithms/Java/contributors",
"subscribers_url": "https://api.github.com/repos/TheAlgorithms/Java/subscribers",
"subscription_url": "https://api.github.com/repos/TheAlgorithms/Java/subscription",
"commits_url": "https://api.github.com/repos/TheAlgorithms/Java/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/TheAlgorithms/Java/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/TheAlgorithms/Java/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/TheAlgorithms/Java/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/TheAlgorithms/Java/contents/{+path}",
"compare_url": "https://api.github.com/repos/TheAlgorithms/Java/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/TheAlgorithms/Java/merges",
"archive_url": "https://api.github.com/repos/TheAlgorithms/Java/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/TheAlgorithms/Java/downloads",
"issues_url": "https://api.github.com/repos/TheAlgorithms/Java/issues{/number}",
"pulls_url": "https://api.github.com/repos/TheAlgorithms/Java/pulls{/number}",
"milestones_url": "https://api.github.com/repos/TheAlgorithms/Java/milestones{/number}",
"notifications_url": "https://api.github.com/repos/TheAlgorithms/Java/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/TheAlgorithms/Java/labels{/name}",
"releases_url": "https://api.github.com/repos/TheAlgorithms/Java/releases{/id}",
"deployments_url": "https://api.github.com/repos/TheAlgorithms/Java/deployments",
"created_at": "2016-07-16T10:21:02Z",
"updated_at": "2019-01-28T03:48:05Z",
"pushed_at": "2019-01-27T22:20:29Z",
"git_url": "git://github.com/TheAlgorithms/Java.git",
"ssh_url": "[email protected]:TheAlgorithms/Java.git",
"clone_url": "https://github.com/TheAlgorithms/Java.git",
"svn_url": "https://github.com/TheAlgorithms/Java",
"homepage": null,
"size": 1007,
"stargazers_count": 10134,
"watchers_count": 10134,
"language": "Java",
"has_issues": true,
"has_projects": true,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 3910,
"mirror_url": null,
"archived": false,
"open_issues_count": 85,
"license": null,
"forks": 3910,
"open_issues": 85,
"watchers": 10134,
"default_branch": "master",
"score": 121.78253
},]*/<file_sep>/js/reducer/trending/index.js
import Types from '../../action/types'
const defaultState = {};
/**
* popular:{
* java:{
* items:[],
* isLoading:false,
* },
* ios:{
* items:[],ios
* isLoading:false,
* }
* }
*
* 0.state树,横向扩展
* 1.如何动态的设置store,和动态获取store(难点:store key不固定);
* @param state
* @param action
* @returns {{}}
*/
export default function onAction(state = defaultState, action) {
switch (action.type) {
case Types.TRENDING_REFRESH: { // 下拉刷新时
return {
...state,
[action.storeName]: {
...state[action.storeName],
isLoading: true,
hideLoadingMore: true,
},
}
}
case Types.TRENDING_REFRESH_SUCCESS: { // 下拉刷新成功
return {
...state,
[action.storeName]: {
...state[action.storeName],
items: action.items, // 原始数据
projectModels: action.projectModels, // 此次要展示的数据
isLoading: false,
hideLoadingMore: false,
pageIndex: action.pageIndex,
},
};
}
case Types.TRENDING_REFRESH_FAIL: { // 下拉刷新失败
return {
...state,
[action.storeName]: {
...state[action.storeName],
isLoading: false,
},
}
}
case Types.TRENDING_LOAD_MORE_SUCCESS: { // 上拉加载成功
return {
...state,
[action.storeName]: {
...state[action.storeName],
projectModels: action.projectModels,
hideLoadingMore: false,
pageIndex: action.pageIndex,
},
}
}
case Types.TRENDING_LOAD_MORE_FAIL: { // 上拉加载完成
return {
...state,
[action.storeName]: {
...state[action.storeName],
hideLoadingMore: true,
pageIndex: action.pageIndex,
},
}
}
case Types.FLUSH_TRENDING_FAVORITE:{//刷新收藏状态
return {
...state,
[action.storeName]: {
...state[action.storeName],
projectModels: action.projectModels,
}
}
}
default:
return state;
}
}
// 数据样例
/*
* {
"total_count": 987198,
"incomplete_results": false,
"items": [
{
"id": 63477660,
"node_id": "MDEwOlJlcG9zaXRvcnk2MzQ3NzY2MA==",
"name": "Java",
"full_name": "TheAlgorithms/Java",
"private": false,
"owner": {
"login": "TheAlgorithms",
"id": 20487725,
"node_id": "MDEyOk9yZ2FuaXphdGlvbjIwNDg3NzI1",
"avatar_url": "https://avatars1.githubusercontent.com/u/20487725?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/TheAlgorithms",
"html_url": "https://github.com/TheAlgorithms",
"followers_url": "https://api.github.com/users/TheAlgorithms/followers",
"following_url": "https://api.github.com/users/TheAlgorithms/following{/other_user}",
"gists_url": "https://api.github.com/users/TheAlgorithms/gists{/gist_id}",
"starred_url": "https://api.github.com/users/TheAlgorithms/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/TheAlgorithms/subscriptions",
"organizations_url": "https://api.github.com/users/TheAlgorithms/orgs",
"repos_url": "https://api.github.com/users/TheAlgorithms/repos",
"events_url": "https://api.github.com/users/TheAlgorithms/events{/privacy}",
"received_events_url": "https://api.github.com/users/TheAlgorithms/received_events",
"type": "Organization",
"site_admin": false
},
"html_url": "https://github.com/TheAlgorithms/Java",
"description": "All Algorithms implemented in Java",
"fork": false,
"url": "https://api.github.com/repos/TheAlgorithms/Java",
"forks_url": "https://api.github.com/repos/TheAlgorithms/Java/forks",
"keys_url": "https://api.github.com/repos/TheAlgorithms/Java/keys{/key_id}",
"collaborators_url": "https://api.github.com/repos/TheAlgorithms/Java/collaborators{/collaborator}",
"teams_url": "https://api.github.com/repos/TheAlgorithms/Java/teams",
"hooks_url": "https://api.github.com/repos/TheAlgorithms/Java/hooks",
"issue_events_url": "https://api.github.com/repos/TheAlgorithms/Java/issues/events{/number}",
"events_url": "https://api.github.com/repos/TheAlgorithms/Java/events",
"assignees_url": "https://api.github.com/repos/TheAlgorithms/Java/assignees{/user}",
"branches_url": "https://api.github.com/repos/TheAlgorithms/Java/branches{/branch}",
"tags_url": "https://api.github.com/repos/TheAlgorithms/Java/tags",
"blobs_url": "https://api.github.com/repos/TheAlgorithms/Java/git/blobs{/sha}",
"git_tags_url": "https://api.github.com/repos/TheAlgorithms/Java/git/tags{/sha}",
"git_refs_url": "https://api.github.com/repos/TheAlgorithms/Java/git/refs{/sha}",
"trees_url": "https://api.github.com/repos/TheAlgorithms/Java/git/trees{/sha}",
"statuses_url": "https://api.github.com/repos/TheAlgorithms/Java/statuses/{sha}",
"languages_url": "https://api.github.com/repos/TheAlgorithms/Java/languages",
"stargazers_url": "https://api.github.com/repos/TheAlgorithms/Java/stargazers",
"contributors_url": "https://api.github.com/repos/TheAlgorithms/Java/contributors",
"subscribers_url": "https://api.github.com/repos/TheAlgorithms/Java/subscribers",
"subscription_url": "https://api.github.com/repos/TheAlgorithms/Java/subscription",
"commits_url": "https://api.github.com/repos/TheAlgorithms/Java/commits{/sha}",
"git_commits_url": "https://api.github.com/repos/TheAlgorithms/Java/git/commits{/sha}",
"comments_url": "https://api.github.com/repos/TheAlgorithms/Java/comments{/number}",
"issue_comment_url": "https://api.github.com/repos/TheAlgorithms/Java/issues/comments{/number}",
"contents_url": "https://api.github.com/repos/TheAlgorithms/Java/contents/{+path}",
"compare_url": "https://api.github.com/repos/TheAlgorithms/Java/compare/{base}...{head}",
"merges_url": "https://api.github.com/repos/TheAlgorithms/Java/merges",
"archive_url": "https://api.github.com/repos/TheAlgorithms/Java/{archive_format}{/ref}",
"downloads_url": "https://api.github.com/repos/TheAlgorithms/Java/downloads",
"issues_url": "https://api.github.com/repos/TheAlgorithms/Java/issues{/number}",
"pulls_url": "https://api.github.com/repos/TheAlgorithms/Java/pulls{/number}",
"milestones_url": "https://api.github.com/repos/TheAlgorithms/Java/milestones{/number}",
"notifications_url": "https://api.github.com/repos/TheAlgorithms/Java/notifications{?since,all,participating}",
"labels_url": "https://api.github.com/repos/TheAlgorithms/Java/labels{/name}",
"releases_url": "https://api.github.com/repos/TheAlgorithms/Java/releases{/id}",
"deployments_url": "https://api.github.com/repos/TheAlgorithms/Java/deployments",
"created_at": "2016-07-16T10:21:02Z",
"updated_at": "2019-01-28T03:48:05Z",
"pushed_at": "2019-01-27T22:20:29Z",
"git_url": "git://github.com/TheAlgorithms/Java.git",
"ssh_url": "[email protected]:TheAlgorithms/Java.git",
"clone_url": "https://github.com/TheAlgorithms/Java.git",
"svn_url": "https://github.com/TheAlgorithms/Java",
"homepage": null,
"size": 1007,
"stargazers_count": 10134,
"watchers_count": 10134,
"language": "Java",
"has_issues": true,
"has_projects": true,
"has_downloads": true,
"has_wiki": true,
"has_pages": false,
"forks_count": 3910,
"mirror_url": null,
"archived": false,
"open_issues_count": 85,
"license": null,
"forks": 3910,
"open_issues": 85,
"watchers": 10134,
"default_branch": "master",
"score": 121.78253
},]*/<file_sep>/js/page/SortKeyPage.js
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
DeviceInfo,
TouchableOpacity,
TouchableHighlight,
Alert
} from 'react-native';
import {connect} from 'react-redux'
import actions from '../action/index'
import NavigationBar from '../common/NavigationBar'
import NavigationUtil from "../navigator/NavigationUtil";
import {FLAG_LANGUAGE} from '../expand/dao/LanguageDao'
import BackPressComponent from "../common/BackPressComponent";
import LanguageDao from "../expand/dao/LanguageDao";
import ViewUtil from "../util/ViewUtil";
import SortableListView from 'react-native-sortable-listview'
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'
import ArrayUtil from "../util/ArrayUtil";
import SafeAreaViewPlus from "../common/SafeAreaViewPlus";
const THEME_COLOR = '#678';
type Props = {};
export class SortKeyPage extends Component<Props> {
constructor(props) {
super(props);
this.params = this.props.navigation.state.params; // 取出上级界面传过来的参数
this.backPress = new BackPressComponent({backPress: this.onBackPress}); //设置安卓物理返回键
const {flag} = this.params;
this.languageDao = new LanguageDao(flag); // flag 代表是标签排序还是语言排序
this.state = {
checkedArray: [] // 初始化默认标签数组
};
}
componentDidMount() {
this.backPress.componentDidMount();
// 1. 如果props中标签为空则从本地存储中获取标签
if (SortKeyPage._keys(this.props).length === 0) {
let {onLoadLanguageData} = this.props;
onLoadLanguageData(this.params.flag);
}
// 2. 通过设置state以及来getDerivedStateFromProps赋值render
this.setState({
checkedArray: SortKeyPage._keys(this.props),
});
}
componentWillUnmount() {
this.backPress.componentWillUnmount();
}
static _flag(props) {
const {flag} = props.navigation.state.params;
return flag === FLAG_LANGUAGE.flag_key ? "keys" : "languages";
}
/**
*
* @param props
* @param state
* @returns {*}
* @private
*/
static _keys(props, state) {
//如果state中有checkedArray则使用state中的checkedArray
if (state && state.checkedArray && state.checkedArray.length) {
return state.checkedArray;
}
const flag = SortKeyPage._flag(props);
let dataArray = props.language[flag] || [];
let keys = [];
for (let i = 0, len = dataArray.length; i < len; i++) {
let data = dataArray[i];
if (data.checked) {
keys.push(data);
}
}
return keys;
}
onBackPress = () => {
this.onBack();
return true;
};
onBack() {
// 比较原数组和现有的数组的是否相同
if (!ArrayUtil.isEqual(SortKeyPage._keys(this.props), this.state.checkedArray)) {
Alert.alert('提示', '要保存修改吗?', [
{
text: '否',
onPress: () => {
NavigationUtil.goBack(this.props.navigation);
}
},
{
text: '是',
onPress: () => {
this.onSave(true);
}
}
])
} else {
NavigationUtil.goBack(this.props.navigation);
}
}
onSave(hasChecked) {
if (!hasChecked) {
if (ArrayUtil.isEqual(SortKeyPage._keys(this.props), this.state.checkedArray)) {
NavigationUtil.goBack(this.props.navigation);
return;
}
}
//保存排序后的数据
//获取排序后的数据
//更新本地数据
this.languageDao.save(this.getSortResult());
//重新加载排序后的标签,以便其他页面能够及时更新
const {onLoadLanguageData} = this.props;
//更新store
onLoadLanguageData(this.params.flag);
NavigationUtil.goBack(this.props.navigation);
}
/**
* 获取排序后的标签结果
* @returns {Array}
*/
getSortResult() {
const flag = SortKeyPage._flag(this.props);
//从原始数据中复制一份数据出来,以便对这份数据进行进行排序
let sortResultArray = ArrayUtil.clone(this.props.language[flag]);
//获取排序之前的排列顺序
const originalCheckedArray = SortKeyPage._keys(this.props);
//遍历排序之前的数据,用排序后的数据checkedArray进行替换
for (let i = 0, len = originalCheckedArray.length; i < len; i++) {
let item = originalCheckedArray[i];
//找到要替换的元素所在位置
let index = this.props.language[flag].indexOf(item);
//进行替换
sortResultArray.splice(index, 1, this.state.checkedArray[i]);
}
return sortResultArray;
}
renderRightButton() {
return <TouchableOpacity
style={{alignItems: 'center',}}
onPress={() => this.onSave()}>
<Text style={{fontSize: 20, color: '#FFFFFF', marginRight: 10}}>完成</Text>
</TouchableOpacity>
}
render() {
const {theme} = this.params;
let title = this.params.flag === FLAG_LANGUAGE.flag_language ? '语言排序' : '标签排序';
let statusBar = {
backgroundColor: theme.themeColor,
barStyle: 'light-content'
};
let navigationBar = <NavigationBar
title={title}
statusBar={statusBar}
style={{backgroundColor: theme.themeColor}}
rightButton={this.renderRightButton()}
leftButton={ViewUtil.getLeftBackButton(() => this.onBack())}
/>;
// SortableListView的用法具体参考 https://github.com/deanmcpherson/react-native-sortable-listview/blob/master/example.js
return (
<SafeAreaViewPlus style={{flex: 1}} topColor={theme.themeColor}>
{navigationBar}
<SortableListView
data={this.state.checkedArray}
order={Object.keys(this.state.checkedArray)}
onRowMoved={e => {
this.state.checkedArray.splice(e.to, 0, this.state.checkedArray.splice(e.from, 1)[0])
this.forceUpdate()
}}
renderRow={row => <SortCell data={row} {...this.params}/>}
/>
</SafeAreaViewPlus>
);
}
}
class SortCell extends Component {
render(): React.ReactNode {
const {theme} = this.props;
return <TouchableHighlight
underlayColor={'#eee'}
style={this.props.data.checked ? styles.item : styles.hidden}
{...this.props.sortHandlers}
>
<View style={{marginLeft: 10, flexDirection: 'row'}}>
< MaterialCommunityIcons
name={'sort'}
size={16}
style={{
marginRight: 10,
color: theme.themeColor,
}}/>
<Text>{this.props.data.name}</Text>
</View>
</TouchableHighlight>;
}
}
const mapSortKeyStateToProps = state => ({
language: state.language,
});
const mapSortKeyDispatchToProps = dispatch => ({
onLoadLanguageData: (flagKey) => dispatch(actions.onLoadLanguageData(flagKey)),
});
export default connect(mapSortKeyStateToProps, mapSortKeyDispatchToProps)(SortKeyPage);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
line: {
flex: 1,
height: 0.3,
backgroundColor: 'darkgray',
},
item: {
backgroundColor: "#F8F8F8",
borderBottomWidth: 1,
borderColor: '#eee',
height: 50,
justifyContent: 'center'
},
hidden: {
height: 0,
}
});
<file_sep>/js/action/types.js
export default {
THEME_CHANGE: "THEME_CHANGE",
SHOW_THEME_VIEW: "SHOW_THEME_VIEW",
POPULAR_REFRESH: "POPULAR_REFRESH", // popular列表下拉刷新的action
POPULAR_REFRESH_FAIL: "POPULAR_REFRESH_FAIL", // popular列表加载失败的action
POPULAR_REFRESH_SUCCESS: "POPULAR_REFRESH_SUCCESS", // popular列表加载成功的action
POPULAR_LOAD_MORE_FAIL: "POPULAR_LOAD_MORE_FAIL", // popular列表上拉加载更多失败的action
POPULAR_LOAD_MORE_SUCCESS: "POPULAR_LOAD_MORE_SUCCESS", // popular列表上拉加载更多成功的action
TRENDING_REFRESH: "TRENDING_REFRESH", // trending列表下拉刷新的action
TRENDING_REFRESH_FAIL: "TRENDING_REFRESH_FAIL", // trending列表加载失败的action
TRENDING_REFRESH_SUCCESS: "TRENDING_REFRESH_SUCCESS", // trending列表加载成功的action
TRENDING_LOAD_MORE_FAIL: "TRENDING_LOAD_MORE_FAIL", // trending列表上拉加载更多失败的action
TRENDING_LOAD_MORE_SUCCESS: "TRENDING_LOAD_MORE_SUCCESS", // trending列表上拉加载更多成功的action
FAVORITE_LOAD_DATA: "FAVORITE_LOAD_DATA", // 收藏列表加载过程的action
FAVORITE_LOAD_FAIL: "FAVORITE_LOAD_FAIL", // 收藏列表加载失败的action
FAVORITE_LOAD_SUCCESS: "FAVORITE_LOAD_SUCCESS", // 收藏列表加载成功的action
FLUSH_POPULAR_FAVORITE: "FLUSH_POPULAR_FAVORITE", // 刷新popular列表的收藏状态
FLUSH_TRENDING_FAVORITE: "FLUSH_TRENDING_FAVORITE", // 刷新trending列表的收藏状态
LANGUAGE_LOAD_SUCCESS: "LANGUAGE_LOAD_SUCCESS", // 获取语言或者标签成功
SEARCH_LOAD_MORE_SUCCESS: "SEARCH_LOAD_MORE_SUCCESS",
SEARCH_LOAD_MORE_FAIL: "SEARCH_LOAD_MORE_FAIL",
SEARCH_REFRESH: "SEARCH_REFRESH",
SEARCH_CANCEL: "SEARCH_CANCEL",
SEARCH_FAIL: "SEARCH_FAIL",
SEARCH_REFRESH_SUCCESS: "SEARCH_REFRESH_SUCCESS",
SEARCH_SAVE_KEY: "SEARCH_SAVE_KEY",
}<file_sep>/js/page/AsyncStorageDemoPage.js
import React, {Component} from 'react';
import { TextInput, StyleSheet, AsyncStorage, Text, View } from 'react-native';
const KEY = 'save_key';
export default class AsyncStorageDemoPage extends Component {
constructor(props) {
super(props);
this.state = {
showText: '',
}
}
async doSave() {
// 用法一
AsyncStorage.setItem(KEY, this.value, error => {
error && console.log(error.toString())
});
// 用法二
// AsyncStorage.setItem(KEY, this.value).catch(error => {
// error && console.log(error.toString())
// });
//
// // 用法三
// try {
// await AsyncStorage.setItem(KEY, this.value);
// } catch (error) {
// error && console.log(error.toString())
// }
}
async doRemove() {
// 用法一
AsyncStorage.removeItem(KEY,error => {
error && console.log(error.toString())
});
// 用法二
// AsyncStorage.removeItem(KEY)
// .catch(error => {
// error && console.log(error.toString())
// });
//
// 用法三
// try {
// await AsyncStorage.removeItem(KEY);
// } catch (error) {
// error && console.log(error.toString())
// }
}
async getData() {
// 用法一
AsyncStorage.getItem(KEY,(error, result) => {
this.setState({
showText:result,
});
console.log(result);
error && console.log(error.toString());
});
// 用法二
// AsyncStorage.getItem(KEY)
// .then(result => {
// this.setState({
// showText:result,
// });
// })
// .catch(error => {
// error && console.log(error.toString());
// });
// 用法三
// try {
// const value = await AsyncStorage.getItem(KEY);
// if (value !== null) {
// // We have data!!
// this.setState({
// showText:value,
// })
// }
// } catch (error) {
// error && console.log(error.toString())
// }
}
render() {
return (
<View style={styles.container}>
<Text style={styles.homePage}>AsyncStorage 基本使用</Text>
<View>
<TextInput style={styles.textInput} onChangeText={text => {
this.value = text;
}}/>
</View>
<View style={styles.textContainer}>
<Text onPress={() => {
this.doSave();
}}>
保存
</Text>
<Text onPress={() => {
this.doRemove();
}}>
删除
</Text>
<Text onPress={() => {
this.getData();
}}>
获取
</Text>
</View>
<Text>{this.state.showText}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
homePage: {
justifyContent: 'center',
fontSize: 20,
},
textInput: {
height: 40,
borderWidth: 1,
borderColor: 'black',
margin: 10,
},
textContainer: {
flexDirection: 'row',
alignItems: 'center',
height: 50,
justifyContent: 'space-around',
}
});
|
7ca5df5e1e65fe88510ea578aa9581158df7de66
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 11 |
JavaScript
|
isllyend/RNLearnDemo
|
2d58cf7dc18cd8b220d6eae40899f5159e4842ca
|
0a736261fd4f6812e8674d5d0dfe1ae3d8e94f43
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.