branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>akinsbo/setupRecipe<file_sep>/Makefile DEV_DIR = dev DEV_FRONTEND_DIR = dev/frontend_dev/ UTIL_SCRIPTS_DIR = utils/ help: @echo "" @echo "Author: <NAME>" @echo "Commands" @echo " help - generates this" @echo " install-all - installs docker(for amd64 systems), \ create-react-app (with nodejs and npm), jenkins. \ Best for a virgin Linux OS setup" @echo " run-frontend - builds and runs create-react-app and docker" @echo "view-images-in-registry - list images in docker repository \ and their tags where the bash script is customized to do so\ or use the url to" # install all you need on fresh linux system # install-all: @echo " navigating into utils folder" @echo " running all install data" cd $(UTIL_SCRIPTS_DIR)&& $(MAKE) install-all run-frontend: @echo " navigating into the frontend dev directory $(DEV_FRONTEND_DIR)" cd $(DEV_FRONTEND_DIR)&& $(MAKE) docker-build @echo " run-build create-react-app and build docker" @echo " run docker" cd $(DEV_FRONTEND_DIR)&& $(MAKE) docker-run stop-frontend: @echo " stopping docker container" cd $(DEV_FRONTEND_DIR)&& $(MAKE) docker-stop pull-image-to-docker-private-reg: @echo " pulling image to private repository" cd $(UTIL_SCRIPTS_DIR)&& $(MAKE) pull-image-to-docker-private-reg view-images-in-registry: @echo " listing images in docker private repository" cd $(UTIL_SCRIPTS_DIR)&& $(MAKE) view-images-in-registry <file_sep>/utils/shell-scripts/stop-scripts/Makefile DEV_DIR = dev DEV_FRONTEND_DIR = dev/frontend_dev setup-reactjs-project: @echo " Setting up reactjs for frontend" sudo bash $(DEV_FRONTEND_DIR)/utils\ /shell-scripts/setups/reactjs-setup.sh setup-docker-registry: @echo " Setting up docker registry" sudo bash $ <file_sep>/dev/frontend_dev/Dockerfile FROM localhost:5000/my-ubuntu:16.04 LABEL vendor="<NAME>" LABEL com.projectb.version="0.0.1-beta" LABEL Description="This is one of the frontend boxes for A/B testing" MAINTAINER <NAME> version:0.1 RUN apt-get update COPY build/ /var/www/html/ #VOLUME var/www/html/ # RUN echo 'setting environment variables' # Persisted environment variables for this container ENV container-type=frontend language=js ENV framework=reactjs ENV environment=dev version="0.0.1-beta" # EXPOSE 80 # HEALTHCHECK --interval=5m --timeout=3s \ # CMD curl -f http://localhost:3000/ || exit 1 <file_sep>/README.md #The readme JENKINS DOES NOT TERMINATE ON JEST TEST -Did this: add --forceExit to package.json "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom --forceExit", "eject": "react-scripts eject" } -Result: Didn't work -Conclusion: Avoid using jest for testing with Jenkins(except for manual testing) -Action: Use Mocha instead. First setup docker registry and install files by running #installed in this order create-react-app jenkins docker <file_sep>/build.sh #!/bin/dash echo 'Building building building building akinsbo projectb' <file_sep>/utils/Makefile INSTALL_SCRIPTS_DIR = shell-scripts/installation SETUP_SCRIPTS_DIR = shell-scripts/setups VIEW_SCRIPTS_DIR = shell-scripts/view #using space or tab is an important choice in formatting @echo statements help: @echo @echo "Author: <NAME>" @echo @echo " Commands: " @echo " help - show this message" @echo " install-docker-jenkins-react - install docker, jenkins and react" @echo " install-docker - installs docker on device. if device is not amd-64, please edit dev/utils/shell-scripts/installation/docker.sh" @echo " install-docker-compose - installs docker-compose." @echo " install-jenkins - installs jenkins on device" @echo " install-reactjs - installs nodejs, npm and create-react-app" @echo " url - view url" @echo " test-producer - Run the unit tests for the procuder" @echo " deps - Check for all dependecies" @echo "On a fresh Linux system, Use 'make install-all' command./ if you run into any errors, check the installation-scripts folder/ $(INSTALL_SCRIPTS_DIR) or setups folder at $(SETUP_SCRIPTS_DIR)" install-all: @echo "installing docker" sudo bash $(INSTALL_SCRIPTS_DIR)/docker.sh @echo "installing Jenkins" sudo bash $(INSTALL_SCRIPTS_DIR)/jenkins.sh @echo "installing nodejs, npm and create-react-app" sudo bash $(INSTALL_SCRIPTS_DIR)/create-react-app.sh @echo "installing docker-compose" sudo bash $(INSTALL_SCRIPTS_DIR)/docker-compose.sh install-docker: @echo "installing docker" sudo bash $(INSTALL_SCRIPTS_DIR)/docker.shinstall-jenkins: install-jenkins: @echo "installing Jenkins" sudo bash $(INSTALL_SCRIPTS_DIR)/jenkins.sh install-reactjs: @echo "installing nodejs, npm and create-react-app" sudo bash $(INSTALL_SCRIPTS_DIR)/create-react-app.sh install-docker-compose: @echo "installing docker-compose" sudo bash $(INSTALL_SCRIPTS_DIR)/docker-compose.sh setup-docker-private-reg: @echo "installing docker private registry" sudo bash $(SETUP_SCRIPTS_DIR)/docker-registry-setup.sh #setup-reactjs-project: #@echo "Install reactjs for frontend" ##sudo ln -s /usr/bin/nodejs /usr/bin #mkdir frontend_dev #sudo create-react-app frontend_dev # pull-image-to-docker-private-reg: @echo "installing docker private registry" sudo bash $(SETUP_SCRIPTS_DIR)/pull-image-to-docker-registry.sh sudo docker images stop-docker-registry: @echo "as with any container, use docker stop" sudo docker stop registry view-images-in-registry: @echo "viewing images in registry" sudo bash $(VIEW_SCRIPTS_DIR)/view-docker-registry-images.sh remove-docker-registry: @echo "Stopping the registry container" sudo docker stop registry @echo "Removing the registry container" sudo docker rm -v registry <file_sep>/dev/frontend_dev/Makefile #.SILENT IMAGE_NAME = image-name CONTAINER_NAME = container-name TAG_NAME =v0.01 CONTAINER_PORT = 80 HOST_PORT = 3005 REACT_DEV_DIR = /home/olaolu/Documents/projectb/dev/frontend_dev #using space or tab is an important choice in formatting @echo statements help: @echo @echo "Author: <NAME>" @echo @echo " Commands: " @echo " help - show this message" @echo " docker-build - build docker image if not already done" @echo " docker-run - start this service, and all of its deps, locally(docker)" @echo " docker-stop - stop the container" @echo " docker-remove-image - remove the image" @echo " docker-url - view url" @echo " test-producer - Run the unit tests for the procuder" @echo " deps - Check for all dependecies" docker-build: @echo " first install node modules for building reactjs if not installed - i.e. no node_modules folder present" sudo npm install @echo " running build of react-js in case build folder does not exist - i.e. no build folder present" sudo npm run build @echo " building docker image" sudo docker build -t $(IMAGE_NAME):$(TAG_NAME) . docker-run: @echo " updating build folder of react-js" sudo npm run build @echo " running docker image with volume mount at " sudo docker run -d -p $(HOST_PORT):$(CONTAINER_PORT) \ -v $(REACT_DEV_DIR)/build/:/var/www/html/ \ --name $(CONTAINER_NAME) $(IMAGE_NAME):$(TAG_NAME) sudo curl http://localhost:$(HOST_PORT) docker-stop: sudo docker stop $(CONTAINER_NAME) sudo docker rm $(CONTAINER_NAME) docker-remove-image: sudo docker rmi $(IMAGE_NAME):$(TAG_NAME) docker-curl: curl http://localhost:$(HOST_PORT) deps: @echo " *docker"
8fe5dd7e96856979afde91d08c4bddb9f429f976
[ "Markdown", "Makefile", "Dockerfile", "Shell" ]
7
Makefile
akinsbo/setupRecipe
6893096b961ac92368f47e6bd5fbd8d8e4897a6f
97b68470db90e1ebfd7859b345cf7a402b4da474
refs/heads/master
<repo_name>svger/button<file_sep>/build/index.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _ButtonGroup = require('./ButtonGroup'); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } require('./style/index.css'); var defaultPrefix = 'cefc-button'; var Button = function (_Component) { _inherits(Button, _Component); function Button() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Button); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Button.__proto__ || Object.getPrototypeOf(Button)).call.apply(_ref, [this].concat(args))), _this), _this.getBtnClass = function () { var _config; var _this$props = _this.props, color = _this$props.color, disabled = _this$props.disabled, radius = _this$props.radius, block = _this$props.block, clickedColor = _this$props.clickedColor, prefix = _this$props.prefix, fixed = _this$props.fixed; var config = (_config = {}, _defineProperty(_config, '' + prefix, true), _defineProperty(_config, prefix + '-default', true), _defineProperty(_config, prefix + '-radius', radius), _defineProperty(_config, prefix + '-disabled', disabled), _defineProperty(_config, prefix + '-block', block), _config); if (color) { config = Object.assign(config, _defineProperty({}, prefix + '-bg-' + color, true)); } if (fixed) { config = Object.assign(config, _defineProperty({}, prefix + '-fixed-' + fixed, true)); } if (clickedColor) { config = Object.assign(config, _defineProperty({}, prefix + '-clicked-' + clickedColor, true)); } return (0, _classnames2.default)(config); }, _this.getStyleObj = function () { var _this$props2 = _this.props, height = _this$props2.height, width = _this$props2.width, style = _this$props2.style; var styleObj = Object.assign({}, style); width && (styleObj.width = width / 100 + 'rem'); height && (styleObj.height = height / 100 + 'rem'); return styleObj; }, _this.handleClick = function (e) { _this.props.onClick && _this.props.onClick(e); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Button, [{ key: 'render', value: function render() { var _props = this.props, disabled = _props.disabled, text = _props.text; return _react2.default.createElement( 'button', { style: this.getStyleObj(), className: this.getBtnClass(), disabled: disabled, onClick: this.handleClick }, this.props.children || text ); } }]); return Button; }(_react.Component); Button.propTypes = { prefix: _propTypes2.default.string, children: _propTypes2.default.node, text: _propTypes2.default.string, //button中的文字 fixed: _propTypes2.default.string, //fix定位的位置 color: _propTypes2.default.string, //按钮颜色(样式中同时定义字体以及背景颜色) radius: _propTypes2.default.bool, //是否是圆角样式 disabled: _propTypes2.default.bool, //是否禁用 block: _propTypes2.default.bool, //是否独占一行 height: _propTypes2.default.string, //重新定义高度 width: _propTypes2.default.string, //重新定义宽度 clickedColor: _propTypes2.default.string, //点击后的button颜色 onClick: _propTypes2.default.func, //点击触发事件, maskColor: _propTypes2.default.string, //button的遮罩层颜色, className: _propTypes2.default.string, //外部传入的样式 style: _propTypes2.default.string //外部传入的style }; Button.defaultProps = { prefix: defaultPrefix }; Button.Group = _ButtonGroup2.default; exports.default = Button;<file_sep>/README.md ## Button ## API ### Button 按钮的属性说明如下: 属性 | 说明 | 类型 | 默认值 -----|-----|-----|------ prefix | 样式前缀,如:`cefc-button`, 可用于自定义样式 | String | `cefc-button` children | 子元素 | React.element | 无 text | button中的文字内容 | String | 无 fixed | button的fix定位位置,`bottom`或者`top` | String | 无 color | button的按钮颜色,`white`, `blue` | String | `blue` disabled | 按钮是否可用 | String | false radius | 按钮是否需要圆角样式 | String | false block | 按钮是否独占一行 | String | false height | 按钮高度 | String | 无 width | 按钮宽度 | String | 无 clickedColor | 按钮点击后的颜色 | String | 无 maskColor | 按钮遮罩层颜色,为了处理透明样式时的透视问题 | String | 无 className | 组件外部传入的class | String | 无 style | 组件外部传入的style | Object | 无 onClick | 按钮点击触发事件 | Func | 无 ### Button.Group 属性 | 说明 | 类型 | 默认值 -----|-----|-----|------ prefix | 样式前缀,如:`cefc-button`, 可用于自定义样式 | String | `cefc-button` children | 子元素 | React.element | 无 justify | 是否自适应宽度 | String | false vertical | 是否垂直排列 | String | false <file_sep>/CHANGELOG.md ## CHANGE LOG ### 2017-12-18 - 添加Readme ### 2017-12-28 * 修改color为white时的背景色和边框。 <file_sep>/build/ButtonGroup.js 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } require('./style/index.css'); var defaultPrefix = 'cefc-button'; var ButtonGroup = function (_Component) { _inherits(ButtonGroup, _Component); function ButtonGroup() { var _ref; var _temp, _this, _ret; _classCallCheck(this, ButtonGroup); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ButtonGroup.__proto__ || Object.getPrototypeOf(ButtonGroup)).call.apply(_ref, [this].concat(args))), _this), _this.getWrapperCls = function () { var _csn; var _this$props = _this.props, prefix = _this$props.prefix, justify = _this$props.justify, vertical = _this$props.vertical; return (0, _classnames2.default)((_csn = {}, _defineProperty(_csn, prefix + '-group-justify', justify), _defineProperty(_csn, prefix + '-group-vertical', vertical), _csn)); }, _this.getBtnStyle = function () { var _this$props2 = _this.props, justify = _this$props2.justify, children = _this$props2.children; var btnLen = children.length; var styleObj = {}; justify && (styleObj.width = 100 / btnLen + '%'); return styleObj; }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(ButtonGroup, [{ key: 'render', value: function render() { var _this2 = this; return _react2.default.createElement( 'div', { className: this.getWrapperCls() }, this.props.children.map(function (node, index) { return _react2.default.cloneElement(node, { style: _this2.getBtnStyle(), key: 'btnGroup-' + index }); }) ); } }]); return ButtonGroup; }(_react.Component); ButtonGroup.propTypes = { prefix: _propTypes2.default.string, justify: _propTypes2.default.bool, //是否自适应宽度 vertical: _propTypes2.default.bool, //是否垂直排列 children: _propTypes2.default.node.isRequired }; ButtonGroup.defaultProps = { prefix: defaultPrefix }; exports.default = ButtonGroup;<file_sep>/src/ButtonGroup.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import csn from 'classnames'; require('./style/index.less'); const defaultPrefix = 'cefc-button'; class ButtonGroup extends Component { static propTypes = { prefix: PropTypes.string, justify: PropTypes.bool, //是否自适应宽度 vertical: PropTypes.bool, //是否垂直排列 children: PropTypes.node.isRequired } static defaultProps = { prefix: defaultPrefix } getWrapperCls = () => { const { prefix, justify, vertical } = this.props; return csn({ [`${prefix}-group-justify`]: justify, [`${prefix}-group-vertical`]: vertical }) } getBtnStyle = () => { const { justify, children } = this.props; const btnLen = children.length; const styleObj = {}; justify && (styleObj.width = `${100 / btnLen}%`); return styleObj; } render() { return ( <div className={this.getWrapperCls()}> {this.props.children.map((node, index) => { return React.cloneElement(node, { style: this.getBtnStyle(), key: `btnGroup-${index}` }); })} </div> ) } } export default ButtonGroup;<file_sep>/src/index.js 'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import csn from 'classnames'; import ButtonGroup from './ButtonGroup'; require('./style/index.less'); const defaultPrefix = 'cefc-button'; class Button extends Component { static propTypes = { prefix: PropTypes.string, children: PropTypes.node, text: PropTypes.string, //button中的文字 fixed: PropTypes.string, //fix定位的位置 color: PropTypes.string, //按钮颜色(样式中同时定义字体以及背景颜色) radius: PropTypes.bool, //是否是圆角样式 disabled: PropTypes.bool, //是否禁用 block: PropTypes.bool, //是否独占一行 height: PropTypes.string, //重新定义高度 width: PropTypes.string, //重新定义宽度 clickedColor: PropTypes.string, //点击后的button颜色 onClick: PropTypes.func, //点击触发事件, maskColor: PropTypes.string, //button的遮罩层颜色, className: PropTypes.string, //外部传入的样式 style: PropTypes.string, //外部传入的style } static defaultProps = { prefix: defaultPrefix } getBtnClass = () => { const { color, disabled, radius, block, clickedColor, prefix, fixed } = this.props; let config = { [`${prefix}`]: true, [`${prefix}-default`]: true, [`${prefix}-radius`]: radius, [`${prefix}-disabled`]: disabled, [`${prefix}-block`]: block, }; if (color) { config = Object.assign(config, { [`${prefix}-bg-${color}`]: true, }); } if (fixed) { config = Object.assign(config, { [`${prefix}-fixed-${fixed}`]: true, }); } if (clickedColor) { config = Object.assign(config, { [`${prefix}-clicked-${clickedColor}`]: true, }); } return csn(config); } getStyleObj = () => { let { height, width, style } = this.props; let styleObj = Object.assign({}, style); width && (styleObj.width = `${width / 100}rem`); height && (styleObj.height = `${height / 100}rem`); return styleObj; } handleClick = (e) => { this.props.onClick && this.props.onClick(e); } render() { const { disabled, text } = this.props; return ( <button style={this.getStyleObj()} className={this.getBtnClass()} disabled={disabled} onClick={this.handleClick}> {this.props.children || text} </button> ) } } Button.Group = ButtonGroup; export default Button;
a7eb5af2114fcb26876f7e8c39ed7cf5aa4c8eec
[ "JavaScript", "Markdown" ]
6
JavaScript
svger/button
e095e0fc15139d04162045ab3d47c99b69011211
fcd19fed40504ccd89bed492686dc4dd6ff9d462
refs/heads/master
<file_sep>const http = new EasyHTTP(); //Setting Routes const GETPOSTS = 'https://jsonplaceholder.typicode.com/posts'; const POSTPOSTS = 'https://jsonplaceholder.typicode.com/posts'; const PUTPOSTS = 'https://jsonplaceholder.typicode.com/posts/'; const DELETEPOSTS = 'https://jsonplaceholder.typicode.com/posts/'; //Load data function loadData(){ const loadStarted = new Date(); let output = ''; http.get(GETPOSTS) .then((data) => { console.log(data); data.forEach(post => { output += ` <div class="card mb-1" id="post-row-${post.id}"> <h5 class="card-header">${post.title}</h5> <div class="card-body"> <p class="card-text">${post.body}</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">ID: ${post.id} User ID: ${post.userId}</li> </ul> <div class="card-body text-right"> <input type="button" class="btn btn-secondary" value="Delete" onClick="deletePost(${post.id})"> </div> </div> `; }); document.querySelector('.posts').innerHTML = output; const loadFinished = new Date(); console.log(`Last load time: ${loadFinished.toLocaleString()}`); const diffTime = Math.abs(loadFinished - loadStarted); console.log(`Total load time: ${diffTime} miliseconds`); }).catch((err) => { output = '<p>Something went wrong.</p>'; console.log(err); }); } loadData(); //Add Event Listeners document.getElementById('btn-add-post').addEventListener('click', addPost); //Action Functions function addPost(e) { const data = { title: document.getElementById('title').value, body: document.getElementById('body').value }; http.post(POSTPOSTS, data) .then(data => console.log(data)) .catch(err => console.log(err)); e.preventDefault(); } function deletePost(postID) { console.log(`delete clicked:${postID}`); http.delete(`${DELETEPOSTS + postID}`) .then(data => console.log(data)) .then(() => loadData()) .catch(err => console.log(err)); document.getElementById(`post-row-${postID}`).remove(); } <file_sep># easyhttp This is a sample implementation of an HTTP library from the course Modern JavaScript From The Beginning by [@bradtraversy](https://github.com/bradtraversy). This repository is for learning objectives only. To use the library just put it in your HTML file with the following markup: `<script src="easyhttp3.js"></script>` jubt before the closing `</body>` tag. ## Intantiate the EasyHTTP object: ```javascript const http = new EasyHTTP(); ``` ## Calling GET method: Gets a resource by its corresponding URL. ```javascript http.get(url) ``` **URL:** The resource to be called. **Returns:** It returs a promise object with *data* and *error* objects so you can call it asychronously. * Data - the response data in JSON format. * Error - any error message. Example: ```javascript http.get('https://jsonplaceholder.typicode.com/posts') .then(data => console.log(data)) .catch(err => console.log(err)); ``` ## Calling POST method: Adds a new resource by its corresponding URL. ```javascript http.post(url, data) ``` **URL:** The resource to be called. **Data:** The data to be sent in JSON format. **Returns:** It returs a promise object with *data* and *error* objects so you can call it asychronously. * Data - the response data in JSON format. * Error - any error message. Example: ```javascript const data = { title: document.getElementById('title').value, body: document.getElementById('body').value }; http.post('https://jsonplaceholder.typicode.com/posts', data) .then(data => console.log(data)) .catch(err => console.log(err)); ``` ## Calling PUT method: Updates a resource by its corresponding URL. ```javascript http.put(url, data) ``` **URL:** The resource to be called. **Data:** The data to be sent in JSON format. **Returns:** It returs a promise object with *data* and *error* objects so you can call it asychronously. * Data - the response data in JSON format. * Error - any error message. Example: ```javascript const data = { title: document.getElementById('title').value, body: document.getElementById('body').value }; http.put('https://jsonplaceholder.typicode.com/posts', data) .then(data => console.log(data)) .catch(err => console.log(err)); ``` ## Calling DELETE method: Deletes a resource by its corresponding url. ```javascript http.delete(url) ``` **URL:** The resource to be called. **Data:** The data to be sent in JSON format. **Returns:** It returs a promise object with *data* and *error* objects so you can call it asychronously. * Data - the response data in JSON format. * Error - any error message. Example: ```javascript http.delete('https://jsonplaceholder.typicode.com/posts', data) .then(data => console.log(data)) .catch(err => console.log(err)); ``` <file_sep>/** * EasyHTTP Library * Library for making HTTP requests * @author <NAME> * @version 2.0 * @license MIT * @since 2019-10-05 12:42:08 */ class EasyHTTP { //Make an HTTP GET Request get(url) { return new Promise((resolve, reject) => { fetch(url) .then(res => res.json()) .then(data => resolve(data)) .catch(err => reject(err)); }); } //Make an HTTP POST Request post(url, data) { return new Promise((resolve, reject) => { fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(data => resolve(data)) .catch(err => reject(err)); }); } //Make an HTTP PUT Request put(url, data) { return new Promise((resolve, reject) => { fetch(url, { method: 'PUT', headers: { 'Content-type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(data => resolve(data)) .catch(err => reject(err)); }); } //Make an HTTP DELETE Request delete(url) { return new Promise((resolve, reject) => { fetch(url, { method: 'DELETE', headers: { 'Content-type': 'application/json' } }) .then(res => res.json()) .then(() => resolve('Resource deleted')) .catch(err => reject(err)); }); } } //VERSION 1 CODE BELLOW // function easyHTTP() { // this.http = new XMLHttpRequest(); // } // //Make an HTTP GET Request // easyHTTP.prototype.get = function (url, callback) { // this.http.open('GET', url, true); // let self = this; // this.http.onload = function () { // if (self.http.status === 200) { // callback(self.http.responseText, self.http.status); // } else { // callback(null, self.http.status) // } // } // this.http.send(); // } // //Make an HTTP POST Request // easyHTTP.prototype.post = function (url, data, callback) { // this.http.open('POST', url, true); // this.http.setRequestHeader('Content-type', 'application/json'); // let self = this; // this.http.onload = function () { // callback(self.http.responseText, self.http.status); // } // this.http.send(JSON.stringify(data)); // } // //Make an HTTP PUT Request // easyHTTP.prototype.put = function (url, data, callback) { // this.http.open('PUT', url, true); // this.http.setRequestHeader('Content-type', 'application/json'); // let self = this; // this.http.onload = function () { // callback(self.http.responseText, self.http.status); // } // this.http.send(JSON.stringify(data)); // } // //Make an HTTP DELETE Request // easyHTTP.prototype.delete = function (url, callback) { // this.http.open('DELETE', url, true); // let self = this; // this.http.onload = function () { // if (self.http.status === 200) { // callback(self.http.responseText, self.http.status); // } else { // callback(null, self.http.status) // } // } // this.http.send(); // }
3960a093c2cb7f9154d7f0c87cb244ece3ea6218
[ "JavaScript", "Markdown" ]
3
JavaScript
compadrejunior/easyhttp
db71df07bdb9a80436cd227947551898b5a648fb
dac332a0681ac3b218a55e8e04b7633df47c5c5a
refs/heads/master
<file_sep>#!/usr/bin/python3 import sys def miles_to_km(miles): return miles * 1.60934 if __name__ == "__main__": miles = int(sys.argv[1]) print("{0} miles".format(miles)) print("{0} km".format(miles_to_km(miles))) <file_sep>#!/bin/sh xinput set-prop 10 279 1 <file_sep>alias e='emacs' alias ne='emacs' alias p='python3' <file_sep>#!/bin/sh CPU_UTILIZATION=`ps -A -o pcpu | tail -n+2 | paste -sd+ | bc` echo "CPU: $CPU_UTILIZATION %" <file_sep>#!/bin/sh DISK_UTILIZATION=`iostat -N -h -d sda -x | tail -n 2 | head -n 1 | awk '{print $13}'` echo "HDD: $DISK_UTILIZATION%" <file_sep>#!/bin/sh HDD_TEMP=`sudo hddtemp /dev/sda1 | cut -d ' ' -f 4` echo "HDD: $HDD_TEMP" <file_sep>grep -B2 'Module class: X.Org Video Driver' /var/log/Xorg.0.log <file_sep>!#/bin/sh sudo mkdir /mnt/server sudo mount -t <file_sep>#!/usr/bin/python3 import subprocess import sys hostname = "google.com" command_line = "ping -c 1 {0}".format(hostname) try: response = subprocess.check_output(command_line, shell=True, stderr=subprocess.STDOUT, timeout=5) except subprocess.CalledProcessError as pe: print("PING: error") sys.exit(1) except subprocess.TimeoutExpired as te: print("PING: timeout") sys.exit(1) for line in response.decode('utf-8').split('\n'): for i in line.split(' '): if i.startswith('time='): print("PING: {0} ms".format(i[5:])) sys.exit(0) print("PING: ?") <file_sep>personnal collection of useful scripts <file_sep>#!/bin/sh DISK_USAGE=`df -h /home | tail -n 1 | awk '{print $3"/"$2, $5}'` echo "HDD: $DISK_USAGE" <file_sep>#!/bin/sh LOAD=`cat /proc/loadavg | cut -d ' ' -f 1,2,3` echo "LOAD: $LOAD" <file_sep>#!/usr/bin/python3 import sys from datetime import timedelta speeds = {"snail": 0.0036, "mosquito" : 2, "sprinter" : 36, "walker" : 10, "bus" : 90, "normal_car": 110, "sport_car": 200, "tgv" : 350, "plane": 850, "sound": 1225, "fighter_airplane": 3500, "rocket": 8000, "orbital_station": 28800, "earth": 107320, "sun" : 965000, "light": 1079252848.8} def human_readable_time(hours): return timedelta(hours=hours) if __name__ == "__main__": distance_km = float(sys.argv[1]) print("Race {0} km".format(distance_km)) for key in sorted(speeds, key=speeds.get): speed = speeds[key] hours = distance_km / speed print("{0} speed:{1} km/h time: {2}".format(key, speed, human_readable_time(hours))) <file_sep>#!/usr/bin/python3 import sys def km_to_miles(km): return km * 0.621371 if __name__ == "__main__": km = float(sys.argv[1]) print("{0} km".format(km)) print("{0} km".format(km_to_miles(km))) <file_sep>#!/usr/bin/python3 import subprocess import sys response = subprocess.check_output("free -b", shell=True, stderr=subprocess.STDOUT, timeout=5) responses = response.decode('utf-8').split('\n') keys = responses[0].split() values = responses[2].split()[1:] mydict = dict(zip(keys, map(int, values))) activity = (mydict['total'] - mydict['free']) / mydict['total'] * 100 print("SWAP: {0:.1f}%".format(activity)) <file_sep>export EDITOR='emacs' export PATH=$PATH:~/script/ <file_sep>#!/usr/bin/python3 import sys def meterssecond_to_kmh(meters_by_second): return meters_by_second * 3.6 if __name__ == "__main__": meters_by_second = float(sys.argv[1]) print("{0} m/s".format(meters_by_second)) print("{0} km/h".format( meterssecond_to_kmh(meters_by_second))) <file_sep>#!/opt/opensvc/bin/python import xml.etree.ElementTree as xmllib import re import urllib2 import logging import zipfile import os.path import os from pprint import pprint def get_rame_number_from_zip(zip_file) : # creating tmp dir to uncompress zip file if not os.path.exists(DIR_TMP): os.makedirs(DIR_TMP) zfile = zipfile.ZipFile(zip_file) for name in zfile.namelist(): (dirname, filename) = os.path.split(name) print "Decompressing " + filename + " on " + dirname zfile.extract(name, DIR_TMP) rame_num = get_rame_number_from_xml(DIR_TMP + '/' + name) os.remove(DIR_TMP + '/' + name) return rame_num def get_rame_number_from_xml(xml_file) : root = xmllib.parse(xml_file).getroot() # for child in root: str = root[0].get('message') rame_num = re.findall(r'\d+', str)[0] return rame_num; def read_webpage(url): response = urllib2.urlopen(url) html = response.read() links = re.findall(r'href=[\'"]?([^\'" >]+)', html) good_links = [] for link in links : if (link.lower().startswith('vb2n') or link.lower().startswith('z2n')) and link.lower().endswith('.zip'): good_links.append(link) return good_links # variables # SERVER_URL = "https://pscs-wi-prd.dsit.sncf.fr/cluster/pscs/files/" SERVER_URL = "http://127.0.0.1/webpage.html" # logging.basicConfig(filename='recup_2n.log',level=logging.DEBUG) # logging.info("START") DIR_IN = "/home/moesoe/scripts/test" DIR_TMP = '/home/moesoe/scripts/test/tmp' # ZIP_FILE = 'vb2n_sive_jdb_151118-205407_7604.xml.zip' ZIP_FILE = 'z2n_sive_jdb_151117-131306_186.xml.zip' links = read_webpage(SERVER_URL) # rame_num = get_rame_number_from_zip(DIR_IN + '/' + ZIP_FILE) # print rame_num # logging.info("END") <file_sep>#!/usr/bin/python3 import sys def kmph_to_mps(kmph): return kmph / 3.6 if __name__ == "__main__": kmph = int(sys.argv[1]) print("{0} km/h".format(kmph)) print("{0} m/s".format( kmph_to_mps(kmph))) <file_sep>#!/bin/sh INTERFACE="wlp2s0" INTERFACE_USB="wlx18a6f70ef124" # timeout 5 ping www.google.co.uk -c 1; echo $? while [ 1 ] do sleep 1 timeout 5 ping www.google.co.uk -c 1 #timeout 5 ping www.google.com -c 1 ret=$? echo $ret if [ $ret -gt 0 ] then echo "reco..." nmcli d disconnect $INTERFACE nmcli d connect $INTERFACE fi done
a2d0cde511bf1b8d4c62965a963a4277af5547af
[ "Markdown", "Python", "Shell" ]
20
Python
Sun42/script
f737ae7d2c97ec67338cf0a6d60f2a2cb5b2c680
0b9b84895bcf6c1cdb66d80050822325bb16b54c
refs/heads/master
<repo_name>Xufysz/Space-Invaders<file_sep>/SpaceInvadersGame/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; namespace SpaceInvadersGame { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.KeyDown += this.Form1_KeyDown; } private Graphics spaceInvanders; private Canon playerIcon; private List<Alien> aliens; private List<Bullet> bullets; private void Form1_Load(object sender, EventArgs e) { this.initGame(); } private void initGame() { this.playerIcon = new Canon(25, 15, (this.picCanvas.Width / 2), (this.picCanvas.Height - 25)); this.aliens = new List<Alien>(); this.bullets = new List<Bullet>(); // Create multiple array lists that represent the waves of aliens that come towards the player: int currentY = 0; for (int i = 0; i < 8; i++) //Y { int offsetX = this.picCanvas.Width / 12; for (int j = 0; j < 8; j++) //X { this.aliens.Add(new Alien(25, 50, offsetX += 100, currentY)); } currentY += 50; } // Set up timer to control game: Timer timer = new Timer() { Interval = 10 }; timer.Tick += timer_Tick; timer.Start(); //List<Alien> row1 = new List<Alien>(); //for (int i = 0; i < 8; i++) //{ // row1.Add(new Alien(25, 50, offsetX, 0)); // offsetX += 100; //} //this.aliens.Add(row1); //offsetX = this.picCanvas.Width / 12; //List<Alien> row2 = new List<Alien>(); //for (int i = 0; i < 8; i++) //{ // row2.Add(new Alien(25, 50, offsetX, 50)); // offsetX += 100; //} //Aliens.Add(row2); //offsetX = this.picCanvas.Width / 12; //List<Alien> row3 = new List<Alien>(); //for (int i = 0; i < 8; i++) //{ // row3.Add(new Alien(25, 50, offsetX, 100)); // offsetX += 100; //} //Aliens.Add(row3); //offsetX = this.picCanvas.Width / 12; //List<Alien> row4 = new List<Alien>(); //for (int i = 0; i < 8; i++) //{ // row4.Add(new Alien(25, 50, offsetX, 150)); // offsetX += 100; //} //Aliens.Add(row4); } // Method used to organize the X and Y location of the aliens: private void setFormation(Alien row) { } private void timer_Tick(object sender, EventArgs e) { draw(); } private void draw() { // Set up canvas: using (this.spaceInvanders = this.picCanvas.CreateGraphics()) { spaceInvanders.Clear(Color.Black); // Draw player icon (canon): spaceInvanders.FillRectangle(Brushes.White, playerIcon.getPosX(), playerIcon.getPosY(), playerIcon.getWidth(), playerIcon.getHeight()); for (int i = 0; i < this.aliens.Count; i++) { Alien alien = this.aliens[i]; this.spaceInvanders.FillRectangle(Brushes.Green, Convert.ToSingle(alien.getPosX()), Convert.ToSingle(alien.getPosY()), alien.getWidth(), alien.getHeight()); alien.move(); } for (int i = 0; i < this.bullets.Count; i++) { // Draw bullets: spaceInvanders.FillRectangle(Brushes.White, this.bullets[i].getPosX(), this.bullets[i].getPosY(), this.bullets[i].getWidth(), this.bullets[i].getHeight()); // Enable bullet behaviours: this.bullets[i].move(); } //for (int i = 0; i < Aliens[0].Count; i++) //{ // spaceInvanders.FillRectangle(alienBrush, Convert.ToSingle(Aliens[0][i].getPosX()), Convert.ToSingle(Aliens[0][i].getPosY()), Aliens[0][i].getWidth(), Aliens[0][i].getHeight()); // // Enable behaviours: // Aliens[0][i].move(); // if (Aliens[0][i].reachBottom(this.picCanvas.Height)) // { // } //} //for (int i = 0; i < Aliens[1].Count; i++) //{ // spaceInvanders.FillRectangle(alienBrush, Convert.ToSingle(Aliens[1][i].getPosX()), Convert.ToSingle(Aliens[1][i].getPosY()), Aliens[1][i].getWidth(), Aliens[1][i].getHeight()); // // Enable behaviours: // Aliens[1][i].move(); // if (Aliens[1][i].reachBottom(this.picCanvas.Height)) // { // } //} //for (int i = 0; i < Aliens[2].Count; i++) //{ // spaceInvanders.FillRectangle(alienBrush, Convert.ToSingle(Aliens[2][i].getPosX()), Convert.ToSingle(Aliens[2][i].getPosY()), Aliens[2][i].getWidth(), Aliens[2][i].getHeight()); // // Enable behaviours: // Aliens[2][i].move(); // if (Aliens[2][i].reachBottom(this.picCanvas.Height)) // { // } //} //for (int i = 0; i < Aliens[3].Count; i++) //{ // spaceInvanders.FillRectangle(alienBrush, Convert.ToSingle(Aliens[3][i].getPosX()), Convert.ToSingle(Aliens[3][i].getPosY()), Aliens[3][i].getWidth(), Aliens[3][i].getHeight()); // // Enable behaviours: // Aliens[3][i].move(); // if (Aliens[3][i].reachBottom(this.picCanvas.Height)) // { // } //} } } // Method used to handle the movement of the canon: private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Left) // Move left { playerIcon.move(1, 0, this.picCanvas.Width); } else if (e.KeyCode == Keys.Right) // Move right { playerIcon.move(2, 0, this.picCanvas.Width); } else if (e.KeyCode == Keys.Up) // Fire weapon { this.bullets.Add(new Bullet(20, 3, playerIcon.getPosX() + 5, playerIcon.getPosY(), playerIcon.getDamageDealt())); } } } }
717747ad52cfbac80af26fb21adc0692e76bbcc8
[ "C#" ]
1
C#
Xufysz/Space-Invaders
e9a980b3384a382034c3dd0f53a7b9a433ab1e9b
6d6134f386479e82240db974253db0ff66eb5d52
refs/heads/main
<repo_name>rahul-sk/Simplilearn_Phase1_RainbowSchoolProject<file_sep>/README.md # Simplilearn_Phase1_RainbowSchoolProject Project submission for phase 1 of the .NET Full stack dev course
19f1e86076890f8621d5887ede03404c1fae4b7c
[ "Markdown" ]
1
Markdown
rahul-sk/Simplilearn_Phase1_RainbowSchoolProject
a0e893968321748c290b1eb9a9b248dd0a33ce7d
3380fab5de5080c08e95e773dd39ab3fa115cf4f
refs/heads/master
<repo_name>vasmarm/WeatherPyt<file_sep>/README.md # WeatherPy Creating a Python script to visualize the weather of 500+ cities across the world of varying distance from the equator. To accomplish this, you'll be utilizing a simple Python library, the OpenWeatherMap API, and a little common sense to create a representative model of weather across world cities. Objective is to build a series of scatter plots to showcase the following relationships: - Maximum Temperature (F) vs. Latitude - Humidity (%) vs. Latitude - Cloudiness (%) vs. Latitude - Wind Speed (mph) vs. Latitude Final notebook : - Randomly select at least 500 unique (non-repeat) cities based on latitude and longitude. - Perform a weather check on each of the cities using a series of successive API calls. - Include a print log of each city as it's being processed with the city number, city name, and requested URL. - Save both a CSV of all data retrieved and png images for each scatter plot. <file_sep>/config.py # Google API Key <<<<<<< HEAD gkey = "<KEY>" wkey = "<KEY>" ======= gkey = "XXXXXX" wkey = "YYYYYY" >>>>>>> 9c17937e2a7672bd24683dab86f4a0587006b416
6e3a6f7f279230af7e5aff5bba7b56b27f840055
[ "Markdown", "Python" ]
2
Markdown
vasmarm/WeatherPyt
0889b5a1e5e7c71b361f4543eb5fe9e321bdc239
fa527de195e755de310b842e9b71a2f0d6a6dc24
refs/heads/master
<file_sep>def merge(a,b) la = a.length() lb = b.length() c = Array.new(la+lb) # c.length() = la + lb ia = 0 ib = 0 ic = 0 # ic = ia + ib while ia < la && ib < lb if a[ia] < b[ib] c[ic] = a[ia] ia = ia + 1 else c[ic] = b[ib] ib = ib + 1 end ic = ic + 1 end # if ia == la for j in ib..(lb-1) c[la+j] = b[j] # ic = la + j end # else # ib == lb for j in ia..(la-1) c[j+lb] = a[j] # ic = j + lb end # end c end def merge_rec(a,l,r) if l == r [a[l]] else m = (l+r)/2 merge(merge_rec(a,l,m),merge_rec(a,m+1,r)) end end # mergesort_r(a) # n = a.length() としたとき、計算量は、O(nlogn)。 # 繰り返しで書いたmergesort(a)と、計算量は同じ。 def mergesort_r(a) merge_rec(a,0,a.length()-1) end <file_sep>load "pg10.rb" def search1(t,s) i=0 while i<t.length && t[i]!=s i += 1 end if i<t.length print s, ": ", i, "\n" else print s, ": not found\n" end end search1(pg10,"God") search1(pg10,"god") <file_sep># -*- coding: utf-8 -*- def stops ["渋谷","神泉","東大前","駒場","池ノ上","下北沢"] end t = stops print t*",", "\n" i = t.index("東大前") t[i..i+1] = ["駒場東大前"] print t*",", "\n" <file_sep># -*- coding: utf-8 -*- load"Inokashira6.rb" def find(t,s) i = 0 while i < t.length && t[i] != s i += 1 end return i end p find(stops,"東大前") <file_sep># -*- coding: utf-8 -*- def stops ["大井町駅","下神明駅","戸越公園駅","中延駅","荏原町駅","旗の台駅","北千束駅","大岡山駅","緑が丘駅","自由が丘駅","九品仏駅","尾山台駅","等々力駅","上野毛駅","二子玉川駅","溝の口駅"] end <file_sep>load "pg10.rb" def search(s,a) i=0 while i<s.length if a == s[i] return false else i += 1 end end true end t = pg10 s = [] last = 0 for i in 0..t.length-1 if search(s,t[i]) last = i s << t[i] end end print t[last], ": ", last, "\n" <file_sep># -*- coding: utf-8 -*- def stops ["渋谷","神泉","東大前","駒場","池ノ上","下北沢"] end t = stops f = Hash.new # ハッシュを生成 for i in 0..t.length-1 f[t[i]] = i # f["東大前"]=2となるように記録。(関数の定義) end p f["東大前"] <file_sep>def f(i) if i true else false end end include(Math) p f(0) p f(1) p f(2) p f(-1) p f(3.12) p f(PI) p f("abABaCa") p f(true) p f(false) p f(nil) <file_sep># -*- coding: utf-8 -*- class ComplexNumber def initialize(x, y) # ComplexNumber.new(x,y)を実行した時の呼ばれる関数 @realPart = x # @をつけた変数はインスタンス変数。newで作られたオブジェクトごとにできる @imaginaryPart = y end def realPart() # インスタンス変数を読み出すインスタンスメソッド(関数)。x.realPart()のように適用。attr_accessor :realPartを使う方法もある。 @realPart end def imaginaryPart() @imaginaryPart end def multiply(z) # x.multiply(z)のように使い、xとzをかけたものを返すインスタンスメソッド。xやzは変化しない。 ComplexNumber.new(@realPart * z.realPart - @imaginaryPart * z.imaginaryPart , @realPart * z.imaginaryPart + @imaginaryPart * z.realPart) end def inv # x.invのように使い、xの逆数を返すインスタンスメソッド。 r = rad2.to_f # 長さの二乗を求めておく。to_fは実数に変換するメソッド。(整数の割り算をしないため) ComplexNumber.new(@realPart/r,-@imaginaryPart/r) end def division(z) # x.division(z)のように使い、xをzで割ったものを返すインスタンスメソッド。xやzは変化しない。 multiply(z.inv) end def add(z) # x.add(z)のように使い、xにzを足したものを返すインスタンスメソッド。xやzは変化しない。 ComplexNumber.new(@realPart + z.realPart , @imaginaryPart + z.imaginaryPart) end def sub(z) # x.sub(z)のように使い、xからzを引いたものを返すインスタンスメソッド。xやzは変化しない。 ComplexNumber.new(@realPart - z.realPart , @imaginaryPart - z.imaginaryPart) end def rad2() # x.rad2のように使い、xの長さの二乗を計算するインスタンスメソッド @realPart * @realPart + @imaginaryPart * @imaginaryPart end include(Math) def rad() # x.radのように使い、xの長さを計算するインスタンスメソッド sqrt(rad2) end end c = ComplexNumber.new(3, 4) p c.realPart x1 = ComplexNumber.new(1,2) x2 = ComplexNumber.new(3,-4) x3 = x1.multiply(x2) p x3 x4 = x3.division(x1) p x4 x5 = x3.division(x2) p x5 p x1.inv p x1.inv.multiply(x1) <file_sep>load "pg10r.rb" t = pg10r max_index = 0 for i in 1..t.length-1 if t[i][1][0] > t[max_index][1][0] max_index = i end end print t[max_index][0],": ",t[max_index][1][0],"\n" <file_sep># -*- coding: utf-8 -*- def ooimachiStops ["大井町駅","下神明駅","戸越公園駅","中延駅","荏原町駅","旗の台駅","北千束駅","大岡山駅","緑が丘駅","自由が丘駅","九品仏駅","尾山台駅","等々力駅","上野毛駅","二子玉川駅","溝の口駅"] end def denentoshiStops ["渋谷駅","池尻大橋駅","三軒茶屋駅","駒沢大学駅","桜新町駅","用賀駅","二子玉川駅","二子新地駅","高津駅","溝の口駅","梶が谷駅","宮崎台駅","宮前平駅","鷺沼駅","たまプラーザ駅","あざみ野駅","江田駅","市が尾駅","藤が丘駅","青葉台駅","田奈駅","長津田駅","つくし野駅","すずかけ台駅","南町田駅","つきみ野駅","中央林間駅"] end def expressStops ["渋谷駅","三軒茶屋駅","二子玉川駅","溝の口駅","鷺沼駅","たまプラーザ駅","あざみ野駅","青葉台駅","長津田駅","中央林間駅"] end for i in 0..ooimachiStops.length-1 for j in 0..denentoshiStops.length-1 if ooimachiStops[i]==denentoshiStops[j] k = i l = j break end end end t = ooimachiStops[0..k] + denentoshiStops[l+1..denentoshiStops.length-1] print t*",","\n" <file_sep># -*- coding: utf-8 -*- def stops ["品川駅","大崎駅","五反田駅","目黒駅","恵比寿駅","渋谷駅","原宿駅","代々木駅","新宿駅","新大久保駅","高田馬場駅","目白駅","池袋駅","大塚駅","巣鴨駅","駒込駅","田端駅","西日暮里駅","日暮里駅","鶯谷駅","上野駅","御徒町駅","秋葉原駅","神田駅","東京駅","有楽町駅","新橋駅","浜松町駅","田町駅"] end <file_sep>load "pg10.rb" def search(s,a) i=0 while i<s.length && a!=s[i] i += 1 end i == s.length end t = pg10 s = [] last = 0 for i in 0..t.length-1 if search(s,t[i]) last = i s << t[i] end end print t[last], ": ", last, "\n" <file_sep># -*- coding: utf-8 -*- def stops ["浅草駅","業平橋駅","押上駅","曳舟駅","東向島駅","鐘ヶ淵駅","堀切駅","牛田駅","北千住駅","小菅駅","五反野駅","梅島駅","西新井駅","竹ノ塚駅","谷塚駅","草加駅","松原団地駅","新田駅","蒲生駅","新越谷駅","越谷駅","北越谷駅","大袋駅","せんげん台駅","武里駅","一ノ割駅","春日部駅","北春日部駅","姫宮駅","宮代町","東武動物公園駅"] end t = stops print t*",","\n" i = t.index("業平橋駅") t[i] = "とうきょうスカイツリー駅" print t*",","\n" <file_sep># quicksort # # swap(a,i,j): # 配列aのi番目の要素とj番目の要素を入れ替える関数 # # pivot(a,i,j): # 配列aのi番目からj番目までの要素のうち、i番目から順に見て、 # 最初に得られた2つの異なる値のうち、大きい方をとってpivot要素とし、 # その要素番号を返す関数である。 # 但し、配列aのi番目からj番目の要素までがすべて等しい場合、-1を返す。 # 計算量O(j-i) # # part(a,i,j,s): # pivot要素の値sをしきい値として、配列aのi番目からj番目に向かってしきい値以上の要素を、 # 配列aのj番目からi番目に向かってしきい値未満の要素を探し、これらの要素を入れ替える。 # これを、双方の検索が交差するまで繰り返す。 # 交差したら、i番目からj番目への検索ラインが最終的に到達した場所(l)を返す。 # このとき、配列aのi番目から(l-1)番目にはs未満の数が、 # l番目からj番目にはs以上の数が集まっている。 # 計算量O(j-i) # # sub_quicksort(a,i,j) # 以上の関数を組み合わせ、配列aのi番目からj番目までを再帰的にソートする。 # i = j 即ち部分配列の要素が1つしかなくなったら、もう並べ替える必要がないので、何もしない。 # i != j ならばpivot要素を求め、 # (-1が返されたら、その部分配列はもう並べ替える必要がないので、何もしない。) # part(a,i,j,a[pivot(a,i,j)])によって、i~j番目をpivot要素の値との大小で二分し、 # 二分したそれぞれを再帰的にソートする。 # # quicksort(a) # sub_quicksort(a,0,a.length())を行い、配列a全体をソートする。 # pivot(a,i,j)とpart(a,i,j,s)はともに計算量O(j-i)、 # つまりデータ数に比例した計算量がかかる。 # 最良の場合、partで、データの分割が効率よく、半分になるように行われれば、 # 再帰の深さはlog(n)/log(2)で、各段階でのデータ数はすべてnだから、 # 計算量はO(nlogn)になる。(最良計算量) # しかし、配列aが降順に並んでいた場合、計算量は最も大きくなり、 # partでの分割は、1つの要素と、残りの要素に分けるという、最も非効率な分割となってしまう。 # よって、再帰の深さはn、各段階でのデータ数もすべてnだから、 # 計算量は、O(n^2)になる。(最悪計算量) # データの並びがランダムな場合、平均計算量はO(nlogn)で、mergesortと同じオーダーであるが、 # 一般にはmergesortよりも高速にソートを行うことができる。 def swap(a,i,j) v = a[i] a[i] = a[j] a[j] = v end def pivot(a,i,j,m) k = i + 1 while k <= j && a[i][m] == a[k][m] k = k + 1 end if k > j -1 else if a[i][m] < a[k][m] k else i end end end def part(a,i,j,s,m) l = i r = j while l <= r while l <= j && a[l][m] < s l = l + 1 end while i <= r && s <= a[r][m] r = r - 1 end if l > r break end swap(a,l,r) l = l + 1 r = r - 1 end l end def sub_quicksort(a,i,j,m) if i != j p = pivot(a,i,j,m) if p != -1 l = part(a,i,j,a[p],m) sub_quicksort(a,i,l-1,m) sub_quicksort(a,l,j,m) end end end def quicksort(a,m) sub_quicksort(a,0,a.length()-1,m) a end <file_sep># -*- coding: utf-8 -*- def stops ["渋谷駅","表参道駅","青山一丁目駅","永田町駅","半蔵門駅","九段下駅","神保町駅","大手町駅","三越前駅","水天宮前駅","清澄白河駅","住吉駅","錦糸町駅","押上駅"] end <file_sep> class A attr_accessor :x,:y def initialize(x,y) @x = x @y = y end def op(z) return A.new(@x + z.x,@y + z.y) end end class B attr_accessor :x,:y def initialize(x,y) @x = x @y = y end def op(z) return B.new(@x - z.x,@y - z.y) end end def o7 a = A.new(1,2) b = B.new(3,4) c = a.op(b) return a.x end <file_sep># -*- coding: utf-8 -*- load"Inokashira6.rb" def find(t,s) # sがtの何番目かを探す i = 0 # 下限 j = t.length-1 # 上限 while i<=j # 間があいていたら、 k = (i+j)/2 # 中間をとり if t[k]==s # sと一致したら return k # その添字を返す else if t[k] < s # 中間より大きければ、 i = k+1 # 下限を引き上げ、 else # 中間より小さければ j = k-1 # 上限を引き下げる。 end end end return nil # 見つからない end t = stops.sort # Rubyの機能でソートしてしまう。 print t*",","\n" p find(t,"東大前") # ソートされているので元の位置と違う結果 <file_sep># -*- coding: utf-8 -*- def stops ["渋谷駅","池尻大橋駅","三軒茶屋駅","駒沢大学駅","桜新町駅","用賀駅","二子玉川駅","二子新地駅","高津駅","溝の口駅","梶が谷駅","宮崎台駅","宮前平駅","鷺沼駅","たまプラーザ駅","あざみ野駅","江田駅","市が尾駅","藤が丘駅","青葉台駅","田奈駅","長津田駅","つくし野駅","すずかけ台駅","南町田駅","つきみ野駅","中央林間駅"] end def expressStops ["渋谷駅","三軒茶屋駅","二子玉川駅","溝の口駅","鷺沼駅","たまプラーザ駅","あざみ野駅","青葉台駅","長津田駅","中央林間駅"] end <file_sep>load "pg10r.rb" def find(u,m,s) # uのm番目の要素をキーとして二分探索する関数 i = 0 j = u.length-1 while i<=j k = (i+j)/2 if u[k][m]==s return k else if u[k][m] < s i = k+1 else j = k-1 end end end return i # 一致するものがなかったら、一つだけ大きいインデックスを返す # (whileループを抜けるときには、iが、探したいキーのインデックス # よりも一つだけおおきなインデックスとなっている) end t = pg10r for i in 0..t.length-1 t[i][1] = t[i][1].length end s = t.sort{ |a,b| a[1] <=> b[1] } k = find(s,1,1000) for i in k..s.length-1 print s[i][0], ": ", s[i][1], "\n" end <file_sep># -*- coding: utf-8 -*- load "pg10.rb" ff = open("ElementSearchEx2.dat","w") # "God"と"god"の出現箇所すべてをファイルに書き出します def searchAll(f,t,s) f.print s, ": " for i in 0..t.length-1 if t[i]==s f.print i," " end end f.print "\n" end searchAll(ff,pg10,"God") ff.print "\n" searchAll(ff,pg10,"god") ff.close <file_sep># -*- coding: utf-8 -*- def transitions(automaton,input) s = 0 for i in 0..input.length-1 c = input[i..i].to_i # i文字目を取り出して、文字を数値に変換する。"0"を0、"1"を1とする。 s = automaton[s][c] end return s end def test automaton = [[0,1], [2,0], [1,2]] p transitions(automaton,"011001") p transitions(automaton,"011011") p transitions(automaton,"011101") end <file_sep>load "pg10.rb" def ins(u,s) i = 0 j = u.length-1 while i<j k = (i+j)/2 if u[k]==s return false else if u[k] < s i = k+1 else j = k-1 end end end if i == j if u[i]==s return false else if u[i]<s u.insert(i+1,s) else u.insert(i,s) end end else u.insert(i,s) end true end s = pg10 u = [] last = 0 for i in 0..s.length-1 if ins(u,s[i]) last = i end end print s[last], ": ", last, "\n" <file_sep># -*- coding: utf-8 -*- def stops ["東武動物公園駅","杉戸高野台駅","幸手駅","南栗橋駅"] end <file_sep># -*- coding: utf-8 -*- def stops ["渋谷駅","池尻大橋駅","三軒茶屋駅","駒沢大学駅","桜新町駅","用賀駅","二子玉川駅","二子新地駅","高津駅","溝の口駅","梶が谷駅","宮崎台駅","宮前平駅","鷺沼駅","たまプラーザ駅","あざみ野駅","江田駅","市が尾駅","藤が丘駅","青葉台駅","田奈駅","長津田駅","つくし野駅","すずかけ台駅","南町田駅","つきみ野駅","中央林間駅"] end def expressStops ["渋谷駅","三軒茶屋駅","二子玉川駅","溝の口駅","鷺沼駅","たまプラーザ駅","あざみ野駅","青葉台駅","長津田駅","中央林間駅"] end i=1 ie=1 j=0 count=0 le = expressStops.length a = Array.new(le-1) while ie<le while stops[i]!=expressStops[ie] i += 1 count += 1 end a[j] = count i += 1 ie += 1 j += 1 count = 0 end p a <file_sep># -*- coding: utf-8 -*- def stops0 ["渋谷駅","池尻大橋駅","三軒茶屋駅","駒沢大学駅","桜新町駅","用賀駅","二子玉川駅","二子新地駅","高津駅","溝の口駅","梶が谷駅","宮崎台駅","宮前平駅","鷺沼駅","たまプラーザ駅","あざみ野駅","江田駅","市が尾駅","藤が丘駅","青葉台駅","田奈駅","長津田駅","つくし野駅","すずかけ台駅","南町田駅","つきみ野駅","中央林間駅"] end def stops1 ["渋谷駅","表参道駅","青山一丁目駅","永田町駅","半蔵門駅","九段下駅","神保町駅","大手町駅","三越前駅","水天宮前駅","清澄白河駅","住吉駅","錦糸町駅","押上駅"] end def stops2 ["浅草駅","業平橋駅","押上駅","曳舟駅","東向島駅","鐘ヶ淵駅","堀切駅","牛田駅","北千住駅","小菅駅","五反野駅","梅島駅","西新井駅","竹ノ塚駅","谷塚駅","草加駅","松原団地駅","新田駅","蒲生駅","新越谷駅","越谷駅","北越谷駅","大袋駅","せんげん台駅","武里駅","一ノ割駅","春日部駅","北春日部駅","姫宮駅","宮代町","東武動物公園駅"] end def stops3 ["東武動物公園駅","杉戸高野台駅","幸手駅","南栗橋駅"] end c = Array.new(4) count=0 l = 0 k = Array.new(3) stops0r = stops0.reverse for i in 0..stops0r.length-1 for j in 0..stops1.length-1 if stops0r[i]==stops1[j] c[0] = i-l count += i-l l = j k[0] = j break end end end for i in l..stops1.length-1 for j in 0..stops2.length-1 if stops1[i]==stops2[j] c[1] = i-l count += i-l l = j k[1] = j break end end end for i in l..stops2.length-1 for j in 0..stops3.length-1 if stops2[i]==stops3[j] c[2] = i-l count += i-l l = j k[2] = j break end end end c[3] = stops3.length-1 - l count += c[3] p c p count m = count/2 if m<=c[0] print stops0r[m],"\n" elsif m<=c[0]+c[1] print stops1[m - c[0]- k[0]],"\n" elsif m<=c[0]+c[1]+c[2] print stops2[m - c[0]- c[1]- k[1]],"\n" else print stops3[m - c[0] - c[1] - c[2] - k[2]],"\n" end <file_sep># -*- coding: utf-8 -*- class Sma CHARS = 128 def initialize(pat) # コンストラクタ @pat = pat # 検索したい文字列を記録 @delta = Array.new(@pat.length+1) for i in 0..@delta.length-1 @delta[i] = Array.new(CHARS,0) # 状態 x 文字 end for q in 0..@pat.length # q文字目までマッチした状態で、 for i in 0..CHARS-1 # 次の文字がiだった時、 k = [@pat.length,q+1].min while !suffix(sub(@pat,0,k-1),@pat[0..q-1]+i.chr) k -= 1 # 次の文字を含めた時、k文字目まで検索文字列と一致 end @delta[q][i] = k # 次の状態はk end end end def sub(s,i,j) if i<=j s[i..j] else "" end end def suffix(s, body) # sがbodyの接尾語 s.length <= body.length && s == sub(body,-s.length,-1) end def match(t) # 状態遷移表を使って一致を検出 q = 0 # 状態0からスタート for i in 0..t.length-1 # 入力文字列に従って、 q = @delta[q][t[i]] # 遷移を繰り返し、 if q == @pat.length print("match at ",(i+1-@pat.length),"\n") # 最終状態まで行ったら一致した位置を表示 end end end end x = Sma.new("waniwaniwato") # 探したい文字列でオートマトンを作って準備しておく。 x.match("uraniwaniwaniwaniwatoriairu") # マッチしたかどうかを表示する。 <file_sep>load "pg10r.rb" load "QuickSort.rb" t = pg10r for i in 0..t.length-1 t[i][1] = t[i][1].length end s = t.sort{ |a,b| a[1] <=> b[1]} k=0 while s[k][1]<1000 k += 1 end for i in k..s.length-1 print s[i][0], ": ", s[i][1], "\n" end <file_sep># -*- coding: utf-8 -*- class BullsAndCows def initialize @secret = [0,0,0] # 3つの数 @used = Array.new(10,false) # その数を使っているかを表す配列 @used[0]は使用しない t = Array.new(9) for i in 0..8 t[i] = i+1 # t = [1,2,3,4,5,6,7,8,9]としておく。 end for i in 0..2 j = ((9-i)*rand()).to_i # 1回目は0〜8の乱数、2回目は0〜7の乱数、3回目は0〜6の乱数 @secret[i] = t[j] # 1回目は1〜9のどれか、2回目は1〜8のどれか、3回目は1〜7のどれか。 t[j] = t[8-i] # 1回目はt[0]〜t[7]に使ってない数、2回目はt[0]〜t[6]に使ってない数を入れる。 @used[@secret[i]] = true # used[j]がtrueならjは@secretのなかにある。 end end def guess(x) bulls = 0 # 場所も含めて一致している数 for i in 0..2 if x[i] == @secret[i] # 同じ位置iに同じ数なら、 bulls += 1 end end cows = 0 # 場所と無関係に一致している数 for i in 0..2 if @used[x[i]] # x[i]が@secretのなかにあれば、 cows += 1 end end cows -= bulls # 場所が一致している分を補正 [bulls,cows] end end <file_sep># -*- coding: utf-8 -*- load "pg10r.rb" def find(u,m,s) # uのm番目の要素をキーとして二分探索する関数。 i = 0 j = u.length-1 while i<=j k = (i+j)/2 if u[k][m]==s return k else if u[k][m] < s i = k+1 else j = k-1 end end end return nil end ff = open("ElementSearchEx3.dat","w") # "God"と"god"の出現箇所すべてをファイルに書き出します t = pg10r i = find(t,0,"God") if i ff.print "God: ", t[i][1]*" "," \n\n" else ff.pring "God: not found\n\n" end i = find(t,0,"god") if i ff.print "god: ", t[i][1]*" "," \n" else ff.print "god: not found\n" end <file_sep># -*- coding: utf-8 -*- def stops ["渋谷","神泉","東大前","駒場","池ノ上","下北沢"] end def swap(u,i,k) # 配列中のi番目とk番目のデータの入れ替え tmp = u[i] u[i] = u[k] u[k] = tmp end def sort(u,m) # uのm番目の要素をキーとしてソートする関数。とりあえずここでは単純ソート。 for i in 0..u.length-2 k = i for j in i+1..u.length-1 if u[j][m] < u[k][m] # m番目が比較対象のキー k = j end end swap(u,i,k) end return u end def genIndex(t) # 索引を作る u = Array.new for i in 0..t.length-1 u[i] = [t[i],i] # [ ..., ["東大前",2], ... ]のようにキーと元の位置をペアにしておく。 end return sort(u,0) # 0番目をキーとしてソートする end def find(u,m,s) # uのm番目の要素をキーとして二分探索する関数。 i = 0 j = u.length-1 while i<=j k = (i+j)/2 if u[k][m]==s return k else if u[k][m] < s i = k+1 else j = k-1 end end end return nil end t = genIndex(stops) # 位置の情報もつけてソートする for i in 0..t.length-1 print t[i][0],",",t[i][1],"\n" # データを表示 end i = find(t,0,"東大前") # 0番目をキーとして検索 p t[i][1] # 元の位置を表示
a87b1e3c43f4270ba7c0eee2e7c267968fdb067c
[ "Ruby" ]
31
Ruby
saceandro/programMethod
d41f06ced9a227ebd2b1af3fe1f987fd12d2b268
5cda248f394b93d14ac8a91142dd3f1ce8cec2af
refs/heads/master
<repo_name>galactus009/ostat<file_sep>/main.go // The MIT License (MIT) // // Copyright (c) 2016 <NAME> // // http://knowyourmeme.com/memes/deal-with-it. // // 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. package main import ( "flag" "fmt" "io" "log" "net" "os" "strings" "time" ) var ( hostname string metrics = &Metrics{ data: make(map[string]map[string]interface{}), inputs: make(map[string]func() interface{}), } settings struct { listenAddr string updateInt int } ) func init() { hostname, _ = os.Hostname() metrics.data[hostname] = make(map[string]interface{}) flag.StringVar(&settings.listenAddr, "listen", "localhost:8080", "Listen address:port") flag.IntVar(&settings.updateInt, "update-int", 30, "Metrics update interval") flag.Parse() } func run() { metrics.fetchMetrics() ticker := time.NewTicker(time.Second * time.Duration(settings.updateInt)) go func() { for _ = range ticker.C { metrics.fetchMetrics() } }() } func listen(bindAddr string) { server, err := net.Listen("tcp", bindAddr) if err != nil { log.Fatalf("Listener error: %s\n", err) } else { log.Printf("Listing on %s\n", bindAddr) } defer server.Close() for { conn, err := server.Accept() if err != nil { log.Printf("Server error: %s\n", err) continue } reqHandler(conn) } } func reqHandler(conn net.Conn) { reqBuf := make([]byte, 8) mlen, err := conn.Read(reqBuf) if err != nil && err != io.EOF { fmt.Println(err.Error()) } req := strings.TrimSpace(string(reqBuf[:mlen])) log.Printf("%s command received from %s\n", req, strings.Split(conn.RemoteAddr().String(), ":")[0]) switch req { case "stats": r, _ := metrics.getMetrics() conn.Write(r) conn.Close() default: m := fmt.Sprintf("Not a command: %s\n", req) conn.Write([]byte(m)) conn.Close() } } func main() { run() listen(settings.listenAddr) }
8c0d735973d2c4c80bee3d9805dce01edde16e13
[ "Go" ]
1
Go
galactus009/ostat
9cecea79e0ad0c8594f7f067bd209a9491973538
8cf0c75dcf21a3c4c0e799d6f428c7a58d8a3543
refs/heads/main
<repo_name>rookiewangsl/Fashion<file_sep>/requirements.txt matplotlib==3.2.1 numpy==1.18.2 prefetch-generator==1.0.1 scikit-learn==0.22.2.post1 tensorboard==2.2.0 tqdm==4.45.0 <file_sep>/train.py import argparse import datetime import json import os import random from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter import torchvision from torchvision import transforms, datasets, models import numpy as np from prefetch_generator import BackgroundGenerator from models.SimpleCNNModel import SimpleCNNModel import utils parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("--model",type=str,default="cnn", choices=["cnn", "resnet18"],help="Name of the model to train.",) parser.add_argument("--name",type=str,default="try", help="Name of the experiement, it will be used to name the directory to store all the data to track and restart the experiment.",) parser.add_argument("--percent",type=int,default=20, choices=range(0, 101),metavar="[0-100]", help="Percentage of data from the training set that should be used as a validation set.",) parser.add_argument("--patience",type=int,default=-1, help="patience of early stopping. Use -1 to desactivate early stopping.",) parser.add_argument("--batch_size",type=int,default=256, choices=range(1, 1025),metavar="[1-1024]",help="Batch size.",) parser.add_argument("--epochs",type=int,default=50, choices=range(1, 1001),metavar="[1-1000]",help="Maximum number of epochs.",) parser.add_argument("--num_workers",type=int,default=1, choices=range(1, 65),metavar="[1-64]",help="Number of workers.",) parser.add_argument("--seed", type=int, default=42, help="Random seed.") parser.add_argument("--lr", type=float, default="0.01", help="Initial learning rate.") parser.add_argument("--lr_factor", type=float, default="0.1", help="Factor of Scheduler.") parser.add_argument("--momentum", default=0, type=float, help="Momentum(usuallly 0.9).") parser.add_argument("--weight_decay", default=0, type=float, help="Weight decay(usually 0.01 of base_lr).") parser.add_argument("--nesterov", help="Enable Nesterov momentum.", action="store_true") parser.add_argument("--path_classes",default=os.path.join("models", "classes.json"),type=str, help="Path to the json containing the classes of the Fashion MNIST.",) parser.add_argument("--random_crop", help="Add random cropping at the beggining of the transformations list.", action="store_true",) # boolean value: True parser.add_argument("--random_erasing", help="Add random erasing at the end of the transformations list.", action="store_true",) parser.add_argument("--rgb", help="Repeat the image over 3 channels to convert it to RGB.", action="store_true",) # parser.add_argument("--pretrained_weights", help="Use pretrained weights if possible with the model.", action="store_true",) args = parser.parse_args() def main(): # --- SETUP --- torch.backends.cudnn.benchmark = True np.random.seed(args.seed) random.seed(args.seed) torch.manual_seed(args.seed) use_cuda = torch.cuda.is_available() if use_cuda: torch.cuda.manual_seed_all(args.seed) # Create experiement name if it doesn't exist if not args.name: current_datetime = datetime.datetime.now() timestamp = current_datetime.strftime("%y%m%d-%H%M%S") args.name = f"{timestamp}_{args.model}" # Create the folder to store the results of all the experiments args.experiment_path = os.path.join("experiments", args.name) if not os.path.isdir(args.experiment_path): os.makedirs(args.experiment_path) # Import the classes with open(args.path_classes) as json_file: classes = json.load(json_file) # --- DATA --- # Generate the transformations train_transforms = [ transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)),] test_transforms = [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)),] # Add random cropping to the list of transformations (fill in with padding) if args.random_crop: train_transforms.insert(0, transforms.RandomCrop(28, padding=4)) # Add random erasing to the list of transformations (cover with blank) if args.random_erasing: train_transforms.append( transforms.RandomErasing(p=0.5,scale=(0.02, 0.33),ratio=(0.3, 3.3),value="random",inplace=False,) ) if args.rgb: convert_to_RGB = transforms.Lambda(lambda x: x.repeat(3, 1, 1)) train_transforms.append(convert_to_RGB) test_transforms.append(convert_to_RGB) # Train Data train_transform = transforms.Compose(train_transforms) train_dataset = datasets.FashionMNIST( root="data", train=True, transform=train_transform, download=True,) # Define the size of the training set and the validation set train_set_length = int( len(train_dataset) * (100 - args.percent) / 100) val_set_length = int(len(train_dataset) - train_set_length) train_set, val_set = torch.utils.data.random_split( train_dataset, (train_set_length, val_set_length)) train_loader = torch.utils.data.DataLoader( train_set,batch_size=args.batch_size,shuffle=True,num_workers=args.num_workers,) val_loader = torch.utils.data.DataLoader( val_set, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers,) # Test Data test_transform = transforms.Compose(test_transforms) test_set = datasets.FashionMNIST( root="./data", train=False, transform=test_transform, download=True) test_loader = torch.utils.data.DataLoader( test_set,batch_size=args.batch_size,shuffle=False,num_workers=args.num_workers,) # --- MODEL --- if args.model == "cnn": model = SimpleCNNModel() elif args.model == "resnet18": model = models.resnet18(pretrained=args.pretrained_weights) model.fc = nn.Linear(model.fc.in_features, len(classes)) num_trainable_parameters = utils.count_parameters(model, only_trainable_parameters=True) # Load the model on the GPU if available if use_cuda: model = model.cuda() model.apply(utils.weights_init) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=args.lr,momentum=args.momentum,weight_decay=args.weight_decay,nesterov=args.nesterov,) # scheduler = ReduceLROnPlateau(optimizer,factor=args.lr_factor,patience=50) # Print information from the parameters and model before training print(f"Loaded {args.model} with {num_trainable_parameters} trainable parameters (GPU: {use_cuda}).") print(args) # --- MODEL TRAINING & TESTING --- start_num_iteration = 0 start_epoch = 0 best_accuracy = 0.0 epochs_without_improvement = 0 purge_step = None # Restore the last checkpoint if available checkpoint_filepath = os.path.join(args.experiment_path, "checkpoint.pth.tar") if os.path.exists(checkpoint_filepath): print(f"Restoring last checkpoint from {checkpoint_filepath}...") checkpoint = torch.load(checkpoint_filepath) model.load_state_dict(checkpoint["model_state_dict"]) optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) # scheduler.load_state_dict(checkpoint["scheduler_state_dict"]) start_epoch = checkpoint["epoch"] + 1 start_num_iteration = checkpoint["num_iteration"] + 1 best_accuracy = checkpoint["best_accuracy"] purge_step = start_num_iteration print( f"Last checkpoint restored. Starting at epoch {start_epoch + 1} with best accuracy at {100 * best_accuracy:05.3f}." ) # Create the tensorboard summary writers for training and validation steps train_writer = SummaryWriter( os.path.join(args.experiment_path, "train"), purge_step=purge_step) valid_writer = SummaryWriter( os.path.join(args.experiment_path, "valid"), purge_step=purge_step) test_writer = SummaryWriter( os.path.join(args.experiment_path, "test"), purge_step=purge_step) # main training loop num_iteration = start_num_iteration for epoch in range(start_epoch, args.epochs): # --- TRAIN --- num_iteration, _, _, _, _ = train( model=model, classes=classes, data_loader=train_loader, criterion=criterion, optimizer=optimizer, epoch=epoch, num_iteration=num_iteration, use_cuda=use_cuda, tensorboard_writer=train_writer, ) # --- VALID --- is_best = False _, valid_accuracy_top1, _, _ = test( model=model, classes=classes, data_loader=val_loader, criterion=criterion, # scheduler=scheduler, epoch=epoch, num_iteration=num_iteration, use_cuda=use_cuda, tensorboard_writer=valid_writer, name_step="Valid", ) # Save the best model if valid_accuracy_top1 > best_accuracy: is_best = True best_accuracy = valid_accuracy_top1 # Re-initialize epochs_without_improvement epochs_without_improvement = 0 # Early stopping elif (args.patience >= 0) and (epochs_without_improvement >= args.patience): print(f"No improvement for the last {epochs_without_improvement} epochs, \ stopping the training (best accuracy: {100 * best_accuracy:05.2f}).") break else: epochs_without_improvement += 1 utils.save_checkpoint( current_epoch=epoch, num_iteration=num_iteration, best_accuracy=best_accuracy, model_state_dict=model.state_dict(), optimizer_state_dict=optimizer.state_dict(), # scheduler_state_dict=scheduler.state_dict(), is_best=is_best, experiment_path=args.experiment_path, ) # increment num_iteration after evaluation for the next epoch of training num_iteration += 1 # --- TEST --- # Restore the best model to test it best_model_filepath = os.path.join(args.experiment_path, "model_best.pth.tar") if os.path.exists(best_model_filepath): print(f"Loading best model from {best_model_filepath}...") checkpoint = torch.load(best_model_filepath) model.load_state_dict(checkpoint["model_state_dict"]) best_accuracy = checkpoint["best_accuracy"] epoch = checkpoint["epoch"] num_iteration = checkpoint["num_iteration"] _, test_accuracy_top1, _, _ = test( model=model, classes=classes, data_loader=test_loader, criterion=criterion, # scheduler=scheduler, epoch=epoch, num_iteration=num_iteration, use_cuda=use_cuda, tensorboard_writer=test_writer, name_step="Test", ) # Print final accuracy of the best model on the test set print(f"Best {args.model} model has an accuracy of {100 * test_accuracy_top1:05.2f} on the Fashion MNIST test set.") def train( model: nn.Module, classes: dict, data_loader: torch.utils.data.DataLoader, criterion: nn.Module, optimizer: nn.Module, epoch: int, num_iteration: int, use_cuda: bool, tensorboard_writer: torch.utils.tensorboard.SummaryWriter, ): """ Train a given model Args: model (nn.Module): model to train. classes (dict): dictionnary containing the classes and their indice. data_loader (torch.utils.data.DataLoader): data loader with the data to train the model on. criterion (nn.Module): loss function. optimizer (nn.Module): optimizer function. epoch (int): epoch of training. num_iteration (int): number of iterations since the beginning of the training. use_cuda (bool): boolean to decide if cuda should be used. tensorboard_writer (torch.utils.tensorboard.SummaryWriter): writer to write the metrics in tensorboard. Returns: num_iteration (int): number of iterations since the beginning of the training (increased during the training). loss (float): final loss accuracy_top1 (float): final accuracy top1 accuracy_top5 (float): final accuracy top5 confidence_mean (float): mean confidence """ # Switch the model to train mode model.train() # Initialize the trackers for the loss and the accuracy loss_tracker = utils.MetricTracker() accuracy_top1_tracker = utils.MetricTracker() accuracy_top5_tracker = utils.MetricTracker() confidence_tracker = utils.MetricTracker() # Initialize confusing matrix confusion_matrix_tracker = utils.ConfusionMatrix(classes) # create BackgroundGenerator and wrap it in tqdm progress bar progress_bar = tqdm( BackgroundGenerator(data_loader, max_prefetch=32), total=len(data_loader)) for i, data in enumerate(progress_bar): inputs, targets = data # Save the inputs to the disk # img_grid = torchvision.utils.make_grid(inputs) # torchvision.utils.save_image(img_grid,"inputs.jpg") if use_cuda: inputs = inputs.cuda() targets = targets.cuda() # Forward pass outputs = model(inputs) loss = criterion(outputs, targets) confidence, prediction = outputs.topk(dim=1, k=5) # Backward pass and optimizer step optimizer.zero_grad() loss.backward() optimizer.step() # Track loss, accuracy and confidence loss_tracker.update(loss.item()) accuracy_top1_tracker.update( (prediction[:, 0] == targets).sum().item(), targets.numel()) accuracy_top5_tracker.update( (prediction[:, :5] == targets[:, None]).sum().item(), targets.numel()) confidence_tracker.update(confidence[:, 0].sum().item(), targets.numel()) # Update the confusion matrix confusion_matrix_tracker.update_confusion_matrix(targets.cpu(), prediction[:, 0].cpu()) # Add the new values to the tensorboard summary writer tensorboard_writer.add_scalar("loss", loss_tracker.average, num_iteration) tensorboard_writer.add_scalar("accuracy_top1", accuracy_top1_tracker.average, num_iteration) tensorboard_writer.add_scalar("accuracy_top5", accuracy_top5_tracker.average, num_iteration) tensorboard_writer.add_scalar( "confidence_mean", confidence_tracker.average, num_iteration ) # Update the progress_bar information progress_bar.set_description(f"Epoch {epoch + 1}/{args.epochs} Train") progress_bar.set_postfix( loss=f"{loss_tracker.average:05.5f}", accuracy_top1=f"{100 * accuracy_top1_tracker.average:05.2f}", accuracy_top5=f"{100 * accuracy_top5_tracker.average:05.2f}", ) # Increment num_iteration on all iterations except the last, # so that the evaluation is logged to the correct iteration if i < len(data_loader) - 1: num_iteration += 1 # Add the normalized confusion matrix to tensorboard and flush it tensorboard_writer.add_figure("confusion_matrix", confusion_matrix_tracker.plot_confusion_matrix(normalize=True), num_iteration) tensorboard_writer.flush() return ( num_iteration, loss_tracker.average, accuracy_top1_tracker.average, accuracy_top5_tracker.average, confidence_tracker.average, ) def test( model: nn.Module, classes: dict, data_loader: torch.utils.data.DataLoader, criterion: nn.Module, # scheduler: nn.Module, epoch: int, num_iteration: int, use_cuda: bool, tensorboard_writer: torch.utils.tensorboard.SummaryWriter, name_step: str, ): """ Test a given model Args: model (nn.Module): model to test. classes (dict): dictionnary containing the classes and their indice. data_loader (torch.utils.data.DataLoader): data loader with the data to test the model on. criterion (nn.Module): loss function. epoch (int): epoch of training corresponding to the model. num_iteration (int): number of iterations since the beginning of the training corresponding to the model. use_cuda (bool): boolean to decide if cuda should be used. tensorboard_writer (torch.utils.tensorboard.SummaryWriter): writer to write the metrics in tensorboard. name_step (str): name of the step to write it in the description of the progress_bar Returns: loss (float): final loss accuracy_top1 (float): final accuracy top1 accuracy_top5 (float): final accuracy top5 confidence_mean (float): mean confidence """ # Switch the model to eval mode model.eval() # Initialize the trackers for the loss and the accuracy loss_tracker = utils.MetricTracker() accuracy_top1_tracker = utils.MetricTracker() accuracy_top5_tracker = utils.MetricTracker() confidence_tracker = utils.MetricTracker() # Initialize confusing matrix confusion_matrix_tracker = utils.ConfusionMatrix(classes) # create BackgroundGenerator and wrap it in tqdm progress bar progress_bar = tqdm(BackgroundGenerator(data_loader, max_prefetch=32), total=len(data_loader)) for data in progress_bar: inputs, targets = data if use_cuda: inputs = inputs.cuda() targets = targets.cuda() # forward pass outputs = model(inputs) loss = criterion(outputs, targets) confidence, prediction = outputs.topk(dim=1, k=5) # scheduler.step(loss) # Track loss, accuracy and confidence loss_tracker.update(loss.item()) accuracy_top1_tracker.update( (prediction[:, 0] == targets).sum().item(), targets.numel()) accuracy_top5_tracker.update( (prediction[:, :5] == targets[:, None]).sum().item(), targets.numel()) confidence_tracker.update(confidence[:, 0].sum().item(), targets.numel()) # Update the confusion matrix confusion_matrix_tracker.update_confusion_matrix(targets.cpu(), prediction[:, 0].cpu()) # Update the progress_bar information progress_bar.set_description(f"Epoch {epoch + 1}/{args.epochs} {name_step}") progress_bar.set_postfix( loss=f"{loss_tracker.average:05.5f}", accuracy_top1=f"{100 * accuracy_top1_tracker.average:05.2f}", accuracy_top5=f"{100 * accuracy_top5_tracker.average:05.2f}",) # Add the new values to the tensorboard summary writer tensorboard_writer.add_scalar("loss", loss_tracker.average, num_iteration) tensorboard_writer.add_scalar("accuracy_top1", accuracy_top1_tracker.average, num_iteration) tensorboard_writer.add_scalar("accuracy_top5", accuracy_top5_tracker.average, num_iteration) tensorboard_writer.add_scalar( "confidence_mean", confidence_tracker.average, num_iteration ) tensorboard_writer.add_figure("confusion_matrix", confusion_matrix_tracker.plot_confusion_matrix(normalize=True), num_iteration) tensorboard_writer.flush() return ( loss_tracker.average, accuracy_top1_tracker.average, accuracy_top5_tracker.average, confidence_tracker.average, ) if __name__ == "__main__": main() <file_sep>/models/SimpleCNNModel.py # source: source: https://github.com/ashmeet13/FashionMNIST-CNN/blob/master/Fashion.py import torch.nn as nn class SimpleCNNModel(nn.Module): """ SimpleCNNModel is a simple CNN model to use as a baseline Model Structure: 2x Convolutional Layers: - ReLU Activation - Batch Normalisation - Uniform Xavier Weights - Max Pooling 1x Fully Connected Layer: - ReLU activation 1x Fully Connected Layer: - Output Layer """ def __init__(self): super(SimpleCNNModel, self).__init__() self.cnn1 = nn.Conv2d( in_channels=1, out_channels=32, kernel_size=5, stride=1, padding=2) self.relu1 = nn.ReLU() self.norm1 = nn.BatchNorm2d(32) nn.init.xavier_uniform_(self.cnn1.weight) self.maxpool1 = nn.MaxPool2d(kernel_size=2) self.cnn2 = nn.Conv2d( in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=2) self.relu2 = nn.ReLU() self.norm2 = nn.BatchNorm2d(64) nn.init.xavier_uniform_(self.cnn2.weight) self.maxpool2 = nn.MaxPool2d(kernel_size=2) self.fc1 = nn.Linear(4096, 4096) self.fcrelu = nn.ReLU() self.fc2 = nn.Linear(4096, 10) def forward(self, x): out = self.cnn1(x) out = self.relu1(out) out = self.norm1(out) out = self.maxpool1(out) out = self.cnn2(out) out = self.relu2(out) out = self.norm2(out) out = self.maxpool2(out) out = out.view(out.size(0), -1) out = self.fc1(out) out = self.fcrelu(out) out = self.fc2(out) return out <file_sep>/utils.py import os import shutil import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import torch import torch.nn as nn # initial weight def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: torch.nn.init.xavier_uniform_(m.weight) elif classname.find('Linear') != -1: torch.nn.init.xavier_uniform_(m.weight) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.01) def count_parameters(model: nn.Module, only_trainable_parameters: bool = True,) -> int: if only_trainable_parameters: num_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) else: num_parameters = sum(p.numel() for p in model.parameters()) return num_parameters def save_checkpoint( current_epoch: int, num_iteration: int, best_accuracy: float, model_state_dict: dict, optimizer_state_dict: dict, # scheduler_state_dict: dict, is_best: bool, experiment_path: str, checkpoint_filename: str = "checkpoint.pth.tar", best_filename: str = "model_best.pth.tar", ): """ Save the checkpoint and the best model to the disk Args: current_epoch (int): current epoch of the training. num_iteration (int): number of iterations since the beginning of the training. best_accuracy (float): last best accuracy obtained during the training. model_state_dict (dict): dictionary containing information about the model's state. optimizer_state_dict (dict): dictionary containing information about the optimizer's state. is_best (bool): boolean to save the current model as the new best model. experiment_path (str): path to the directory where to save the checkpoints and the best model. checkpoint_filename (str: "checkpoint.pth.tar"): filename to give to the checkpoint. best_filename (str: "model_best.pth.tar"): filename to give to the best model's checkpoint. """ print( f'Saving checkpoint{f" and new best model (best accuracy: {100 * best_accuracy:05.2f})" if is_best else f""}...' ) checkpoint_filepath = os.path.join(experiment_path, checkpoint_filename) torch.save( { "epoch": current_epoch, "num_iteration": num_iteration, "best_accuracy": best_accuracy, "model_state_dict": model_state_dict, "optimizer_state_dict": optimizer_state_dict, # "scheduler_state_dict": scheduler_state_dict, }, checkpoint_filepath, ) if is_best: shutil.copyfile( checkpoint_filepath, os.path.join(experiment_path, best_filename), ) class MetricTracker: """Computes and stores the average and current value of a metric.""" def __init__(self): self.reset() def reset(self): """ Reset all the tracked parameters """ self.value = 0 self.average = 0 self.sum = 0 self.count = 0 def update(self, value: float, num: int = 1): """ Update the tracked parameters Args: value (float): new value to update the tracker with num (int: 1): number of elements used to compute the value """ self.value = value self.sum += value self.count += num self.average = self.sum / self.count class ConfusionMatrix: """Store, update and plot a confusion matrix.""" def __init__(self, classes: dict): """ Create and initialize a confusion matrix Args: classes (dict): dictionary containing all the classes (e.g. {"0": "label_0", "1": "label_1",...}) """ self.classes = classes self.num_classes = len(self.classes) self.labels_classes = range(self.num_classes) self.list_classes = list(self.classes.values()) self.cm = np.zeros([len(classes), len(classes)], dtype=np.int) def update_confusion_matrix(self, targets: torch.Tensor, predictions: torch.Tensor): """ Update the confusion matrix Args: targets (torch.Tensor): tensor on the cpu containing the target classes predictions(torch.Tensor): tensor on the cpu containing the predicted classes """ # use sklearn to update the confusion matrix self.cm += confusion_matrix(targets, predictions, labels=self.labels_classes) def plot_confusion_matrix( self, normalize: bool = True, title: str = None, cmap: matplotlib.colors.Colormap = plt.cm.Blues, ) -> matplotlib.figure.Figure: """ This function plots the confusion matrix. Args: normalize (bool: True): boolean to control the normalization of the confusion matrix. title (str: ""): title for the figure cmap (matplotlib.colors.Colormap: plt.cm.Blues): color map, defaults to 'Blues' Returns: matplotlib.figure.Figure: the ready-to-show/save figure """ if not title: title = f"Normalized Confusion Matrix" if normalize else f"Confusion Matrix" if normalize: self.cm = self.cm.astype("float") / np.maximum( self.cm.sum(axis=1, keepdims=True), 1 ) # Create figure with size determined by number of classes. fig, ax = plt.subplots( figsize=[0.4 * self.num_classes + 4, 0.4 * self.num_classes + 2] ) im = ax.imshow(self.cm, interpolation="nearest", cmap=cmap) ax.figure.colorbar(im, ax=ax) # Show all ticks and label them with the respective list entries. # Add a tick at the start and end in order to not cut off the figure? ax.set( xticks=np.arange(-1, self.cm.shape[1] + 1), yticks=np.arange(-1, self.cm.shape[0] + 1), xticklabels=[""] + self.list_classes+[""], yticklabels=[""] + self.list_classes+[""], title=title, ylabel="True label", xlabel="Predicted label", ) # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = ".2f" if normalize else "d" thresh = self.cm.max() / 2.0 for i in range(self.cm.shape[0]): for j in range(self.cm.shape[1]): ax.text( j, i, format(self.cm[i, j], fmt), ha="center", va="center", color="white" if self.cm[i, j] > thresh else "black", ) fig.tight_layout() return fig <file_sep>/infer.py import torch import os from PIL import Image from models.SimpleCNNModel import SimpleCNNModel from torchvision import transforms # using a picture to verify the inference model = SimpleCNNModel() name = 'cnn_momentum' use_cuda = torch.cuda.is_available() if use_cuda: model = model.cuda() experiment_path = os.path.join("experiments", name) best_model_filepath = os.path.join(experiment_path, "model_best.pth.tar") if os.path.exists(best_model_filepath): print(f"Loading best model from {best_model_filepath}...") checkpoint = torch.load(best_model_filepath) model.load_state_dict(checkpoint["model_state_dict"]) print("load model success") model.eval() img_transforms = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) image = img_transforms(Image.open('./test_image.jpg')).unsqueeze(0) output = model(image.cuda()) predict = output.argmax(dim = 1,keepdim=True) cls = predict.item() class_dic={0:"Tshirt",1:"trouser",2:"pullover",3:"dress",4:"coat",5:"sandal",6:"shirt",7:"sneaker",8:"bag",9:"ankle boot"} print("result:",class_dic[cls])<file_sep>/demo/utils.py import os import sys import time import cv2 import numpy as np import torch import torch.nn as nn from torchvision import transforms, models # Used to import SIMPLECNNModel from a directory at the same leave of the demo one. PACKAGE_PARENT = ".." SCRIPT_DIR = os.path.dirname( os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))) ) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from models.SimpleCNNModel import SimpleCNNModel def extract_roi(frame, mask, bbox): """ Extract a Region of Interest (ROI) from a frame and remove its background Args: frame: Full RGB image mask: Mask containing the segmentation of the object. Used to remove the background. bbox([x, y, w, h]): (x, y) = top left corner of the bbox, w = width of the bbox and h = height of the bbox. Returns: roi: RGB image of the object in the ROI with its background removed (black) """ # Get bbox dimensions x, y, w, h = bbox # Crop the mask according to the ROI roi_mask = mask[y : y + h, x : x + w] # Create the inverse of the roi_mask roi_mask_inv = cv2.bitwise_not(roi_mask) # Crop the ROI from the frame roi_frame = frame[y : y + h, x : x + w, ::] # Remove the background in the frame roi_frame = cv2.bitwise_and(roi_frame, roi_frame, mask=roi_mask) # Create the background (color: black) roi_background = np.ones(roi_frame.shape, dtype=np.uint8) * 0 #  Remove the object from the background roi_background = cv2.bitwise_and(roi_background, roi_background, mask=roi_mask_inv) # Combine the frame and the background roi = cv2.add(roi_background, roi_frame) return roi class SimpleObjectSegmentation: """ Simple Object Segmentation Technique The segmentation technique is rather simple. It compares the current frame with a reference frame and extract the biggest area with some differences. """ def __init__(self, reference): """ Initialize the SimpleObjectSegmentation Args: reference: RGB image to use as the reference image """ self.update_reference(reference) def update_reference(self, reference): """ Update the reference frame Args: reference: RGB image to use as the new reference image. """ self.reference = reference.copy() def detect_object(self, frame, min_contourArea: int = 2500): """ Detect the biggest object Detect the biggest object in the current frame compared to the reference frame. Args: frame: RGB image of the current frame min_contourArea (int: 2500): minimum area the biggest contour should be to be detected Returns: mask/out: if the detection is successful returns the mask of the detection. Otherwise, returns the binary image used to make the detection for debugging purposes. bbox/None: if the detection is successful returns the bbox around the detection ((x, y) = top left corner of the bbox, w = width of the bbox and h = height of the bbox). Otherwise, returns None. """ # Absolute difference between the background image and the current frame out = cv2.absdiff(self.reference, frame) # Thresholding of the difference out = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY) out = cv2.GaussianBlur(out, (5, 5), 0) out = cv2.threshold(out, 50, 255, cv2.THRESH_BINARY)[1] # Remove small detections and fill the holes in the bigger ones out = cv2.dilate(out, None, iterations=1) out = cv2.erode(out, None, iterations=1) out = cv2.dilate(out, None, iterations=2) # Extract the contours contours, hierarchy = cv2.findContours( out, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE ) # Extract the biggest contour if contours: biggest_contour = max(contours, key=cv2.contourArea) #  Check if the area of the detection is big enough if cv2.contourArea(biggest_contour) >= min_contourArea: # Extract the bounding box around the detection x, y, w, h = cv2.boundingRect(biggest_contour) # Create the mask of the detection based on its contour mask = np.full((frame.shape[0], frame.shape[1]), 0, dtype=np.uint8) cv2.fillPoly(mask, pts=[biggest_contour], color=(255, 255, 255)) return mask, [x, y, w, h] # Return None if no contour was detected or the contour was too small return out, None class FashionClassifier: """ Wrapper for classification models trained on the Fashion-MNIST dataset. """ def __init__(self, model_name: str, weights_path: str, classes: dict): """ Initialise the classifier Args: model (str): name of the model to load weights_path (str): filepath to the weights file for the model classes (dict): dictionary containing all the classes (e.g. {"0": "label_0", "1": "label_1",...}) """ # --- Model --- self.model_name = model_name self.weights_path = weights_path self.use_cuda = torch.cuda.is_available() self.classes = classes # Load the model self.load_model() # To compute the probabilities self.softmax = nn.Softmax(dim=1) self.input_size = 28 # Create the preprocessing transformations list_inference_transforms = [ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), ] # In case the image needs 3 channels to be inputed in the model if self.num_input_channels > 1: duplicate_channel = transforms.Lambda( lambda x: x.repeat(self.num_input_channels, 1, 1) ) list_inference_transforms.append(duplicate_channel) self.inference_transforms = transforms.Compose(list_inference_transforms) def load_model(self): """ Load the model according to some parameters """ print( f"Loading {self.model_name} model with the weights from '{self.weights_path}'..." ) # --- MODEL --- if self.model_name == "SimpleCNNModel": self.model = SimpleCNNModel() self.num_input_channels = 1 elif self.model_name == "ResNet18": self.model = models.resnet18(pretrained=False) self.model.fc = nn.Linear(self.model.fc.in_features, len(self.classes)) self.num_input_channels = 3 # Load the checkpoint containing the weights of the model if self.use_cuda: torch.cuda.benchmark = True self.model = self.model.cuda() checkpoint = torch.load(self.weights_path) else: checkpoint = torch.load(self.weights_path, map_location=torch.device("cpu")) # Load the trained weights in the model self.model.load_state_dict(checkpoint["model_state_dict"]) self.model.eval() # Get the best accuracy from the checkpoint best_accuracy = checkpoint["best_accuracy"] print( f"{self.model_name} model loaded successfully. Its accuracy on the Fashion-MNIST test dataset is {100 * best_accuracy:05.3f}." ) def preprocess_input(self, image): """ Preprocess the image using opencv transformations only Args: image: RGB image Returns: input_image: grayscale image """ # Resize the image for the input size (image_height, image_width) = image.shape[:2] ratio = float(self.input_size) / max([image_height, image_width]) input_height = int(image_height * ratio) input_width = int(image_width * ratio) input_image = cv2.resize(image, (input_width, input_height)) # Pad the image in a square with black borders delta_width = self.input_size - input_width delta_height = self.input_size - input_height top, bottom = delta_height // 2, delta_height - (delta_height // 2) left, right = delta_width // 2, delta_width - (delta_width // 2) color = [0, 0, 0] input_image = cv2.copyMakeBorder( input_image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color ) # Convert the image to grayscale input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY) return input_image def inference(self, image): """ Inference Classify the image using the model Args: image: RGB image to input in the model Returns: input_image: output of preprocess_input() confidence (list): Ordered list of the confidence of the prediction (Bigger first) prediction_name (list): Ordered list of the classes name (One with the biggest confidence first) inference_time (float): time used for the inference in seconds """ # Preprocess the image input_image = self.preprocess_input(image) with torch.no_grad(): # Use the custom transformer to convert the input to a tensor input_tensor = self.inference_transforms(input_image)[None, :] # Put the input image on the GPU is available if self.use_cuda: input_tensor = input_tensor.cuda() # Start the timer for calculation the inference time start_time = time.time() # Inference out = self.model(input_tensor) # Use softmax to convert the output to probability and ordered the results confidence, prediction = self.softmax(out).topk(dim=1, k=10) # Stop the inference timer inference_time = time.time() - start_time # Convert the confidence and prediction tensors to lists confidence = confidence[0, :].tolist() prediction = prediction[0, :].tolist() # Convert the classes id into their name prediction_name = [self.classes[str(x)] for x in prediction] return input_image, confidence, prediction_name, inference_time <file_sep>/demo/run_inference.py import argparse import json import os import statistics import time import cv2 import numpy as np from utils import SimpleObjectSegmentation, FashionClassifier, extract_roi parser = argparse.ArgumentParser() parser.add_argument("--model",type=str,required=True, choices=["cnn", "resnet18"],help="Name of the model to train.", ) parser.add_argument("--weights_path",type=str,required=True, help="Path of the weights to load for the model.", ) parser.add_argument("--device",type=int,default="0", help="ID of the device to use for the realtime video capture.", ) parser.add_argument("--display_input", help="Display the input of the model in the top left corner.", action="store_true", ) parser.add_argument("--display_fps", help="Display the FPS in the top right corner.", action="store_true", ) parser.add_argument("--path_classes", default=os.path.join("..", "models", "classes.json"),type=str, help="Path to the json containing the classes of the Fashion MNIST dataset.", ) args = parser.parse_args() if __name__ == "__main__": # Print instructions print(f"------------- FASHION CLASSIFIER -------------") print(f" -> Press 'q' to quit") print( f" -> Press 'n' to reinitialize the background image for the simple object segmentation algorithm." ) # Import the classes with open(args.path_classes) as json_file: classes = json.load(json_file) # Color use to draw and write color = (0, 255, 0) # list of the inference time list_inference_time = [] # create the webcam device webcam = cv2.VideoCapture(args.device) # Get the first frame as reference for the object segmentation algorithm if webcam.isOpened(): _, first_frame = webcam.read() # Instanciate the class responsible for the object detection and segmentation detector = SimpleObjectSegmentation(first_frame) # Instanciate the class responsible for the classifying the fashion objects fashion_classifier = FashionClassifier( model_name=args.model, weights_path=args.weights_path, classes=classes ) # Initialize the flag to update the reference frame of the detector update_detector_reference = False # Start the capturing and processing loop while True: # Start the timer for the fps computation start_time = time.time() # Capture frame-by-frame _, frame = webcam.read() # Update the reference frame is the flag is set if update_detector_reference: detector.update_reference(frame) update_detector_reference = False print("Updated the reference image of the detector.") # Use the detector to grab the mask and the bounding-box of the biggest object in the frame mask, bbox = detector.detect_object(frame) #  If an object was found if bbox is not None: # --- EXTRACTION --- # Extract the roi around the object and remove its background using the mask roi = extract_roi(frame, mask, bbox) # --- CLASSIFICATION --- ( input_image, confidence, prediction, processing_time, ) = fashion_classifier.inference(roi) # Add the inference time to the list of inference time list_inference_time.append(processing_time) # --- DISPLAY --- x, y, w, h = bbox # Draw the bounding box around the ROI cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) # Write the confidence and predicted class on top of the bounding box cv2.putText( frame, f"{prediction[0]} {confidence[0]:.2f}", (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2, ) # Display the input image in the top left corner if args.display_input: # Resize the input image scale = 3 (input_height, input_width) = input_image.shape[:2] input_image_to_display = cv2.resize( input_image, (input_width * scale, input_height * scale) ) # Convert the input image to 3 channels input_image_rgb = cv2.cvtColor( input_image_to_display, cv2.COLOR_GRAY2BGR ) # Display the input image on top of the current frame frame[ : input_height * scale, : input_width * scale, : ] = input_image_rgb # Display the FPS counter if args.display_fps: fps = 1 / (time.time() - start_time) cv2.putText( frame, f"{fps:05.2f} FPS", (frame.shape[1] - 90, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2, ) # Show the current frame with the other information cv2.imshow("Fashion Classifier", frame) # Wait for the different keys c = cv2.waitKey(1) if c == ord("q"): print( f"Average inference time for the {args.model} model over {len(list_inference_time)} inferences is {statistics.mean(list_inference_time)*1000:.3f}ms." ) break elif c == ord("n"): update_detector_reference = True # When everything done, release the webcam and destroy the window webcam.release() cv2.destroyAllWindows() <file_sep>/README.md # 文件结构(数据挖掘课程作业) 1. data:数据集 2. demo:opencv 库实现摄像头实时推断 3. experiments:每次修参(不同名字的文件夹)保留的模型参数和结果,可用于可视化和复现 4. images:可视化和过程产生的图片 5. models:存的自定义cnn和class 6. train.py:训练主文件 ```python python train.py -h ``` 获得与设置相关参数信息 ``` python train.py ``` 产生一个名为try的实验数据(均为默认参数) 7. util.py:存放一些函数定义 8. infer.py:利用单张测试样例进行推断 9. report.pdf
6a04fc4be886a46c2a290d54fdd7da9727c7a666
[ "Markdown", "Python", "Text" ]
8
Text
rookiewangsl/Fashion
6679f663e3aa385a07267e74135c910303f5fe86
0f48bb361e2c00cdcc8855f1e74aa2715cc35315
refs/heads/master
<repo_name>Dreamest/WarGame-Basic<file_sep>/README.md # WarGame-Basic A card war game android application - Basic version ![Game Screen](https://i.ibb.co/2P3vHY4/Whats-App-Image-2020-11-14-at-21-38-26.jpg) Upon starting the application, a deck of cards will be created, shuffled and split into two halves, one for each player. Pressing the Play button will deal the next card in each deck. The player with the higher score will gain a point, if tied - no one gets a point. After 26 turns, the game activity will close and a results activity screen will open. ![Results Screen](https://i.ibb.co/YXNdrxs/Whats-App-Image-2020-11-14-at-21-38-26-1.jpg) In this screen, the winner and the highest score will be shown. Pressing the 'Restart' button will close the results activity, and re-open the game activity, thus restarting the game. Pressing the 'Exit' button will shut down the activity, and as there are no open activities, close the application. <file_sep>/app/src/main/java/com/dreamest/wargame_basic/Card.java package com.dreamest.wargame_basic; public class Card implements Comparable<Card>{ private int value; private String suit; private String drawableName; private final int VALUE_OFFSET = -2; public Card(){}; public Card(int value, String suit) { this.value = value; this.suit = suit; this.drawableName = suit + "_" + valueToWord(value); } private String valueToWord(int value) { String words[] = {"two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"}; return words[value + VALUE_OFFSET]; } @Override public int compareTo(Card other) { return this.value - other.value; // if (this.value > other.value) // return 1; // else if (this.value < other.value) // return -1; // return 0; } public String getName() { return this.drawableName; } } <file_sep>/app/src/main/java/com/dreamest/wargame_basic/MainActivity.java package com.dreamest.wargame_basic; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.media.Image; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { private ImageButton main_BTN_deal; private ImageView main_IMG_leftCard; private ImageView main_IMG_rightCard; private TextView main_LBL_leftScore; private TextView main_LBL_rightScore; private List<Card> deckOfCards; private List<Card> player1Deck; private List<Card> player2Deck; private int p1Score, p2Score; private int counter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_BTN_deal = findViewById(R.id.main_BTN_deal); main_IMG_leftCard = findViewById(R.id.main_IMG_leftCard); main_IMG_rightCard = findViewById(R.id.main_IMG_rightCard); main_LBL_leftScore = findViewById(R.id.main_LBL_leftScore); main_LBL_rightScore = findViewById(R.id.main_LBL_rightScore); initGame(); main_BTN_deal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(counter == player1Deck.size()) { changeActivity(); } else //turn() plays anyway even if the activity finishes without the 'else' turn(); } }); } @Override protected void onResume() { super.onResume(); hideSystemUI(); //Credit : https://developer.android.com/training/system-ui/immersive#java } private void turn() { Card p1Card = player1Deck.get(counter); Card p2Card = player2Deck.get(counter); int playerOneID = getResources().getIdentifier(p1Card.getName(), "drawable", getPackageName()); int playerTwoID = getResources().getIdentifier(p2Card.getName(), "drawable", getPackageName()); main_IMG_leftCard.setImageResource(playerOneID); main_IMG_rightCard.setImageResource(playerTwoID); counter++; if (p1Card.compareTo(p2Card) > 0) p1Score++; else if(p1Card.compareTo(p2Card) < 0) p2Score++; updateScore(); } private void changeActivity() { Intent myIntent = new Intent(this, ResultsActivity.class); String winner; if (p1Score > p2Score) winner = "Left Player Wins!"; else if (p1Score < p2Score) winner = "Right Player Wins!"; else winner = "It's a tie!"; myIntent.putExtra(ResultsActivity.EXTRA_KEY_SCORE, Math.max(p1Score, p2Score)); myIntent.putExtra(ResultsActivity.EXTRA_KEY_WINNER, winner); startActivity(myIntent); finish(); } private void initGame() { p1Score = 0; p2Score = 0; updateScore(); create_deck(); dealCards(); } private void updateScore() { main_LBL_leftScore.setText(p1Score + ""); main_LBL_rightScore.setText(p2Score + ""); } private void dealCards() { Collections.shuffle(deckOfCards); int halfSize = deckOfCards.size()/2; player1Deck = new ArrayList<>(deckOfCards.subList(0, halfSize)); player2Deck = new ArrayList<>(deckOfCards.subList(halfSize, deckOfCards.size())); //Shuffling again just for kicks. Collections.shuffle(player1Deck); Collections.shuffle(player2Deck); } private void create_deck() { deckOfCards = new ArrayList<Card>(); for (String suit: new String[] {"spades", "clubs", "hearts", "diamonds"}) { for (int value = 2 ; value <=14; value++) { deckOfCards.add(new Card(value, suit)); } } } private void hideSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } // Shows the system bars by removing all the flags // except for the ones that make the content appear under the system bars. private void showSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } }
839f46851b9b946678b413ddbe4f2416c5186d96
[ "Markdown", "Java" ]
3
Markdown
Dreamest/WarGame-Basic
ad7d1db9d0ac09f7c73c8c2d7826462d3ebc223f
cded4ed75f5ad928265d1b036c6933ae30303cdb
refs/heads/master
<repo_name>Ashishw2022/S1_MCA_Ashish_wilson<file_sep>/ADS_Lab/5. Set Data Structure and set operations (Union, Intersection and Difference) using Bit String/5 set operation-ashish wilson (1).c #include<stdio.h> #include<stdlib.h> void main() { int ch,A[50],B[50],C[50],m,n,i; printf("\nEnter cardinality of first set: "); scanf("%d",&m); printf("\nEnter cardinality of second set: "); scanf("%d",&n); printf("\nEnter elements of first set(0/1): "); for(i=0;i<m;i++) { scanf("%d",&A[i]); } printf("\nEnter elements of second set(0/1): "); for(i=0;i<n;i++) { scanf("%d",&B[i]); } do { printf("\nSelect the choice: "); printf("\n1.Union\n2.Intersection\n3.Difference\n4.Exit"); printf("\nEnter a choice: "); scanf("%d",&ch); switch(ch) { case 1: if(m!=n) { printf("\nCannot perform union!"); break; } printf("\nElements of set1 union set2: "); for(i=0;i<m;i++) { C[i]=A[i]|B[i]; printf("%d ",C[i]); } break; case 2: if(m!=n) { printf("\nCannot perform intersection!"); break; } printf("\nElements of set1 intersection set2: "); for(i=0;i<m;i++) { C[i]=A[i]&B[i]; printf("%d ",C[i]); } break; case 3: if(m!=n) { printf("\nCannot perform difference!"); break; } for(i=0;i<n;i++) { if(A[i]==0) C[i]=0; else { if(B[i]==1) C[i]=0; else C[i]=1; } } printf("\nDifference of set1 - set2: "); for(i=0;i<m;i++) { printf("%d ",C[i]); } break; case 4:exit(0); break; default:printf("\nInvalid choice!"); }; }while(1); } <file_sep>/ADS_Lab/4.3 Singly Linked Stack - Push, Pop, Linear Search/singled linked list stack_push_pop_linearsearch (2).C #include <stdio.h> #include<conio.h> #include<stdlib.h>c void push(); void pop(); void search(); void display(); struct node { int data; struct node *next; }; struct node *top; void main() { char ch; int op; clrscr(); while(op!=5) { printf("\n 1.PUSH \n 2.POP \n 3.LINEAR SEARCH \n 4.DISPLAY \n 5.EXIT \n "); printf("Enter your choice:"); scanf("%d",&op); switch(op) { case 1:push();break; case 2:pop();break; case 3:search();break; case 4:display();break; case 5:exit(0);break; default:printf("\nINVALID INPUT"); }; } getch(); } void push() { int val; struct node *newnode; newnode=(struct node*)malloc(sizeof(struct node)); if(newnode==NULL) { printf("\nStack is full"); } else { printf("\nEnter the value"); scanf("%d",&val); if(top==NULL) { top=newnode; newnode->data=val; newnode->next=NULL; } else { newnode->data=val; newnode->next=top; top=newnode; } printf("\n Value pushed"); } } void pop() { if(top==NULL) { printf("\nStack is empty"); } else { struct node*temp; temp=top; top=temp->next; free(temp); printf("\nvalue deleted"); } } void search() { int key,flag; struct node*temp; printf("\nEnter the element to search: "); scanf("%d",&key); temp=top; while(temp!=NULL) { if(temp->data==key) { flag=1; } temp=temp->next; } if(flag==1) { printf("element found %d",key); } else { printf("element not found"); } } void display() { if(top==NULL) { printf("\n Stack is empty"); } else { struct node*temp; temp=top; while(temp->next!=NULL) { printf("%d->",temp->data); temp=temp->next; } printf("%d->NULL",temp->data); } } <file_sep>/ADS_Lab/4.2 Circular Queue - Add, Delete, Search/4_3.c #include<stdio.h> #define max 3 int q[10],front=0,rear=-1; void main() { int ch; void insert(); void delte(); void display(); void search(); printf("\n circular queue operations\n"); printf("1.insert\n2.delete\n3.display\n4.search\n5.exit\n"); while(1) { printf("enter your choice:"); scanf("%d",&ch); switch(ch) { case 1:insert(); break; case 2:delte(); break; case 3:display(); break; case 4:search(); break; case 5:exit(1); break; default:printf("\ninvalid option\n"); } } } void insert() { int x; if((front==0&&rear==max-1)||(front>0&&rear==front-1)) printf("queue is overflow\n"); else { printf("\nenter element to be inserted:"); scanf("%d", &x); if(rear==max-1&&front>0) { rear=0; q[rear]=x; } else { if((front==0&&rear==-1)||(rear!=front-1)) q[++rear]=x; } } } void delte() { int a; if((front==0)&&(rear==-1)) { printf("queue is underflow\n"); getch(); exit(1); } if(front==rear) { a=q[front]; rear=-1; front=0; } else if(front==max-1) { a=q[front]; front=0; } else a=q[front++]; printf("deleted element is:%d\n",a); } void search() { int i,ele; printf("\n enter the element to search "); scanf("%d",&ele); for(i=front;i<=rear;i++) { if(ele==q[i]) { printf("\n element found at %d position : %d",i+1,ele); } } printf("\n element not found"); } void display() { int i,j; if(front==0&&rear==-1) { printf("no elements to display\n"); getch(); exit(1); } if(front>rear) { for(i=0;i<=rear;i++) printf("\t%d",q[i]); for(j=front;j<=max-1;j++) printf("\t%d",q[j]); } else { for(i=front;i<=rear;i++) { printf("\t%d",q[i]); } } printf("\n"); } getch(); <file_sep>/ADS_Lab/4.1.Merge two sorted arrays and store in a third array/Q4_1.C #include <stdio.h> #include<conio.h> int main() { int a1[10],a2[10],res[20],resfinal[20]; int m,n,i,j,k,temp; clrscr(); printf("\n enter the limit of array 1: "); scanf("%d",&m); printf("\nEnter the sorted array 1 : \n"); for(i=0;i<m;i++) { scanf("%d",&a1[i]); } printf("\n enter the limit of array 2: "); scanf("%d",&n); printf("\nEnter the sorted array 2 : \n"); for(j=0;j<n;j++) { scanf("%d",&a2[j]); } i=j=k=0; while(i<m && j<n) { if(a1[i]<a2[j]) { res[k]=a1[i]; i++; k++; } else { res[k]=a2[j]; j++; k++; } } while(i<m) { res[k]=a1[i]; i++; k++; } while(j<n) { res[k]=a2[j]; j++; k++; } printf("\n Array after merging : \n"); for(k=0;k<m+n;k++) { printf(" %d ", res[k]); } getch(); return 0; }
474565bbf83eead843ab004bb4e40f56963b25bf
[ "C" ]
4
C
Ashishw2022/S1_MCA_Ashish_wilson
0a7ce09dda92fd197d0a572506724c992a8aa9d5
e18d9fde078d007118e4f00cf9b5ca9837e35bcd
refs/heads/master
<file_sep>const Joi = require("joi"); module.exports = { validatePackagePurchase: (body) => { const schema = Joi.object({ subscriberNumber: Joi.string() .length(12) .alphanum() .regex(/^233.+/) .required() .messages({"string.pattern.base": "subscriberNumber must start with 233"}), channel: Joi.string() .alphanum() .min(3) .max(50) .required(), transactionId: Joi.string() .min(3) .max(300) .required(), offerId: Joi.string() .min(1) .max(255) .required(), mobileMoneyWallet: Joi.string() .min(1) .max(20) .required(), mobileMoneyProvider: Joi.string() .min(1) .max(20) .required(), offerName: Joi.string() .min(1) .max(255) .required(), accountId: Joi.string() .alphanum() .required(), }); return schema.validate(body) }, validateDataRecharge: (body) => { const schema = Joi.object({ subscriberNumber: Joi.string() .length(12) .alphanum() .regex(/^233.+/) .required() .messages({"string.pattern.base": "subscriberNumber must start with 233"}), channel: Joi.string() .alphanum() .min(3) .max(50) .required(), transactionId: Joi.string() .min(3) .max(300) .required(), offerId: Joi.string() .min(1) .max(255) .required(), offerName: Joi.string() .min(1) .max(255) .required(), subscriptionType: Joi.string() .valid('One-Off', 'Recurrent') .required(), }); return schema.validate(body) }, }
fcc12a076f0599bee9faa03d7566c5f17c7ee98a
[ "JavaScript" ]
1
JavaScript
egyapolley/ussd-flytxt-api
d4887858dc91ce411396ac362016d8e8cb9938b8
cdf4c7c222531a8ea490459bb8f951ae9f58e671
refs/heads/master
<repo_name>CarryItForward/spark-lambdas<file_sep>/src/utils/responses.ts export const successResponse = (body: any, statusCode = 200) => ({ statusCode, body: JSON.stringify(body), }) export const errorResponse = (body: any, statusCode = 500) => ({ statusCode, body: JSON.stringify(body), }) <file_sep>/src/utils/offline.ts import { S3 as awsS3 } from 'aws-sdk' export const isOffline = () => process.env.IS_OFFLINE === 'true' const accessKeyId = process.env.AWS_ACCESS_KEY_ID || '' const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY || '' const sessionToken = process.env.AWS_SESSION_TOKEN || '' const s3Options = { online: { credentials: { accessKeyId, secretAccessKey, sessionToken }, }, offline: { s3ForcePathStyle: true, endpoint: 'http://localhost:5353', credentials: { accessKeyId: 'S3RVER', secretAccessKey: 'S3RVER', }, }, } export class S3 extends awsS3 { constructor(options?: awsS3.Types.ClientConfiguration) { const config = isOffline() ? { ...s3Options.offline, ...options } : { ...s3Options.online, ...options } super(config) } } <file_sep>/README.md <p align="center"> <a href="#"> <img src="https://carryitforward.trifoia.com/branding/CIF_Spark.png" width="350px"> </a> </p> <h1 align="center"> Spark Lambdas λ </h1> <h4 align="center"> The lambdas powering Carry It Forward's Spark project </h4> ## Installation TODO ## Running TODO ## Contributing TODO <file_sep>/src/handler.ts import { APIGatewayEvent } from 'aws-lambda' import { errorResponse, S3, successResponse } from './utils' export const generateContent = async (event: APIGatewayEvent) => { const { WEBSITE_BUCKET } = process.env const s3 = new S3() if (event.pathParameters && event.pathParameters.name) { const { name } = event.pathParameters const params = { Bucket: WEBSITE_BUCKET || '', Key: `${name.toLowerCase()}/index.html`, Body: new Buffer(` <html lang="en"> <head> <title>${name}</title> </head> <body> <h1>${name}'s Profile Page</h1> <p>This is a description about what items ${name} needs.</p> </body> </html> `.trim()), ContentType: 'text/html', ACL: 'public-read', } // Wait for object to be uploaded await s3.putObject(params).promise() return successResponse({ url: `http://${WEBSITE_BUCKET}.s3-website-us-west-2.amazonaws.com/${name.toLowerCase()}`, }) } else { return errorResponse({ message: 'invalid name', }, 400) } } <file_sep>/src/utils/index.ts export * from './responses' export * from './offline'
6d81bb23aff310b3ac0615276f5666eb2e047a41
[ "Markdown", "TypeScript" ]
5
TypeScript
CarryItForward/spark-lambdas
d96be66a170ec224291c65ca4a355aec79859d13
4b8589bcc915f7fa5673093e82c02fb2ac67c301
refs/heads/master
<repo_name>wassertim/kafka-docker<file_sep>/docker-compose.yml version: '2' services: zookeeper: image: wurstmeister/zookeeper ports: - "2181:2181" kafka: build: . ports: - "9092:9092" - "9093:9093" environment: KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_HOST_NAME: localhost KAFKA_BROKER_ID: 0 KAFKA_LISTENERS: "PLAINTEXT://kafka:9092,SSL://kafka:9093" KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://172.29.14.208:9092,SSL://172.29.14.208:9093" KAFKA_SSL_KEYSTORE_LOCATION: "/ssl/kafka.server.keystore.jks" KAFKA_SSL_KEYSTORE_PASSWORD: "<PASSWORD>" KAFKA_SSL_KEY_PASSWORD: "<PASSWORD>" KAFKA_SSL_TRUSTSTORE_LOCATION: "/ssl/kafka.server.truststore.jks" KAFKA_SSL_TRUSTSTORE_PASSWORD: "<PASSWORD>" volumes: - /var/run/docker.sock:/var/run/docker.sock <file_sep>/commands.sh #!/bin/bash export SRVPASS=<PASSWORD> export SERVER="localhost" export VALIDITY_DAYS=365 export SSL_DIR=/ssl export CA_CERT="${SSL_DIR}/ca-cert" export CA_KEY="${SSL_DIR}/ca-key" export CERT_FILE="${SSL_DIR}/cert-file" export CERT_SIGNED="${SSL_DIR}/cert-signed" export KAFKA_SERVER_KEYSTORE="${SSL_DIR}/kafka.server.keystore.jks" export KAFKA_SERVER_TRUSTSTORE="${SSL_DIR}/kafka.server.truststore.jks" mkdir $SSL_DIR # Generate certificates (private and public) openssl req -new -newkey rsa:4096 -days $VALIDITY_DAYS -x509 -subj "/CN=Kafka-Security-CA" \ -keyout $CA_KEY -out $CA_CERT -nodes # Create keystore keytool -genkey -keystore $KAFKA_SERVER_KEYSTORE -validity $VALIDITY_DAYS -alias localhost \ -storepass $SRVPASS -keypass $SRVPASS -dname "CN=$SERVER" -storetype pkcs12 -keyalg RSA keytool -keystore $KAFKA_SERVER_KEYSTORE -alias localhost -certreq -file $CERT_FILE \ -storepass $SRVPASS -keypass $SRVPASS # Sign certificate openssl x509 -req -CA $CA_CERT -CAkey $CA_KEY -in $CERT_FILE -out $CERT_SIGNED -days $VALIDITY_DAYS \ -CAcreateserial -passin pass:$SRVPASS # 7. Create truststore and add certificate there keytool -keystore $KAFKA_SERVER_TRUSTSTORE -alias CARoot -import -file $CA_CERT \ -storepass $SRVPASS -keypass $SRVPASS -noprompt # 8. Add certificate to the keystore keytool -keystore $KAFKA_SERVER_KEYSTORE -alias CARoot -import -file $CA_CERT \ -storepass $SRVPASS -keypass $SRVPASS -noprompt # 9. Add signed certificate to the keystore keytool -keystore $KAFKA_SERVER_KEYSTORE -alias localhost -import -file $CERT_SIGNED \ -storepass $SRVPASS -keypass $SRVPASS -noprompt <file_sep>/commands_2.sh export SRVPASS=<PASSWORD> export SERVER=localhost export VALIDITY_DAYS=365 export SSL_DIR=ssl export CA_CERT="${SSL_DIR}/ca-cert" export CA_KEY="${SSL_DIR}/ca-key" export CERT_FILE="${SSL_DIR}/cert-file" export CERT_SIGNED="${SSL_DIR}/cert-signed" export KAFKA_SERVER_KEYSTORE="${SSL_DIR}/kafka.server.keystore.jks" export KAFKA_SERVER_TRUSTSTORE="${SSL_DIR}/kafka.server.truststore.jks" export KAFKA_CLIENT_TRUSTSTORE="${SSL_DIR}/kafka.client.truststore.jks" mkdir $SSL_DIR #Step 1 keytool -keystore $KAFKA_SERVER_KEYSTORE -alias localhost -validity 365 -keyalg RSA -genkey \ -storepass $SRVPASS -keypass $SRVPASS #Step 2 openssl req -new -x509 -keyout $CA_KEY -key -out $CA_CERT -days 365 keytool -keystore $KAFKA_SERVER_TRUSTSTORE -alias CARoot -import -file $CA_CERT \ -storepass $SRVPASS -keypass $SRVPASS keytool -keystore $KAFKA_CLIENT_TRUSTSTORE -alias CARoot -import -file $CA_CERT \ -storepass $SRVPASS -keypass $SRVPASS #Step 3 keytool -keystore $KAFKA_SERVER_KEYSTORE -alias localhost -certreq -file $CERT_FILE \ -storepass $SRVPASS -keypass $SRVPASS openssl x509 -req -CA $CA_CERT -CAkey $CA_KEY -key -in $CERT_FILE -out $CERT_SIGNED -days 365 -CAcreateserial -passin pass:$SRVPASS keytool -keystore $KAFKA_SERVER_KEYSTORE -alias CARoot -import -file $CA_CERT \ -storepass $SRVPASS -keypass $SRVPASS keytool -keystore $KAFKA_SERVER_KEYSTORE -alias localhost -import -file $CERT_SIGNED \ -storepass $SRVPASS -keypass $SRVPASS
cfca1e1670172dcb10efa124e4afc4099339809d
[ "YAML", "Shell" ]
3
YAML
wassertim/kafka-docker
a39be63a05cf4369177e24447e84517526e4747e
7a1099faee12c19b0c4e0240d863cd295dbdf4a0
refs/heads/master
<repo_name>AriefDR/blogGogreen<file_sep>/assets/js/script.js document.getElementById('subs').addEventListener('click', () => { let emailSubs = document.getElementById('emailSubs') if (emailSubs.value == "" || emailSubs.value == null) { alert("email anda kosong") } else if (emailSubs.value.length < 5) { alert("charkater anda terlalu pendek kurang dari 5") } else if (emailSubs.value.length > 25) { alert("charkater anda terlalu panjang melebihi dari 25") } else if (emailSubs.value.indexOf("@") == -1) { alert("format email anda salah") } else { alert("Success") emailSubs.value = "" } })
1b676fe643f061d64ab2ec23f3cba4f09297c2a4
[ "JavaScript" ]
1
JavaScript
AriefDR/blogGogreen
9c9130b2424762602881d90d51fbe999c35d5f87
c7b33dfb8e86bc79c362ad3ca24ea402008a9335
refs/heads/master
<repo_name>abhishek9910/CSC-535_new<file_sep>/vowelCon.java package week3program; public class vowelCon { public static void main(String []args){ System.out.println("Hello World"); printVowels("AbhiSHEK"); printConsonants("Abhishek"); printDigits("ReadDead2@2017"); System.out.println(processExpression("132+5")); } public static void printVowels(String str) { int l = str.length(); String str1 = str.toUpperCase(); Character ch; for (int i=0;i<l;i++) { ch = new Character(str1.charAt(i)); if(ch.equals('A') || ch.equals('E') || ch.equals('I') || ch.equals('O') || ch.equals('U')) System.out.println(str.charAt(i)); } } public static void printConsonants(String str) { int l = str.length(); String str1 = str.toUpperCase(); Character ch; for (int i=0;i<l;i++) { ch = new Character(str1.charAt(i)); if(!(ch.equals('A') || ch.equals('E') || ch.equals('I') || ch.equals('O') || ch.equals('U'))) System.out.println(str.charAt(i)); } } public static void printDigits(String str) { int l = str.length(); char ch; for (int i=0;i<l;i++) { ch = str.charAt(i); if(Character.isDigit(ch)) System.out.println(ch); } } public static int processExpression(String str) { int l = str.length(); Character ch; boolean flag = false; int num1=0, num2=0, index=0; for (int i=0;i<l;i++) { ch = new Character(str.charAt(i)); if(Character.isDigit(ch)) if(flag == false) num1 = (num1*10) + Character.getNumericValue(ch); else num2 = (num2*10) + Character.getNumericValue(ch); else if(ch.equals('+') || ch.equals('-') || ch.equals('/') || ch.equals('*')) { index = i; flag = true; } } ch = str.charAt(index); if(ch == '+') return num1+num2; else if(ch == '-') return num1-num2; else if(ch == '/') return num1/num2; else if(ch == '*') return num1*num2; else return 0; } }
e887f954e2a65fcbba44bc1d1695ed76efc3cca5
[ "Java" ]
1
Java
abhishek9910/CSC-535_new
99865f798f0e09800f0418f9e20db743fc60f612
c3dfc0e410d1021b8665f5dfca0fa2d80790dd91
refs/heads/master
<file_sep><?php header( 'Location: /presents.html' ) ; ?> <file_sep>"use strict"; function createReceiver(name, ocassion, present, ifBought, price) { if (price === 0 || price === "") { return { name: name, ocassion: ocassion, present: present, ifBought: ifBought, price: 0 }; } else { return { name: name, ocassion: ocassion, present: present, ifBought: ifBought, price: price }; } } function renderTableHedings() { let contentDOM = "<th scope='col'> Index </th>\n\ <th scope='col'> Name </th>\n\ <th scope='col'> Occasion </th>\n\ <th scope='col'> Present </th>\n\ <th scope='col'> Bought </th>\n\ <th scope='col'> Price </th>\n\ <th scope='col'> </th>\n"; const keysDOM = document.getElementById("table-keys"); keysDOM.innerHTML = contentDOM; } function renderReceivers(receiversArray) { const employeesDOM = document.getElementById("table-data"); let contentDOM2 = ""; receiversArray.forEach(function(receiver) { contentDOM2 += "<tr>\n<th scope='row'>" + (receiversArray.indexOf(receiver) + 1) + "</th>"; const employeeValues = Object.values(receiver); employeeValues.forEach(function(value) { if (value === true) { contentDOM2 += "<td><i class='fas fa-check'></i></td>"; } else if (value === false) { contentDOM2 += "<td><i class='fas fa-times'></i></td>"; } else { contentDOM2 += "<td>" + value + "</td>"; } }); contentDOM2 += "<td>\ <button type='button' class='btn btn-outline-danger' onclick=\"removeReceiver('" + receiversArray.indexOf(receiver) + "')\"><i class='fas fa-user-times remove-icon'></i>\ </button>\ <button type='button' class='btn btn-outline-success m-1' onclick=\"editReceiver('" + receiversArray.indexOf(receiver) + "')\" data-toggle='modal' data-target='#edit-receiver-form'><i class='fas fa-user-edit edit-icon'></i></button>\ </td>"; contentDOM2 += "</tr>\n"; }); employeesDOM.innerHTML = contentDOM2; document.querySelector("#sum").innerHTML = pricesSum(); } function refresh() { renderReceivers(retrieveEmployeesFromLocalStorage()); } function addANewPerson() { const name = document.querySelector("#name").value; const ocassion = document.querySelector("#ocassion").value; const present = document.querySelector("#present").value; const ifBought = document.querySelector("#is-bought").checked; const price = document.querySelector("#price").value; if (name) { let receivers = retrieveEmployeesFromLocalStorage(); receivers.push(createReceiver(name, ocassion, present, ifBought, price)); updateReceiversInLocalStorage(receivers); } else { alert("Please enter necessary information"); } } function updateReceiversInLocalStorage(receivers) { window.localStorage.setItem("receivers", JSON.stringify(receivers)); renderReceivers(receivers); } function retrieveEmployeesFromLocalStorage() { let retrievedReceivers = localStorage.getItem("receivers"); if (!retrievedReceivers || retrievedReceivers === "[]") { let receivers = []; return receivers; } else { return JSON.parse(retrievedReceivers); } } function pricesSum() { let receivers = retrieveEmployeesFromLocalStorage(); if (receivers.length === 0) { return 0; } return receivers .map(receiver => parseInt(receiver.price)) .reduce((value, sum) => (value += sum)); } let receivers = retrieveEmployeesFromLocalStorage(); renderTableHedings(); renderReceivers(receivers); const refreshBtn = document.querySelector("#refresh"); refreshBtn.addEventListener("click", refresh); const addButton = document.querySelector("#add-receiver"); addButton.addEventListener("click", addANewPerson); function insertExistingValues(name, ocassion, present, ifBought, price) { document.querySelector("#name-edit").setAttribute("value", name); document.querySelector("#ocassion-edit").setAttribute("value", ocassion); document.querySelector("#present-edit").setAttribute("value", present); document.querySelector("#is-bought-edit").checked = ifBought; document.querySelector("#price-edit").setAttribute("value", price); } function editReceiver(index) { let receivers = retrieveEmployeesFromLocalStorage(); let receiver = receivers[index]; insertExistingValues( receiver.name, receiver.ocassion, receiver.present, receiver.ifBought, receiver.price ); document.getElementById("update-receiver").setAttribute("index", index); } document .getElementById("update-receiver") .addEventListener("click", () => updateAPerson()); function updateAPerson() { let index = document.getElementById("update-receiver").getAttribute("index"); const name = document.querySelector("#name-edit").value; const ocassion = document.querySelector("#ocassion-edit").value; const present = document.querySelector("#present-edit").value; const ifBought = document.querySelector("#is-bought-edit").checked; const price = document.querySelector("#price-edit").value; if (name) { let receivers = retrieveEmployeesFromLocalStorage(); receivers[index] = createReceiver(name, ocassion, present, ifBought, price); updateReceiversInLocalStorage(receivers); } else { alert("Please enter necessary information"); } } function removeReceiver(index) { let receivers = retrieveEmployeesFromLocalStorage(); receivers.splice(index, 1); updateReceiversInLocalStorage(receivers); } <file_sep># Presents-List-App A simple project that should be written in ES5 only. An app should enable for: - creating a list of presents' receivers - editing existing receivers - deleting existing receivers - storing information in localstorage To open the app open presents.html file.
88bc8cc6cb20ee8b8957b2b96b0534e4d47f4054
[ "JavaScript", "Markdown", "PHP" ]
3
PHP
agkoryl/Presents-List-App
00fb36a5ecc97daf67237088283befb3832becfa
825f3c497aceaf15cb8f131160c8767960703ec3
refs/heads/main
<repo_name>kslotes/front-control-ingreso<file_sep>/src/components/DatosPersonales.jsx import React, { useState } from "react"; import { Form,Button } from "react-bootstrap"; import "./Formulario.css"; import axios from 'axios'; import { Link, Redirect } from "react-router-dom"; const URL_HOST="http://areco.gob.ar:9528" const DatosPersonales = () => { var persona={}; const[idPersona,setIdPersona]=useState(null); const[correoElectronico,setCorreoElectronico]=useState(); const[direccion,setDireccion]=useState(); const[dni,setDni ] =useState(); const [nombre,setNombre]=useState(); const [telefono,setTelefono]=useState(); const [redirect,setRedirect]=useState(false); const handleChangeDni=(e)=>{ console.log(e.target.value); const dnis=e.target.value axios.get(URL_HOST+"/api/persona/find/dni/"+dnis) .then((res)=>{ if(res.data.success){ setIdPersona(res.data.data.idPersona); setNombre(res.data.data.nombre); setTelefono(res.data.data.telefono); setCorreoElectronico(res.data.data.correoElectronico) setDni(res.data.data.dni) setDireccion(res.data.data.direccion) }else { setDni( e.target.value) setIdPersona(null); setNombre(""); setTelefono(""); setCorreoElectronico("") setDireccion("") } }) } const handleNombre=(event)=>{setNombre(event.target.value)}; const handleTelefono=(event)=>{setTelefono(event.target.value)}; const handleDireccion=(e)=>{setDireccion(e.target.value)}; const handleCorreoElectronico=(e)=>{setCorreoElectronico(e.target.value)}; const handleSubmit=(e)=>{ e.preventDefault(); if (!idPersona) { persona={ correoElectronico:correoElectronico, direccion:direccion, dni:dni, nombre:nombre, telefono:telefono, } console.log("submit",persona) axios.post(URL_HOST+"/api/persona/create",persona) .then((resp)=>{ console.log(resp.data) localStorage.setItem("id_persona", resp.data.data) localStorage.setItem("nombre", nombre) console.log("id_persona",localStorage.getItem("id_persona")) }) .catch((error)=>{console.log(error)}) setRedirect(true) } else { localStorage.setItem("id_persona", idPersona) localStorage.setItem("nombre", nombre) console.log(localStorage.getItem("id_persona")) setRedirect(true) } } //Render o redirect cuando se complete if (redirect) { return <Redirect to="/ddjj"/> }else{ return( <Form className="seccion-container mt-3 mb-3" onSubmit={handleSubmit}> <h2>Datos Personales</h2> <Form.Group controlId="dni"> <Form.Label className="label-preguntas mt-3">Ingrese DNI </Form.Label> <Form.Control type="text" placeholder="Ingrese DNI" onChange={handleChangeDni} /> </Form.Group> <Form.Group controlId="nombreyapellido"> <Form.Label>Nombre y Apellido</Form.Label> <Form.Control required type="text" placeholder="Nombre y Apellido" onChange={handleNombre} value={nombre}/> </Form.Group> <Form.Group controlId="direccion"> <Form.Label>Direccion</Form.Label> <Form.Control required type="text" placeholder="Direccion" onChange={handleDireccion} value={direccion}/> </Form.Group> <Form.Group controlId="telefono"> <Form.Label>Telefono</Form.Label> <Form.Control required type="text" placeholder="Telefono" onChange={handleTelefono} value={telefono} /> </Form.Group> <Form.Group controlId="correo_electronico"> <Form.Label>Correo Electronico</Form.Label> <Form.Control required type="email" placeholder="Correo Electronico" onChange={handleCorreoElectronico} value={correoElectronico}/> </Form.Group> <Button variant="primary" type="submit" className="mt-2">Confirmar</Button> </Form> ) } } export default DatosPersonales;<file_sep>/src/components/NavBarTop.jsx import {Navbar, Nav, Row, Col} from "react-bootstrap"; import {Link} from "react-router-dom"; import NavbarCollapse from "react-bootstrap/esm/NavbarCollapse"; import "./NavBarTop.css"; import {FaTasks} from "react-icons/fa"; import {AiOutlineBarChart} from "react-icons/ai"; const NavBarTop = () => { return ( <Row> <Navbar className="navbar" expand="md"> <Col xs={2} className="text-center "> <Link id="nav-logo" to="/Admin"> UNSAdA </Link> </Col> <Col xs={6} className="justify-content-around"> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <NavbarCollapse> <Nav onSelect={(selectedKey) => alert(`selected ${selectedKey}`)}> <Nav.Item> <Link className="nav-link" to="/AdminDependencias"> <FaTasks className="mr-3" /> Crear Actividad </Link> </Nav.Item> <Nav.Item> <Link className="nav-link" to="/AdminActividades"> <FaTasks className="mr-2" /> Administrar Actividades </Link> </Nav.Item> <Nav.Item> <Link className="nav-link" to="/AdminSeguimientos" eventKey="Mostrar Tabla Asistencia"> <AiOutlineBarChart className="mr-2" /> Seguimientos </Link> </Nav.Item> </Nav> </NavbarCollapse> </Col> </Navbar> </Row> ); }; export default NavBarTop; <file_sep>/src/components/Ddjj.jsx import React, {useState, useEffect,useRef} from "react"; import {Button, Col, Form} from "react-bootstrap"; import axios from "axios"; import "./Formulario.css"; import { Redirect } from "react-router"; const Ddjj = () => { var date; date = new Date(); date = date.getUTCFullYear() + '-' + ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' + ('00' + date.getUTCDate()).slice(-2) + ' ' //+ // ('00' + date.getUTCHours()).slice(-2) + ':' + //('00' + date.getUTCMinutes()).slice(-2) + ':' + //('00' + date.getUTCSeconds()).slice(-2); console.log(date); const inputRef = useRef([]); const [respuestas,setRespuestas]=useState([]); const [preguntas, setPreguntas] = useState([]); const [factorDeRiesgoData, setFactorDeRiesgoData] = useState([]); const [factorDeRiesgo, setFactorDeRiesgo] = useState([]); const [fecha,setFecha]=useState(); const [ddjj,setDdjj]=useState(); const [redirect,setRedirect]=useState(false); const postDdjj=(ddjjs)=>{ if (typeof ddjjs.fecha !== undefined && ddjj.respuestas.length !== 0) { console.log("Data",ddjjs) axios.post("http://areco.gob.ar:9528/api/ddjj/crear/"+localStorage.getItem("id_persona"),ddjj) .then((resp)=>{ console.log("success") console.log(resp.data.data) localStorage.setItem("ddjj", resp.data.data) console.log("ddjj",localStorage.getItem("ddjj")) setRedirect(true); }) .catch((error)=>{console.log(error)}) } } const handleChangeFactor=(fr,nombre)=>{ console.log(fr,nombre) setFactorDeRiesgo(prevState=>[...prevState,{ idFactorDeRiesgo: fr, nombre: nombre, } ]) } const handleSubmit = (event) => { setFecha(date); inputRef.current.map((data,i)=>{ return( setRespuestas(prevState=>[...prevState,{ pregunta:{ idPregunta:i+1 }, afirmativo: !data.checked } ]) ) }) event.preventDefault(); } useEffect(() => { axios.get(`http://areco.gob.ar:9528/api/pregunta/all`).then((res) => { setPreguntas(res.data.data); }); axios.get(`http://areco.gob.ar:9528//api/FactorDeRiesgo/all`).then((res) => { setFactorDeRiesgoData(res.data.data); }); inputRef.current = new Array(preguntas.length); }, []); useEffect( () => { if(preguntas.length !== 0) { inputRef.current[preguntas.length - 1].focus(); } }, [preguntas]); useEffect(() => { setDdjj({ fecha, factorDeRiesgo, respuestas, }) }, [fecha,factorDeRiesgo,respuestas]) useEffect(() => { if (typeof fecha !== undefined && respuestas.length !== 0) { postDdjj(ddjj) } }, [fecha,ddjj,respuestas]) console.log(localStorage.getItem("id_persona")) console.log(localStorage.getItem("nombre")) if (redirect) { return <Redirect to="/solicitud"/> }else{ if (localStorage.getItem("id_persona")!==null) { return ( <> <Form className="seccion-container mb-3" onSubmit={handleSubmit}> <h2 className="subtitulo">Declaración Jurada</h2> <h3 className="subtitulo">{localStorage.getItem("nombre")}</h3> {preguntas.map((pregunta, i) => { return ( <div > <Form.Label className="label-preguntas mt-3">{pregunta.descripcion}</Form.Label> <Form.Check ref = {el => inputRef.current[i] = el} required xs={6} name={"pregunta"+(i+1)} label="Si" key={i} type="radio" /> <Form.Check ref = {el => inputRef.current[i] = el} required xs={6} name={"pregunta"+(i+1)} label="No" key={10+i} type="radio" /> </div> ); })} {/*TODO: Agregar Todo lo que sea factor de riesgo (select con opciones multiples) Cada vez que una persona realiza la DDJJ, hay que serializarla Value tiene que ser un array. Tamaño = cant preguntas Manejar cuando intercambian de opcion en cada pregunta Antes de hacer el PUT aplicar .filter() al array que usamos*/} <h2 className="subtitulo">Si tu situacion de salud contempla alguna de las siguientes opciones,seleccione algunas de las siguientes opciones </h2> {factorDeRiesgoData.map((data,i)=>{ return( <> <Form.Label key={10+i} className="label-preguntas mt-3">{factorDeRiesgo.nombre}</Form.Label> <Form.Check xs={6} name={data.nombre} label="Si" key={i} type="radio" onChange={()=>handleChangeFactor(data.idFactorDeRiesgo,data.nombre)} /> </> ) })} <Button variant="primary" type="submit" >Confirmar</Button> </Form> </> ); }else return <Redirect to="/"/> } }; export default Ddjj; <file_sep>/src/components/AdminSeguimientos.jsx import NavBarTop from "./NavBarTop"; import {useState, useEffect} from "react"; import {Container, Row, Col} from "react-bootstrap"; import TablaSeguimientos from "./TablaSeguimientos"; import "./AdminSeguimientos.css"; import axios from "axios"; const AdminSeguimientos = () => { const [personas, setPersonas] = useState([]) useEffect(() => { const fetchPersonas = async () => { const result = await axios.get("http://areco.gob.ar:9528/api/persona/all"); setPersonas(result.data.data) } fetchPersonas(); }, []); return ( <Container fluid className="fondo"> <NavBarTop /> <Row className="seccion-container mt-4"> <Col> <h2 className="texto-h2">Seguimientos de Personas</h2> </Col> <TablaSeguimientos data={personas}/> </Row> </Container> ); }; export default AdminSeguimientos; <file_sep>/src/components/AdminActividades.jsx import NavBarTop from "./NavBarTop.jsx"; import {Form, Col, Row, Container, Button, InputGroup} from "react-bootstrap"; import "./AdminActividades.css"; import {useState, useEffect} from "react"; import axios from "axios"; const AdminActividades = () => { const [sedes, setSedes] = useState([]); const [aulas, setAulas] = useState([]); const [actividadesSegunPropuesta, setActividadesSegunPropuesta] = useState([]); const [edificios, setEdificios] = useState([]); const [propuestas, setPropuestas] = useState([]); const [sede, setSede] = useState([]); const [fechaInicio, setFechaInicio] = useState([]); const [fechaFin, setFechaFin] = useState([]); const [actividad, setActividad] = useState([]); const [diaSemana, setDiaSemana] = useState(); const [horaInicio, setHoraInicio] = useState(); const [horaFin, setHoraFin] = useState(); const [modalidad, setModalidad] = useState(); const DIAS_SEMANA = ["Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"]; const MODALIDADES = ["Teórico", "Práctico", "Teórico-Práctico"]; let cohorteJSON = {}; let horarioJSON = {}; const handleChangeModalidad = (event) => { console.log(`Soy la modalidad: ${event.target.value}`); setModalidad(event.target.value); }; const handleDiaChange = (event) => { console.log(`Soy el dia: ${event.target.value}`); setDiaSemana(event.target.value); }; const handleHorarioInicio = (event) => { console.log(`Soy el horario de inicio: ${event.target.value}`); setHoraInicio(event.target.value); }; const handleHorarioFin = (event) => { console.log(`Soy el horario de fin: ${event.target.value}`); setHoraFin(event.target.value); }; const handleCreacionHorario = () => { horarioJSON = { dia: diaSemana, horaInicio: horaInicio, horaFin: horaFin, nombre: modalidad } axios.post(`http://areco.gob.ar:9528/api/horaio/`) }; const handleCreacionCohorte = () => { cohorteJSON = { fechaInicio: fechaInicio, fechaFin: fechaFin, }; axios .post(`http://areco.gob.ar:9528/api/cohorte/create/${sede}/${actividad}`, cohorteJSON) .then(() => alert("Cohorte creado satisfactoriamente.")) .catch(() => alert("Error al crear cohorte. Verifique los datos e intente nuevamente")); }; const handleActividad = (event) => { setActividad(event.target.value); }; const handleFechaInicio = (event) => { console.log(`Soy fecha inicio: ${event.target.value}`); setFechaInicio(event.target.value); }; const handleFechaFin = (event) => { console.log(`Soy fecha fin: ${event.target.value}`); setFechaFin(event.target.value); }; const handlePropuesta = (event) => { const fetchActividadesSegunPropuesta = async () => { const result = await axios.get(`http://areco.gob.ar:9528/api/actividad/find/propuesta/${event.target.value}`); setActividadesSegunPropuesta(result.data.data); }; fetchActividadesSegunPropuesta(); }; const handleSede = (event) => { const fetchEdificio = async () => { const result = await axios.get(`http://areco.gob.ar:9528/api/edificio/sede/find/${event.target.value}`); setEdificios(result.data.data); }; fetchEdificio(); setSede(event.target.value); }; const handleChangeEdificio = (event) => { const fetchAula = async () => { const result = await axios.get(`http://areco.gob.ar:9528/api/aula/find/edificio/${event.target.value}`); setAulas(result.data.data); }; fetchAula(); }; useEffect(() => { const fetchPropuestas = async () => { const result = await axios.get("http://areco.gob.ar:9528/api/propuesta/all"); setPropuestas(result.data.data); }; fetchPropuestas(); const fetchSede = async () => { const result = await axios.get("http://areco.gob.ar:9528/api/sede/all"); setSedes(result.data.data); }; fetchSede(); }, []); return ( <Container fluid className="fondo"> <NavBarTop /> <Form> <Row sm={1} className="seccion-container mt-4"> <h2 className="texto-h2">Administrar Actividades</h2> <Row lg={2}> <Col xs={12} sm={12} lg={6}> <Form.Group className="mt-4"> <Form.Label>Propuesta</Form.Label> <Form.Control as="select" onChange={handlePropuesta}> <option selected disabled> Seleccione una </option> {propuestas.map((propuesta) => { return ( <option value={propuesta.idPropuesta} key={propuesta.idPropuesta}> {propuesta.nombre} </option> ); })} </Form.Control> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Actividad</Form.Label> <Form.Control as="select" onChange={handleActividad}> <option selected disabled> Seleccione una </option> {actividadesSegunPropuesta.map((actividad) => { return ( <option value={actividad.idActividad} key={actividad.idActividad}> {actividad.nombre} </option> ); })} </Form.Control> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Sede</Form.Label> <Form.Control as="select" onChange={handleSede}> <option selected disabled> Seleccione una </option> {sedes.map((sede) => { return ( <option value={sede.idSede} key={sede.idSede}> {sede.nombre} </option> ); })} </Form.Control> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Edificio</Form.Label> <Form.Control as="select" onChange={handleChangeEdificio}> <option selected disabled> Seleccione una </option> {edificios.map((edificio) => { return ( <option value={edificio.idEdificio} key={edificio.idEdificio}> {edificio.nombre} </option> ); })} </Form.Control> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Aula</Form.Label> <Form.Control as="select" onChange={handleSede}> <option selected disabled> Seleccione una </option> {aulas.map((aula) => { return ( <option value={aula.idAula} key={aula.idAula}> {aula.nombre} </option> ); })} </Form.Control> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Fecha Inicio</Form.Label> <Form.Control type="date" onChange={handleFechaInicio} /> </Form.Group> <Form.Group className="mt-3"> <Form.Label>Fecha Fin</Form.Label> <Form.Control type="date" onChange={handleFechaFin} /> </Form.Group> <Button className="mt-3 mb-2" variant="success" onClick={handleCreacionCohorte}> Crear Cohorte </Button> </Col> <Col xs={12} sm={12} lg={6}> <Col xs={12} className="text-center"> <h2 className="texto-h2">Seleccionar días y horarios</h2> </Col> <Col xs={12} sm={6} lg={6}> <InputGroup> <InputGroup.Prepend> <InputGroup.Text>Día:</InputGroup.Text> </InputGroup.Prepend> <Form.Control as="select" onChange={handleDiaChange}> <option selected disabled> Seleccione un dia </option> {DIAS_SEMANA.map((dia) => { return ( <option value={dia} key={dia}> {dia} </option> ); })} </Form.Control> </InputGroup> </Col> <Form.Group> <InputGroup className="mt-3"> <InputGroup.Prepend> <InputGroup.Text>Hora Inicio</InputGroup.Text> </InputGroup.Prepend> <Form.Control type="time" onChange={handleHorarioInicio} /> <InputGroup.Append> <InputGroup.Text>Hora Fin</InputGroup.Text> </InputGroup.Append> <Form.Control type="time" onChange={handleHorarioFin} /> </InputGroup> </Form.Group> <Form.Group> <Col xs={12} sm={6} lg={6}> <InputGroup className="mt-3"> <InputGroup.Prepend> <InputGroup.Text>Modalidad</InputGroup.Text> </InputGroup.Prepend> <Form.Control as="select" onChange={handleChangeModalidad}> <option selected disabled> Seleccione una </option> {MODALIDADES.map((modalidad) => { return ( <option value={modalidad} key={modalidad}> {modalidad} </option> ); })} </Form.Control> </InputGroup> </Col> </Form.Group> <Button className="mt-3" variant="success" onClick={handleCreacionHorario}> Agregar Horario </Button> </Col> </Row> </Row> </Form> </Container> ); }; export default AdminActividades;
447f8ef1588a9dac679c9c28d492f29898cfae1c
[ "JavaScript" ]
5
JavaScript
kslotes/front-control-ingreso
b9463da6869f42ab3e00f9a0157fc22e5a330c93
f519cb981853ad4249184bad9db21b9ec275c67c
refs/heads/main
<file_sep>import React, {useState, useEffect} from "react"; export default function Meal({meal}){ const [imageUrl, setImageUrl] = useState(""); useEffect(()=>{ fetch( `https://api.spoonacular.com/recipes/${meal.id}/information?apiKey=<KEY>&includeNutrition=false` ) .then((response) => response.json()) .then((data) => { setImageUrl(data.image) }) .catch(() => { console.log("error") }) }, [meal.id]) return <div className="card mb-3 mx-auto" style={{width: "25rem"}}> <img src = {imageUrl} className="card-img-top" alt = "recipe" /> <div className="card-body"> <h5 className="card-title">{meal.title}</h5> <ul className = "instructions list-group justify-content-center"> <li className="list-group-item">Preparation Time: {meal.readyInMinutes} minutes</li> <li className="list-group-item">Number of Servings: {meal.servings}</li> </ul> <a href = {meal.sourceUrl} target="_blank" >Go to Recipe </a> </div> </div> }<file_sep>Meal Planner App A web application that allows users to get recommended meals based on caloric count and users can save to a meal list. Things to Note: At the moment the Get meals can only pull 150 requests a day Getting Started First npm install Clone the repository to your PC and open run the virtualenvironment using the command: pipenv shell in the directory. Prerequisites An internet browser Knowledge with terminal commands. Change Dir into meal_app Installing Run the command: npm run dev to dev mode Open a new Terminal and Change Dir meal_app using pipenv shell Run the command: python3 manage.py runserver to start the django project Go to http://localhost:8080 *Adjust url according to the instructions given in the terminal if it is changed. Alternatively, use the production website at https://milark.herokuapp.com/#/ Deployment (Frontend) Heroku - https://milark.herokuapp.com/#/ Built With React.js - Frontend Bootstrap- Visual Presentation Axios - Request Handling Django REST Framework - Backend and REST API Authors **Ce-Bit(<NAME>) && aleksiolivier(<NAME>) - code & deployment **Jads121(<NAME>) - report & powerpoint <file_sep>import React, { Component, Fragment } from 'react'; import { withAlert } from 'react-alert'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { addMeal } from '../../actions/meals'; export class Alerts extends Component { static PropTypes = { error: PropTypes.object.isRequired, message: PropTypes.object.isRequired } componentDidUpdate(prevProps) { const { error, alert, message} = this.props if(error !== prevProps.error) { if(error.msg.name) alert.error(`Name: ${error.msg.name.join()}`) if(error.msg.link) alert.error(`Link: ${error.msg.link.join()}`) if(error.msg.non_field_errors) alert.error(error.msg.non_field_errors.join()); if (error.msg.username) alert.error(error.msg.username.join()); } if(message !== prevProps.message) { if(message.mealDeleted) alert.success(message.mealDeleted); if(message.addMeal) alert.success(message.addMeal); if(message.passwordNotMatch) alert.error(message.passwordNotMatch); } } render() { return <Fragment />; } } const mapStateToProps = state => ({ error: state.errors, message: state.messages }) export default connect(mapStateToProps)(withAlert()(Alerts)); <file_sep>import React, { Component, Fragment } from 'react' import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { getMeals, deleteMeal } from '../../actions/meals'; export class Meals extends Component { static propTypes = { meals: PropTypes.array.isRequired, getMeals: PropTypes.func.isRequired, deleteMeal: PropTypes.func.isRequired }; componentDidMount() { this.props.getMeals(); } render() { return ( <Fragment> <h2>Saved Meals</h2> <table className="table table-striped"> <thead> <tr> <th>#</th> <th>Meal</th> <th>Link</th> <th>SavedOn</th> <th>Delete</th> <th /> </tr> </thead> <tbody> { this.props.meals.map( meal => ( <tr key={meal.id}> <td>{meal.id}</td> <td>{meal.name}</td> <td><a href={meal.link} target="_blank" >{meal.link}</a></td> <td>{meal.savedOn}</td> <td><button onClick= {this.props.deleteMeal.bind(this, meal.id)} className="btn btn-danger btn-sm">Delete</button></td> </tr> ))} </tbody> </table> </Fragment> ); } } const mapStateToProps = state => ({ meals: state.meals.meals }); export default connect(mapStateToProps, { getMeals, deleteMeal })(Meals); <file_sep>import { GET_MEALS, DELETE_MEAL, ADD_MEAL, LOGOUT_SUCCESS } from '../actions/types.js' const initialState = { meals: [ ] } export default function(state = initialState, action) { switch(action.type){ case GET_MEALS: return { ...state, meals: action.payload }; case DELETE_MEAL: return { ...state, meals: state.meals.filter(meal => meal.id !== action.payload) }; case ADD_MEAL: return{ ...state, meals: [...state.meals, action.payload] }; case LOGOUT_SUCCESS: return { ...state, leads: [ ] }; default: return state; } }<file_sep>from django.apps import AppConfig class MealFrontendConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'meal_frontend' <file_sep>from django.db import models from django.contrib.auth.models import User # Create your models here. class Meal(models.Model): name = models.CharField(max_length=100) link = models.CharField(max_length=100, unique = True) owner = models.ForeignKey( User, related_name="meals", on_delete=models.CASCADE, null=True) savedOn = models.DateTimeField(auto_now_add=True)<file_sep>from rest_framework import routers from .api import MealViewSet router = routers.DefaultRouter() router.register('api/meal_api', MealViewSet, 'meal_api') urlpatterns = router.urls<file_sep>import React, { Fragment } from 'react'; import Form from './Form'; import Meals from './Meals'; export default function Dashboard() { return ( <Fragment> <Form /> <Meals /> </Fragment> ) } <file_sep>import axios from 'axios'; import { createMessage } from './messages' import { tokenConfig } from './auth' import { GET_MEALS, DELETE_MEAL, ADD_MEAL, GET_ERRORS } from './types'; // GET MEALS export const getMeals = () => (dispatch, getState) => { axios .get('/api/meal_api/' , tokenConfig(getState)) .then(res => { dispatch({ type: GET_MEALS, payload: res.data }); }).catch(err => console.log(err)); }; //DELETE MEAL export const deleteMeal = (id) => (dispatch, getState) => { axios .delete(`/api/meal_api/${id}/`, tokenConfig(getState)) .then(res => { dispatch(createMessage({ mealDeleted: "Meal Deleted"})); dispatch({ type: DELETE_MEAL, payload: id }); }).catch(err => console.log(err)); }; //ADD MEAL export const addMeal = (meal) => (dispatch, getState) => { axios .post("/api/meal_api/", meal, tokenConfig(getState)) .then(res => { dispatch(createMessage({ addMeal: "Meal Added"})); dispatch({ type: ADD_MEAL, payload: res.data }); }).catch((err) => dispatch(returnErrors(err.response.data, err.response.status))); };<file_sep>from .models import Meal from rest_framework import viewsets, permissions from .serializers import MealSerializer # Meal ViewSet class MealViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = MealSerializer def get_queryset(self): return self.request.user.meals.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) <file_sep>from django.shortcuts import render def index(request): return render(request, 'meal_frontend/index.html')<file_sep>import React from "react"; import Meal from "./Meal"; export default function MealList({mealData}){ const nutrients = mealData.nutrients; return <main> <section className = "nutrients mx-auto justify-content-center" > <h1>Macros</h1> <ul className="list-group mb-3 mx-auto justify-content-center"> <li className="list-group-item">Calories: {nutrients.calories.toFixed(0)}</li> <li className="list-group-item">Carbohydrates: {nutrients.carbohydrates.toFixed(0)}</li> <li className="list-group-item">Fat: {nutrients.fat.toFixed(0)}</li> <li className="list-group-item">Protein: {nutrients.protein.toFixed(0)}</li> </ul> </section> <section className = "meals mx-auto mb-3 justify-content-center"> {mealData.meals.map((meal) =>{ return <Meal key={meal.id} meal={meal} /> })} </section> </main> }
6e7ddde2fad7605933314302389b0942e464c738
[ "JavaScript", "Python", "Markdown" ]
13
JavaScript
Ce-bit/Meal_Planner_App
e1cd47c8d3f6bf064f45a434b06a52ed13be18ba
230f4107b92d54abc1332136374595660a1d216e
refs/heads/master
<repo_name>AdamOrtolf/reactEmployeeDir<file_sep>/src/components/GenerateEmployees.js import React, {Component} from "react"; import API from "../utils/API"; import SearchFilter from "./SearchFilter"; import ResultSearch from "./ResultSearch"; class GenerateEmployees extends Component { // need to create a state variable that can be used to generate results based upon search keyword. state = { search: "", results: [], order: "ascend" // !!ASK BRIAN IF THIS SHOULD BE "ASCEND" OR "ASCENDING", can't seem to find appropriate syntax on google } handleInputChange = event => { console.log("input change occured" + event) const search = event.target.name; const value = event.target.value; this.setState({ [search]: value }); }; componentDidMount() { this.apiCall();} // ask brian if I need anything inside parenthesis of this.apiCall(HERE)// apiCall = () => { API.search().then(res => this.setState({ results: res.data.results})).catch(error => console.log(error)); } searchArray = () => { const matchingName = [...this.state.results].sort((b, a) => b.name.first > a.name.first ? 1 : -1) this.setState({...this.state, results: matchingName}) } // ill need an API call function plus a componentDidMount, a handleinputchange and a function to render array of names based upon this.state.search render () { return( <> <div> <SearchFilter handleInputChange={this.handleInputChange} search={this.state.search} /> <br></br> <br></br> <ResultSearch results={this.state.results} matchingName={this.matchingName} search={this.state.search} order={this.state.order} /> </div> <footer> <strong>IF NO EMPLOYEES SHOW FROM YOUR SEARCH THEN EMPLOYEE WAS NOT FOUND IN DATABASE.</strong> </footer> </> ) } } export default GenerateEmployees;<file_sep>/src/utils/Api.js import axios from "axios"; export default { search: function() { return axios.get("https://randomuser.me/api/?results=100") } }; // EXAMPLE OBJECT FROM API CALL BELOW!!! // EXAMPLE OBJECT FROM API CALL BELOW!!! // EXAMPLE OBJECT FROM API CALL BELOW!!! // "gender": "female", // "name": { // "title": "Mrs", // "first": "Anita", // "last": "Akbari" // }, // "location": { // "street": { // "number": 1894, // "name": "Thulstrups gate" // }, // "city": "Mogrenda", // "state": "Hordaland", // "country": "Norway", // "postcode": "3300", // "coordinates": { // "latitude": "52.0264", // "longitude": "167.1356" // }, // "timezone": { // "offset": "+5:45", // "description": "Kathmandu" // } // }, // "email": "<EMAIL>", // "login": { // "uuid": "107c3d85-45b1-4d39-a5fe-550b42348c83", // "username": "tinyfrog420", // "password": "<PASSWORD>", // "salt": "<PASSWORD>", // "md5": "9b93a083bf1c20986953de4078c080b5", // "sha1": "d73ec6025abd2c6d59a15b2aea1b373dfea144ec", // "sha256": "4db241eee4817fc8b9e7f623a9c06bfb6d275128dc3036bba5c4cf7d3c3a5765" // }, // "dob": { // "date": "1945-02-16T18:31:36.672Z", // "age": 75 // }, // "registered": { // "date": "2015-03-05T10:05:22.165Z", // "age": 5 // }, // "phone": "21257521", // "cell": "99838732", // "id": { // "name": "FN", // "value": "16024505646" // }, // "picture": { // "large": "https://randomuser.me/api/portraits/women/25.jpg", // "medium": "https://randomuser.me/api/portraits/med/women/25.jpg", // "thumbnail": "https://randomuser.me/api/portraits/thumb/women/25.jpg" // }, // "nat": "NO" // },
20a589ce7aaf536e9e8a480c4a036214aca22609
[ "JavaScript" ]
2
JavaScript
AdamOrtolf/reactEmployeeDir
ee9f032f0093262ea47b166a991d74212a4ed962
0b0956ac2ee3f7c68afe3c47cc724c12c78256bf
refs/heads/master
<file_sep>module.exports = { IP:'10.0.0.169', PORT: 50541, MOVE_UP_KEY: "w", MOVE_DOWN_KEY: "s", MOVE_LEFT_KEY: "a", MOVE_RIGHT_KEY: "d", EXIT_KEY: '\u0003', };<file_sep># -snake-client
4cc7f74535561c9d31c3ea161e28a6eac350c44e
[ "JavaScript", "Markdown" ]
2
JavaScript
RongxinZhang/-snake-client
16b6a1b2bb0485e894f390dc5c3bce55105638a3
4167bb83be4ffe6ae8d2670e68e12d7cf1e4a700
refs/heads/master
<file_sep># RedisResourceMap COVID-19 Resource Dashboard is a project leveraging the power of RediSearch, RedisGears, and Redis PubSub to create a live-updating, crowdsourced dashboard to connect places with excess supply of masks, oxygen, and vaccines to places lacking in such supplies. Users can add locations to indicate both excess supply and required resources, and the RedisGears matching engine will utilize the power of RediSearch geospatial querying to match up supplies with requirements. ## How data is stored - Resource and location data are stored as documents in the RediSearch format. They contain the fields: - masks (Numerical) - vaccines (Numerical) - oxygen (Numerical) - updated (Numerical) - coords (Geo) ## How data is processed - Data is inserted (as RediSearch documents) using the `HSET` command. Details on query construction are abstracted away with the `RediSearch` Python API, but the fields are as mentioned above - Data is queried using `FT.SEARCH`: - Since this uses geospatial querying, heavy use of `GEORADIUS`/geospatial query syntax is used - Example query: `FT.SEARCH @coords[long lat radius km] FILTER masks 1 10000 INKEYS 1 -76,40` - Update are published with PUBLISH and read with SUBSCRIBE - New data is processed with RedisGears async jobs, and sent via Redis PubSub on either the `new_data` channel or `match_data` channel (if a resource is matched) - Example: `PUBLISH new_data "{masks: 10, ...}"`, `SUBSCRIBE new_data` ## Screenshots ### Architecture Diagram ![Architecture](https://raw.githubusercontent.com/pranavmk98/RedisResourceMap/master/img/architecture.png) ![Main Page](https://raw.githubusercontent.com/pranavmk98/RedisResourceMap/master/img/MainPage.jpg) ![Match graph](https://raw.githubusercontent.com/pranavmk98/RedisResourceMap/master/img/Graph.jpg) ## Instructions - Run the Redis labs RedisModules docker image: `docker run -p 6379:6379 redislabs/redismod` - Using pip and python 3.7, install the requirements in `requirements.txt`, or create a Conda environment using `conda env create --file conda_env.yml` and then run `conda activate redis` to activate the environment. - Run `python server.py` from `backend/`. This will create a server accessible at `localhost:5000` - Install node.js and npm if you do not already have it installed (see [https://nodejs.org/en/download/](https://nodejs.org/en/download/)). Then run `npm install` and `npm start` from `frontend/`, and the React frontend should appear in your web browser at `localhost:3000/admin/dashboard` <file_sep>import time import redis import json from redis_json import RedisJson from redis_search import RediSearch, NumericFilter, GeoFilter from redis_gears import create_gears_jobs from flask import Flask, request, jsonify from flask_cors import CORS from flask_socketio import SocketIO, emit ''' Flask server to interface with Redis APIs ''' ############# ## Globals ## ############# # RediSearch index name INDEX = 'resource_map' # Numeric fields in RediSearch NUMERIC_FIELDS = [ 'masks', 'vaccines', 'oxygen', 'updated', # last updated unix time in seconds ] # Geospatial fields in RediSearch GEO_FIELDS = [ 'coords', ] # Socket namespace to publish updates on SOCKET_NAMESPACE = '' GEARS_JOB_RUNNING = False # Not really int max, but hopefully numbers don't exceed this for our purposes # (I think this is 10 billion) INT_MAX = 10000000000 app = Flask(__name__) CORS(app) # TODO: install eventlet if this is too slow socket_app = SocketIO(app, cors_allowed_origins='*') redisJson = RedisJson() rediSearch = RediSearch(INDEX, NUMERIC_FIELDS, GEO_FIELDS) redisClient = redis.Redis(host='localhost', port=6379) ################ ## Helper fns ## ################ ''' Given long + lat, construct key to store data at ''' def get_key(lat, long): return f'{long},{lat}' ''' Given long + lat + radius, construct name of socket namespace ''' def get_socket_namespace(lat, long, radius): return f'{abs(long)}_{abs(lat)}_{radius}' ###################### ## Server endpoints ## ###################### ''' Endpoint to insert JSON data @requires 'lat' and 'long' keys to exist in the data Example of expected POST data: { 'lat': 10.573, 'long': -48.62, 'masks': 500, 'vaccines': 345, 'oxygen': 23 } ''' @app.route('/insert', methods=['POST']) def insert_data(): json = request.json if 'lat' in json and 'long' in json: key = get_key(json['lat'], json['long']) rediSearch.insert_doc( key, masks=(0 if 'masks' not in json else json['masks']), vaccines=(0 if 'vaccines' not in json else json['vaccines']), oxygen=(0 if 'oxygen' not in json else json['oxygen']), updated=time.time(), coords=key ) return jsonify({'lat': json['lat'], 'long': json['long']}), 200 return "Bad request", 400 ''' Endpoint to retrieve existing data by filter @requires 'lat' and 'long' and 'radius' keys to exist in the data Note: Can only filter by 1 numeric quantity (RediSearch restriction) Example of expected POST data: { 'lat': 10.573, 'long': -48.62, 'radius': 25, (in kilometers) 'numeric': 'masks' [optional arg] } Return JSON data format: { 'results' : [ { 'lat': 10.573, 'long': -48.62, 'masks': 500, 'vaccines': 345, 'oxygen': 23, 'updated': 18727939423 }, ... ], 'namespace' : 'socket_namespace_1' } ''' @app.route('/get', methods=['POST']) def get_data(): global GEARS_JOB_RUNNING json = request.json if 'lat' in json and 'long' in json: lat, long, radius = json['lat'], json['long'], json['radius'] key = get_key(lat, long) geo_filter = GeoFilter('coords', long, lat, radius, unit='km') # Note: sort of hard coding this "must be >= 1" check, but if we feel # that we need more flexible queries we can look into making this more # customizable later numeric_filter = NumericFilter(json['numeric'], 1, INT_MAX) if 'numeric' in json else None results = rediSearch.get(numeric_filter=numeric_filter, geo_filter=geo_filter) # This looks like a bottleneck at scale, but we probably don't have to # worry about this for now response = [] for doc in results: longlat = doc.coords.split(',') # "long,lat" response.append({ 'lat' : longlat[1], 'long' : longlat[0], 'masks': doc.masks, 'vaccines': doc.vaccines, 'oxygen' : doc.oxygen, 'updated' : doc.updated, }) # SOCKET_NAMESPACE = get_socket_namespace(lat, long, radius) if not GEARS_JOB_RUNNING: create_gears_jobs(lat, long, radius) GEARS_JOB_RUNNING = True return {'results' : response, 'namespace' : SOCKET_NAMESPACE}, 200 return "Bad request", 400 ''' Process message received from Redis PubSub channels and push it onto websocket Format of new data: { 'masks': 20, 'vaccines': 30, 'oxygen': 40, 'updated': 16979930.9901 'coords': '-10.0,15.0' (long,lat) } Format of match data (e.g. for masks): { 'masks_match': 1, 'qty': 40, 'need_lat': 15.0, 'need_long': -10.0, 'has_lat': 15.2, 'has_long': -10.1, 'distance': 450 (in km) } ''' def process_channel_msg(msg): if msg['type'] == 'message': with app.test_request_context(): data = msg['data'].decode('utf-8') json_data = json.dumps(data) socket_app.emit('message', data, namespace=SOCKET_NAMESPACE) if __name__ == "__main__": pubsub = redisClient.pubsub() pubsub.subscribe(**{'new_data': process_channel_msg, 'match_data': process_channel_msg}) pubsub.run_in_thread(sleep_time=0.1) socket_app.run(app) <file_sep>/*! ========================================================= * Paper Dashboard React - v1.2.0 ========================================================= * Product Page: https://www.creative-tim.com/product/paper-dashboard-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/paper-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import RTChart from 'react-rt-chart'; import './styles.css' // reactstrap components import { Card, CardHeader, CardBody, CardTitle, Row, Col, } from "reactstrap"; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive } class MatchedDashboard extends React.Component { componentDidMount() { setInterval(() => this.forceUpdate(), 1000); } render() { var data = { date: new Date(), Masks: getRandomInt(0, 4000), Oxygen: getRandomInt(0, 4000), Vaccines: getRandomInt(0, 4000) }; return ( <> {/* <link rel="stylesheet" href="https://raw.githubusercontent.com/c3js/c3/master/c3.css"></link> */} <div className="content"> <Row> <Col md="12"> <Card> <CardHeader> <CardTitle tag="h4">Matched Resources</CardTitle> </CardHeader> <CardBody> <RTChart fields={['Masks', 'Oxygen', 'Vaccines']} data={data} /> </CardBody> </Card> </Col> </Row> </div> </> ); } } export default MatchedDashboard; <file_sep>bidict==0.21.2 click==7.1.2 cloudpickle==1.6.0 Flask==1.1.2 Flask-Cors==3.0.10 Flask-SocketIO==5.0.1 gearsclient==1.0.1 hiredis==2.0.0 itsdangerous==1.1.0 Jinja2==2.11.3 MarkupSafe==1.1.1 python-engineio==4.1.0 python-socketio==5.2.1 redis==3.5.3 redisearch==2.0.0 rejson==0.5.4 rmtest==0.7.0 six==1.16.0 Werkzeug==1.0.1 <file_sep>from redisearch import * class RediSearch: ''' Create a RediSearch index using the given index, numeric fields, and geo fields. ''' def __init__(self, index, numeric_fields, geo_fields): self._rsearch = Client(index) fields = [GeoField(geo) for geo in geo_fields] + [NumericField(num) for num in numeric_fields] self._rsearch.create_index(fields) ''' Insert document to be indexed Note: kwargs passed in must have been present on RediSearch() creation ''' def insert_doc(self, key, **kwargs): self._rsearch.add_document(key, **kwargs) ''' Return list of all documents, filtered by numeric_filter and geo_filter (if passed in) ''' def get(self, query_string='*', numeric_filter=None, geo_filter=None): query = Query(query_string) if numeric_filter: query = query.add_filter(numeric_filter) if geo_filter: query = query.add_filter(geo_filter) result = self._rsearch.search(query) return result.docs ''' Update a document and reindex it ''' def update(self, key, **kwargs): self._rsearch.add_document(key, replace=True, **kwargs) ''' Delete a document ''' def delete(self, key): self._rsearch.delete_document(key) <file_sep>/*! ========================================================= * Paper Dashboard React - v1.2.0 ========================================================= * Product Page: https://www.creative-tim.com/product/paper-dashboard-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/paper-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import ResourceDashboard from "views/ResourceDashboard.js"; import MatchedDashboard from "views/MatchedDashboard"; var routes = [ { path: "/dashboard", name: "Resource Dashboard", icon: "nc-icon nc-bank", component: ResourceDashboard, layout: "/admin", }, { path: "/matches", name: "Matched Resources", icon: "nc-icon nc-bank", component: MatchedDashboard, layout: "/admin", }, ]; export default routes; <file_sep>/*! ========================================================= * Paper Dashboard React - v1.2.0 ========================================================= * Product Page: https://www.creative-tim.com/product/paper-dashboard-react * Copyright 2020 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/paper-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import { withScriptjs, withGoogleMap, GoogleMap, Marker, } from "react-google-maps"; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import { cloneDeep } from 'lodash'; // reactstrap components import { Button, Card, CardHeader, CardBody, CardTitle, CardFooter, FormGroup, Form, Input, Row, Col, Label, } from "reactstrap"; import socketIOClient from 'socket.io-client'; const MapWrapper = withScriptjs( withGoogleMap((props) => { return ( <GoogleMap defaultZoom={10} center={{ lat: props.centerLat, lng: props.centerLong }} defaultOptions={{ scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page disableDefaultUI: true, zoomControl: true, styles: [ { featureType: "water", stylers: [ { saturation: 43, }, { lightness: -11, }, { hue: "#0088ff", }, ], }, { featureType: "road", elementType: "geometry.fill", stylers: [ { hue: "#ff0000", }, { saturation: -100, }, { lightness: 99, }, ], }, { featureType: "road", elementType: "geometry.stroke", stylers: [ { color: "#808080", }, { lightness: 54, }, ], }, { featureType: "landscape.man_made", elementType: "geometry.fill", stylers: [ { color: "#ece2d9", }, ], }, { featureType: "poi.park", elementType: "geometry.fill", stylers: [ { color: "#ccdca1", }, ], }, { featureType: "road", elementType: "labels.text.fill", stylers: [ { color: "#767676", }, ], }, { featureType: "road", elementType: "labels.text.stroke", stylers: [ { color: "#ffffff", }, ], }, { featureType: "poi", stylers: [ { visibility: "off", }, ], }, { featureType: "landscape.natural", elementType: "geometry.fill", stylers: [ { visibility: "off", }, { color: "#b8cb93", }, ], }, { featureType: "poi.park", stylers: [ { visibility: "off", }, ], }, { featureType: "poi.sports_complex", stylers: [ { visibility: "off", }, ], }, { featureType: "poi.medical", stylers: [ { visibility: "off", }, ], }, { featureType: "poi.business", stylers: [ { visibility: "off", }, ], }, { featureType: "transit", stylers: [ { visibility: "off", } ] } ], }} > {props.locations.map((loc, idx) => <Marker position={{ lat: parseFloat(loc.lat), lng: parseFloat(loc.long) }} key={idx}/>)} </GoogleMap> ); }) ); class ResourceDashboard extends React.Component { constructor(props) { super(props) this.state = { centerLat: 0, centerLong: 0, radius: 100000, numLocations: 0, locations: [], namespace: '', checkedMasks: false, checkedVaccines: false, checkedOxygen: false, inputLat: 0, inputLong: 0, inputExcessResources: true, inputResourceType: 'masks', inputResourceQuantity: 0, } this.handleFilterChange = this.handleFilterChange.bind(this); this.handleInputResourceExcessChange = this.handleInputResourceExcessChange.bind(this); this.handleInputResourceTypeChange = this.handleInputResourceTypeChange.bind(this); this.handleInputResourceQuantityChange = this.handleInputResourceQuantityChange.bind(this); } componentDidMount() { this.getCenterLatLong(); } getCenterLatLong() { navigator.geolocation.getCurrentPosition((position) => { this.setState({ centerLat: position.coords.latitude, centerLong: position.coords.longitude, inputLat: position.coords.latitude, inputLong: position.coords.longitude }); this.fetchData(); }); } fetchData() { const url = "http://localhost:5000/get" return fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ lat: this.state.centerLat, long: this.state.centerLong, radius: this.state.radius, }) }) .then(response => response.json()) .then(data => { this.setState({locations: data.results, namespace: data.namespace}); this.connectWebsocket(); }) .catch(error => console.log(error)) } connectWebsocket() { let socketEndpoint = "localhost:5000/" + this.state.namespace; this.socket = socketIOClient(socketEndpoint); this.socket.on('connect', (message)=> {}); this.socket.on('message', (message) => { message = message.replace(/'/g, '"'); let jsonData = JSON.parse(message); let lat_long = jsonData['coords'].split(',') let lat = lat_long[0] let long = lat_long[1] let newLocations = cloneDeep([...this.state.locations, {lat: lat, long: long, updated: jsonData['updated']}]); this.setState({ locations: newLocations, numLocations: this.state.numLocations++ }); this.fetchData(); }) } addLocation = () => { const url = "http://localhost:5000/insert" let body = { lat: this.state.inputLat + Math.random(), long: this.state.inputLong + Math.random(), } if (this.state.inputExcessResources) { body[this.state.inputResourceType] = this.state.inputResourceQuantity } else { body[this.state.inputResourceType] = -this.state.inputResourceQuantity } fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(body) }) .then(response => response.json()) .then(data => {}) .catch(error => console.log(error)) return false; } handleInputResourceExcessChange(event) { if (event.target.value == "I Have Resources to Give") { this.setState({ inputExcessResources: true }); } else { this.setState({ inputExcessResources: false }); } } handleInputResourceTypeChange(event) { this.setState({ inputResourceType: event.target.id }); } handleInputResourceQuantityChange(event) { this.setState({ inputResourceQuantity: event.target.value }); } fetchDataFiltered(field) { const url = "http://localhost:5000/get" return fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ lat: 0.1, long: 0.1, radius: 10000000, numeric: field }) }) .then(response => response.json()) .then(data => { this.setState({locations: data.results}); } ) .catch(error => console.log(error)) } handleFilterChange = (event) => { // For some reason the setState function isn't working, but this does this.state[[event.target.name]] = event.target.checked; if (this.state.checkedMasks) { this.fetchDataFiltered('masks'); } else if (this.state.checkedVaccines) { this.fetchDataFiltered('vaccines'); } else if (this.state.checkedOxygen) { this.fetchDataFiltered('oxygen'); } else { this.fetchData(); } }; render() { return ( <> <div className="content"> <Row> <Col sm="12" lg="8"> <Card> <CardHeader> <CardTitle tag="h5">View Existing Resource Requests</CardTitle> </CardHeader> <CardBody> <div id="map" className="map" style={{ position: "relative", overflow: "hidden" }} > <MapWrapper googleMapURL="https://maps.googleapis.com/maps/api/js?key=<KEY>" loadingElement={<div style={{ height: `100%` }} />} containerElement={<div style={{ height: `100%` }} />} mapElement={<div style={{ height: `100%` }} />} centerLat={this.state.centerLat} centerLong={this.state.centerLong} locations={this.state.locations} key={this.state.numLocations} /> </div> <CardFooter> <div className="card-stats"> <i className="nc-icon nc-compass-05" /> Filter resources on Map </div> <FormGroup> <FormControlLabel control={<Checkbox checked={this.state.checkedMasks} onChange={this.handleFilterChange} name="checkedMasks" />} label="Masks" color="red" /> <FormControlLabel control={<Checkbox checked={this.state.checkedVaccines} onChange={this.handleFilterChange} name="checkedVaccines" />} label="Vaccines" color="blue" /> <FormControlLabel control={<Checkbox checked={this.state.checkedOxygen} onChange={this.handleFilterChange} name="checkedOxygen" />} label="Oxygen" color="green" /> </FormGroup> </CardFooter> </CardBody> </Card> </Col> <Col sm="12" lg="4"> <Card className="card-user"> <CardHeader> <CardTitle tag="h5">Create Resource Request</CardTitle> </CardHeader> <CardBody> <Form> <Row> <Col> <FormGroup> <label>Do you have a surplus or deficit of resources?</label> <Input type="select" onChange={this.handleInputResourceExcessChange}> <option>I Have Resources to Give</option> <option>I Need Resources</option> </Input> </FormGroup> </Col> </Row> <Row> <Col className="pc-1" md="12"> <FormGroup tag="fieldset" onChange={this.handleInputResourceTypeChange}> <label>What type of resources are you interested in? </label> <FormGroup check> <Label check> <Input type="radio" name="radio1" id="masks"/>{' '} Masks </Label> </FormGroup> <FormGroup check> <Label check> <Input type="radio" name="radio1" id="vaccines"/>{' '} Vaccines </Label> </FormGroup> <FormGroup check> <Label check> <Input type="radio" name="radio1" id="oxygen"/>{' '} Oxygen </Label> </FormGroup> </FormGroup> </Col> <Col className="pc-1" md="12"> <FormGroup> <label>Quantity of Resources</label> <Input defaultValue="0" placeholder="0" type="number" onChange={this.handleInputResourceQuantityChange} /> </FormGroup> </Col> </Row> <Row> <Col className="pr-1" md="6"> <FormGroup disabled > <label>Latitude</label> <div className="update ml-auto mr-auto"> {this.state.centerLat} </div> </FormGroup> </Col> <Col className="pl-1" md="6"> <FormGroup disabled > <label>Longitude</label> <div className="update ml-auto mr-auto"> {this.state.centerLong} </div> </FormGroup> </Col> </Row> <Row> <div className="update ml-auto mr-auto"> <Button className="btn-round" color="primary" type="button" onClick={this.addLocation} > Add Resource Request to Map </Button> </div> </Row> </Form> </CardBody> </Card> </Col> </Row> </div> </> ); } } export default ResourceDashboard; <file_sep>from gearsclient import GearsRemoteBuilder as GB from gearsclient import execute, log INDEX = 'resource_map' INT_MAX = 10000000000 ''' Register RedisGears jobs ''' def create_gears_jobs(lat, long, radius): # Function to execute on each added key def publish_new_data(x): # Use geospatial querying from RediSearch args = [INDEX, f'@coords:[{long} {lat} {radius} km]', 'INKEYS', 1, x['key']] results = execute('FT.SEARCH', *args) if str(results) == "0": return # Nasty, lots of hardcoding, assumes result format: result = results[2] if len(result) % 2 != 0: return # Publish update on pubsub channel output_dict = {result[i] : result[i + 1] for i in range(0, len(result), 2)} execute('PUBLISH', 'new_data', str(output_dict)) # Function to match up required resources with existing ones def get_match_resource(resource): def match_resource(x): import ast new_data = ast.literal_eval(str(x['value'])) long, lat = new_data['coords'].split(',') if int(new_data[resource]) >= 0: return required = abs(int(new_data[resource])) # Use geospatial querying from RediSearch to find closest # matching location results = None log(str(resource) + "," + str(required) + "," + str(radius)) for radi_iter in range(1, radius + 1): args = [ INDEX, f'@coords:[{long} {lat} {radi_iter} km]', 'FILTER', resource, required, INT_MAX, 'LIMIT', 0, 1 ] results = execute('FT.SEARCH', *args) if str(results) != "[0]": break # If no available locations, return if not results: return results_py = ast.literal_eval(str(results)) first_result = results_py[2] data_dict = {first_result[i] : first_result[i + 1] for i in range(0, len(first_result), 2)} data_dict[resource + '_match'] = 1 has_long, has_lat = data_dict['coords'].split(',') output_data = {} output_data[resource + '_match'] = 1 output_data['qty'] = required output_data['need_lat'] = lat output_data['need_long'] = long output_data['has_lat'] = has_lat output_data['has_long'] = has_long output_data['distance'] = radi_iter execute('PUBLISH', 'match_data', str(output_data)) return match_resource redisGears = GB('KeysReader').foreach(publish_new_data).register(prefix='*', eventTypes=['hset', 'hmset']) redisGears = GB('KeysReader').foreach(get_match_resource('masks')).register(prefix='*', eventTypes=['hset', 'hmset']) redisGears = GB('KeysReader').foreach(get_match_resource('vaccines')).register(prefix='*', eventTypes=['hset', 'hmset']) redisGears = GB('KeysReader').foreach(get_match_resource('oxygen')).register(prefix='*', eventTypes=['hset', 'hmset']) <file_sep>from rejson import Client, Path class RedisJson: def __init__(self): self._rjson = Client(host='localhost', port=6379, decode_responses=True) self._root_path = Path.rootPath() ''' Insert JSON into db Structure of JSON to insert: { 'lat' : 80.844, 'long' : -43.139, 'resources' : { 'mask' : 450, 'vaccine' : 56, 'oxygen' : 800, ... }, 'updated' : <unix time ms> } ''' def insert(self, key, data): self._rjson.jsonset(key, self._root_path, data) ''' Return list of all JSON objects stored in db TODO: added this for now, but loading everything in memory doesn't seem like a great idea, maybe RedisSearch will help with this. Or maybe make this return a generator which can be iterated through ''' def get(self): results = [] for key in self._rjson.scan_iter(): results.append(self._rjson.jsonget(key, self._root_path)) return results ''' Update field of a JSON object in db Syntax for `path` argument: E.g. we have { 'key1' : value1, 'key2' : { 'key3' : value2 } } To update value2, `path` should be ".key2.key3" ''' def update(self, key, path, new_value): self._rjson.jsonset(key, path, new_value) ''' Delete a JSON value from the db ''' def delete(self, key): self._rjson.jsondel(key, self._root_path)
b94cfd9f2487f4e2e69938aa33a6254e81874cd4
[ "Markdown", "Python", "JavaScript", "Text" ]
9
Markdown
pranavmk98/RedisResourceMap
f0cb22c4d63cdcfb56bfbfa645529577dcb3a60a
7a02d7db4a197a35134dfb7cf9daa30321607e37
refs/heads/master
<repo_name>ez-webcomponents/ez-groupby-tree-mixin<file_sep>/src/components/ez-groupby-tree-mixin.js /** @license Copyright (c) 2018 <NAME> This program is available under MIT license, available at https://github.com/ez-webcomponents/ez-groupby-tree-mixin */ /** * @file ez-groupby-tree-mixin.js * @author <NAME> <<EMAIL>> * @description * A mixin to add javascript 'groupby' cababilities to a data set using recursive tree processing. * Note: Mainly useful for getting data in a format to be visualized in drilldown graphs. */ /* @polymerMixin */ export const EzGroupbyTreeMixin = (superclass) => class extends superclass { //globalColors = ["#7cb5ec", "#434348", "#90ed7d", "#f7a35c", "#8085e9", "#f15c80", "#e4d354", "#2b908f", "#f45b5b", "#91e8e1"]; /** * @function groupBy() * @author <NAME> <<EMAIL>> * Groups up the 'data' into a tree object based on the 'groups' parameter. * * @param data An array of objects that is to be grouped up * @param groups An array of objects that represents the order in which the data is to be grouped up. * @param fullGropuBy Same as 'groups' except that it contained the full groupby array each time through the recursion. * @param func The function to use on each grouping. Default is aggFunction() * @param pathFunc The path function to use on each grouping. Default is pathAgFunction() * * Given a 'data' set with the follows fields: * [{ * "_id": "1", * "revenue": "112", * "division": "Development", * "company": "Nucore", * "startdate": "2018-01-01", * "age": "10", * "eyeColor": "green", * "name": "<NAME>", * "gender": "Male" * },{ * ... * }] * * Example of 'groups' Object: * var groups = [ * {"field": "company", * "datasets": [ * {"label": "Sum of Ages", "backgroundcolor": "rgba(255, 99, 132, 0.2)", "bordercolor": "rgba(255, 99, 132, 0.9)", "data": "sum(age)", "type": "line"}, * {"label": "Sum Revenue", "backgroundcolor": "rgba(54, 162, 235, 0.2)", "bordercolor": "rgba(54, 162, 235, 0.9)", "data": "sum(revenue)", "type": "bar"} * ], * {"field": "date_trunc(month,startdate)", * "datasets": [ * {"label": "Sum Ages", "backgroundcolor": "rgba(255, 99, 132, 0.2)", "bordercolor": "rgba(255, 99, 132, 0.2)", "data": "sum(age)", "type": "line"}, * {"label": "Revenue", "backgroundcolor": "rgba(54, 162, 235, 0.2)", "bordercolor": "rgba(54, 162, 235, 0.2)", "data": "sum(revenue)", "type": "bar"} * ], * {"field": "division", * "datasets": [ * {"label": "Revenue", "backgroundcolor": "#8e95cd", "bordercolor": "#8e95cd", "data": "sum(revenue)", "type": "stackedbar"}, * {"label": "Sum Ages", "backgroundcolor": "rgba(54, 162, 235, 0.2)", "bordercolor": "rgba(54, 162, 235, 0.9)", "data": "sum(age)", "type": "stackedbar"} * ]}, * {"field": "age", * "datasets": [ * {"label": "Revenue", "backgroundcolor": "#8e95cd", "bordercolor": "#8e95cd", "data": "sum(revenue)", "type": "bar"} * ]}, * {"field": "gender", * "datasets": [ * {"label": "Revenue", "backgroundcolor": "#8e95cd", "bordercolor": "#8e95cd", "data": "sum(revenue)", "type": "line"} * ]} * ]; * * * @return returns a Tree Object which has the data grouped up in each node of the tree * The first level of the tree represents the first groupby field specififed in the 'groups' object. * The second level of the tree represents the first & second groupby fields specified in the 'groups' object. * the third level ... etc, etc... */ groupBy(data, groups, fullGroupBy, aggFunc = this.aggFunction, pathAggFunc = this.pathAggFunction) { if (groups.length == 0) { //base case -- this returns the leaf nodes return Object.assign({},data); } else { let group = groups[0]; let r = []; let names = []; for (var i=0; i < group.datasets.length; i++) { group.datasets[i]['aggField'] = this.parseAggStr(group.datasets[i].data); } group = this.parseGroupByField(group,group.field); // Loop through the data set to get the 'unique' group values for this level of the drilldown for (let i = 0; i < data.length; i++) { if(! this.IN(names, this.applyModifier(data[i][group.field], group))) { names.push(this.applyModifier(data[i][group.field], group)); } } // Sort the names so that time series will come out in ASC order names.sort(); // Now loop through (this reduced set of) the unique grouped up values for (let index = 0; index < names.length; index++) { let name = names[index]; let pathArray = []; let f = []; for (let i = 0; i < data.length; i++) { // Push the data onto the f[] that match this particular grouping. // Note: f[] will become the new data[] when we recurse. if (this.applyModifier(data[i][group.field],group) == name) { pathArray.push(i); f.push(data[i]); } } var path = name; r.push({ name : name, chart : group.chart, y : aggFunc(this, f, group, name), drilldown : this.groupBy(f, groups.slice(1, groups.length), fullGroupBy, aggFunc, pathAggFunc), group : group, path : pathAggFunc(this, f, fullGroupBy, group, name), data : f, groups: fullGroupBy, downloadObj: this.downloadFields }); } return r; } } /** * @function IN() * @author <NAME> <<EMAIL>> * Quickly check to see if the val is in the list. * Note: The list starts empty and we push onto it when we find a unique value. * * @param list The array to check * @param val The value to check if it exists in the array already * * @return true or false */ IN(list, val) { if (list.indexOf(val) == -1) { return false; } return true; } /** * @function applyModifier() * @author <NAME> <<EMAIL>> * Check to see if a modifier exists for this field. If it doesn't quickly return. * If it does exists then apply the modifier to the field and return the modified value. * This is mostly useful for datetime fields. * * @param list The array to check * @param val The value to check if it exists in the array already * * @return The modified value. */ applyModifier(val, group) { if (typeof group.modifier == 'undefined') { return val; } else { switch(true){ case /^date_trunc/.test(group.modifier): var truncType = group.modifierParams[0]; switch(true) { case /^day/.test(truncType): try { val = new Date(val).toISOString().slice(0, 10); } catch (e) { } break; case /^month/.test(truncType): try { val = new Date(val).toISOString().slice(0, 7); } catch (e) { } break; case /^year/.test(truncType): try { val = new Date(val).toISOString().slice(0, 4); } catch (e) { } break; default: } break; default: } return val; } } /** * @function parseAggStr() * @author <NAME> <<EMAIL>> * Parses the datasets.data string to pull out the field that needs to be aggregated on. * Example: sum(revenue) will return the string "revenue" * * @param str The aggregate field in the form of agg(field) * * @return The field to be aggregated on */ parseAggStr(str) { let match = str.match(/\((.*)\)/); return match[1]; } /** * @function parseGroupByField() * @author <NAME> <<EMAIL>> * Parses the group by field to see if there are any modifiers. If a modifier is found * then the group.modifier field and modifierParams are filled in. * Example: date_trunc(month,startdate) will return the string "startdate" * * @param group The group object for this level of the tree. * @param str The group by 'field' we want to check for modifiers * * @return Returns the modifield group object */ parseGroupByField(group, str) { switch(true){ case /^date_trunc/.test(str): let match = str.match(/\((.*)\)/); if (typeof match != 'undefined' && match != null) { group.modifier = "date_trunc"; group.modifierParams = match[1].split(/,/); group.field = group.modifierParams[1]; } break; default: } return group; } /** * @function aggFunction() * @author <NAME> <<EMAIL>> * This function is called for each node of the grouping tree. The group.datasets[j].data represents this grouping * based on the aggregate defined (i.e. sum, max, min etc) and based on the field being agregated on (i.e. sum(revenue)). * * @param me A reference to 'this' object * @param data The data object for this grouping (an array of objects) * @param group The current group object for this level in the tree * @param name The actual field value that we are grouping on for this node of the tree. * * @return Returns the modifield group object */ aggFunction(me, data, group, name) { var returnArray = []; // loop over each dataset in this grouping to aggregate each one. for (var j=0; j<group.datasets.length; j++) { if (typeof group.datasets[j] != 'undefined') { var str = group.datasets[j].data; switch(true){ case /^sum/.test(str): var aggField = group.datasets[j]['aggField']; var returnNum = 0; for (var i=0; i<data.length; i++) { if (me.applyModifier(data[i][group.field],group) == name) { returnNum = parseInt(data[i][aggField]) + returnNum; } } returnArray.push(returnNum); break; case /^max/.test(str) : var aggField = group.datasets[j]['aggField']; var returnNum = Number.MIN_SAFE_INTEGER; for (var i=0; i<data.length; i++) { if (me.applyModifier(data[i][group.field],group) == name && returnNum < parseInt(data[i][aggField])) { returnNum = parseInt(data[i][aggField]); } } returnArray.push(returnNum); break; case /^min/.test(str) : var aggField = group.datasets[j]['aggField']; var returnNum = Number.MAX_SAFE_INTEGER ; for (var i=0; i<data.length; i++) { if (me.applyModifier(data[i][group.field],group) == name && returnNum > parseInt(data[i][aggField])) { returnNum = parseInt(data[i][aggField]); } } returnArray.push(returnNum); break; case /^count/.test(str) : var returnNum = 0; for (var i=0; i<data.length; i++) { if (me.applyModifier(data[i][group.field],group) == name) { returnNum++; } } returnArray.push(returnNum); break; case /^boxplot/.test(str) : var aggField = group.datasets[j]['aggField']; var boxplot = {max: Number.MIN_SAFE_INTEGER, min:Number.MAX_SAFE_INTEGER, median: 0, q1:0, q3:0}; var sum1 = 0; var arrayOfValues = []; for (var i=0; i<data.length; i++) { if (me.applyModifier(data[i][group.field],group) == name && boxplot.min > parseInt(data[i][aggField])) { boxplot.min = parseInt(data[i][aggField]); } if (me.applyModifier(data[i][group.field],group) == name && boxplot.max < parseInt(data[i][aggField])) { boxplot.max = parseInt(data[i][aggField]); } if (me.applyModifier(data[i][group.field],group) == name) { arrayOfValues.push(parseInt(data[i][aggField])); } } boxplot.q1 = me.Quartile_25(arrayOfValues); boxplot.median = me.Quartile_50(arrayOfValues); boxplot.q3 = me.Quartile_75(arrayOfValues); returnArray.push(boxplot); break; default: console.log("Unknown datasets.data Function "+str) } } } return returnArray; } Median(data) { return this.Quartile_50(data); } Quartile_25(data) { return this.Quartile(data, 0.25); } Quartile_50(data) { return this.Quartile(data, 0.5); } Quartile_75(data) { return this.Quartile(data, 0.75); } Quartile(data, q) { data=this.Array_Sort_Numbers(data); var pos = ((data.length) - 1) * q; var base = Math.floor(pos); var rest = pos - base; if( (data[base+1]!==undefined) ) { return data[base] + rest * (data[base+1] - data[base]); } else { return data[base]; } } Array_Sort_Numbers(inputarray){ return inputarray.sort(function(a, b) { return a - b; }); } Array_Sum(t){ return t.reduce(function(a, b) { return a + b; }, 0); } Array_Average(data) { return this.Array_Sum(data) / data.length; } Array_Stdev(tab){ var i,j,total = 0, mean = 0, diffSqredArr = []; for(i=0;i<tab.length;i+=1){ total+=tab[i]; } mean = total/tab.length; for(j=0;j<tab.length;j+=1){ diffSqredArr.push(Math.pow((tab[j]-mean),2)); } return (Math.sqrt(diffSqredArr.reduce(function(firstEl, nextEl){ return firstEl + nextEl; })/tab.length)); } /** * @function pathAggFunction() * @author <NAME> <<EMAIL>> * This function calculates the path for this node in the tree using the current groups object * and the first record in the current data object. * * @param me A reference to 'this' object * @param data The data object for this grouping (an array of objects) * @param group The current group object for this level in the tree * @param name The actual field value that we are grouping on for this node of the tree. * * @return Returns a string in the form: "path > path > path..." */ pathAggFunction(me, data, groups, group, name) { var path = ""; for (var i=0; i<groups.length; i++) { if (groups[i].field != group.field) { path += me.applyModifier(data[0][groups[i].field],groups[i]) + " > "; } else { path += me.applyModifier(data[0][groups[i].field],groups[i]); break; } } return path; } /** * @function downloadData() * @author <NAME> <<EMAIL>> * Dumps out the data for this particular 'data' object into csv format. * * @param series The series object which holds the path information for this data object * @param downloadObj Holds which fields to download. * @param data The data object to download. * * @return a csv file of the data */ downloadDataToCsv(series, downloadObj, data) { var me = this; var exportStr = ""; exportStr += me.title; exportStr += "\n\n"; if (typeof series.path != 'undefined') { exportStr += "Local Filter:\n"; series.path = series.path.replace(/,/g, " "); if (parseInt(series.path) > 0) { exportStr += '="'+series.path+'"'+","; } else { exportStr += '"'+series.path+'"'+","; } exportStr += "\n\n\n"; } // Dump out header for (var item in downloadObj) { exportStr += '"'+downloadObj[item]+'"'+","; } exportStr += "\n"; // Now dump out data. for (var k= 0; k < data.length; k++) { for (var i=0; i< downloadObj.length; i++) { exportStr += '"'+data[k][downloadObj[i]]+'"'+","; } exportStr += "\n"; } me.export(exportStr, "ez_download.csv", 'text/csv;charset=utf-8;'); } /** * @function export() * Downloads the formatted string to the client computer in csv format. * * @param exportStr The data string to download * @param filename The name of the file to download to client computer * @param fileType The format of the file -- in this case text/csv * * @return a csv file of the data */ export(exportStr, filename, fileType) { var blob = new Blob([exportStr], { type: fileType }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } };<file_sep>/README.md # ez-groupby-tree-mixin A mixin to add javascript 'groupby' cababilities to a data set using recursive tree processing
9752c8082c0c50bd4dbd3ccb4868a0e6a3b253a2
[ "JavaScript", "Markdown" ]
2
JavaScript
ez-webcomponents/ez-groupby-tree-mixin
c277827282cc32755b9dcb2bce8813af93fd6646
0229d4e7413d6383f7bf95a353549d62a482c7f0
refs/heads/master
<repo_name>DiegoSalas11/Line<file_sep>/src/ofApp.h #pragma once #include "ofMain.h" #include"ofMath.h" class ofApp : public ofBaseApp { public: int x, y, x1, y1; int dx, dy, a, b,d, difE, difNE, Subebaja , unoOmenosUno; bool filtroDeAlberca; ofTexture textura; ofPixels pixeles; void putPixel(int x, int y, int red, int green, int blue, int A); void getPixel(); void line(int x1,int y1,int x2,int y2,int r,int g , int b , int a); void circleLine(int x, int y, int radio, int r, int g, int b, int a); void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); }; <file_sep>/src/ofApp.cpp #include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofBackground(0); pixeles.allocate(1024, 768, OF_PIXELS_BGRA); textura.allocate(1024, 768, GL_BGRA); circleLine(ofGetWidth()/2 , ofGetHeight()/2 , 300, 255,255,255,255); ///*line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth() , ofGetHeight()/2+15 ); //line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth()/2+15, ofGetHeight() );*/ //line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth() / 2 - 15, ofGetHeight()); ///*line(ofGetWidth() / 2, ofGetHeight() / 2, 0, ofGetHeight()/2+15); //line(ofGetWidth() / 2, ofGetHeight() / 2, 0, ofGetHeight() / 2 -15); //line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth()/2 -15, 0);*/ //line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth() / 2 +15, 0); ///*line(ofGetWidth() / 2, ofGetHeight() / 2, ofGetWidth(), ofGetHeight() / 2 - 15);*/ } //-------------------------------------------------------------- void ofApp::update() { //putPixel(ofRandom(ofGetWidth()), ofRandom(ofGetHeight()), ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255), ofRandom(0, 255)); getPixel(); } //-------------------------------------------------------------- void ofApp::draw() { textura.draw(0, 0); } void ofApp::putPixel(int x, int y, int red, int green, int blue, int A) { pixeles.setColor(x, y, (red, green, blue, A)); } void ofApp::getPixel() { textura.loadData(pixeles); } void ofApp::line(int x1, int y1, int x2, int y2, int r, int g, int b, int a) { if (x1 > x2)// invierte { int xNew = x1; int yNew = y1; x1 = x2; y1 = y2; x2 = xNew; y2 = yNew; } if(y1>y2)// diferencia negativa? { unoOmenosUno = -1; dy = y1 - y2; } else { dy = y2 - y1; unoOmenosUno = 1; } dx = x2 - x1; if(dy>=dx)// Base mayor { a = dx; b = -dy; Subebaja = x1; filtroDeAlberca = true; } else { a = dy; b = -dx; Subebaja = y1; filtroDeAlberca = false; } d = 2 * a + b; difE = 2 * a; difNE = 2 * a + 2 * b; putPixel(x1,y1,r,g,b,a); if (!filtroDeAlberca) { for (int x = x1 + 1; x <= x2; x++) { if (d < 0) { d += 2 * a; } else { d += 2 * a + 2 * b; Subebaja += unoOmenosUno; } putPixel(x, Subebaja, r,g,b,a); } } else { cout << "el agua esa limpia" << endl; int elintquesepasodeverga; int otra=y2*=unoOmenosUno; for (int y = y1 + unoOmenosUno; (elintquesepasodeverga=y*unoOmenosUno) <= (otra); y+=unoOmenosUno) { if (d < 0) { d += 2 * a; } else { d += 2 * a + 2 * b; Subebaja ++; } putPixel(Subebaja,y, r, g, b, a); } } //-------------------------------------- 1 /*int x, y, dx, dy, d, deltaE, deltaNE; x = x1; y = y1; dx = x2 - x1; dy = y2 - y1; d = 2 * dy - dx; deltaE = 2 * dy; deltaNE = 2 * dy - dx; putPixel(x, y, 255, 255, 255, 255); while (x < x2) { if (d < 0) { d = d + deltaE; } else { d = d + deltaNE; y++; } putPixel(x, y, 255, 255, 255, 255); x++; } */ //---------------------------------2 //int x, y, dx, dy, d, deltaE, deltaNE; //x = x1; //y = y1; //dx = x2 - x1; //dy = y2 - y1; //d = 2 * dx - dy; //deltaE = 2 * dx; //deltaNE = 2 * dx - dy; //putPixel(x, y, 255, 255, 255, 255); //while (y < y2) //{ // if (d < 0) // { // d = d + deltaE; // } // else { // d = d + deltaNE; // // x++; // } // y++; // putPixel(x, y, 255, 255, 255, 255); //} //------------------- 3 /*int xNew = x1; int yNew = y1; x1 = x2; y1 = y2; x2 = xNew; y2 = yNew; x = x1; y = y1; dx = x2 - x1; c d = 2 * dx - dy; deltaE = 2 * dx; deltaNE = 2 * dx - dy; putPixel(x1, y1, 255, 255, 255, 255); while (y > y2) { if (d < 0) { d = d + deltaE; } else { d = d + deltaNE; x++; } y--; putPixel(x, y, 255, 255, 255, 255); }*/ //------------------------------------ 4 /*int xNew = x1; int yNew = y1; x1 = x2; y1 = y2; x2 = xNew; y2 = yNew; x = x1; y = y1; dx = x2 - x1; dy = y1 - y2; d = 2 * dy - dx; deltaE = 2 * dy; deltaNE = 2 * dy - dx; putPixel(x, y, 255, 255, 255, 255); while (x < x2) { if (d < 0) { d = d + deltaE; } else { d = d + deltaNE; y--; } putPixel(x, y, 255, 255, 255, 255); x++; }*/ //------------------------------- 5 //int xNew = x1; //int yNew = y1; // //x1 = x2; //y1 = y2; // //x2 = xNew; //y2 = yNew; // //x = x1; //y = y1; // //dx = x2 - x1; //dy = y2 - y1; // //d = 2 * dy - dx; // //deltaE = 2 * dy; //deltaNE = 2 * dy - dx; // //putPixel(x, y, 255, 255, 255, 255); // // //while (x < x2) //{ // if (d < 0) // { // d = d + deltaE; // // } // else { // d = d + deltaNE; // // y++; // } // putPixel(x, y, 255, 255, 255, 255); // x++; //} //------------------------------------- 6 //int xNew = x1; //int yNew = y1; // //x1 = x2; //y1 = y2; // //x2 = xNew; //y2 = yNew; // //x = x1; //y = y1; //dx = x2 - x1; //dy = y2 - y1; // //d = 2 * dx - dy; // //deltaE = 2 * dx; //deltaNE = 2 * dx - dy; // //putPixel(x, y, 255, 255, 255, 255); // // //while (y < y2) //{ // if (d < 0) // { // d = d + deltaE; // } // else { // d = d + deltaNE; // // x++; // } // y++; // putPixel(x, y, 255, 255, 255, 255); // //} //------------------------------ 7 //x = x1; //y = y1; // //dx = x2 - x1; //dy = y1 - y2; // //d = 2 * dx - dy; // //deltaE = 2 * dx; //deltaNE = 2 * dx - dy; // //putPixel(x1, y1, 255, 255, 255, 255); // // //while (y > y2) //{ //if (d < 0) //{ //d = d + deltaE; //} //else { //d = d + deltaNE; // //x++; //} //y--; //putPixel(x, y, 255, 255, 255, 255); // //} //----------------------------- 8 //x = x1; //y = y1; // //dx = x2 - x1; //dy = y1 - y2; // //d = 2 * dy - dx; // //deltaE = 2 * dy; //deltaNE = 2 * dy - dx; // //putPixel(x, y, 255, 255, 255, 255); // // //while (x < x2) //{ // if (d < 0) // { // d = d + deltaE; // // } // else { // d = d + deltaNE; // // y--; // } // putPixel(x, y, 255, 255, 255, 255); // x++; //} } void ofApp::circleLine(int x, int y, int radio, int r, int g, int b, int a) { float angles; int x2, y2; x2 = 0; y2 = 0; for (int ActualAngle = 0; ActualAngle < 360; ActualAngle++) { angles = radio*cos(ActualAngle); x2 = round(angles); angles = radio*sin(ActualAngle); y2 = round(angles); line(x, y, x + x2, y + y2, r,g,b,a); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { }
3c65f8033f5ee7b0a50b272535412f72a2b16830
[ "C++" ]
2
C++
DiegoSalas11/Line
d9d8560489cdbf33d5a02bdf4d4c5ba1a0ed3eb7
4a144833d4007c832101a5ddb95f4b9d79201092
refs/heads/master
<repo_name>austingibb/SnakeGame<file_sep>/SnakeGame/Timer.cpp #include "Timer.h" Timer::Timer() { _running = false; _paused = false; } Timer::~Timer() { } void Timer::start() { if (!_running) { _running = true; _paused = false; _start_time = SDL_GetTicks(); } } void Timer::stop() { if (_running) { _running = false; } } void Timer::reset() { if (_running) { _paused = false; _start_time = SDL_GetTicks(); } } void Timer::pause() { if (!_paused && _running) { _paused = true; _pause_time = SDL_GetTicks(); } } void Timer::resume() { if (_paused && _running) { _paused = false; _start_time = SDL_GetTicks() - (_pause_time - _start_time); } } Uint32 Timer::get_runtime() { Uint32 time = 0; if (_running) { if (_paused) { time = (_pause_time - _start_time); } else { time = SDL_GetTicks() - _start_time; } } return time; } bool Timer::is_paused() { return _paused; } bool Timer::is_running() { return _running; } <file_sep>/SnakeGame/SpriteAnimationFrameRotations.h #pragma once #include "SpriteAnimationFrames.h" class SpriteAnimationFrameRotations { public: SpriteAnimationFrameRotations(); void LoadRotations(SDL_Renderer* renderer_, std::string texture_path_, int cols_, int rows_, int width_, int height_, int num_sprites_); void LoadRotations(SDL_Renderer* renderer_, std::string texture_path_, int cols_, int rows_, int width_, int height_, int num_sprites_, Uint8 red_, Uint8 green_, Uint8 blue_); SpriteAnimationFrames* get_rotation_frames(Sprite::Rotation rotation_); private: SpriteAnimationFrames _rotations[4]; }; <file_sep>/SnakeGame/SnakeGame.h #pragma once #include <string> #include <random> #include <SDL_mixer.h> #include "Graphics.h" #include "Sprite.h" #include "Grid.h" #include "Snake.h" #include "Timer.h" #include "SpriteAnimationFrameRotations.h" class SnakeGame { public: const static std::string VERSION; // these sizes allow perfect scaling for the pixel art enum GameSize { SIX = 6, NINE = 9, TWELVE = 12, EIGHTEEN = 18, THRITY_SIX = 36 }; enum GameState { RUNNING, OVER }; SnakeGame(GameSize size_); ~SnakeGame(); void RunGame(); private: GameState _game_state; Grid* _grid = NULL; Snake* _snake = NULL; Graphics _graphics; Timer _fps_timer; int _frames; std::mt19937 _rng; Sprite _food; Sprite _ground; Sprite _wall; Mix_Music* _intro_music = NULL; Mix_Music* _main_music = NULL; Mix_Chunk* _hit_sound = NULL; Mix_Chunk* _death_sound = NULL; Mix_Chunk* _grow_sound = NULL; Mix_Chunk* _movement_sound = NULL; Mix_Chunk* _turn_sound = NULL; void LoadMedia(); void UpdateAll(); void RenderAll(); void AddFood(); }; <file_sep>/SnakeGame/Snake.h #pragma once #include "LimitQueue.h" #include "Animation.h" #include "SpriteAnimationFrameRotations.h" #include "Direction.h" #include "Grid.h" #include "Segment.h" #include "Timer.h" #include "Graphics.h" class Snake { public: enum SnakeState { AGAINST_WALL, AGAINST_SEGMENT, MOVING, DEAD }; /* UpdateStatus */ const static Uint8 NONE = 0, ATE = 1, HIT_WALL_INITIAL = 2, HIT_WALL = 4, HIT_SELF_INITIAL = 8, HIT_SELF = 16, MOVED = 32, TURNED = 64, DIED = 128; Snake(Graphics* graphics_, Uint8 red_, Uint8 green_, Uint8 blue_, Grid* grid_, int length_, int head_x_, int head_y_, Direction direction_); ~Snake(); void LoadAnimationFrames(SDL_Renderer* renderer_); void HandleInput(SDL_Keycode key_); void HandleRepeatInput(SDL_Keycode key_); Uint16 Update(); void Render(); SnakeState get_state(); private: Grid* _grid; int _frames_per_action = 5; int _ticks_per_frame = 1; int _total_ticks; int _current_tick; int _ticks_before_fail = 20; int _fail_tick = 0; Uint16 _update_status; SnakeState _state; int _head_x, _head_y; int _tail_x, _tail_y; int _length; Segment* _head; Segment* _tail; bool _extending; LimitQueue _input_queue; Direction _queued_direction; Direction _last_direction; static const bool _debug_input = false; Graphics* _graphics; Uint8 _red = 255, _green = 255, _blue = 255; SpriteAnimationFrameRotations _head_straight_rotations; SegmentAnimationTemplate _head_straight_template[4]; SpriteAnimationFrameRotations _head_turn_rotations; SegmentAnimationTemplate _head_turn_template[8]; SpriteAnimationFrameRotations _body_straight_rotations; SegmentAnimationTemplate _body_straight_template[4]; SpriteAnimationFrameRotations _body_turn_rotations; SegmentAnimationTemplate _body_turn_template[8]; SpriteAnimationFrameRotations _tail_straight_rotations; SegmentAnimationTemplate _tail_straight_template[4]; SpriteAnimationFrameRotations _tail_turn_rotations; SegmentAnimationTemplate _tail_turn_template[8]; SpriteAnimationFrameRotations _tail_wait_rotations; SegmentAnimationTemplate _tail_wait_template[4]; static const bool _debug_animations = false; int _debug_animation_tick = 0; SDL_Point _debug_animation_tile = { 0, 1 }; Animation* _debug_anim; int _queued_anim_update = 1; int _current_anim = 0; void UpdateTmpAnim(); Segment* CreateSegment(); void ActionComplete(); void UpdateSegments(); void UpdateSegmentAnimation(Segment* segment_); void CommitHeadDirection(); void CheckHeadTile(); OnTile CheckNextTile(Direction direction_); void CommitInput(); void Extend(); int update_based_on_direction(Direction direction_, int& x_, int& y_, bool force_bound_ = true); Direction direction_from_key(SDL_Keycode key_); }; <file_sep>/SnakeGame/Animation.h #pragma once #include "SpriteAnimationFrames.h" class Animation { public: Animation(SpriteAnimationFrames* frames_, bool loop_); void Render(SDL_Renderer* renderer_); void advance_frame(); void restart(); void set_frames(SpriteAnimationFrames* frames_); void set_pos(int x_, int y_); void set_bounds(int width_, int height_); void set_dst(SDL_Rect &rect_); void set_center(int x_, int y_); void set_rotation(double rotation_); void set_flip(SDL_RendererFlip flip_); private: SpriteAnimationFrames* _frames; int _current_frame; bool _loop; SDL_Rect _dst; SDL_Point _center; double _rotation; SDL_RendererFlip _flip; }; <file_sep>/SnakeGame/OnTile.h #pragma once enum OnTile { NOTHING, FOOD, SEGMENT, WALL };<file_sep>/SnakeGame/LimitQueue.h #pragma once #include <queue> #include "Direction.h" class LimitQueue { public: LimitQueue(int limit_); void enqueue(Direction direction); Direction pop(); Direction peek(); void clear(); bool has_more(); int get_size(); private: std::queue<Direction> _queue; int _limit; }; <file_sep>/SnakeGame/Segment.h #pragma once #include <SDL.h> #include "Direction.h" #include "Animation.h" #include "Grid.h" struct SegmentAnimationTemplate { SpriteAnimationFrames* frames; SDL_Rect bound; SDL_RendererFlip flip; }; class Segment { public: enum SegmentType { HEAD, BODY, TAIL }; Segment(Animation* anim_); ~Segment(); void RenderAll(SDL_Renderer* renderer_); void AdvanceAllAnimations(); void ResetAllAnimations(); void UpdateAnimation(const SegmentAnimationTemplate &animation_template_, int scale_factor_); Animation* get_animation(); void insert_before(Segment* segment_); void remove(); void set_type(SegmentType type_); SegmentType get_type(); void set_next(Segment* next_); Segment* get_next(); void set_previous(Segment* previous_); Segment* get_previous(); void set_incoming(Direction incoming_); Direction get_incoming(); void set_outgoing(Direction outgoing_); Direction get_outgoing(); void set_tile(Tile* tile_); Tile* get_tile(); private: SegmentType _type; Animation* _anim; Tile* _tile; Direction _incoming; Direction _outgoing; Segment* _next; Segment* _previous; }; <file_sep>/SnakeGame/RandomPointer.cpp #include "RandomPointer.h" template<class type> RandomPointer::RandomPointer() { std::random_device rd; } template<class type> RandomPointer::~RandomPointer() { } <file_sep>/SnakeGame/Direction.h #ifndef DIRECTION_H #define DIRECTION_H enum Direction { INVALID, UP, DOWN, LEFT, RIGHT }; Direction get_opposite_direction(Direction direction_); #endif<file_sep>/SnakeGame/Graphics.cpp #include "Graphics.h" #include <cstdio> Graphics::Graphics() : _window(NULL), _renderer(NULL) {} Graphics::~Graphics() { SDL_DestroyRenderer(_renderer); SDL_DestroyWindow(_window); } bool Graphics::Init(std::string title_, Uint32 window_flags_, Uint32 renderer_flags_, int img_flags_, int x_, int y_, int width_, int height_) { SCREEN_WIDTH = width_; SCREEN_HEIGHT = height_; if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { printf("SDL video didn't initialize. %s", SDL_GetError()); return false; } if (!(IMG_Init(img_flags_) & img_flags_)) { printf("SDL image didn't initialize. %s", SDL_GetError()); return false; } if (_window == NULL) { _window = SDL_CreateWindow(title_.c_str(), x_, y_, width_, height_, window_flags_); if (_window == NULL) { printf("Could not create window. %s", SDL_GetError()); return false; } } if (_renderer == NULL) { _renderer = SDL_CreateRenderer(_window, -1, renderer_flags_); if (_renderer == NULL) { printf("Could not create renderer. %s", SDL_GetError()); return false; } } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 0); SDL_RenderSetLogicalSize(_renderer, width_, height_); return true; } SDL_Window* Graphics::get_window() { return _window; } SDL_Renderer* Graphics::get_renderer() { return _renderer; } int Graphics::get_screen_width() { return SCREEN_WIDTH; } int Graphics::get_screen_height() { return SCREEN_HEIGHT; } <file_sep>/SnakeGame/Grid.h #ifndef GRID_H #define GRID_H #include "OnTile.h" #include <SDL.h> class Tile { public: int grid_x, grid_y; OnTile on_tile; SDL_Rect pixel_rect; Tile() {} void Init(int grid_x_, int grid_y_, int pixel_x_, int pixel_y_, int pixel_width_, int pixel_height_, OnTile on_tile_) { grid_x = grid_x_; grid_y = grid_y_; on_tile = on_tile_; pixel_rect.x = pixel_x_; pixel_rect.y = pixel_y_; pixel_rect.w = pixel_width_; pixel_rect.h = pixel_height_; } }; class Grid { public: Grid(int pixel_width_, int pixel_height_, int grid_size_); ~Grid(); Tile* get_tile(int row_, int col_); void set_on_tile(int row_, int col_, OnTile on_tile_); void set_on_tile(Tile* tile_, OnTile on_tile_); int get_scale_factor(); int get_available_tiles(); int get_grid_size(); int get_margin_offset(); int get_pixels_per_tile(); void print_grid(); private: Tile** _tiles; int _available_tiles; int _grid_size; int _grid_pixels; int _margin_offset; int _pixels_per_tile; int _scale_factor; }; #endif <file_sep>/SnakeGame/Snake.cpp #include "Snake.h" Snake::Snake(Graphics* graphics_, Uint8 red_, Uint8 green_, Uint8 blue_, Grid* grid_, int length_, int head_x_, int head_y_, Direction direction_) : _red(red_), _green(green_), _blue(blue_), _input_queue(3), _queued_direction(direction_), _last_direction(direction_), _head_x(head_x_), _head_y(head_y_), _current_tick(0), _extending(false), _state(SnakeState::MOVING), _update_status(NONE), _total_ticks(_ticks_per_frame * _frames_per_action) { _grid = grid_; if (length_ < 3) { length_ = 3; } _length = length_; _graphics = graphics_; _input_queue.enqueue(direction_); LoadAnimationFrames(_graphics->get_renderer()); _grid->set_on_tile(head_y_, head_x_, SEGMENT); _grid->set_on_tile(head_y_ - 1, head_x_, SEGMENT); _grid->set_on_tile(head_y_ - 2, head_x_, SEGMENT); _grid->set_on_tile(head_y_ - 3, head_x_, SEGMENT); _head = CreateSegment(); _head->set_type(Segment::SegmentType::HEAD); Tile* head_tile = _grid->get_tile(head_y_,head_x_); _head->set_tile(head_tile); _head->set_incoming(Direction::DOWN); _head->set_outgoing(Direction::UP); UpdateSegmentAnimation(_head); Tile* body_tile = _grid->get_tile(head_y_ - 1, head_x_); Segment* body = CreateSegment(); body->set_tile(body_tile); body->set_type(Segment::SegmentType::BODY); body->set_incoming(Direction::DOWN); body->set_outgoing(Direction::UP); UpdateSegmentAnimation(body); Tile* body_tile2 = _grid->get_tile(head_y_ - 2, head_x_); Segment* body2 = CreateSegment(); body2->set_tile(body_tile2); body2->set_type(Segment::SegmentType::BODY); body2->set_incoming(Direction::DOWN); body2->set_outgoing(Direction::UP); UpdateSegmentAnimation(body2); Tile* tail_tile = _grid->get_tile(head_y_ - 3, head_x_); _tail = CreateSegment(); _tail->set_tile(tail_tile); _tail->set_type(Segment::SegmentType::TAIL); _tail->set_incoming(Direction::DOWN); _tail->set_outgoing(Direction::UP); UpdateSegmentAnimation(_tail); _head->set_next(body); body->set_previous(_head); body->set_next(body2); body2->set_previous(body); body2->set_next(_tail); _tail->set_previous(body2); if (_debug_animations) { _debug_anim = new Animation(NULL, true); UpdateTmpAnim(); _queued_anim_update = 0; } } Snake::~Snake() { if (_debug_animations) { delete _debug_anim; } Segment* _next = _head; while (_next != NULL) { Segment* segment = _next; _grid->set_on_tile(segment->get_tile(), OnTile::NOTHING); Animation* animation = _next->get_animation(); _next = _next->get_next(); delete segment; delete animation; } } void Snake::LoadAnimationFrames(SDL_Renderer* renderer_) { /* head */ _head_straight_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyHeadStraight.png", 4, 3, 10, 20, 12, _red, _green, _blue); _head_straight_template[0].frames = _head_straight_rotations.get_rotation_frames(Sprite::NONE); _head_straight_template[0].bound = { 0, -10, 10, 20 }; _head_straight_template[1].frames = _head_straight_rotations.get_rotation_frames(Sprite::ONE); _head_straight_template[1].bound = { 0, 0, 20, 10 }; _head_straight_template[2].frames = _head_straight_rotations.get_rotation_frames(Sprite::TWO); _head_straight_template[2].bound = { 0, 0, 10, 20 }; _head_straight_template[3].frames = _head_straight_rotations.get_rotation_frames(Sprite::THREE); _head_straight_template[3].bound = { -10, 0, 20, 10 }; _head_turn_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyHeadTurn.png", 3, 4, 20, 10, 12, _red, _green, _blue); _head_turn_template[0].frames = _head_turn_rotations.get_rotation_frames(Sprite::NONE); _head_turn_template[0].bound = { -10, 0, 20, 10 }; _head_turn_template[0].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _head_turn_template[1].frames = _head_turn_rotations.get_rotation_frames(Sprite::NONE); _head_turn_template[1].bound = { 0, 0, 20, 10 }; _head_turn_template[2].frames = _head_turn_rotations.get_rotation_frames(Sprite::ONE); _head_turn_template[2].bound = { 0, -10, 10, 20 }; _head_turn_template[2].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _head_turn_template[3].frames = _head_turn_rotations.get_rotation_frames(Sprite::ONE); _head_turn_template[3].bound = { 0, 0, 10, 20 }; _head_turn_template[4].frames = _head_turn_rotations.get_rotation_frames(Sprite::TWO); _head_turn_template[4].bound = { 0, 0, 20, 10 }; _head_turn_template[4].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _head_turn_template[5].frames = _head_turn_rotations.get_rotation_frames(Sprite::TWO); _head_turn_template[5].bound = { -10, 0, 20, 10 }; _head_turn_template[6].frames = _head_turn_rotations.get_rotation_frames(Sprite::THREE); _head_turn_template[6].bound = { 0, 0, 10, 20 }; _head_turn_template[6].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _head_turn_template[7].frames = _head_turn_rotations.get_rotation_frames(Sprite::THREE); _head_turn_template[7].bound = { 0, -10, 10, 20 }; /* head */ /* body */ _body_straight_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyBodyStraight.png", 2, 3, 10, 10, 6, _red, _green, _blue); _body_straight_template[0].frames = _body_straight_rotations.get_rotation_frames(Sprite::TWO); _body_straight_template[0].bound = { 0, 0, 10, 10 }; _body_straight_template[1].frames = _body_straight_rotations.get_rotation_frames(Sprite::THREE); _body_straight_template[1].bound = { 0, 0, 10, 10 }; _body_straight_template[2].frames = _body_straight_rotations.get_rotation_frames(Sprite::NONE); _body_straight_template[2].bound = { 0, 0, 10, 10 }; _body_straight_template[3].frames = _body_straight_rotations.get_rotation_frames(Sprite::ONE); _body_straight_template[3].bound = { 0, 0, 10, 10 }; _body_turn_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyBodyTurn.png", 2, 3, 10, 10, 6, _red, _green, _blue); _body_turn_template[0].frames = _body_turn_rotations.get_rotation_frames(Sprite::NONE); _body_turn_template[0].bound = { 0, 0, 10, 10 }; _body_turn_template[0].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _body_turn_template[1].frames = _body_turn_rotations.get_rotation_frames(Sprite::NONE); _body_turn_template[1].bound = { 0, 0, 10, 10 }; _body_turn_template[2].frames = _body_turn_rotations.get_rotation_frames(Sprite::ONE); _body_turn_template[2].bound = { 0, 0, 10, 10 }; _body_turn_template[2].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _body_turn_template[3].frames = _body_turn_rotations.get_rotation_frames(Sprite::ONE); _body_turn_template[3].bound = { 0, 0, 10, 10 }; _body_turn_template[4].frames = _body_turn_rotations.get_rotation_frames(Sprite::TWO); _body_turn_template[4].bound = { 0, 0, 10, 10 }; _body_turn_template[4].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _body_turn_template[5].frames = _body_turn_rotations.get_rotation_frames(Sprite::TWO); _body_turn_template[5].bound = { 0, 0, 10, 10 }; _body_turn_template[6].frames = _body_turn_rotations.get_rotation_frames(Sprite::THREE); _body_turn_template[6].bound = { 0, 0, 10, 10 }; _body_turn_template[6].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _body_turn_template[7].frames = _body_turn_rotations.get_rotation_frames(Sprite::THREE); _body_turn_template[7].bound = { 0, 0, 10, 10 }; /* body */ /* tail */ _tail_straight_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyTailStraight.png", 4, 3, 10, 20, 12, _red, _green, _blue); _tail_straight_template[0].frames = _tail_straight_rotations.get_rotation_frames(Sprite::NONE); _tail_straight_template[0].bound = { 0, 0, 10, 20 }; _tail_straight_template[1].frames = _tail_straight_rotations.get_rotation_frames(Sprite::ONE); _tail_straight_template[1].bound = { -10, 0, 20, 10 }; _tail_straight_template[2].frames = _tail_straight_rotations.get_rotation_frames(Sprite::TWO); _tail_straight_template[2].bound = { 0, -10, 10, 20 }; _tail_straight_template[3].frames = _tail_straight_rotations.get_rotation_frames(Sprite::THREE); _tail_straight_template[3].bound = { 0, 0, 20, 10 }; _tail_turn_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyTailTurn.png", 4, 3, 10, 20, 12, _red, _green, _blue); _tail_turn_template[0].frames = _tail_turn_rotations.get_rotation_frames(Sprite::NONE); _tail_turn_template[0].bound = { 0, 0, 10, 20 }; _tail_turn_template[0].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _tail_turn_template[1].frames = _tail_turn_rotations.get_rotation_frames(Sprite::NONE); _tail_turn_template[1].bound = { 0, 0, 10, 20 }; _tail_turn_template[2].frames = _tail_turn_rotations.get_rotation_frames(Sprite::ONE); _tail_turn_template[2].bound = { -10, 0, 20, 10 }; _tail_turn_template[2].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _tail_turn_template[3].frames = _tail_turn_rotations.get_rotation_frames(Sprite::ONE); _tail_turn_template[3].bound = { -10, 0, 20, 10 }; _tail_turn_template[4].frames = _tail_turn_rotations.get_rotation_frames(Sprite::TWO); _tail_turn_template[4].bound = { 0, -10, 10, 20 }; _tail_turn_template[4].flip = SDL_RendererFlip::SDL_FLIP_HORIZONTAL; _tail_turn_template[5].frames = _tail_turn_rotations.get_rotation_frames(Sprite::TWO); _tail_turn_template[5].bound = { 0, -10, 10, 20 }; _tail_turn_template[6].frames = _tail_turn_rotations.get_rotation_frames(Sprite::THREE); _tail_turn_template[6].bound = { 0, 0, 20, 10 }; _tail_turn_template[6].flip = SDL_RendererFlip::SDL_FLIP_VERTICAL; _tail_turn_template[7].frames = _tail_turn_rotations.get_rotation_frames(Sprite::THREE); _tail_turn_template[7].bound = { 0, 0, 20, 10 }; _tail_wait_rotations.LoadRotations(_graphics->get_renderer(), "Art/Snake/GreyTailWait.png", 1, 1, 10, 10, 1, _red, _green, _blue); _tail_wait_template[0].frames = _tail_wait_rotations.get_rotation_frames(Sprite::NONE); _tail_wait_template[0].bound = { 0, 0, 10, 10 }; _tail_wait_template[1].frames = _tail_wait_rotations.get_rotation_frames(Sprite::ONE); _tail_wait_template[1].bound = { 0, 0, 10, 10 }; _tail_wait_template[2].frames = _tail_wait_rotations.get_rotation_frames(Sprite::TWO); _tail_wait_template[2].bound = { 0, 0, 10, 10 }; _tail_wait_template[3].frames = _tail_wait_rotations.get_rotation_frames(Sprite::THREE); _tail_wait_template[3].bound = { 0, 0, 10, 10 }; /* tail */ } void Snake::HandleInput(SDL_Keycode key_) { if (_debug_input) { switch (key_) { case SDLK_UP: printf("tryU "); break; case SDLK_DOWN: printf("tryD "); break; case SDLK_LEFT: printf("tryL "); break; case SDLK_RIGHT: printf("tryR "); break; } } Direction ahead_direction; Direction opposite_direction; Direction key_direction; if (_input_queue.get_size() == 0) { ahead_direction = _last_direction; } else { ahead_direction = _input_queue.peek(); } opposite_direction = get_opposite_direction(ahead_direction); key_direction = direction_from_key(key_); // If it is a turn, allow it. If it is the same direction as forward, and it is moving there is no need to enqueue. if (key_direction != INVALID && (_state != MOVING || ahead_direction != key_direction) && opposite_direction != key_direction) { _input_queue.enqueue(key_direction); if (_debug_input) { std::string key_symbol; switch (key_direction) { case UP: key_symbol = "U"; break; case DOWN: key_symbol = "D"; break; case LEFT: key_symbol = "L"; break; case RIGHT: key_symbol = "R"; break; } printf("+%s%02d ", key_symbol.c_str(), _input_queue.get_size()); } _ticks_per_frame = 1; } if (_debug_animations) { if (key_ == SDLK_e) { _queued_anim_update = 1; } else if (key_ == SDLK_q) { _queued_anim_update = -1; } } } void Snake::HandleRepeatInput(SDL_Keycode key_) { if (_queued_direction == UP && key_ == SDLK_UP) { _ticks_per_frame = 1; } else if (_queued_direction == DOWN && key_ == SDLK_DOWN) { _ticks_per_frame = 1; } else if (_queued_direction == LEFT && key_ == SDLK_LEFT) { _ticks_per_frame = 1; } else if (_queued_direction == RIGHT && key_ == SDLK_RIGHT) { _ticks_per_frame = 1; } } Uint16 Snake::Update() { SDL_RenderFillRect(_graphics->get_renderer(), &_head->get_tile()->pixel_rect); _update_status = NONE; switch (_state) { case SnakeState::AGAINST_SEGMENT: _update_status |= HIT_SELF; break; case SnakeState::AGAINST_WALL: _update_status |= HIT_WALL; break; } switch (_state) { case SnakeState::MOVING: if(_debug_input) printf("%04d ", _current_tick); if (_current_tick >= _total_ticks) { ActionComplete(); _current_tick = 0; if (_debug_input) printf("\n"); } else { if (_current_tick % _ticks_per_frame == 0 && _current_tick != 0) { if (_debug_animations) { _debug_anim->advance_frame(); } _head->AdvanceAllAnimations(); _head->AdvanceAllAnimations(); //_head->AdvanceAllAnimations(); } _current_tick++; } break; case SnakeState::AGAINST_SEGMENT: case SnakeState::AGAINST_WALL: _fail_tick++; if (_fail_tick >= _ticks_before_fail) { _state = SnakeState::DEAD; _update_status |= DIED; } if (_input_queue.get_size() > 0) { OnTile next_on_tile = CheckNextTile(_input_queue.peek()); if (next_on_tile == NOTHING || next_on_tile == FOOD) { CommitInput(); CommitHeadDirection(); _fail_tick = 0; _state = MOVING; } else { if (_debug_input) printf("cl:%d ", _input_queue.get_size()); _input_queue.clear(); } } break; case SnakeState::DEAD: break; } if (_debug_animations) { if (_debug_animation_tick >= _ticks_per_frame * _frames_per_action) { if (_queued_anim_update < 0) { _current_anim = ((_current_anim + 36) + _queued_anim_update) % 36; } else if (_queued_anim_update > 0) { _current_anim = (_current_anim + _queued_anim_update) % 36; } UpdateTmpAnim(); _queued_anim_update = 0; _debug_animation_tick = 0; } else { if (_debug_animation_tick % _ticks_per_frame == 0 && _debug_animation_tick != 0) { _debug_anim->advance_frame(); } _debug_animation_tick++; } } return _update_status; } void Snake::Render() { _head->RenderAll(_graphics->get_renderer()); if(_debug_animations) _debug_anim->Render(_graphics->get_renderer()); } Snake::SnakeState Snake::get_state() { return _state; } void Snake::UpdateTmpAnim() { if (_queued_anim_update != 0) { SegmentAnimationTemplate *fill_anim = &_body_straight_template[0]; if (_current_anim < 4) { fill_anim = &_head_straight_template[_current_anim]; } else if (_current_anim < 12) { fill_anim = &_head_turn_template[_current_anim - 4]; } else if (_current_anim < 16) { fill_anim = &_body_straight_template[_current_anim - 12]; } else if (_current_anim < 24) { fill_anim = &_body_turn_template[_current_anim - 16]; } else if (_current_anim < 28) { fill_anim = &_tail_straight_template[_current_anim - 24]; } else if (_current_anim < 36) { fill_anim = &_tail_turn_template[_current_anim - 28]; } Tile* tile = _grid->get_tile(_debug_animation_tile.y, _debug_animation_tile.x); _debug_anim->set_frames(fill_anim->frames); _debug_anim->set_pos(fill_anim->bound.x * _grid->get_scale_factor() + tile->pixel_rect.x, fill_anim->bound.y * _grid->get_scale_factor() + tile->pixel_rect.y); _debug_anim->set_bounds(fill_anim->bound.w * _grid->get_scale_factor(), fill_anim->bound.h * _grid->get_scale_factor()); _debug_anim->set_flip(fill_anim->flip); _debug_anim->restart(); } } Segment* Snake::CreateSegment() { Animation* seg_animation = new Animation(NULL, true); Segment* segment = new Segment(seg_animation); return segment; } void Snake::ActionComplete() { update_based_on_direction(_last_direction, _head_x, _head_y); CheckHeadTile(); UpdateSegments(); CommitInput(); switch (CheckNextTile(_queued_direction)) { case FOOD: case NOTHING: _ticks_per_frame = 1; CommitHeadDirection(); break; case SEGMENT: _state = SnakeState::AGAINST_SEGMENT; _update_status |= HIT_SELF_INITIAL; if (_debug_input) printf("cl:%d ", _input_queue.get_size()); _input_queue.clear(); break; case WALL: _state = SnakeState::AGAINST_WALL; _update_status |= HIT_WALL_INITIAL; if (_debug_input) printf("cl:%d ", _input_queue.get_size()); _input_queue.clear(); break; } } void Snake::UpdateSegments() { if (_length <= 3) { int tail_x = _tail->get_tile()->grid_x, tail_y = _tail->get_tile()->grid_y; update_based_on_direction(_tail->get_incoming(), tail_x, tail_y); _tail->set_tile(_grid->get_tile(tail_y, tail_x)); _tail->set_incoming(_tail->get_previous()->get_incoming()); _tail->set_outgoing(_tail->get_previous()->get_outgoing()); Segment* next = _head->get_next(); int middle_x = next->get_tile()->grid_x, middle_y = next->get_tile()->grid_y; update_based_on_direction(next->get_incoming(), middle_x, middle_y); next->set_tile(_grid->get_tile(middle_y, middle_x)); next->set_incoming(next->get_previous()->get_incoming()); next->set_outgoing(next->get_previous()->get_outgoing()); _head->set_tile(_grid->get_tile(_head_y, _head_x)); _grid->set_on_tile(tail_x, tail_y, OnTile::NOTHING); _grid->set_on_tile(_head_y, _head_x, OnTile::SEGMENT); } else { if (!_extending) { int tail_x = _tail->get_tile()->grid_x, tail_y = _tail->get_tile()->grid_y; _grid->set_on_tile(tail_y, tail_x, OnTile::NOTHING); update_based_on_direction(_tail->get_incoming(), tail_x, tail_y); _tail->set_tile(_grid->get_tile(tail_y, tail_x)); _tail->set_incoming(_tail->get_previous()->get_incoming()); _tail->set_outgoing(_tail->get_previous()->get_outgoing()); UpdateSegmentAnimation(_tail); } else { _tail->set_outgoing(get_opposite_direction(_tail->get_incoming())); UpdateSegmentAnimation(_tail); _extending = false; } Segment* after_tail = _tail->get_previous(); after_tail->remove(); _head->insert_before(after_tail); after_tail->set_incoming(_head->get_incoming()); after_tail->set_outgoing(_head->get_outgoing()); after_tail->set_tile(_head->get_tile()); _head->set_tile(_grid->get_tile(_head_y, _head_x)); UpdateSegmentAnimation(_head->get_next()); _grid->set_on_tile(_head_y, _head_x, OnTile::SEGMENT); } } void Snake::UpdateSegmentAnimation(Segment * segment_) { SegmentAnimationTemplate* animation_template = &_body_straight_template[0]; int index = 0; bool straight = false; switch (segment_->get_outgoing()) { case DOWN: switch (segment_->get_incoming()) { case LEFT: index = 0; break; case UP: straight = true; index = 0; break; case RIGHT: index = 1; break; } break; case LEFT: switch (segment_->get_incoming()) { case UP: index = 2; break; case RIGHT: straight = true; index = 1; break; case DOWN: index = 3; break; } break; case UP: switch (segment_->get_incoming()) { case RIGHT: index = 4; break; case DOWN: straight = true; index = 2; break; case LEFT: index = 5; break; } break; case RIGHT: switch (segment_->get_incoming()) { case DOWN: index = 6; break; case LEFT: straight = true; index = 3; break; case UP: index = 7; break; } break; } switch (segment_->get_type()) { case Segment::SegmentType::HEAD: if (straight) { animation_template = &_head_straight_template[index]; } else { animation_template = &_head_turn_template[index]; } break; case Segment::SegmentType::BODY: if (straight) { animation_template = &_body_straight_template[index]; } else { animation_template = &_body_turn_template[index]; } break; case Segment::SegmentType::TAIL: if (!_extending) { if (straight) { animation_template = &_tail_straight_template[index]; } else { animation_template = &_tail_turn_template[index]; } } else { animation_template = &_tail_wait_template[index]; } break; } segment_->UpdateAnimation(*animation_template, _grid->get_scale_factor()); } void Snake::CommitHeadDirection() { _update_status |= MOVED; if (_queued_direction != _last_direction) { _update_status |= TURNED; } _head->set_outgoing(get_opposite_direction(_last_direction)); _head->set_incoming(_queued_direction); UpdateSegmentAnimation(_head); _last_direction = _queued_direction; _head->ResetAllAnimations(); } void Snake::CheckHeadTile() { Tile* tile = _grid->get_tile(_head_y, _head_x); switch(tile->on_tile) { case FOOD: Extend(); _grid->set_on_tile(_head_y, _head_x, NOTHING); _update_status |= ATE; break; } } OnTile Snake::CheckNextTile(Direction direction_) { int next_x = _head_x, next_y = _head_y; update_based_on_direction(direction_, next_x, next_y, false); if (0 > next_x || next_x > _grid->get_grid_size() - 1 || 0 > next_y || next_y > _grid->get_grid_size() - 1) { return WALL; } else { return _grid->get_tile(next_y, next_x)->on_tile; } } void Snake::CommitInput() { if (_input_queue.has_more()) { _queued_direction = _input_queue.pop(); switch (_queued_direction) { case UP: if (_debug_input) printf("-U%02d ", _input_queue.get_size()); break; case DOWN: if (_debug_input) printf("-D%02d ", _input_queue.get_size()); break; case LEFT: if (_debug_input) printf("-L%02d ", _input_queue.get_size()); break; case RIGHT: if (_debug_input) printf("-R%02d ", _input_queue.get_size()); break; } } } void Snake::Extend() { _extending = true; Segment* segment = CreateSegment(); segment->set_type(Segment::SegmentType::BODY); _tail->get_previous()->insert_before(segment); } int Snake::update_based_on_direction(Direction direction_, int& x_, int& y_, bool force_bound_) { switch (direction_) { case UP: if (y_ == 0 && force_bound_) { return 0; } else { y_--; } break; case DOWN: if (y_ == _grid->get_grid_size() - 1 && force_bound_) { return 0; } else { y_++; } break; case LEFT: if (x_ == 0 && force_bound_) { return 0; } else { x_--; } break; case RIGHT: if (x_ == _grid->get_grid_size() - 1 && force_bound_) { return 0; } else { x_++; } break; } return 1; } Direction Snake::direction_from_key(SDL_Keycode key_) { switch (key_) { case SDLK_UP: return UP; case SDLK_DOWN: return DOWN; case SDLK_LEFT: return LEFT; case SDLK_RIGHT: return RIGHT; default: return INVALID; } } <file_sep>/SnakeGame/SpriteAnimationFrames.cpp #include "SpriteAnimationFrames.h" void SpriteAnimationFrames::Render(SDL_Renderer* renderer_, SDL_Rect* dst_, int sprite_index_, double angle_, SDL_Point* center_, SDL_RendererFlip flip_) { SDL_Rect* src = NULL; if (_sprite_defs.size() > 0) { src = &_sprite_defs[sprite_index_]; if (center_ == NULL) { SDL_Point point = { _sprite_defs[sprite_index_].w / 2, _sprite_defs[sprite_index_].h / 2 }; center_ = &point; } } SDL_RenderCopyEx(renderer_, _texture, src, dst_, angle_, center_, flip_); } void SpriteAnimationFrames::AddSpriteDef(SDL_Rect def_) { _sprite_defs.push_back(def_); } void SpriteAnimationFrames::ClearSpriteDefs() { _sprite_defs.clear(); } void SpriteAnimationFrames::CreateSpriteDefs(int cols_, int rows_, int width_, int height_, int num_sprites_, bool up_first_, bool left_first_, bool cols_first_) { _sprite_defs.clear(); int col_mod = 0, col_start = 0, row_mod = 0, row_start = 0;; if (left_first_) { col_mod = 1; } else { col_mod = -1; col_start = cols_ - 1; } if (up_first_) { row_mod = 1; } else { row_mod = -1; row_start = rows_ - 1; } int sprite_counter = 0; if (cols_first_) { for (int row = row_start; row < rows_ && row >= 0; row += row_mod) { for (int col = col_start; col < cols_ && col >= 0; col += col_mod) { SDL_Rect rect = { col * width_, row * height_, width_, height_ }; _sprite_defs.push_back(rect); sprite_counter++; if (sprite_counter >= num_sprites_) goto sprites_finished; } } } else { for (int col = col_start; col < cols_ && col >= 0; col += col_mod) { for (int row = row_start; row < rows_ && row >= 0; row += row_mod) { SDL_Rect rect = { col * width_, row * height_, width_, height_ }; _sprite_defs.push_back(rect); sprite_counter++; if (sprite_counter >= num_sprites_) goto sprites_finished; } } } sprites_finished:; } void SpriteAnimationFrames::CreateSpriteDefs(int cols_, int rows_, int width_, int height_, bool up_first_, bool left_first_, bool cols_first_) { CreateSpriteDefs(cols_, rows_, width_, height_, cols_ * rows_, up_first_, left_first_, cols_first_); } SDL_Rect SpriteAnimationFrames::get_frame(int frame_) { return _sprite_defs[frame_]; } int SpriteAnimationFrames::get_num_frames() { return _sprite_defs.size(); } <file_sep>/SnakeGame/SpriteAnimationFrames.h #pragma once #include "Sprite.h" class SpriteAnimationFrames : public Sprite { public: void Render(SDL_Renderer* renderer_, SDL_Rect* dst_ = NULL, int sprite_index_ = 0, double angle_ = 0.0, SDL_Point* center_ = NULL, SDL_RendererFlip flip_ = SDL_FLIP_NONE); void AddSpriteDef(SDL_Rect def_); void ClearSpriteDefs(); void CreateSpriteDefs(int cols_, int rows_, int width_, int height_, int num_sprites_, bool up_first_ = true, bool left_first_ = true, bool cols_first_ = true); void CreateSpriteDefs(int cols_, int rows_, int width_, int height_, bool up_first_ = true, bool left_first_ = true, bool cols_first_ = true); SDL_Rect get_frame(int frame_); int get_num_frames(); private: std::vector<SDL_Rect> _sprite_defs; }; <file_sep>/SnakeGame/LimitQueue.cpp #include "LimitQueue.h" LimitQueue::LimitQueue(int limit_) { _limit = std::max(limit_, 1); } void LimitQueue::enqueue(Direction direction) { if (_queue.size() == _limit) { _queue.pop(); } _queue.push(direction); } Direction LimitQueue::pop() { Direction direction = _queue.front(); _queue.pop(); return direction; } Direction LimitQueue::peek() { return _queue.front(); } void LimitQueue::clear() { while (_queue.size() > 0) _queue.pop(); } bool LimitQueue::has_more() { return (_queue.size() > 0); } int LimitQueue::get_size() { return _queue.size(); } <file_sep>/SnakeGame/Sprite.h #pragma once #include <SDL.h> #include <vector> #include <string> #include "SDL2_rotozoom.h" class Sprite { public: Sprite(); ~Sprite(); enum Rotation { NONE, ONE, TWO, THREE }; bool LoadTexture(SDL_Renderer* renderer_, std::string texture_path_, Rotation rotation_ = NONE); void Render(SDL_Renderer* renderer_, SDL_Rect* dst_ = NULL, double angle_ = 0.0, SDL_Point* center_ = NULL, SDL_RendererFlip flip_ = SDL_FLIP_NONE); void SetColor(Uint8 red_, Uint8 green_, Uint8 blue_); int get_texture_width(); int get_texture_height(); protected: SDL_Texture* _texture; int _texture_width; int _texture_height; }; <file_sep>/SnakeGame/Segment.cpp #include "Segment.h" Segment::Segment(Animation* anim_) : _anim(anim_), _next(NULL), _previous(NULL) {} Segment::~Segment() { } void Segment::RenderAll(SDL_Renderer * renderer_) { _anim->Render(renderer_); if (_next != NULL) { _next->RenderAll(renderer_); } } void Segment::AdvanceAllAnimations() { _anim->advance_frame(); if(_next != NULL) { _next->AdvanceAllAnimations(); } } void Segment::ResetAllAnimations() { _anim->restart(); if (_next != NULL) { _next->ResetAllAnimations(); } } void Segment::UpdateAnimation(const SegmentAnimationTemplate &animation_template_, int scale_factor_) { _anim->set_frames(animation_template_.frames); _anim->set_pos(animation_template_.bound.x * scale_factor_ + _tile->pixel_rect.x, animation_template_.bound.y * scale_factor_ + _tile->pixel_rect.y); _anim->set_bounds(animation_template_.bound.w * scale_factor_, animation_template_.bound.h * scale_factor_); _anim->set_flip(animation_template_.flip); _anim->restart(); } Animation * Segment::get_animation() { return _anim; } void Segment::insert_before(Segment * segment_) { segment_->_previous = this; segment_->_next = _next; _next->_previous = segment_; _next = segment_; } void Segment::remove() { _previous->_next = _next; _next->_previous = _previous; } void Segment::set_type(SegmentType type_) { _type = type_; } Segment::SegmentType Segment::get_type() { return _type; } void Segment::set_next(Segment * next_) { _next = next_; } Segment * Segment::get_next() { return _next; } void Segment::set_previous(Segment * previous_) { _previous = previous_; } Segment * Segment::get_previous() { return _previous; } void Segment::set_incoming(Direction incoming_) { _incoming = incoming_; } Direction Segment::get_incoming() { return _incoming; } void Segment::set_outgoing(Direction outgoing_) { _outgoing = outgoing_; } Direction Segment::get_outgoing() { return _outgoing; } void Segment::set_tile(Tile * tile_) { _tile = tile_; } Tile * Segment::get_tile() { return _tile; } <file_sep>/SnakeGame/Grid.cpp #include "Grid.h" #include <cstdio> Grid::Grid(int pixel_width_, int pixel_height_, int grid_size_) { bool width_larger = true; int larger = 0; if (pixel_width_ > pixel_height_) { larger = pixel_width_; _grid_pixels = pixel_height_; } else { width_larger = false; larger = pixel_height_; _grid_pixels = pixel_width_; } _grid_size = grid_size_; _margin_offset = (larger - _grid_pixels) / 2; _pixels_per_tile = _grid_pixels / _grid_size; _scale_factor = _pixels_per_tile / 10; _tiles = new Tile*[_grid_size]; for (int row = 0; row < _grid_size; ++row) { _tiles[row] = new Tile[_grid_size]; } for (int row = 0; row < _grid_size; ++row) { for (int col = 0; col < _grid_size; ++col) { int pixel_x = col * _pixels_per_tile; int pixel_y = row * _pixels_per_tile; if (width_larger) { pixel_x += _margin_offset; } else { pixel_y += _margin_offset; } _tiles[row][col].Init(col, row, pixel_x, pixel_y, _pixels_per_tile, _pixels_per_tile, OnTile::NOTHING); } } _available_tiles = _grid_size * _grid_size; } Grid::~Grid() { for (int row = 0; row < _grid_size; ++row) { delete[] _tiles[row]; } delete[] _tiles; } Tile * Grid::get_tile(int row_, int col_) { return &_tiles[row_][col_]; } void Grid::set_on_tile(int row_, int col_, OnTile on_tile_) { Tile* tile = &_tiles[row_][col_]; if (tile->on_tile == NOTHING && on_tile_ != NOTHING) { _available_tiles--; } else if (tile->on_tile != NOTHING && on_tile_ == NOTHING) { _available_tiles++; } tile->on_tile = on_tile_; } void Grid::set_on_tile(Tile * tile_, OnTile on_tile_) { set_on_tile(tile_->grid_y, tile_->grid_x, on_tile_); } int Grid::get_scale_factor() { return _scale_factor; } int Grid::get_available_tiles() { return _available_tiles; } int Grid::get_grid_size() { return _grid_size; } int Grid::get_margin_offset() { return _margin_offset; } int Grid::get_pixels_per_tile() { return _pixels_per_tile; } void Grid::print_grid() { for (int row = 0; row < _grid_size; ++row) { for (int col = 0; col < _grid_size; ++col) { printf("%d", get_tile(row, col)->on_tile); } printf("\n"); } } <file_sep>/SnakeGame/Animation.cpp #include "Animation.h" Animation::Animation(SpriteAnimationFrames* frames_, bool loop_) { _frames = frames_; _loop = loop_; } void Animation::Render(SDL_Renderer* renderer_) { _frames->Render(renderer_, &_dst, _current_frame, _rotation, &_center, _flip); } void Animation::advance_frame() { if (_current_frame + 1 >= _frames->get_num_frames()) { if (_loop) { restart(); } } else { _current_frame++; } } void Animation::restart() { _current_frame = 0; } void Animation::set_frames(SpriteAnimationFrames * frames_) { _frames = frames_; } void Animation::set_pos(int x_, int y_) { _dst.x = x_; _dst.y = y_; } void Animation::set_bounds(int width_, int height_) { _dst.w = width_; _dst.h = height_; } void Animation::set_dst(SDL_Rect &rect_) { _dst = rect_; } void Animation::set_center(int x_, int y_) { _center.x = x_; _center.y = y_; } void Animation::set_rotation(double rotation_) { _rotation = rotation_; } void Animation::set_flip(SDL_RendererFlip flip_) { _flip = flip_; } <file_sep>/SnakeGame/SnakeGame.cpp #include "SnakeGame.h" #include <iostream> #include <SDL.h> #include <SDL_image.h> #include <cstdio> #include <math.h> const std::string SnakeGame::VERSION = "1.0"; SnakeGame::SnakeGame(GameSize size_) : _rng(std::random_device()()), _frames(0) { SDL_Init(0); _graphics.Init("Snake Game Version " + SnakeGame::VERSION, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP , SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC, IMG_INIT_PNG, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 480, 360); // possibly make a class for this instead of just doing audio here. SDL_InitSubSystem(SDL_INIT_AUDIO); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) < 0) { printf("Mixer failed to initialize. %s\n", Mix_GetError()); } // make "background" refresh color black SDL_SetRenderDrawColor(_graphics.get_renderer(), 0x00, 0x00, 0x00, 0xFF); LoadMedia(); _grid = new Grid(_graphics.get_screen_width(), _graphics.get_screen_height(), size_); for (int i = 0; i < 4; i++) { AddFood(); } _grid->set_on_tile(1, 1, OnTile::WALL); _grid->set_on_tile(2, 2, OnTile::WALL); _grid->set_on_tile(3, 3, OnTile::WALL); _grid->set_on_tile(4, 4, OnTile::WALL); _grid->set_on_tile(5, 5, OnTile::WALL); _grid->set_on_tile(6, 6, OnTile::WALL); _grid->set_on_tile(7, 7, OnTile::WALL); _grid->set_on_tile(8, 8, OnTile::WALL); _grid->set_on_tile(9, 9, OnTile::WALL); _grid->set_on_tile(10, 10, OnTile::WALL); _grid->set_on_tile(11, 11, OnTile::WALL); _grid->set_on_tile(12, 12, OnTile::WALL); _grid->set_on_tile(13, 13, OnTile::WALL); _grid->set_on_tile(14, 14, OnTile::WALL); _grid->set_on_tile(15, 15, OnTile::WALL); _grid->set_on_tile(16, 16, OnTile::WALL); _snake = new Snake(&_graphics, 100, 100, 200, _grid, 4, 9, 4, Direction::DOWN); _fps_timer.start(); } SnakeGame::~SnakeGame() { delete _snake; delete _grid; Mix_FreeMusic(_intro_music); Mix_FreeMusic(_main_music); Mix_FreeChunk(_hit_sound); Mix_FreeChunk(_death_sound); Mix_FreeChunk(_grow_sound); Mix_FreeChunk(_movement_sound); Mix_FreeChunk(_turn_sound); Mix_Quit(); IMG_Quit(); SDL_Quit(); } void SnakeGame::RunGame() { bool quit = false; SDL_Event e; Uint32 start = SDL_GetTicks(); while (!quit) { while (SDL_PollEvent(&e) > 0) { if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE || e.type == SDL_QUIT) { quit = true; } else { switch (_game_state) { case RUNNING: if (e.key.repeat == 0) { _snake->HandleInput(e.key.keysym.sym); } else { _snake->HandleRepeatInput(e.key.keysym.sym); } break; case OVER: if (e.key.keysym.sym == SDLK_r) { delete _snake; _snake = new Snake(&_graphics, 100, 100, 200, _grid, 4, 9, 4, Direction::DOWN); _game_state = RUNNING; } break; } } } } switch (_game_state) { case RUNNING: UpdateAll(); RenderAll(); break; case OVER: break; } /* if (_frames > 0 && _frames % 240 == 0) { double fps = ((double)_frames) / (((double)_fps_timer.get_runtime()) / 1000); printf("fps: %.2f\n", fps); } _frames++; system("CLS"); _grid->print_grid(); */ } } void SnakeGame::UpdateAll() { Uint8 _result; _result = _snake->Update(); if (_result & Snake::ATE) { Mix_PlayChannel(-1, _grow_sound, 0); AddFood(); } if (_result & Snake::HIT_SELF_INITIAL || _result & Snake::HIT_WALL_INITIAL) { Mix_PlayChannel(-1, _hit_sound, 0); } if (_result & Snake::DIED) { Mix_PlayChannel(-1, _death_sound, 0); _game_state = OVER; } if (_result & Snake::TURNED) { Mix_PlayChannel(-1, _turn_sound, 0); } else if (_result & Snake::MOVED) { Mix_PlayChannel(-1, _movement_sound, 0); } } void SnakeGame::RenderAll() { SDL_RenderClear(_graphics.get_renderer()); for (int row = 0; row < _grid->get_grid_size(); row++) { for (int col = 0; col < _grid->get_grid_size(); col++) { Tile* tile = _grid->get_tile(row, col); _ground.Render(_graphics.get_renderer(), &tile->pixel_rect); switch (tile->on_tile) { case FOOD: _food.Render(_graphics.get_renderer(), &tile->pixel_rect); break; case WALL: _wall.Render(_graphics.get_renderer(), &tile->pixel_rect); break; } } } _snake->Render(); SDL_RenderPresent(_graphics.get_renderer()); } void SnakeGame::AddFood() { int available_tiles = _grid->get_available_tiles(); if (available_tiles <= 0) { return; } std::uniform_int_distribution<int> dist(1, available_tiles); int tile_index = dist(_rng) - 1; int available_count = 0; for (int row = 0; row < _grid->get_grid_size(); row++) { for (int col = 0; col < _grid->get_grid_size(); col++) { Tile* tile = _grid->get_tile(row, col); if (tile->on_tile == NOTHING) { if (available_count >= tile_index) { printf("Food added at: (%d, %d)\n", col, row); _grid->set_on_tile(row, col, FOOD); goto food_placed; } else { available_count++; } } } } food_placed:; } void SnakeGame::LoadMedia() { _wall.LoadTexture(_graphics.get_renderer(), "Art/Grid/PlaceholderWall.png"); _ground.LoadTexture(_graphics.get_renderer(), "Art/Grid/PlaceholderGround.png"); _food.LoadTexture(_graphics.get_renderer(), "Art/Grid/TempFood.png"); /*_intro_music = Mix_LoadMUS("Sound/Snake_Intro.wav"); if (_intro_music == NULL) { printf("Failed to load intro music. %s\n", Mix_GetError()); } _main_music = Mix_LoadMUS("Sound/Snake_Main.wav"); if (_main_music == NULL) { printf("Failed to load main music. %s\n", Mix_GetError()); }*/ _hit_sound = Mix_LoadWAV("Sound/Snake_Pre-Death.wav"); if (_hit_sound == NULL) { printf("Failed to load hit sound. %s\n", Mix_GetError()); } _death_sound = Mix_LoadWAV("Sound/Snake_Death.wav"); if (_death_sound == NULL) { printf("Failed to load death sound. %s\n", Mix_GetError()); } _grow_sound = Mix_LoadWAV("Sound/Snake_Grow.wav"); if (_grow_sound == NULL) { printf("Failed to load grow sound. %s\n", Mix_GetError()); } _movement_sound = Mix_LoadWAV("Sound/Snake_Movement.wav"); if (_movement_sound == NULL) { printf("Failed to load move sound. %s\n", Mix_GetError()); } _turn_sound = Mix_LoadWAV("Sound/Snake_Turn.wav"); if (_turn_sound == NULL) { printf("Failed to load turn sound. %s\n", Mix_GetError()); } } int main(int argc, char* args[]) { SnakeGame game(SnakeGame::GameSize::EIGHTEEN); game.RunGame(); /* Graphics graphics; graphics.Init("Snake Game Version " + SnakeGame::VERSION, SDL_WINDOW_SHOWN //| SDL_WINDOW_FULLSCREEN_DESKTOP , SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC, IMG_INIT_PNG, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 200, 200); SpriteAnimationFrameRotations rotations; rotations.LoadRotations(graphics.get_renderer(), "Art/Snake/PlaceholderHeadStraight.png", 4, 3, 10, 20, 12); SpriteAnimationFrames frames = rotations.get_rotation_frames(Sprite::THREE); Animation anim(&frames, true); //anim.set_flip(SDL_RendererFlip::SDL_FLIP_VERTICAL); SDL_Rect dst = { 0, 0, 100, 200 }; anim.set_dst(dst); SDL_SetRenderDrawColor(graphics.get_renderer(), 0xFF, 0xFF, 0xFF, 0xFF); int count = 0; while (true) { count++; if (count % 5) { anim.advance_frame(); } SDL_RenderClear(graphics.get_renderer()); anim.Render(graphics.get_renderer()); SDL_RenderPresent(graphics.get_renderer()); SDL_Delay(100); } */ return 0; }<file_sep>/SnakeGame/Timer.h #pragma once #include <SDL.h> class Timer { public: Timer(); ~Timer(); void start(); void stop(); void reset(); void pause(); void resume(); Uint32 get_runtime(); bool is_paused(); bool is_running(); private: int _start_time; int _pause_time; bool _paused; bool _running; }; <file_sep>/SnakeGame/Sprite.cpp #include "Sprite.h" #include <SDL_image.h> #include <cstdio> Sprite::Sprite() : _texture(NULL) {} Sprite::~Sprite() { SDL_DestroyTexture(_texture); } bool Sprite::LoadTexture(SDL_Renderer* renderer_, std::string texture_path_, Rotation rotation_) { SDL_Surface* surface = IMG_Load(texture_path_.c_str()); if (surface == NULL) { printf("Texture at %s couldn't load. %s", texture_path_, IMG_GetError()); return false; } if (rotation_ != NONE) { surface = rotateSurface90Degrees(surface, rotation_); } _texture_width = surface->w; _texture_height = surface->h; SDL_Texture* loaded_texture = SDL_CreateTextureFromSurface(renderer_, surface); if (loaded_texture == NULL) { printf("Texture at %s couldn't load. %s", texture_path_, SDL_GetError()); return false; } SDL_FreeSurface(surface); _texture = loaded_texture; return true; } void Sprite::Render(SDL_Renderer* renderer_, SDL_Rect* dst_, double angle_, SDL_Point* center_, SDL_RendererFlip flip_) { SDL_RenderCopyEx(renderer_, _texture, NULL, dst_, angle_, center_, flip_); } void Sprite::SetColor(Uint8 red, Uint8 green, Uint8 blue) { SDL_SetTextureColorMod(_texture, red, green, blue); } int Sprite::get_texture_width() { return _texture_width; } int Sprite::get_texture_height() { return _texture_height; }<file_sep>/SnakeGame/Graphics.h #pragma once #include <string> #include <SDL.h> #include <SDL_image.h> class Graphics { public: Graphics(); ~Graphics(); bool Init(std::string title_, Uint32 window_flags_, Uint32 renderer_flags_, int img_flags_, int x_, int y_, int width_, int height_); SDL_Window* get_window(); SDL_Renderer* get_renderer(); int get_screen_width(); int get_screen_height(); private: int SCREEN_WIDTH; int SCREEN_HEIGHT; SDL_Window* _window; SDL_Renderer* _renderer; }; <file_sep>/SnakeGame/SpriteAnimationFrameRotations.cpp #include "SpriteAnimationFrameRotations.h" SpriteAnimationFrameRotations::SpriteAnimationFrameRotations() { } void SpriteAnimationFrameRotations::LoadRotations(SDL_Renderer* renderer_, std::string texture_path_, int cols_, int rows_, int width_, int height_, int num_sprites_) { _rotations[0].LoadTexture(renderer_, texture_path_); _rotations[1].LoadTexture(renderer_, texture_path_, Sprite::ONE); _rotations[2].LoadTexture(renderer_, texture_path_, Sprite::TWO); _rotations[3].LoadTexture(renderer_, texture_path_, Sprite::THREE); _rotations[0].CreateSpriteDefs(cols_, rows_, width_, height_, num_sprites_); _rotations[1].CreateSpriteDefs(rows_, cols_, height_, width_, num_sprites_, true, false, false); _rotations[2].CreateSpriteDefs(cols_, rows_, width_, height_, num_sprites_, false, false, true); _rotations[3].CreateSpriteDefs(rows_, cols_, height_, width_, num_sprites_, false, true, false); } void SpriteAnimationFrameRotations::LoadRotations(SDL_Renderer * renderer_, std::string texture_path_, int cols_, int rows_, int width_, int height_, int num_sprites_, Uint8 red_, Uint8 green_, Uint8 blue_) { _rotations[0].LoadTexture(renderer_, texture_path_); _rotations[0].SetColor(red_, green_, blue_); _rotations[1].LoadTexture(renderer_, texture_path_, Sprite::ONE); _rotations[1].SetColor(red_, green_, blue_); _rotations[2].LoadTexture(renderer_, texture_path_, Sprite::TWO); _rotations[2].SetColor(red_, green_, blue_); _rotations[3].LoadTexture(renderer_, texture_path_, Sprite::THREE); _rotations[3].SetColor(red_, green_, blue_); _rotations[0].CreateSpriteDefs(cols_, rows_, width_, height_, num_sprites_); _rotations[1].CreateSpriteDefs(rows_, cols_, height_, width_, num_sprites_, true, false, false); _rotations[2].CreateSpriteDefs(cols_, rows_, width_, height_, num_sprites_, false, false, true); _rotations[3].CreateSpriteDefs(rows_, cols_, height_, width_, num_sprites_, false, true, false); } SpriteAnimationFrames* SpriteAnimationFrameRotations::get_rotation_frames(Sprite::Rotation rotation_) { return &_rotations[rotation_]; } <file_sep>/SnakeGame/Direction.cpp #include "Direction.h" Direction get_opposite_direction(Direction direction_) { switch (direction_) { case UP: return DOWN; case DOWN: return UP; case LEFT: return RIGHT; case RIGHT: return LEFT; } }
8ff5b007c83bb24eb00d4388a4d888783b1576c7
[ "C", "C++" ]
26
C++
austingibb/SnakeGame
23a46c74984448628c80e90a03365039f504dd0e
9b6592c54a1c9816206df9daf63764abb682cf0b
refs/heads/master
<repo_name>kylemarshall962/Monte-Carlo-Ex<file_sep>/Monte Carlo Example.R ##Monte Carlo Simulation to determine pi given a jpeg of a circumscirbed square and an ratio of areas of pi/4 ## Libraries library("jpeg") library("raster") ##Cicle Image jpg <- readJPEG("squareCircle.jpg") res = dim(jpg)[1:2] plot(1,1,xlim=c(1,res[1]),ylim=c(1,res[2]),asp=1,type='n',xaxs='i',yaxs='i',xaxt='n',yaxt='n',xlab='',ylab='',bty='n') rasterImage(jpg,1,1,res[1],res[2]) rst.blue <- raster(jpg[,,1]) rst.green <- raster(jpg[,,2]) rst.red <- raster(jpg[,,3]) Y = 0.2126*rst.red + 0.7152*rst.green + 0.0722*rst.blue bw <- as.matrix(Y) as.numeric(Sys.time())-> t set.seed((t - floor(t)) * 1e8 -> seed) mc <- round(sample(bw, 30000), 0) tbl <- table(mc) pi <- round(4*tbl[2]/(tbl[1]+tbl[2]),6) print(paste("estimate of pi:", pi)) error <- round((100*abs(3.14159-pi)/3.14159),6) print(paste("Error:", error))
bf9d127a36e3a740c657ebee9616e677348086ec
[ "R" ]
1
R
kylemarshall962/Monte-Carlo-Ex
19f0b92f5c0921f14866e97db1fddb0d5c1b90cd
90e65a6ddc306faa2b63721f43b109e33c58dee7
refs/heads/master
<repo_name>mbakhoff/sockets-template<file_sep>/readme.md # TCP sockets in Java TCP sockets enable communication between programs within the same machine or across different machines. Data can be sent/received using the regular Java OutputStream/InputStream. ``` Socket s = connect(); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // send and receive data from the connected program ``` ## Estabilishing a connection The connection is established between two programs. One of the programs (the server) will wait for an incoming connection and accept it. The other program (the client) will create an outgoing connection to the server. To connect to the server, the client needs to know the server's **IP address** and **port number**. An IP address uniquely identifies a machine in the network. It is usually written as 4 dot-separated integers, e.g. `192.168.1.1`. A machine can have several IP addresses if it has several network cards (some may be virtual). Each machine also has a loopback IP address called *localhost*: `127.0.0.1`. This can be used to refer to the local machine and make connections to it. Each machine can have multiple programs running on it, each of them creating and accepting connections. Port numbers are used to differentiate between different connections. A program can claim any free port number for any local IP address and use it to accept and create connections. The connections are identified by the quadruples of { local ip, local port, remote ip, remote port }. One way to think about the IP addresses and ports is to use the apartment building analogy. The IP address is the building's address. The port number is the mailbox number in a building. Different owners (programs) can own different mailboxes in a building (IP). When a message arrives at some building (IP), the house keeper (operating system) will deliver the message to the right mailbox (program) by looking at the mailbox number (port number). Incoming connections can be accepted in Java using the `ServerSocket` class: ``` int portNumber = 8080; // allocate port on all available IP addresses try (ServerSocket ss = new ServerSocket(portNumber)) { // wait for an incoming connection try (Socket socket = ss.accept()) { // use connection } } ``` What's the difference between `Socket` and `ServerSocket`? * A ServerSocket **holds a queue of incoming connections** on the specified port. It does not represent a connection. * A Socket **represents a connection**. It is defined by its { local ip, local port, remote ip, remote port } quadruple. Outgoing connections can be created in Java using the `Socket` class: ``` // connect to port 8080 of the local machine using the loopback address // note that 8080 is the "remote port". local port number is chosen automatically (randomly) try (Socket socket = new Socket("localhost", 8080)) { // use the input/output streams here } ``` ## Tips and tricks * This repository includes a runnable example. Start the server first. Start the client while the server is still running, otherwise there is nothing to accept the client's connection. * It is possible to accept multiple connections from a single `ServerSocket`. Usually `accept()` is called in some sort of loop. * Sockets accepted from the same ServerSocket use the same local port, but the remote ip/port are different. * InputStream methods can block when trying to read more than the remote has sent. To see what the code is waiting for, use the "Thread dump" button in the IDE debugger panel or the *jstack* command line utility. * Ports numbered 1-1024 are *privileged ports*, often used to run system services. Trying to use these can throw an exception unless the program is runnings with admin rights. Use a higher numbered port instead. * You can check your machine's IP using these commands: `ip addr` (Linux), `ifconfig` (Mac) or `ipconfig` (Windows). * Sometimes the local firewall configuration prevents accepting connections from remote machines (Windows or locked down Linux). Sometimes the router configuration prevents creating connections to other machines in the local network (e.g. university wifi). ## How to organize network communication The most common way to communicate over the network is to use the [request-response pattern](https://en.wikipedia.org/wiki/Request%E2%80%93response). The client sends a message to the server and the server sends a reply. The client won't send a new message before receiving a reply for the previous one. The server never sends any non-reply messages to the client. Another important aspect in communication is the message syntax. A socket only provides the input/output streams that transfer bytes. The syntax describes how the data is encoded into bytes so it can be later reconstructed. ### Example syntax Here's an example of network communication between a service that can register students to courses and a client. The first byte of a message contains the message type. The next bytes contain the message content depending on the message type. 1) the client sends a byte array `[1,4,155,141,162,164]`. the first byte shows the message type `1` for "new registration". the second byte `4` is the length of the student's name, followed by 4 bytes `[155,141,162,164]` for a UTF-8 encoded string "mart". 2) the server responds with a single byte `[2]` - the message type for "registration ok". alternatively the server could respond with `[3,155,..]`, where the type `3` is for "registration error", followed by `155` for error length, followed by 155 bytes containing the bytes for the error string. 3) the client sends a new message.. The key to a good syntax is to add a length prefix to every variable length piece of data. Otherwise the receiver will have no way of knowing how much it needs to read. ### Using data streams Java has the DataOutputStream and DataInputStream classes with many useful helper methods. Make use of them! Sending strings is one of the most common operation. Let's take a look on how it could be done using data streams. ``` void writeStrings(DataOutputStream out) throws Exception { // bad example; don't do this! byte[] m1bytes = "message1".getBytes("UTF-8"); byte[] m2bytes = "message2".getBytes("UTF-8"); out.write(m1bytes); out.write(m2bytes); } ``` This code successfully sends two strings to the output stream. However, how can the receiver reconstruct this data? How could they find out where one string ends and another starts? There is not way to make such approach work reliably. The solution is to **send a length prefix** before each variable length piece of data. ``` void myWriteUTF(DataOutputStream out, String str) throws Exception { byte[] encoded = str.getBytes("UTF-8"); // always specify encoding out.writeInt(encoded.length); // int is always exactly 4 bytes out.write(encoded); } String myReadUTF(DataInputStream in) throws Exception { int length = in.readInt(); // read exactly 4 bytes byte[] encoded = in.readNBytes(length); // useful method! return new String(encoded, "UTF-8"); } ``` The above methods are so commonly needed that they were built into the data stream classes. The above could be replaced with simply `out.writeUTF(str)` and `in.readUTF()`. Datastreams make it easy to write more complex messages as well. Sending a request to get a student's grade for a course: ``` static final int TYPE_GET_GRADE = 4; void sendGetGradeRequest(DataOutputStream out, String studentId, int courseId) throws Exception { out.writeInt(TYPE_GET_GRADE); out.writeUTF(studentId); out.writeInt(courseId); } ``` Reading the request on the server side: ``` static final int TYPE_GET_GRADE = 4; static final int TYPE_GRADE_OK = 5; static final int TYPE_GRADE_ERROR = 6; void processRequest(DataInputStream in, DataOutputStream out) throws Exception { int type = in.readInt(); if (type == TYPE_GET_GRADE) { processGetGrade(in, out); } else { throw new RuntimeException("unknown type " + type); } } void processGetGrade(DataInputStream in, DataOutputStream out) throws Exception { String studentId = in.readUTF(); int courseId = in.readInt(); if (hasCompletedCourse(studentId, courseId)) { out.writeInt(TYPE_GRADE_OK); out.writeDouble(getGrade(studentId, courseId)); } else { out.writeInt(TYPE_GRADE_ERROR); } } ``` A few issues to avoid: * instead of `writeUTF(name + ";" + description)` use `writeUTF(name); writeUTF(description);`. this way there's no need split the strings manually and the code also works with names that include the `;` symbol. * instead of `writeUTF(Integer.toString(123))` use `writeInt(123)`. always try to use the right type and avoid unnecessary string conversions. * use `writeInt(123)` instead if `write(123)`. the parameter of `write` is an int (4 bytes), but it only sends a single byte (wtf java). ### Use xml/json for more complex data structures When you need to send a more complicated object over the network, then manually encoding and decoding it to/from bytes can be quite annoying. Encode the object into a string using [gson](https://github.com/google/gson/blob/master/UserGuide.md#TOC-Object-Examples), then send the string as the message value. Gson can decode the string back into the object on the receiving side. The string should still be wrapped with the regular type-length-value syntax. Note that string encoded messages are very space-inefficient. ## Notes on IPv6 There are two formats of IP addresses: IPv4 and IPv6. The old IPv4 addresses (e.g. `192.168.1.1`) are essentially 32-bit integers (the dot separated string is just a convenient notation). There are more computers on the planet than there are 32-bit integers, which causes all sorts of problems. The new IPv6 addresses are 128-bit integers that look something like `2001:0db8:0000:0000:0000:ff00:0042:8329` (8 groups of 16 bits each). The world is slowly moving to use these instead of IPv4. Some things to keep in mind when using IPv6 addresses: * leading zeros from any group can be removed * consecutive groups of zeroes can be omitted. this can only be done once in an address, otherwise it's impossible to reconstruct the address. * the address is often wrapped in brackets to avoid confusing the port number separator with the address group separators (both use `:`) For example, an URL containing the above address could be written as `https://[2001:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:42:8329]:8443/`. Note that the three groups of zeros have been omitted and all leading zeros have been removed. The port number 8443 is placed outside the brackets. <file_sep>/src/sample/Client.java package sample; import java.io.OutputStream; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { System.out.println("connecting to server"); try (Socket socket = new Socket("localhost", 8080); OutputStream out = socket.getOutputStream()) { System.out.println("connected; sending data"); int byteToSend = 42; out.write(byteToSend); System.out.println("sent " + byteToSend); } System.out.println("finished"); } }
a37af60832cad899f0791bc7b26a0fdf924e1ac3
[ "Markdown", "Java" ]
2
Markdown
mbakhoff/sockets-template
f4e55264a82d664855c522044060ac7bff5647e9
a407708a0fed8363e69e2c0b67d76c6950d4e95e
refs/heads/master
<file_sep>//je crée une variable firstname et j'attribut comme valeur une chaîne de caractères 'sylvie' var firstname = 'Sylvie'; //je demande à ce que ma variable firstname s'affiche dans une boite de dialogue grace à la fonction alert() alert(firstname);
a795859de8f8011330908916569cdacdaec0e11d
[ "JavaScript" ]
1
JavaScript
lenavenecsylvie95/JavascriptPartie1Exercice1
f210cb63c935236b7045a0e0330e1e34abe4292a
4eab023f0cdf2d6cb1bf55abdd20307dd522736f
refs/heads/master
<file_sep>/*! * @overview Simple data layer for ember * @copyright Copyright (c) 2013-2014 <NAME> * @author <NAME> (<EMAIL>) * * @license Licensed under MIT License * see: https://raw.github.com/BowlingX/simple-data/master/LICENSE */ (function (window, $, Ember) { "use strict"; /** * Init SimpleData Object */ if ('undefined' === typeof window.SD) { window.SD = {}; } /** * A Mixin for serialization * @link http://byronsalau.com/blog/convert-ember-objects-to-json/ * @type {*} */ SD.Serializable = Ember.Mixin.create({ serialize: function () { var result = {}; for (var key in $.extend(true, {}, this)) { // Skip these if (key === 'isInstance' || key === 'isDestroyed' || key === 'isDestroying' || key === 'concatenatedProperties' || typeof this[key] === 'function') { continue; } result[key] = this[key]; } return result; } }); /** * A Basic model that provides basic Caching algorithms * @type {*} */ SD.Model = Ember.Object.extend(SD.Serializable, { /** * Reloads a record * @returns {*} */ reload: function () { var $this = this; var data = this.constructor.reload(this); return data.then(function (r) { $this.replace(r); return $this; }); }, replace: function (data) { var newModel = this.constructor.applyMapping(data); this.setProperties(newModel); }, /** * Removes a record * @returns {*} */ remove: function () { var removed = this.constructor.remove(this); var $this = this; return removed.then(function () { $this.afterRemove(); return $this; }); }, afterRemove: function () { } }); /** * A Mixin that is applied when model is embedded into an array of parent Object * @type {*} */ SD.ModelArrayHolderMixin = Ember.Mixin.create({ _parent: null, _path: null, /** * A Reference to collection * @returns {*} */ getArrayRef: function () { return SD.Model.findPath(this._parent, this._path); }, /** * @returns parent element */ getParent: function () { return this._parent; }, /** * Removes element from parent array * @returns {*} */ removeFromArray: function () { return this.getArrayRef().removeObject(this); }, afterRemove: function () { this._super(); this.removeFromArray(); } }); /** * Holds Collection of Models * @type {*} */ SD.ModelArrayHolder = Ember.ArrayProxy.extend({ _parent: null, _path: null, add: function (thisRecord) { var $this = this; var addedRecord = thisRecord.constructor.add(thisRecord); return addedRecord.then(function (r) { var record = thisRecord.constructor.applyMappingForArray(r, $this._parent, $this._path); $this.addObject(record); return record; }); }, /** * Inserts a fully loaded record into collection at the beginning * @param idx index * @param data object */ insertElementAt: function (idx, data, type) { var object = type.applyMappingForArray(data, this._parent, this._path); this.insertAt(idx, object); return object; }, insertAfter: function (data, type) { var object = type.applyMappingForArray(data, this._parent, this._path); this.addObject(object); return object; } }); SD.AdapterOperationsMixin = Ember.Mixin.create({ /** * This creates a new Record * @param newRecord */ add: function (newRecord) { }, /** * Called when record.reload() ist called * @param oldRecord */ reload: function (oldRecord) { }, /** * Called when record.remove() is called * @param record */ remove: function (record) { }, /** * Called when Model.find(id) is called and record was not found in cache * Any number of arguments is allowed * @param id */ findRecord: function (id) { } }); /** * Static Methods for model */ SD.Model.reopenClass(SD.AdapterOperationsMixin, { _cache: [], _mapping: {}, /** * Will preload the data in a cache so find() method will ask the cache first * @param data either an object or an array */ preload: function (data) { data = this.serialize(data); if (data instanceof Array) { this._cache[this] = data; } else { this._cache[this] = []; this._cache[this].push(data); } }, serialize: function (payload) { return payload; }, map: function (key, type) { if (!this._mapping[this]) { this._mapping[this] = {} } this._mapping[this][key] = type; return this; }, /** * Executed if path is an Object * Will apply any mapping that is defined for this Model * @param object */ applyMapping: function (object) { // Create a Model of root Object (found Model) var appliedModel = (object instanceof this) ? object : this.create(object); // Now Apply mapping defined on this model to describe more models on this path // Valid mappings: // App.Model.map("object.path", App.MyModel) var $this = this; return object instanceof Array ? SD.ModelArrayHolder.create( {_parent: appliedModel, _path: "this", content: object.map(function (item) { return $this.applyMappingForArray(item, appliedModel, "this"); })}) : this._applyMapping(appliedModel); }, /** * Applys mapping to Model * @param appliedModel * @returns {*} * @private */ _applyMapping: function (appliedModel) { var $this = this; for (var prop in this._mapping[this]) { if (this._mapping[this].hasOwnProperty(prop)) { var model = this._mapping[this][prop]; $this._deepFindAndApply(appliedModel, prop, model) } } return appliedModel; }, /** * Executed if path is an array * @param object * @param p * @param path * @returns {*} */ applyMappingForArray: function (object, p, path) { var applied = this.createWithMixins(object, SD.ModelArrayHolderMixin); applied.set('_parent', p); applied.set('_path', path); return this._applyMapping(applied); }, /** * Finds an object by path * @param obj * @param path * @returns {*} */ findPath: function (obj, path) { var paths = path.split('.'), current = obj , i; for (i = 0; i < paths.length; ++i) { if (current[paths[i]] == undefined) { return undefined; } else { current = current[paths[i]]; } } return current; }, /** * Finds an Object, applies mapping and apply changes to object * @param obj * @param path * @param model * @returns {*} * @private */ _deepFindAndApply: function (obj, path, model) { var current = this.findPath(obj, path); if (!current) { return; } if (typeof current === 'object') { var value = current instanceof Array ? SD.ModelArrayHolder.create( {_parent: obj, _path: path, content: current.map(function (item) { return model.applyMappingForArray(item, obj, path); })}) : model.applyMapping(current); } this._setObjectPathToValue(obj, value, path); return obj; }, /** * Sets an object graph * @param obj object to modify * @param value value to set * @param path path to modify * @private */ _setObjectPathToValue: function (obj, value, path) { var paths = path.split('.'), parent = obj; for (var i = 0; i < paths.length - 1; i += 1) { parent = parent[paths[i]]; } parent[paths[paths.length - 1]] = value; }, /** * Will find an item by ID * @param id * @returns promise */ find: function (id) { var def = $.Deferred(); if (!this._cache[this]) { this._cache[this] = []; } var object = this._cache[this].find(function (item) { if (id === undefined) { return item; } return item.id && item.id === id; }); if (object) { return def.resolve(this.applyMapping(object)).promise(); } else { var $this = this; return this.findRecord.apply(this, arguments).then(function (result) { return $this.applyMapping(result); }); } }, /** * Invalidates cache */ invalidateCache: function () { this._cache[this] = []; } }); })(window, jQuery, Ember); <file_sep>simple-data =========== A very simple data wrapper for ember Usage ===== ```javascript // Define Model, no need to set any properties App.MyModel = SD.Model.extend({}); App.OtherModel = SD.Model.extend({}); // Map objects or arrays to other models simply by using dot notation App.Community.map('otherModelsProperty', App.OtherModel); ```
72ca1d81a85d567e4ed39b9a717d389510d4bcc1
[ "JavaScript", "Markdown" ]
2
JavaScript
BowlingX/simple-data
e7119acdbd9746eb98eaa420216aaceeea8352b9
ccac11cec45b59f88dc76e3bce3fd5853caeb680
refs/heads/main
<file_sep>require "rest-client" require "json" require "csv" # Get all posts from remote url posts_url = "https://jsonplaceholder.typicode.com/posts?_start=0&_limit=20" posts = RestClient.get(posts_url) # Create CSV File for posts def create_csv_doc(source, file_link) # Get all headers @headers = [] JSON.parse(source).each do |h| h.keys.each do |key| @headers << key end end # Uniq headers uniq_headers = @headers.uniq finalrow = [] JSON.parse(source).each do |h| final = {} @headers.each do |key2| final[key2] = h[key2] end finalrow << final end CSV.open(file_link , 'w') do |csv| csv << uniq_headers finalrow.each do |deal| csv << deal.values end end end create_csv_doc(posts, 'posts.csv')<file_sep>require "rest-client" require "json" require "csv" # Get all posts from remote url posts_url = "https://jsonplaceholder.typicode.com/posts?_start=0&_limit=20" comments_url = "https://jsonplaceholder.typicode.com/post/5/comments" list_comments = Array.new all_comments = Array.new comments_array = Array.new for i in 1..20 comment = "https://jsonplaceholder.typicode.com/post/#{i}/comments" list_comments.push(comment) end for comments_link in list_comments comments = RestClient.get(comments_link) all_comments.push(JSON.parse(comments)) # puts comments.class end posts = RestClient.get(posts_url) comments = RestClient.get(comments_url) p all_comments # Create CSV File for posts def create_csv_doc(source, file_link) # Get all headers @headers = [] JSON.parse(source).each do |h| h.keys.each do |key| @headers << key end end # Uniq headers uniq_headers = @headers.uniq finalrow = [] JSON.parse(source).each do |h| final = {} @headers.each do |key2| final[key2] = h[key2] end finalrow << final end CSV.open(file_link , 'w') do |csv| csv << uniq_headers finalrow.each do |deal| csv << deal.values end end end # create_csv_doc(posts, 'posts.csv') create_csv_doc(all_comments, 'comments.csv')<file_sep>require "rest-client" require "json" require "csv" array_link = [] for key in 1..20 url = "https://jsonplaceholder.typicode.com/posts/#{key}/comments" array_link.push(url) end array_values_link = [] for values in array_link read_url = RestClient.get(values) array_values_link.push(JSON.parse(read_url)) end head = array_values_link[0][0] collect = [] head.each do |index, value| collect.push(index) end array_comment = [] array_values_link.each do |values| values.each do |response| array_comment.push(response) end end CSV.open("comments.csv" , "wb") do |csv| csv << collect array_comment.each do |element| csv << element.values end end<file_sep>require "sinatra" url = "https://jsonplaceholder.typicode.com/post/1" get "/" do "Hello world !" end get "https://jsonplaceholder.typicode.com/post/1" do content_type :json post.to_json end
2c362aceb0bfbd6054fbf783a978a747ecda795b
[ "Ruby" ]
4
Ruby
medericgb/16-08-2021
1115ee9c6e33c5b628335d1ce90a0065bb01e520
4bd475998eeb62c559ed32e91d8e633f021ceb49
refs/heads/main
<file_sep>const express= require('express'); const mongoose= require('mongoose'); const app= express(); app.use(express.json()); mongoose.connect("mongodb://localhost:27017/pokemon_api",{useNewUrlParser :true},()=>{ console.log("connected to database"); }) //schema const pokeschema = new mongoose.Schema({ name:String, type:String, imageurl:String }) //create model to connect to schema const pokemodel= new mongoose.model('pokemons',pokeschema); // endpoints for crud operations app.get("/pokemons", async(req,res)=>{ let data= await pokemodel.find() res.send(data) }) //to add new pokemon app.post('/pokemon',(req,res)=>{ console.log(req.body) insertdata =req.body; modelobj= new pokemodel(insertdata); modelobj.save((err,data)=>{ res.send({message:"created"}) }) }) // delete data app.delete("/pokemon/:id",(req,res)=>{ let id=req.params.id; console.log(id) pokemodel.deleteOne({_id:id}) }) //fetch one pokemon using id app.get("/pokemon/:id", async(req,res)=>{ let id=req.params.id; let data= await pokemodel.find({_id:id}); res.send(data); console.log(data) }) //update pokemon app.put("/pokemon/:id",(req,res)=>{ let id=req.params.id; let data=req.body; pokemodel.updateOne({_id:id},data,(err,data)=>{ if(err===null){ res.send({mesage:"updated"}) } }) }) //fetch pokemon using type app.get("/pokemon/type/:type", async(req,res)=>{ let usr_type=req.params.type; let data= await pokemodel.find({type:usr_type}); res.send(data); console.log(data) }) app.listen(8000,()=>{ console.log("server started") }) <file_sep>const express= require('express'); const app= express(); app.use(express.json()); app.get('/test',(req,res)=>{ res.send({message:"hellooo endpoint 1"}) }) app.get('/test1',(req,res)=>{ res.send({message:"hellooo endpoint 2"}) }) app.get('/test2',(req,res)=>{ res.send({message:"hellooo endpoint 3"}) }) app.post("/create",(req,res)=>{ res.send({"data":"hii everyone"}); console.log(req.body) }) app.listen(8000,()=>{ console.log("server started") })
3c85b6c8c800158729eb4cf2b395eff6fd02010c
[ "JavaScript" ]
2
JavaScript
Adarshvarghese/Node_asignments
90d2c9281c7c3c566474f6e80b25e418b50a970d
154e99962f2b68c52273c71e78d962eb2276e051
refs/heads/master
<file_sep>package com.example.kamil.justjava; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import java.text.NumberFormat; public class MainActivity extends AppCompatActivity { TextView textViewQuantity; TextView textViewOrderSummary; EditText editTextName; CheckBox checkBoxWhipped; CheckBox checkBoxChocolate; final int coffeePrice = 5; final int creamPrice = 2; final int chocolatePrice = 1; int quantity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewQuantity = (TextView) findViewById(R.id.textViewQuantity); textViewOrderSummary = (TextView) findViewById(R.id.textViewOrderSummary); editTextName = (EditText) findViewById(R.id.editTextName); checkBoxWhipped = (CheckBox) findViewById(R.id.checkBoxWhipped); checkBoxChocolate = (CheckBox) findViewById(R.id.checkBoxChocolate); quantity = 0; } public void submit(View view){ displayOrder(calculatePrice(quantity, coffeePrice)); } public void displayQuantity(int nr){ textViewQuantity.setText("" + nr); } public int calculatePrice(int quantity, int coffeePrice) { int singleOrderPrice = coffeePrice; if(checkBoxChocolate.isChecked()) { singleOrderPrice += chocolatePrice; } if(checkBoxWhipped.isChecked()){ singleOrderPrice += creamPrice; } return quantity * singleOrderPrice; } public void displayOrder(int price) { textViewOrderSummary.setText(createOrderSummary(price)); } public void increment(View view) { quantity++; displayQuantity(quantity); } public void decrement(View view){ quantity--; if(quantity < 0){ quantity = 0; } displayQuantity(quantity); } public String createOrderSummary(int price) { StringBuilder summary = new StringBuilder(); summary.append("Name: " + editTextName.getText() + "\n"); summary.append("Quantity: " + quantity + "\n"); if(checkBoxWhipped.isChecked()){ summary.append("Whipped cream" + "\n"); } if(checkBoxChocolate.isChecked()){ summary.append("Chocolate" + "\n"); } summary.append("Total: " + NumberFormat.getCurrencyInstance().format(price) + "\n"); summary.append("\nThank you!"); return summary.toString(); } }
e1c609b5346dbbc6ca2da0c7ba4130ea44b2567f
[ "Java" ]
1
Java
GlaDdos/JustJava
32e93fc8ef00d7f53d8dc04adf077946f6ccb882
0da610d6fa40c4643472aa1a481a4cf316446f97
refs/heads/master
<file_sep>https://www.python.org/downloads/ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python -m pip install -U matplotlib pip install pandas pip install numpy pip install seaborn<file_sep>import math import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from scipy.optimize import least_squares import matplotlib.pyplot as plt import seaborn as sb from sklearn.neural_network import MLPRegressor import warnings warnings.filterwarnings("ignore") # Reading dataset file filename = 'forestfires.csv' df = pd.read_csv(filename) # Taking temp,RH,wind,rain and area data = df[df.columns[-5:]].values np.random.shuffle(data) X = data[:, :-1] # temp RH wind rain y = data[:, -1] # area # Splitting train and test dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # print(X) # print(y) def rmse(y_true, y_predict): # Root mean Square Error retval = mean_squared_error(y_true, y_predict) return math.sqrt(retval) # Defining Levenberg-Marquardt Model def model(x, a, b, c, d, e): # 0 -> temp # 1 -> RH # 2 -> wind # 3 -> rain top = (x[:, 0] * a) ** 2 + (x[:, 2] * c) ** 2 bottom = (x[:, 1] * b) ** 2 + (x[:, 3] * d) ** 2 return (top / bottom) + e def func(params, xdata, ydata): return ydata - model(xdata, *params) # Activation alternatives: 'identity', 'logistic', 'tanh', 'relu' print('MLPRegressor Model') mdl = MLPRegressor(hidden_layer_sizes=(16, 8), max_iter=5000, activation='relu', learning_rate='constant', learning_rate_init=0.001) mdl.fit(X_train, y_train) # Printing RMSE of training and test dataset for MLP Model y_predict = mdl.predict(X_train) print('Training set rmse: %.3f' % rmse(y_train, y_predict)) y_predict = mdl.predict(X_test) print('Test set rmse: %.3f' % rmse(y_test, y_predict)) print() x0 = np.ones(5) # taking ones print('Least Squares Model with Levenberg-Marquardt algorithm') result = least_squares(func, x0, args=(X_train, y_train), method='lm') params = result.x # Printing RMSE of training and test dataset for MLP Model Levenberg-Marquardt y_predict = model(X_train, *params) print('Training set rmse: %.3f' % rmse(y_train, y_predict)) y_predict = model(X_test, *params) print('Test set rmse: %.3f' % rmse(y_test, y_predict)) def histogram(): data2 = pd.read_csv(filename) # reading data-set again months = data2[data2.columns[2]].values # taking months from data-set area = data2[data2.columns[-1]].values # taking area from data-set # creating dictionary value and adding items inside of monthDict = {} for monthName in range(len(months)): if months[monthName] not in monthDict: monthDict[months[monthName]] = 0 # sum up area for every months for areaindex in range(len(area)): monthDict[months[areaindex]] += area[areaindex] # print(monthDict) monthArray = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] arr = [] arrValue = [] # splitting the dictionary as a key and value for checkMont in monthArray: for keys, values in monthDict.items(): if checkMont == keys: arr.append(keys) arrValue.append(values) # print(monthDict) # print(arr) # print(arrValue) # drawing the histogram plt.xlabel("Months") plt.ylabel("Total Burned Area (in ha)") plt.title("Histogram") plt.bar(arr, arrValue) plt.grid(color='#95a5a6', linestyle='--', linewidth=2, axis='y', alpha=0.7) plt.show() histogram() def heatmeapFunc(): copyDf = df.copy() # copy it to not lose original data-set xCor = copyDf[copyDf.columns[0]].values # taking all x coordinates yCor = copyDf[copyDf.columns[1]].values # taking all y coordinates temp = copyDf[copyDf.columns[8]].values # taking all temp # to count reapeted coordinates there are (e.g 7-5 repeated 11 times) xYCorDict = {} averageTemp = {} # put temp average of every coordinates for xY in range(len(xCor)): # define their keys (e.g 75,99) addToKey = str(xCor[xY]) + str(yCor[xY]) if addToKey not in xYCorDict: # to prevent redundancy xYCorDict[addToKey] = 0 # define them as 0 for now averageTemp[addToKey] = 0 # define them as 0 for now for xYCount in range(len(xCor)): addToKey = str(xCor[xYCount]) + str(yCor[xYCount]) # count repeated xYCorDict[addToKey] += 1 # add 1 for every repetation for tempCount in range(len(xCor)): addToKey = str(xCor[tempCount]) + str(yCor[tempCount]) # take the id averageTemp[addToKey] += temp[tempCount] # sum up all temp for keys, values in xYCorDict.items(): averageTemp[keys] = averageTemp[keys] / xYCorDict[keys] # divided it arrayTemp = [] # put id and its average temp for keys, values in averageTemp.items(): arrayTemp.append([keys, values]) heatMapArray = [] # heat map array 10X10 array # since we know the X and Y coordinates is upto 9 we run it 10 times to create heatmap for xCordinate in range(10): addToHeatmap = [] for yCordinate in range(10): addToHeatmap.append(0) heatMapArray.append(addToHeatmap) for i in range(len(arrayTemp)): heatMapArray[int(arrayTemp[i][0][0])][int(arrayTemp[i][0][1])] = float(arrayTemp[i][1]) # for keys, value in averageTemp.items(): # print(keys, value) heatMap = sb.heatmap(heatMapArray, annot=True, cmap='Reds') plt.xlabel('Y Coordinate') plt.ylabel('X Coordinate') plt.title('Average Temperature In X,Y Coordinate (C)') heatMap.invert_yaxis() plt.show() heatmeapFunc() <file_sep> # Description: The aim of this project is to predict the forest fires to decrease the harm that would occur by these fires. Different machine learning methods including Multilayer Perceptron (MLP) have been used to detect the forest fires; however, in this project We are planning to apply MLP with more than one hidden layer(16,8) with 'relu' activation function and also apply to Levenberg-Marquardt (LM) algorithm to predict forest fires and compare the result of them. The RMSE(Root Means Square Error) values of the models have been computed to determine the performance of the forest fires prediction models. # Team & Roles: <NAME>(370709069) and <NAME>(170709055). We both worked in every places such as report and source code e.t.c. # Structure: You can reach source code which name is finalProject.py and csv file which name is forestfires.csv. # Language, version, and main file: We used python language on this project. One of us worked python 3.7 version, the other one worked python 3.9 version. The main file is finalProject.py . # Additional: Report.tex file is in the latex folder Also, We would like you to know in our commiting part sultanguvenbas and U170709055 are the same person. We do not know why some commits taking from sultanguvenbas, some commits taking from U170709055. However they are the same person as you can guest. You can check it though the insights -> network part. The same problem occured akglali and U370709069.
5c000ca3852901624e2e6fcda33e60807a6fffe9
[ "Markdown", "Python", "Text" ]
3
Text
sultanguvenbas/Data_mining
bb2c69ce4716fd4c5d34d460ed64c2cd2e0a9dc6
55440b9ce2407b8c7d6cfcbe0c4ac33c3231d74c
refs/heads/master
<repo_name>lukebrowell/vscode-python-starter<file_sep>/README.md # Polyglot Python Development Starter (Containers) As a Polyglot Software Engineer, a significant part of your work will require you to ensure that your code always works consistently no matter where it is run. Please follow through these instructions to get set up in Visual Studio code with a sandboxed 'container' environment. For a background on containers in VSCode - please read **[VS Code Remote - Containers](https://aka.ms/vscode-remote/containers)** extension in a few easy steps. ## Pre-requesites - Windows 10 (Depending on your experience you may be able to follow along on other operating systems) - **[VsCode for Windows](https://code.visualstudio.com/Download)** - **[Git for Windows](https://git-scm.com/download/win)** ## Getting a copy of this code - the right way - Open this repo's page on GitHub.com - Make sure you have a personal GitHub account for your learning and you are logged in. - Instead of Cloning this repo - Fork it as a Private repo for yourself - Clone your own fork of this repo* to ~/localGIT/[this repo] - Open the local folder in VSCode - After a moment VSCode should detect that you have a container configuration and offer to let you 'Restart in Container' - click this. - If you've not used containers before see the 'Setting up the development container' section. ## Setting up the development container Follow these steps to open this sample in a container: 1. Since this is likely your first time using a development container, please follow the [getting started steps](https://aka.ms/vscode-remote/containers/getting-started). 2. To use this repository, open the repository in an isolated Docker volume (we'll cover these steps in the workshop): - Fork this repository on your own GitHub - Clone your fork of this repository to your local filesystem. - Follow the prompts to setup your Docker instance - Post any questions to the channel. ## Things to try Once you have this sample opened in a container, you'll be able to work with it like you would locally. 1. **Edit:** - Open `src/App.python`. - Try adding some code and check out the language features. 2. **Terminal:** Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>\`</kbd> and type `uname` and other Linux commands from the terminal window. 3. **Build, Run, and Debug:** - Open `src/App.python`. - Add a breakpoint. - Press <kbd>F5</kbd> to launch the app in the container. - Once the breakpoint is hit, try hovering over variables, examining locals, and more. 4. **Run a Test:** - Open `src/test/AppTest.python`. - Put a breakpoint in a test. - Click the `Debug Test` in the Code Lens above the function and watch it hit the breakpoint. > **Note:** We'll be adding features to this as we go and you'll be given access to new branches in this repository to base your ideas on. <file_sep>/src/test/java/com/mycompany/app/AppTest.java package com.mycompany.app; import org.junit.Test; import static org.junit.Assert.*; public class AppTest { public AppTest() { } @Test public void testApp() { // arrange App testAppInstance = new App(); Integer a = 1; Integer b = 2; Integer expected = 3; // act Integer actual = testAppInstance.sum(a,b); // assert assertTrue( expected.equals(actual) ); } }
00e36a95b24aac55489499f3cdbdcf8c6f2a4e26
[ "Markdown", "Java" ]
2
Markdown
lukebrowell/vscode-python-starter
8bef7866fc51cf9acfaad20cb0e0c263aff6359c
e0d15ef3aaace94b1b92a42d534f5dd16b669d8e
refs/heads/master
<repo_name>jnibrahim/flaskappengineskeleton<file_sep>/src/main.py import logging from flask import Flask app = Flask(__name__) from handlers.helloworld import get_helloworld get_helloworld(app) @app.errorhandler(500) def server_error(e): # Log the error and stacktrace. logging.exception('An error occurred during a request.') return 'An internal error occurred.', 500
f5271f74ed9f07961b99edbcea30f03e5dd74214
[ "Python" ]
1
Python
jnibrahim/flaskappengineskeleton
11f58975798113c57419f369793ba5e8c0dfeb61
81e462c66b1f42fceef404396216ab531d343ece
refs/heads/master
<repo_name>wildchild97/COMP1004-W2017-MidTermAssign-200311158<file_sep>/COMP1004-W2017-MidTermAssign-200311158/FinalForm.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; //App name: Character Generator //<NAME> and <NAME> Student ID: 200311158 //App Creation Date: February 21, 2017 namespace COMP1004_W2017_MidTermAssign_200311158 { public partial class FinalForm : Form { //Constructors++++++++++++++++++++++ public FinalForm() { InitializeComponent(); //show all details from previus forms _characterPicture(); RaceTextBox.Text = _character; JobTextBox.Text = _job; HealthTextBox.Text = _Health.ToString(); STRTextBox.Text = _STR.ToString(); DEXTextBox.Text = _DEX.ToString(); INTTextBox.Text = _INT.ToString(); ENDTextBox.Text = _END.ToString(); PERTextBox.Text = _PER.ToString(); CHATextBox.Text = _CHA.ToString(); } //PUBLIC PROPERTIES++++++++++++++++++ public string _character { get; private set; } public string _job { get; private set; } public int _Health { get; private set; } public int _STR { get; private set; } public int _DEX { get; private set; } public int _INT { get; private set; } public int _END { get; private set; } public int _PER { get; private set; } public int _CHA { get; private set; } //PRIVATE METHODS+++++++++++++++++++++ /// <summary> /// this method sees what the user chose as a character and sets the right picture for that character /// </summary> private void _characterPicture () { if (_character.Equals("Human")) { CharacterPictureBox.Load("M_Human1.png"); } else if(_character.Equals("Dwarf")) { CharacterPictureBox.Load("M_Dwarf1.png"); } else if (_character.Equals("Elf")) { CharacterPictureBox.Load("M_Elf1.png"); } else if (_character.Equals("Halfling")) { CharacterPictureBox.Load("M_Halfling2.png"); } } /// <summary> /// this method exits the program when exit button or exit tool clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _exit_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// this method gives details about the program when selected /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { // Step 1. Create a new Form AboutForm aboutForm = new AboutForm(); // Step 2. show the About Form with ShowDialog (a modal method to display the form) aboutForm.ShowDialog(); } /// <summary> /// this method allows the user to change the text fonts /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fontToolStripMenuItem_Click(object sender, EventArgs e) { CharacterFontDialog.ShowDialog(); } /// <summary> /// this method prints a preview of the final form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void printToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Now Printing your Character"); } } } <file_sep>/COMP1004-W2017-MidTermAssign-200311158/AbilityForm.cs using COMP1004_W2017_MidTermAssign_200311158; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //App name: Character Generator //<NAME> and <NAME> Student ID: 200311158 //App Creation Date: February 21, 2017 namespace COMP1004_W2017_MidTermAssgnment_StudentID { public partial class AbilityForm : Form { public Form PreviousForm; // Random Number object Random random = new Random(); //PRIVATE VARIABLES++++++++++++++++ private int _STR; private int _DEX; private int _END; private int _INT; private int _PER; private int _CHA; //Constructors++++++++++++++++++++++ public AbilityForm() { InitializeComponent(); } //PRIVATE METHODS+++++++++++++++++++++ /// <summary> /// This method simulates the rolling of three 10-sided dice /// </summary> /// <returns> /// This method returns a number between 3 and 30 (The result of rolling 3d10) /// </returns> private int Roll3D10() { int result = 0; for (int dice = 0; dice < 3; dice++) { result += random.Next(1, 11); } return result; } /// <summary> /// this method assigns the character's abilities random stats and display's them /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RollButton_Click(object sender, EventArgs e) { this._STR = Roll3D10(); this._DEX = Roll3D10(); this._END = Roll3D10(); this._INT = Roll3D10(); this._PER = Roll3D10(); this._CHA = Roll3D10(); STRTextBox.Text = _STR.ToString(); DEXTextBox.Text = _DEX.ToString(); ENDTextBox.Text = _END.ToString(); INTTextBox.Text = _INT.ToString(); PERTextBox.Text = _PER.ToString(); CHATextBox.Text = _CHA.ToString(); } /// <summary> /// this method goes to the next page when next button is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NextButton_Click(object sender, EventArgs e) { // Instantiate the next form RaceForm raceForm = new RaceForm(); // pass a reference from the current form to the next form raceForm.PreviousForm = this; raceForm.Show(); this.Hide(); } } } <file_sep>/COMP1004-W2017-MidTermAssign-200311158/JobForm.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; //App name: Character Generator //<NAME> and <NAME> Student ID: 200311158 //App Creation Date: February 21, 2017 namespace COMP1004_W2017_MidTermAssign_200311158 { public partial class JobForm : Form { //PRIVATE VARIABLES++++++++++++++++ private int _Health; private string _job; //Constructors++++++++++++++++++++++ public JobForm() { InitializeComponent(); } //PUBLIC PROPERTIES++++++++++++++++++ public JobForm PreviousForm { get; set; } public int _STR { get; private set; } public int _DEX { get; private set; } public int _INT { get; private set; } public int _END { get; private set; } public int _PER { get; private set; } public int _CHA { get; private set; } public string _character { get; private set; } //PRIVATE METHODS+++++++++++++++++++++ /// <summary> /// this method changes the characters stats based of which job the user chose /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _jobRadioButton_CheckedChanged(object sender, EventArgs e) { if (SoldierRadioButton.Checked) { this._Health = 30 + _END; _job = "Soldier"; } else if (RogueRadioButton.Checked) { this._Health = 28 + _DEX; _job = "Rogue"; } else if (MagickerRadioButton.Checked) { this._Health = 15 + _INT; _job = "Magicker"; } else if (CultistRadioButton.Checked) { this._Health = 24 + _CHA; _job = "Cultist"; } } /// <summary> /// this method moves to the next form when the next button is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NextButton_Click(object sender, EventArgs e) { // Instantiate the next form FinalForm finalForm = new FinalForm(); // pass a reference from the current form to the next form finalForm.PreviousForm = this; finalForm.Show(); this.Hide(); } } } <file_sep>/COMP1004-W2017-MidTermAssign-200311158/RaceForm.cs using COMP1004_W2017_MidTermAssgnment_StudentID; using COMP1004_W2017_MidTermAssign_200311158; 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; //App name: Character Generator //<NAME> and <NAME> Student ID: 200311158 //App Creation Date: February 21, 2017 namespace COMP1004_W2017_MidTermAssign_200311158 { public partial class RaceForm : Form { //PRIVATE VARIABLES++++++++++++++++ private string _character; //Constructors++++++++++++++++++++++ public RaceForm() { InitializeComponent(); CharacterPictureBox.Load("M_Human1.png"); RacialBonusTextBox.Text = "All Stats increased by 5 points"; } //PUBLIC PROPERTIES++++++++++++++++++ public AbilityForm PreviousForm { get; set; } public int _STR { get; private set; } public int _DEX { get; private set; } public int _INT { get; private set; } public int _END { get; private set; } public int _PER { get; private set; } public int _CHA { get; private set; } //PRIVATE METHODS+++++++++++++++++++++ /// <summary> /// this method changes the character picture when a diffrent race is selected /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _raceRadioButton_CheckedChanged(object sender, EventArgs e) { if (HumanRadioButton.Checked) { CharacterPictureBox.Load("M_Human1.png"); RacialBonusTextBox.Text = "All Stats increased by 5 points"; } else if(DwarfRadioButton.Checked) { CharacterPictureBox.Load("M_Dwarf1.png"); RacialBonusTextBox.Text = "STR and PER increased by 20 points, CHA decreased by 20 points"; } else if(ElfRadioButton.Checked) { CharacterPictureBox.Load("M_Elf1.png"); RacialBonusTextBox.Text = "DEX and PER increased by 15 points"; } else if(HalflingRadioButton.Checked) { CharacterPictureBox.Load("M_Halfling2.png"); RacialBonusTextBox.Text = "DEX and INT incteased by 20 points, STR decreased by 10 points"; } } /// <summary> /// this method changes the characters stats based off which character race they chose then moves to the next page when the next button is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _nextButton_Click(object sender, EventArgs e) { if (HumanRadioButton.Checked) { _STR += 5; _DEX += 5; _END += 5; _INT += 5; _PER += 5; _CHA += 5; _character = "Human"; } else if (DwarfRadioButton.Checked) { _STR += 20; _PER += 20; _CHA -= 20; _character = "Dwarf"; } else if (ElfRadioButton.Checked) { _DEX += 15; _PER += 15; _character = "Elf"; } else if (HalflingRadioButton.Checked) { _DEX += 20; _INT += 20; _STR -= 10; _character = "Halfling"; } // Instantiate the next form JobForm jobForm = new JobForm(); // pass a reference from the current form to the next form jobForm.PreviousForm = this; jobForm.Show(); this.Hide(); } } }
b320e09b6f991f3bf0317c500bcdf59611162dba
[ "C#" ]
4
C#
wildchild97/COMP1004-W2017-MidTermAssign-200311158
06c1197521a7440765c3feeb00c2b5ac55c9a347
c95e971014b1c1eda771529d4ae92554c1cc8a62
refs/heads/master
<repo_name>carlosisairomero/spring-mvc-demo<file_sep>/src/com/luv2code/springdemo/mvc/HelloWorldController.java package com.luv2code.springdemo.mvc; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloWorldController { // controller method to show the initial HTML form @RequestMapping("/showForm") public String showForm(){ return "helloworld-form"; } // controller method to process the HTML form @RequestMapping("/processForm") public String processForm(){ return "helloworld"; } // controller method to process the HTML form using a MODEL @RequestMapping("/processForm2") public String processForm2(HttpServletRequest request, Model model){ //read the request parameter String theName = request.getParameter("studentName"); //convert the data to all caps theName = theName.toUpperCase(); //create the message String message = "Yo! " + theName; //add message to the model model.addAttribute("message", message); return "helloworld"; } }
03cc3c872d2f42dba674712b5a7c1614e875693b
[ "Java" ]
1
Java
carlosisairomero/spring-mvc-demo
7e0eba42864187f73370792aa513f58d399504c9
7830fd3c2740e24239c2414f791efcbcbdcb0431
refs/heads/master
<repo_name>nicolasnobelis/Explorers_Springboot<file_sep>/src/main/resources/application.properties server.port=9090 dbServerURL=http://localhost:5984 dbTable=/expeditions<file_sep>/src/main/java/nino/explorers/dao/couchdb/ExpeditionDocument.java package nino.explorers.dao.couchdb; import com.fasterxml.jackson.annotation.JsonInclude; import model.Expedition; import java.time.LocalDateTime; import java.util.UUID; public class ExpeditionDocument { private UUID _id; private String _rev; private LocalDateTime creationDate; private Expedition expedition; public UUID get_id() { return _id; } public void set_id(UUID _id) { this._id = _id; } @JsonInclude(JsonInclude.Include.NON_NULL) public String get_rev() { return _rev; } public void set_rev(String _rev) { this._rev = _rev; } public LocalDateTime getCreationDate() { return creationDate; } public void setCreationDate(LocalDateTime creationDate) { this.creationDate = creationDate; } public Expedition getExpedition() { return expedition; } public void setExpedition(Expedition expedition) { this.expedition = expedition; } } <file_sep>/src/main/java/nino/explorers/ExpeditionService.java package nino.explorers; import model.Expedition; import model.enums.ExpeditionStatus; import nino.explorers.dao.couchdb.CouchExpeditionDao; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.UUID; @RestController @RequestMapping("/rest") public class ExpeditionService implements rest.ExpeditionService { private final CouchExpeditionDao couchExpeditionDao; public ExpeditionService(CouchExpeditionDao couchExpeditionDao) { this.couchExpeditionDao = couchExpeditionDao; } @Override public void abortExpedition(@NotNull UUID uuid, int i) { } @Override public void assignExplorer(@NotNull UUID uuid, @NotNull UUID uuid1) { } @Override public void assignShip(@NotNull UUID uuid, @NotNull UUID uuid1) { } @NotNull @Override @RequestMapping(path = "/expedition/createOrUpdate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public UUID createOrUpdateExpedition(@NotNull @RequestBody Expedition expedition) { return couchExpeditionDao.createOrUpdateExpedition( expedition ); } @Override public void deleteExpedition(@NotNull UUID uuid) { } @NotNull @Override public Expedition getExpedition(@NotNull UUID uuid) { return null; } @NotNull @Override public List<Expedition> listExpeditions() { return null; } @NotNull @Override public List<Expedition> listExpeditions(@NotNull ExpeditionStatus expeditionStatus) { return null; } @Override public void startExpedition(@NotNull UUID uuid) { } } <file_sep>/init_couchdb_sys_tables.ini [couchdb] single_node=true
93c21d0105d7436b523b3b0ee8a8aaf415e86943
[ "Java", "INI" ]
4
INI
nicolasnobelis/Explorers_Springboot
b4eef5aa4613786f999f29e45ffde60fa65f54eb
9325da9d8a5bff439a98bb93ce5219e13abba08f
refs/heads/master
<file_sep>分享几个实验的数据处理小程序。具体保留有效数字位数自行参照要求,一般为3~4位有效数字。 实验平台地址:http://192.168.127.12/ ### 使用方法: (C++)在可执行文件的目录下,将仿真实验测得数据存入in.txt文件中。各数据间以空格分隔。 输入数据格式可参考解压所得的in.txt数据,用实际测得数据覆盖即可。in.txt保存完毕后,运行exe文件,秒出结果。 ![运行结果示例](https://images.gitee.com/uploads/images/2020/0420/074417_781b9333_6530859.png "QQ截图20200420072128.png") (Python)按提示输入数据<file_sep>#include <iostream> #include <fstream> #include <cmath> using namespace std; int main() { fstream in; in.open("in.txt", ios::out | ios::in); int i; double l[8], r[8], D[8], squareDiff[4], sqDifAvg, R; cout << "按实验中的测量顺序,即从小到大,在in.txt中输入十字叉丝从左到右移动测得的16个数据" << endl; for (i = 0; i < 8; i++) { in >> l[i]; l[i] /= 1000; } for (i = 0; i < 8; i++) { in >> r[i]; r[i] /= 1000; D[i] = fabs(r[i] - l[7-i]); cout << "D[" << (i+1) << "](m) = " << D[i] << endl; } cout << endl; for (i = 0, sqDifAvg = 0; i < 4; i++) { squareDiff[i] = D[i+4]*D[i+4] - D[i]*D[i]; sqDifAvg += squareDiff[i]; } sqDifAvg /= 4; R = sqDifAvg / (80 * 589 * 1e-9); cout << "R(m) = " << R << endl; cin.get(); return 0; } <file_sep>data = input("请按顺序(升序/降序均可)在一行里输入16个测量的数值(mm):\n") mm = data.split() for i in range(16): mm[i] = float(mm[i]) * 1e-3 D = [] for i in range(8): D.append(abs(mm[i]-mm[-i-1])) print("直径D[{}] = {:.3f}mm".format(i+1, D[i]*1e3)) squareDiffAvg = 0 for i in range(4): squareDiffAvg += D[i] ** 2 - D[i+4] ** 2 squareDiffAvg /= 4 R = squareDiffAvg / (80 * 589 * 1e-9 ) print("最终求得R = {:.3f}m".format(R)) input()<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace 牛顿环计算 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { try { double[] l = new double[8]; double[] r = new double[8]; double[] D = new double[8]; double[] squareDiff = new double[4]; double sqDifAvg = 0, R = 0; string[] Data = data.Text.Split(); for (int i = 0; i < 8; i++) { l[i] = Convert.ToDouble(Data[i]) / 1e3; } for (int i = 0; i < 8; i++) { r[i] = Convert.ToDouble(Data[i+8]) / 1e3; } for (int i = 0; i < 8; i++) { D[i] = Math.Abs(r[i] - l[7-i]); } for (int i = 0; i < 4; i++) { squareDiff[i] = D[i+4] * D[i+4] - D[i] * D[i]; sqDifAvg += squareDiff[i]; } sqDifAvg /= 4; R = sqDifAvg / (80 * 589 * 1e-9); answer.Content = "R = " + string.Format("{0:.000}", R) + " m"; } catch { answer.Content = "输入格式错误!"; } } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { } } } <file_sep>#include <iostream> #include <iomanip> #include <cmath> #include <fstream> using namespace std; int main() { fstream in; in.open("in.txt", ios::out | ios::in); double U[8], U_avg, t[8], t_avg, e_std, e_computed, RE, q; U_avg = t_avg = 0.0; e_std = 1.602; for (int i = 0; i < 8; i++) { in >> U[i]; U_avg += U[i]; } for (int i = 0; i < 8; i++) { in >> t[i]; t_avg += t[i]; } U_avg /= 8; t_avg /= 8; q = 1.43 / (pow(t_avg * (1 + 0.02 * sqrt(t_avg)), 1.5) * U_avg) * 1e5; e_computed = q / round(q / e_std); RE = fabs(e_std - e_computed) / e_std; cout << "U_avg = " << setiosflags(ios::fixed) << setprecision(6) << U_avg << endl; cout << "t_avg = " << t_avg << endl; cout << "q = " << q << endl; cout << "e_computed = " << e_computed << endl; cout << "RE% = " << RE * 100 << endl; cin.get(); return 0; }<file_sep>from math import * print("元电荷标准值采用1.602e-19") e_std = 1.602 print("计算结果均保留4位有效数字\n") t = [] U = [] for i in range(8): U.append(eval(input("请输入第{}次测得平衡电压(V)\n".format(i+1)))) t.append(eval(input("请输入第{}次测得油滴下降2mm所用时间(s)\n".format(i+1)))) U = sum(U)/len(U) t = sum(t)/len(t) print("平均平衡电压为{:.2f}V".format(U)) print("油滴下降2mm平均时间为{:.2f}s".format(t)) q = 1.43 / ((t*(1+0.02*t**0.5))**1.5 * U) * 1e5 e_computed = q / round(q/e_std) RE = abs(e_computed-e_std)/e_std print("测得油滴的带电量 q = {:.4f}".format(q)) print("测得基本电荷的带电量 e = {:.4f}".format(e_computed)) print("测量值与已知值的误差 RE(%) = {:.4%}".format(RE)) input()
88b9771e09649d1c98695eee895411f7b636396c
[ "Markdown", "C#", "Python", "C++" ]
6
Markdown
CHxCOOH/SimulationPhysicsExperiment-Calculator
251306dfdb526c781e0d28c66fb0bc5684110109
34ba8a304c18a20fc98ab35971833f9382a9e872
refs/heads/master
<repo_name>sablesoft/yii2-stuff<file_sep>/src/interfaces/IsDefaultInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; /** * Interface IsDefaultInterface * @package sablesoft\stuff\interfaces * * @property bool $isDefault */ interface IsDefaultInterface { const FIELD = 'is_default'; const IS_DEFAULT_FIELD = 'isDefaultField'; /** * @return bool */ public function getIsDefault() : bool; /** * @param bool $isDefault * @return $this */ public function setIsDefault(bool $isDefault) : self; } <file_sep>/src/rbac/OwnerRule.php <?php /** @noinspection PhpMissingFieldTypeInspection */ declare(strict_types=1); namespace sablesoft\stuff\rbac; use yii\rbac\Item; use yii\rbac\Rule; use yii\db\ActiveRecord; use yii\helpers\ArrayHelper; use yii\base\InvalidConfigException; use sablesoft\stuff\interfaces\IsIsOwnerInterface; /** * Class OwnerRule * @package app\models\rbac */ class OwnerRule extends Rule { public $name = 'isOwner'; /** * @param int|string $userId * @param Item $item * @param array $params * @return bool * @throws InvalidConfigException */ public function execute($userId, $item, $params) : bool { /** @var IsIsOwnerInterface|ActiveRecord $model */ if (!$model = ArrayHelper::remove($params, 'model')) { return false; } if (!$model->hasMethod('isOwner')) { throw new InvalidConfigException("OwnerRule: model must implement IsOwnerInterface!"); } return $model->isOwner((string) $userId); } } <file_sep>/src/interfaces/SelectInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; /** * Interface SelectInterface * @package app\interfaces */ interface SelectInterface { const DEFAULT_FIELD_FROM = 'id'; const DEFAULT_FIELD_TO = 'name'; const CONFIG_TO = 'to'; const CONFIG_FROM = 'from'; const CONFIG_WHERE = 'where'; /** * @param array $config * @param bool $withParams * @return array */ public static function getSelect(array $config = [], bool $withParams = false): array; } <file_sep>/src/traits/SearchTrait.php <?php declare(strict_types=1); namespace sablesoft\stuff\traits; use yii\db\Expression; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use sablesoft\stuff\interfaces\SearchInterface; /** * Trait SearchTrait * @package sablesoft\stuff\traits * @property array $filters */ trait SearchTrait { /** * @param ActiveQuery $query */ public function applyFilters(ActiveQuery $query) { foreach ($this->filters as $operator => $fields) { foreach($fields as $field => $dbField) { if (is_int($field)) { $field = $dbField; } $query->andFilterWhere([$operator, $dbField, $this->$field]); } } } /** * @param ActiveQuery $query * @param string $field * @param string $elseOperator */ public function nullFilter(ActiveQuery $query, string $field, string $elseOperator = 'eq') { if ($this->$field === SearchInterface::FILTER_IS_NULL) { $query->andFilterWhere(['is', $field, new Expression('null')]); } else { $query->andFilterWhere([$elseOperator, $field, $this->$field]); } } /** * @param ActiveQuery $query * @param string $column * @return array|null[] */ protected function fetchColumn(ActiveQuery $query, $column = 'id') : array { $raw = $query->asArray()->all(); $values = ArrayHelper::getColumn($raw, $column); return $values ? $values : [null]; } } <file_sep>/src/helpers/AccessHelper.php <?php declare(strict_types=1); namespace sablesoft\stuff\helpers; use Yii; use yii\web\Controller; use yii\base\InvalidConfigException; use sablesoft\stuff\traits\ParamsTrait; use sablesoft\stuff\interfaces\ParamsInterface; /** * Class AccessHelper * @package sablesoft\stuff\helper */ class AccessHelper implements ParamsInterface { use ParamsTrait; const PARAMS = 'access'; const PARAMS_PATTERN = 'pattern'; const PARAMS_SKIP_MODULE = 'skipModule'; const PARAMS_SKIP_CONTROLLER = 'skipController'; const PARAMS_DEFAULT_ACTIONS = 'defaultActions'; const PARAMS_DOMAINS = 'domains'; const PARAMS_AREAS = 'areas'; const PARAMS_ROLES = 'roles'; const PARAMS_CUSTOM = 'custom'; const PARAMS_USERS = 'users'; const DEFAULT_PATTERN = "{module}.{controller}.{action}"; const ROLE_ADMIN = 'admin'; const AREA_PROFILE = 'profile'; const PERMISSION_ROLE_ASSIGN = 'role.assign'; /** * @return bool */ public static function isConsole() : bool { return Yii::$app->request->isConsoleRequest; } /** * @return bool */ public static function canAssignRole() : bool { return self::isConsole() || Yii::$app->user->can( static::PERMISSION_ROLE_ASSIGN ); } /** * @return array */ public static function defaultActions() : array { return static::get(static::PARAMS_DEFAULT_ACTIONS, []); } /** * @return bool */ public static function isAdmin() : bool { return self::isConsole() || Yii::$app->user->can(static::ROLE_ADMIN); } /** * @return bool * @throws InvalidConfigException */ public static function isProfile() : bool { if (self::isConsole()) { return false; } return strpos( Yii::$app->request->getPathInfo(), self::AREA_PROFILE) === 0; } /** * @param Controller $sender * @return bool */ public static function isSkip(Controller $sender) : bool { if (static::have($sender->module->id, static::PARAMS_SKIP_MODULE)) return true; if (static::have($sender->getUniqueId(), static::PARAMS_SKIP_CONTROLLER)) return true; return false; } /** * @param Controller $sender * @return string */ public static function getPermission(Controller $sender) : string { static::prepare(); /** @noinspection RegExpRedundantEscape */ return preg_replace( ['/\{module}/', '/\{controller}/', '/\{action}/'], [$sender->module->id, $sender->getUniqueId(), $sender->action->id], static::getPattern($sender) ); } /** * @param Controller $sender * @return string */ protected static function getPattern(Controller $sender) : string { $key = static::PARAMS_PATTERN; $moduleKey = $sender->module->id; return static::get("$key.$moduleKey", static::DEFAULT_PATTERN); } /** * @return string|null */ public static function paramsPath() : ?string { return self::PARAMS; } } <file_sep>/src/widgets/Menu.php <?php declare(strict_types=1); namespace sablesoft\stuff\widgets; use Yii; use yii\helpers\Url; use yii\helpers\Html; use yii\bootstrap\Nav; use yii\helpers\ArrayHelper; use sablesoft\stuff\traits\ParamsTrait; use sablesoft\stuff\interfaces\ParamsInterface; /** * Class Menu * @package sablesoft\stuff\widgets */ class Menu extends Nav implements ParamsInterface { use ParamsTrait; const PARAMS = 'menu'; const CONFIG_MENU = '_menu'; const CONFIG_SUBMIT = '_submit'; const CONFIG_ACCESS = '_access'; const CONFIG_DIVIDER = '_divider'; const CONFIG_LABEL = 'label'; const CONFIG_URL = 'url'; const CONFIG_ITEMS = 'items'; const PLACEHOLDER_USERNAME = '_username'; /** * @return array */ public static function items() : array { $params = self::get(); $items = static::prepareItems($params); return $items ? $items[self::CONFIG_ITEMS] : []; } /** * @param $config * @param null $oldKey * @return array|mixed */ protected static function prepareItems($config, $oldKey = null) { $items = []; foreach ((array) $config as $key => $subConfig) { if ($key === self::CONFIG_SUBMIT) { return self::submitButton($subConfig); } if ($key === self::CONFIG_MENU) { $items = $subConfig; foreach($items as $field => $value) { if($field == self::CONFIG_LABEL) { $items[$field] = ($value === self::PLACEHOLDER_USERNAME) ? Yii::$app->user->identity->username : Yii::t('app', $value); } } continue; } if (strpos($key, self::CONFIG_DIVIDER) !== false) { $items[self::CONFIG_ITEMS][] = "<li class='divider'></li>"; continue; } if (!static::checkAccess($subConfig, $key, $oldKey )) { continue; } $items[self::CONFIG_ITEMS][] = static::prepareItems( $subConfig, trim( "$oldKey.$key", '.' ) ); } return $items; } /** * @param array $config * @return string */ protected static function submitButton(array $config): string { $options = $config['options'] ?? []; return '<li>' . Html::beginForm(Url::to($config[self::CONFIG_URL]), 'post') . Html::submitButton( Yii::t('app', $config[self::CONFIG_LABEL]), $options ) . Html::endForm() . '</li>'; } /** * @param array $config * @param string $key * @param null|string $oldKey * @return bool */ protected static function checkAccess(array &$config, string $key, $oldKey = null) { $default = $oldKey ? "$oldKey.$key" : $key; $permission = ArrayHelper::remove($config, self::CONFIG_ACCESS, $default); if ($permission === '@') { return !Yii::$app->user->isGuest; } if ($permission === '?') { return Yii::$app->user->isGuest; } return Yii::$app->user->can($permission); } /** * @inheritDoc */ public static function paramsPath(): ?string { return self::PARAMS; } } <file_sep>/src/interfaces/IsDeletedInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; /** * Interface IsDeletedInterface * @package sablesoft\stuff\interfaces */ interface IsDeletedInterface { const DELETED_FIELD = 'fieldDeleted'; const FIELD = 'deleted'; /** * @return bool */ public function getIsDeleted() : bool; } <file_sep>/src/controllers/CrudController.php <?php declare(strict_types=1); namespace sablesoft\stuff\controllers; use Yii; use yii\web\Response; use yii\web\Controller; use yii\db\ActiveRecord; use yii\filters\VerbFilter; use yii\helpers\ArrayHelper; use yii\db\StaleObjectException; use yii\base\InvalidRouteException; use sablesoft\vue\VueManager; use sablesoft\stuff\interfaces\SearchInterface; /** * CrudController implements the CRUD actions for all CRUD controllers. * * @property-read array $vueConfig */ class CrudController extends Controller { protected string $modelsPath = 'app\models\\'; protected string $searchModelsPath = 'app\models\search\\'; protected ?string $modelClass = null; protected ?string $searchModelClass = null; protected array $primaryKey = ['id']; /** @var ActiveRecord|null $model */ protected ?ActiveRecord $model = null; /** * @var array */ protected array $_vueConfig = []; /** * @param string|null $path * @param null $default * @return array */ public function getVueConfig(string $path = null, $default = null) { return $path ? ArrayHelper::getValue($this->_vueConfig, $path, $default) : $this->_vueConfig; } /** * @param string|null $path * @param mixed $config * @return $this */ public function setVueConfig($config, string $path = null) : self { ArrayHelper::setValue($this->_vueConfig, $path, $config); return $this; } /** * @param array $config * @param string|null $path * @return $this */ public function addVueConfig(array $config, string $path = null) : self { $oldConfig = (array) $this->getVueConfig($path); $newConfig = ArrayHelper::merge($oldConfig, $config); $this->setVueConfig($newConfig, $path); return $this; } /** * @param string $modelKey * @param array $where * @return array */ public function gridParams(string $modelKey, array $where) : array { $class = $this->searchModelsPath . ucfirst($modelKey) . 'Search'; /** @var SearchInterface|ActiveRecord $search */ $search = new $class(); $search->setAttributes($where); $provider = $search->search(\Yii::$app->request->queryParams); return [ "${modelKey}Search" => $search, "${modelKey}Provider" => $provider ]; } /** * @param ActiveRecord $model */ public function setModel(?ActiveRecord $model) { $this->model = $model; } /** * @return ActiveRecord */ public function getModel() { return $this->model; } /** * {@inheritdoc} */ public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::class, 'actions' => [ 'delete' => ['POST'] ] ] ]; } /** * @param string $id * @param array $params * @return mixed * @throws InvalidRouteException */ public function runAction($id, $params = []) { if ($pk = $this->primaryKey($params)) { $this->setModel($this->findModel($pk)); } return parent::runAction($id, $params); } /** * @param string $view * @param array $params * @return string */ public function render($view, $params = []) { $this->applyVue($view, $params); return parent::render($view, $params); } /** * Lists all models. * @return mixed */ public function actionIndex() { $class = $this->getModelClass(true); /** @var ActiveRecord|SearchInterface $searchModel */ $searchModel = new $class(); $dataProvider = $searchModel->search($this->getParams()); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider ]); } /** * Displays a single model. * @return mixed */ public function actionView() { if(!$model = $this->getModel()) { return $this->redirect('index'); } $model->load($this->getParams()); return $this->render('view', [ 'model' => $this->getModel() ]); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = $this->createModel(); if ($model->load(Yii::$app->request->post()) && $model->save()) { $modelName = ucfirst($this->getUniqueId()); Yii::$app->session->addFlash('success', "$modelName created!"); if ($this->isAjax()) { return $this->asJson([ 'success' => true, 'model' => $model->getAttributes() ]); } else { /** @noinspection PhpPossiblePolymorphicInvocationInspection */ return $this->redirect(['view', 'id' => $model->id]); } } if ($this->isAjax()) { return $this->asJson([ 'success' => false, 'errors' => $model->getErrors() ]); } else { return $this->render('create', [ 'model' => $model ]); } } /** * Updates an existing model. * If update is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionUpdate() { if (!$this->getModel()) { return $this->redirect('index'); } if ($this->getModel()->load(Yii::$app->request->post())) { if ($this->getModel()->save()) { $name = ucfirst($this->getUniqueId()); Yii::$app->session->addFlash('success', Yii::t('app', "$name successfully updated!")); return $this->redirect(['view', 'id' => $this->getModel()->id]); } else { foreach($this->getModel()->getErrors() as $error) Yii::$app->session->addFlash('error', reset($error)); } } return $this->render('update', [ 'model' => $this->getModel() ]); } /** * Deletes an existing model. * If deletion is successful, the browser will be redirected to the 'index' page. * @return mixed */ public function actionDelete() { if (!$this->getModel()) { Yii::$app->session->addFlash('error', 'Model for deleting not founded!'); return $this->goReferrer(); } try { if (!$this->getModel()->delete()) { foreach ((array) $this->getModel()->getErrors() as $attribute => $errors) { foreach ($errors as $error) { Yii::$app->session->addFlash('error', ucfirst($attribute) . ': ' . $error); } } } else { $modelName = ucfirst($this->getUniqueId()); Yii::$app->session->addFlash('success', Yii::t('app', "$modelName deleted!")); } } catch (StaleObjectException $e) { Yii::$app->session->addFlash('error', $e->getMessage()); } catch (\Throwable $e) { Yii::$app->session->addFlash('error', $e->getMessage()); } return $this->goReferrer(); } /** * Finds the model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param array $pk * @return ActiveRecord|null the loaded model */ protected function findModel(array $pk) { /** @var ActiveRecord $class */ $class = $this->getModelClass(); if (($model = $class::findOne($pk)) !== null) { return $model; } $error = \Yii::t('yii', 'The requested page does not exist.'); Yii::$app->session->addFlash('error', $error ); return null; } /** * @param bool $isSearch * @return string */ protected function getModelClass(bool $isSearch = false) : string { $class = $isSearch ? $this->modelClass : $this->searchModelClass; if ($class) { return $class; } $name = get_class($this); $parts = explode("\\", $name); $name = end($parts); $name = preg_replace('/Controller/', '', $name); return $isSearch ? $this->searchModelsPath . "${name}Search" : $this->modelsPath . $name; } /** * @param bool $useCache * @param bool $searchModel * @return ActiveRecord */ protected function createModel(bool $useCache = true, bool $searchModel = false) : ActiveRecord { if ($useCache && $this->getModel()) { return $this->getModel(); } $class = $this->getModelClass($searchModel); $model = new $class(); $this->setModel($model); return $model; } /** * @param array $params * @return array|null */ protected function primaryKey(array $params) : ?array { $pk = []; foreach ($this->primaryKey as $key) { if (empty($params[$key])) { return null; } $pk[$key] = $params[$key]; } return $pk; } /** * @return Response */ protected function goReferrer() : Response { return $this->redirect(\Yii::$app->request->referrer ?: \Yii::$app->homeUrl); } /** * @param string $view * @param array $params */ protected function applyVue(string $view, array $params) : void { $config = $this->getVueConfig(); if (!array_key_exists($view, $config)) { return; } $config = $config[$view]; $data = $config['data'] ?? []; $data['area'] = $this->getUniqueId(); foreach ($params as $param) { if (!is_object($param)) { continue; } if (method_exists($param, 'getModelArea') && method_exists($param, 'safeAttributes')) { $attributes = []; foreach($param->safeAttributes() as $attribute) { $attributes[$attribute] = $param->$attribute; } $data = ArrayHelper::merge($data, [ $param->getModelArea() => $attributes ]); } } $config['data'] = $data; /** @var VueManager $manager */ /** @noinspection PhpUndefinedFieldInspection */ $manager = \Yii::$app->vueManager; $manager->register($config); } /** * @param $model * @param string $attribute * @param $value */ protected function updateAttribute(ActiveRecord $model, string $attribute, $value) { $model->$attribute = $value; $model->updateAttributes([ $attribute => $value, ]); $model->afterSave(false, [ $attribute => $value, ]); $class = get_class($model); $parts = explode('\\', $class); $name = end($parts); \Yii::$app->session->setFlash( 'success', \Yii::t('app', "$name $attribute successfully set as $value!") ); } /** * @return array */ public function getParams() : array { if (Yii::$app->request->isPost) { return Yii::$app->request->post(); } if (Yii::$app->request->isGet) { return Yii::$app->request->get(); } return []; } /** * @return bool */ protected function isAjax() : bool { return Yii::$app->request->isAjax; } } <file_sep>/src/commands/RbacController.php <?php declare(strict_types=1); namespace sablesoft\stuff\commands; use yii\helpers\ArrayHelper; use yii\rbac\Role; use yii\base\Exception; use yii\rbac\Permission; use yii\console\Controller; use sablesoft\stuff\helpers\AccessHelper; /** * Class RbacController * @package sablesoft\stuff\commands */ class RbacController extends Controller { const CONFIG_RULE = 'rule'; const CONFIG_DESC = 'desc'; const CONFIG_CHILD = 'child'; /** * Init users roles * * @throws \Exception */ public function actionInit() { $admin = $this->createAdmin(); $this->stdout("Admin role installed!\r\n"); $this->createDomains($admin); $this->stdout("App domains installed!\r\n"); $this->createRoles(); $this->stdout("App roles installed and configured!\r\n"); } /** * @return Role * @throws \Exception */ protected function createAdmin() : Role { $auth = \Yii::$app->authManager; $admin = $auth->getRole(AccessHelper::ROLE_ADMIN); if (!$admin) { $admin = $auth->createRole(AccessHelper::ROLE_ADMIN); $admin->description = "Super admin role"; $auth->add($admin); } return $admin; } /** * @param Role $admin * @throws Exception * @throws \Exception */ protected function createDomains(Role $admin) : void { $auth = \Yii::$app->authManager; $domains = AccessHelper::get(AccessHelper::PARAMS_DOMAINS, []); if (!$domains) { $this->createApp($admin); } foreach ($domains as $domain => $config) { $name = ucfirst($domain); $permission = $auth->getPermission($domain); if (!$permission) { $permission = $auth->createPermission($domain); $permission->description = "$name domain"; $auth->add($permission); } if (!$auth->hasChild($admin, $permission)) { $auth->addChild($admin, $permission); } $this->createAreas($config, $admin, $permission); $this->stdout("$name areas permissions installed!\r\n"); $this->createCustom($config, $domain); $this->stdout("$name custom permissions installed!\r\n"); } } /** * @param Role $admin * @throws Exception */ protected function createApp(Role $admin) : void { $config = AccessHelper::get(); $this->createAreas($config, $admin); $this->stdout("Areas permissions installed!\r\n"); $this->createCustom($config); $this->stdout("Custom permissions installed!\r\n"); } /** * @param array $config * @param Role $admin * @param Permission $domain * @throws Exception */ protected function createAreas(array $config, Role $admin, ?Permission $domain = null) : void { $auth = \Yii::$app->authManager; $parent = $domain ?? $admin; foreach (ArrayHelper::getValue($config, AccessHelper::PARAMS_AREAS, []) as $key => $actions) { $area = is_string($key) ? $key : $actions; $area = $domain ? $domain->name .".". $area : $area; $actions = is_array($actions) ? $actions : ArrayHelper::getValue($config, AccessHelper::PARAMS_DEFAULT_ACTIONS, []); $permission = $this->areaPermissions($area, $actions); if (!$auth->hasChild($parent, $permission)) { $auth->addChild($parent, $permission); } } } /** * @param string $area * @param array $actions * @return Permission * @throws Exception * @throws \Exception */ protected function areaPermissions(string $area, array $actions) : Permission { $auth = \Yii::$app->authManager; $name = preg_replace('/\./', ' ', $area); $name = ucfirst($name); $parent = $auth->getPermission($area); if (!$parent) { $parent = $auth->createPermission($area); $parent->description = "$name area"; $auth->add($parent); } foreach ($actions as $action) { $permission = $auth->getPermission("$area.$action"); if (!$permission) { $permission = $auth->createPermission("$area.$action"); $permission->description = "$name $action action"; $auth->add($permission); } if (!$auth->hasChild($parent, $permission)) { $auth->addChild($parent,$permission); } } return $parent; } /** * @param string $domain * @param array $config * @throws Exception */ protected function createCustom(array $config, ?string $domain = null) : void { $custom = ArrayHelper::getValue($config, AccessHelper::PARAMS_CUSTOM, []); $custom = $domain ? [$domain => [self::CONFIG_CHILD => $custom]] : $custom; $this->_createCustom($custom); } /** * @param array $custom * @return array * @throws Exception * @throws \Exception */ protected function _createCustom(array $custom) : array { $permissions = []; $auth = \Yii::$app->authManager; foreach ($custom as $name => $config) { if (is_int($name) && is_string($config)) { $name = $config; $config = []; } $permission = $auth->getPermission($name); $isNew = !$permission; if ($isNew) { $permission = $auth->createPermission($name); } if ($config[self::CONFIG_DESC]) { $permission->description = $config[self::CONFIG_DESC]; } if ($config[self::CONFIG_RULE]) { $permission->ruleName = $config[self::CONFIG_RULE]; } $isNew ? $auth->add($permission) : $auth->update($name, $permission); if (!empty($config[self::CONFIG_CHILD])) { $children = $this->_createCustom((array) $config[self::CONFIG_CHILD]); foreach ($children as $child) { if (!$auth->hasChild($permission, $child)) { $auth->addChild($permission, $child); } } } $permissions[] = $permission; } return $permissions; } /** * @throws \Exception */ protected function createRoles() : void { $auth = \Yii::$app->authManager; foreach (AccessHelper::get(AccessHelper::PARAMS_ROLES, []) as $name => $permissions) { $role = $auth->getRole($name); if (!$role) { $role = $auth->createRole($name); $role->description = ucfirst($name) . " role"; $auth->add($role); } foreach ($permissions as $name) { $permission = $auth->getPermission($name); if (!$permission) { throw new Exception("Invalid role permission config!"); } if (!$auth->hasChild($role, $permission)) { $auth->addChild($role, $permission); } } } } } <file_sep>/src/traits/IsDeletedTrait.php <?php declare(strict_types=1); namespace sablesoft\stuff\traits; use yii\base\Exception; use sablesoft\stuff\interfaces\IsDeletedInterface; /** * Trait IsDeletedTrait * @package sablesoft\stuff\traits * @property bool $isDeleted * @method updateAttributes(array $attributes) * @method hasAttribute(string $attribute) */ trait IsDeletedTrait { /** * @return bool * @throws Exception */ public function getIsDeleted() : bool { $field = $this->deletedField(); if (!$this->hasAttribute($field)) { throw new Exception("Invalid deleted field!"); } return (bool) $this->$field; } /** * @param array $condition * @param string $deletedField * @return mixed */ public static function findDeleted(array $condition, string $deletedField = IsDeletedInterface::FIELD) { return static::findOne(array_merge($condition, ['not', $deletedField, null])); } /** * @param array $condition * @param string $deletedField * @return mixed */ public static function findNotDeleted(array $condition, string $deletedField = IsDeletedInterface::FIELD) { return static::findOne(array_merge($condition, [$deletedField => null])); } /** * @return string */ protected function deletedField() : string { $property = IsDeletedInterface::DELETED_FIELD; return property_exists($this, $property) ? $this->$property : IsDeletedInterface::FIELD; } } <file_sep>/src/traits/DateTimeTrait.php <?php /** @noinspection PhpUnusedParameterInspection */ declare(strict_types=1); namespace sablesoft\stuff\traits; use Yii; use Exception; use yii\db\Expression; use yii\db\ActiveQuery; use yii\db\ActiveRecord; use yii\behaviors\AttributeBehavior; use kartik\date\DatePicker; use sablesoft\stuff\helpers\DateTimeHelper; use sablesoft\stuff\interfaces\DateTimeInterface; /** * Trait DateTimeTrait * * @package app\models\base * * @property string|null $created * @property string|null $updated * @property string|null $deleted * @property string|null $lastAction * * @property array $dateFilterFields * @method hasAttribute(string $attribute) */ trait DateTimeTrait { /** * @return array|array[] */ public function datetimeBehaviors() : array { return [ 'created.save' => [ 'class' => AttributeBehavior::class, 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => [$this->getCreatedField()], ActiveRecord::EVENT_BEFORE_UPDATE => [$this->getCreatedField()] ], 'value' => function($event) { $field = $this->getCreatedField(); return $this->$field ? $this->$field : DateTimeHelper::now(); } ], 'updated.save' => [ 'class' => AttributeBehavior::class, 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => [$this->getUpdatedField()], ActiveRecord::EVENT_BEFORE_UPDATE => [$this->getUpdatedField()] ], 'value' => function($event) { return DateTimeHelper::now(); } ] ]; } /** * @param string $attribute * @param bool $asDate * @return array * @throws Exception */ public function datetimeColumn(string $attribute, $asDate = false) : array { $format = $asDate ? 'date' : 'datetime'; return [ 'attribute' => $attribute, 'format' => $format, 'filter' => DatePicker::widget([ 'model' => $this, 'attribute' => $attribute, 'options' => [ 'autocomplete' => 'off', 'placeholder' => Yii::t('app','Date') .'...' ], 'pluginOptions' => [ 'forceParse' => true, 'format' => 'yyyy-mm-dd', 'autoclose' => true, 'todayHighlight' => true ] ]) ]; } /** * @return string */ protected function getCreatedField() : string { return property_exists($this, 'fieldCreated') ? $this->fieldCreated : DateTimeInterface::FIELD_CREATED; } /** * @return string|null */ public function getCreated(): ?string { $field = $this->getCreatedField(); return $this->hasProperty($field) ? $this->$field : null; } /** * @param string $created * @return $this */ public function setCreated(string $created) { $field = $this->getCreatedField(); if ($this->hasProperty($field) && !$this->$field) { $this->$field = $created; } return $this; } /** * @return string */ protected function getUpdatedField() : string { return property_exists($this, 'fieldUpdated') ? $this->fieldUpdated : DateTimeInterface::FIELD_UPDATED; } /** * @return string|null */ public function getUpdated(): ?string { $field = $this->getUpdatedField(); return $this->hasProperty($field) ? $this->$field : null; } /** * @param string $updated * @return $this */ public function setUpdated(string $updated) { $field = $this->getUpdatedField(); if ($this->hasProperty($field)) { $this->$field = $updated; } return $this; } /** * @return string */ protected function getDeletedField() : string { return property_exists($this, 'fieldDeleted') ? $this->fieldDeleted : DateTimeInterface::FIELD_DELETED; } /** * @return string|null */ public function getDeleted(): ?string { $field = $this->getDeletedField(); return $this->hasProperty($field) ? $this->$field : null; } /** * @param string $deleted * @return $this */ public function setDeleted(string $deleted) { $field = $this->getDeletedField(); if ($this->hasProperty($field) && !$this->$field) { $this->$field = $deleted; } return $this; } /** * @return string */ protected function getLastActionField() : string { return property_exists($this, 'fieldLastAction') ? $this->fieldLastAction : DateTimeInterface::FIELD_LAST_ACTION; } /** * @return string|null */ public function getLastAction(): ?string { $field = $this->getLastActionField(); return $this->hasProperty($field) ? $this->$field : null; } /** * @param string $lastAction * @return $this */ public function setLastAction(string $lastAction) { $field = $this->getLastActionField(); if ($this->hasProperty($field)) { $this->$field = $lastAction; } return $this; } /** * @return $this */ public function updateLastAction() { $field = $this->getLastActionField(); if (!$this->hasProperty($field)) { return $this; } $this->$field = DateTimeHelper::now(); $this->updateAttributes([$field => $this->$field]); return $this; } /** * @param string $attribute * @param ActiveQuery $query */ public function applyDateFilter(string $attribute, ActiveQuery $query) { if(!$this->hasProperty($attribute) || empty($this->$attribute)) { return; } $date = $this->$attribute; $query->andFilterWhere([ 'BETWEEN', $attribute, $this->dateExpression($date), $this->dateExpression($date, false) ]); } /** * @param ActiveQuery $query */ public function applyDateFilters(ActiveQuery $query) { foreach ($this->dateFields() as $field) { $this->applyDateFilter($field, $query); } } /** * @param $attributes * @return int */ public function updateAttributes($attributes) { $attributes[$this->getUpdatedField()] = DateTimeHelper::now(); /** @noinspection PhpUndefinedClassInspection */ $result = parent::updateAttributes($attributes); if ($result) { $this->afterSave(false, $attributes); } return $result; } /** * @return array */ protected function dateFields() : array { return $this->getDateFilterFields() ?? [ $this->getCreatedField(), $this->getUpdatedField(), $this->getLastActionField(), $this->getDeletedField() ]; } /** * @param string $date * @param bool $begin * @return Expression */ protected function dateExpression(string $date, bool $begin = true) : Expression { $time = $begin ? "00:00:00" : "23:59:59"; return new Expression("STR_TO_DATE('$date $time', '%Y-%m-%d %H:%i:%s')"); } } <file_sep>/src/interfaces/DateTimeInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; use yii\db\ActiveQuery; /** * Interface DateTimeInterface * @package sablesoft\stuff\interfaces */ interface DateTimeInterface { const FIELD_CREATED = 'created'; const FIELD_UPDATED = 'updated'; const FIELD_DELETED = 'deleted'; const FIELD_LAST_ACTION = 'last_action'; /** * @param string $attribute * @param ActiveQuery $query */ public function applyDateFilter(string $attribute, ActiveQuery $query); /** * @param ActiveQuery $query */ public function applyDateFilters(ActiveQuery $query); /** * @return string|null */ public function getCreated() : ?string; /** * @param string $created * @return mixed */ public function setCreated(string $created); /** * @return string|null */ public function getUpdated() : ?string; /** * @param string $updated * @return string|null */ public function setUpdated(string $updated); /** * @return string|null */ public function getDeleted() : ?string; /** * @param string $deleted * @return mixed */ public function setDeleted(string $deleted); /** * @return string|null */ public function getLastAction() : ?string; /** * @param string $lastAction * @return mixed */ public function setLastAction(string $lastAction); /** * @return mixed */ public function updateLastAction(); /** * @return array */ public function getDateFilterFields() : ?array; }<file_sep>/src/db/Migration.php <?php declare(strict_types=1); namespace sablesoft\stuff\db; use yii\db\ColumnSchemaBuilder; /** * Class Migration * @package app\models\base */ class Migration extends \yii\db\Migration { const COLUMN_TYPE_BLOB = 'longblob'; const COLUMN_TYPE_BIT = 'bit'; /** * @param string $type * @param null $length * @return ColumnSchemaBuilder */ public function custom(string $type, $length = null) : ColumnSchemaBuilder { return $this->getDb()->getSchema()->createColumnSchemaBuilder($type, $length); } /** * @return ColumnSchemaBuilder */ public function bit() : ColumnSchemaBuilder { return $this->custom(self::COLUMN_TYPE_BIT, 1); } /** * @return ColumnSchemaBuilder */ public function blob() : ColumnSchemaBuilder { return $this->custom(self::COLUMN_TYPE_BLOB); } } <file_sep>/src/interfaces/SearchInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; use yii\db\ActiveQuery; use yii\data\ActiveDataProvider; /** * Interface SearchInterface * @package sablesoft\stuff\interfaces * * @property array $filters */ interface SearchInterface { const FILTER_IS_NULL = '_null'; /** * @param array $params * @return ActiveDataProvider */ public function search(array $params) : ActiveDataProvider; /** * @return array */ public function getFilters() : array; /** * @param ActiveQuery $query * @return ActiveQuery */ public function applyFilters(ActiveQuery $query); /** * @param ActiveQuery $query * @param string $field * @param string $elseOperator * @return ActiveQuery */ public function nullFilter(ActiveQuery $query, string $field, string $elseOperator = 'eq'); } <file_sep>/src/interfaces/ParamsInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; /** * Interface ParamsInterface * @package sablesoft\stuff\interfaces */ interface ParamsInterface { /** * @return string|null */ public static function paramsPath() : ?string; /** * @param string|null $path * @return array */ public static function keys(string $path = null) : array; /** * @param string $path * @return bool */ public static function checked(string $path) : bool; /** * @param string|null $path * @param null $default * @return mixed */ public static function get(?string $path = null, $default = null); /** * @param string $value * @param string|null $path * @return bool */ public static function have(string $value, ?string $path = null) : bool; } <file_sep>/src/traits/ParamsTrait.php <?php declare(strict_types=1); namespace sablesoft\stuff\traits; use yii\helpers\ArrayHelper; /** * Trait ParamsTrait * @package sablesoft\stuff\traits */ trait ParamsTrait { /** * @var array|null */ protected static ?array $_params = null; /** * @param string|null $path * @return array */ public static function keys(string $path = null) : array { $params = static::get($path, []); return array_keys($params); } /** * @param string $path * @return bool */ public static function checked(string $path) : bool { static::prepare(); return (bool) static::get($path); } /** * @param string|null $path * @param null $default * @return mixed|null */ public static function get(?string $path = null, $default = null) { static::prepare(); if ($path == null) { return static::$_params; } return ArrayHelper::getValue(static::$_params, $path, $default); } /** * @param string $value * @param string $path * @return bool */ public static function have(string $value, ?string $path = null) : bool { static::prepare(); $array = $path ? (array) static::get($path, []) : static::$_params; return in_array($value, $array); } /** * Init access params */ protected static function prepare() : void { if (static::$_params !== null) { return; } $path = static::paramsPath(); if ($path == null) { static::$_params = \Yii::$app->params; return; } static::$_params = !empty(\Yii::$app->params[$path]) ? \Yii::$app->params[$path] : []; $preparer = static::$preparer ?? null; if ($preparer !== null) { static::$preparer(); } } } <file_sep>/src/helpers/DateTimeHelper.php <?php declare(strict_types=1); namespace sablesoft\stuff\helpers; /** * Class DateTimeHelper * @package app\helper */ class DateTimeHelper { /** * @param string $timeZone * @return string */ public static function now(string $timeZone = 'Utc') : string { $dateTime = new \DateTime('now'); $dateTime = $dateTime->setTimezone(new \DateTimeZone($timeZone)); return $dateTime->format('Y-m-d H:i:s'); } /** * @param int $timestamp * @param string $timeZone * @return string */ public static function timestampNow(int $timestamp, string $timeZone = 'Utc') : string { $dateTime = new \DateTime(); $dateTime->setTimestamp($timestamp); $dateTime = $dateTime->setTimezone(new \DateTimeZone($timeZone)); return $dateTime->format('Y-m-d H:i:s'); } } <file_sep>/src/traits/SelectTrait.php <?php declare(strict_types=1); namespace sablesoft\stuff\traits; use yii\helpers\ArrayHelper; use sablesoft\stuff\interfaces\SelectInterface; /** * Trait SelectTrait * @package app\models\base * * @property array $dropDown */ trait SelectTrait { /** * @param array $config * @param bool $withParams * @return array */ public static function getSelect(array $config = [], bool $withParams = false) : array { // prepare items: $query = static::find(); $where = !empty($config[SelectInterface::CONFIG_WHERE])? $config[SelectInterface::CONFIG_WHERE] : false; if(is_array($where)) { $query = $query->where($where); } $models = $query->all(); $from = !empty($config[SelectInterface::CONFIG_FROM])? $config[SelectInterface::CONFIG_FROM] : SelectInterface::DEFAULT_FIELD_FROM; $to = !empty($config[SelectInterface::CONFIG_TO])? $config[SelectInterface::CONFIG_TO] : SelectInterface::DEFAULT_FIELD_TO; $items = ArrayHelper::map($models, $from, $to); if (!$withParams) { return $items; } // prepare params: $params = []; if (!empty($config['selected'])) { $selected = static::find()->where(['is_default' => 1])->one(); if ($selected->id) { $params = [ 'options' => [ $selected->id => ['Selected' => true] ] ]; } } if (isset($config['prompt'])) { $params['prompt'] = $config['prompt']; } return [$items, $params]; } } <file_sep>/src/traits/IsDefaultTrait.php <?php /** @noinspection PhpUndefinedClassInspection */ declare(strict_types=1); namespace sablesoft\stuff\traits; use yii\db\ActiveRecord; use sablesoft\stuff\helpers\DateTimeHelper; use sablesoft\stuff\interfaces\IsDefaultInterface; /** * Trait IsDefaultTrait * @package app\models\base * * @property bool $isDefault * @method getOldAttribute(string $attribute) * @method updateAttributes(array $attributes) * @method addError(string $attribute, string $message) * @method static find() */ trait IsDefaultTrait { /** * @return bool */ public function getIsDefault() : bool { $field = $this->isDefaultField(); return (bool) $this->$field; } /** * @param bool $isDefault * @return $this */ public function setIsDefault(bool $isDefault) : self { $field = $this->isDefaultField(); $this->$field = $isDefault; return $this; } /** * @return string */ protected function isDefaultField() : string { $property = IsDefaultInterface::IS_DEFAULT_FIELD; return property_exists($this, $property) ? $this->$property : IsDefaultInterface::FIELD; } /** * @return bool */ protected function checkDefault() : bool { if (!$this->isDefault && $this->getOldAttribute($this->isDefaultField())) { $this->addError($this->isDefaultField(), 'Cannot uncheck default!'); return false; } if ($this->isDefault && !$this->getOldAttribute($this->isDefaultField())) { /** @var ActiveRecord|IsDefaultInterface $oldDefault */ $oldDefault = static::find()->where([$this->isDefaultField() => 1])->one(); $oldDefault->isDefault = false; $oldDefault->updateAttributes([ $this->isDefaultField() => $oldDefault->isDefault, 'updated' => DateTimeHelper::now() ]); } return true; } } <file_sep>/src/interfaces/IsOwnerInterface.php <?php declare(strict_types=1); namespace sablesoft\stuff\interfaces; /** * Interface IsOwnerInterface * @package sablesoft\stuff\interfaces */ interface IsOwnerInterface { /** * @param string|null $ownerKey * @return bool */ public function isOwner(string $ownerKey = null) : bool; }
6f7aab2a7061e61d6f2c680ea6643f9ff01749bc
[ "PHP" ]
20
PHP
sablesoft/yii2-stuff
9fd99c593d616a64bfd3964e86945bc3f483bf5b
54a17acae9e0fa28186bea203a781ca9e4d69777
refs/heads/master
<repo_name>SeonMyungLim/context-menu<file_sep>/README.md # context-menu light weight right click context menu library. download or clone repo and play with it. <file_sep>/src/main.js $(document).ready(function() { //basic example console.log('ready'); var target = $('#target1'); var options = []; var alertA = { enable: true, text: 'alertA', callback: function() { alert('alertA'); } }; var alertB = { enable: true, text: 'alertB', callback: function() { alert('alertB'); } }; var disabled = { enable: false, text: 'disabled text', callback: function() { alert('not gonna work'); } }; options.push(alertA); options.push(alertB); options.push(disabled); ContextMenu.bindContextMenu(target, options); //class name example target = $('#target2'); options = []; alertA = { enable: true, text: 'alertA custom', callback: function() { alert('alertA custom'); } }; alertB = { enable: true, text: 'alertB custom', callback: function() { alert('alertB custom'); } }; disabled = { enable: false, text: 'disabled text custom', callback: function() { alert('not gonna work'); } }; options.push(alertA); options.push(alertB); options.push(disabled); ContextMenu.bindContextMenu(target, options, 'custom-class-name'); }); <file_sep>/src/context-menu.js 'use strict'; (function() { var ctx = {}; ctx.createDom = function() { var that = this; this.dom = $('<ul>', { id: 'contextmenu' }); $('body').append(this.dom); disableContextMenu(this.dom); $(document).mousedown(function(e) { that.hide(); }); }; ctx.show = function(options, className, e) { if (!this.dom) this.createDom(); if (options.length === 0) return; var that = this; if (className !== undefined) { this._className = className; this.dom.addClass(className); } var parent = this.dom; parent.empty(); for (var i=0, len=options.length; i<len; i++) { var option = options[i]; var text = option.text; var enable = option.enable !== false; var elem = $('<li>', { class: enable ? 'menuAble' : 'menuDisable' }); parent.append(elem); elem.text(text); if (enable && option.callback) { (function(elem, cb) { elem.mousedown(function(e){ e.preventDefault(); that.hide(); cb(e); }); })(elem, option.callback); } } parent.css('display', 'block'); this.position(e); }; ctx.position = function(e) { var pos = { x: e.clientX, y: e.clientY }; var dom = this.dom; dom.css({ left: 0, top: 0 }); var width = dom.width(); var height = dom.height(); var win = $(window); var winWidth = win.width(); var winHeight = win.height(); if (pos.x + width > winWidth) pos.x -= width + 3; if (pos.y + height > winHeight) pos.y -= height; dom.css({ left: pos.x, top: pos.y }); }; ctx.hide = function() { this.dom.empty(); this.dom.css('display', 'none'); if (this._className) { this.dom.removeClass(this._className); delete this._className; } }; ctx.bindContextMenu = function(elem, options, className) { var that = this; elem = $(elem); disableContextMenu(elem); elem.bind('contextmenu' ,function(e) { that.show(options, className, e); }); }; ctx.unbindContextMenu = function(elem) { elem.unbind('contextmenu'); }; function disableContextMenu(dom) { dom.bind('contextmenu' ,function(e) { e.preventDefault(); }); } window.ContextMenu = ctx; })();
4e17b6b0be8e06fb5729956cd18154624f717cc3
[ "Markdown", "JavaScript" ]
3
Markdown
SeonMyungLim/context-menu
43fc77711f04a296cd0af8fc6b28a15e30e36a3a
e076eaebdf1d118138a7568c244707801d82ccda
refs/heads/main
<file_sep><div class="supercard cont"> <div class="card" > <img src="../assets/colosseo.jfif" class=" img-card card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Colosseo</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div><file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-attrazioni', templateUrl: './attrazioni.component.html', styleUrls: ['./attrazioni.component.scss'] }) export class AttrazioniComponent implements OnInit { listAttrazioni = [{ id:1, place:"Peschiera di Carta", name:"<NAME>", image:"../assets/colosseo.jfif" }, { id:2, place:"Peschiera di Carta", name:"<NAME>, Venezia", image:"../assets/San Marco.jpg" }, { id:3, place:"Peschiera di Carta", name:"<NAME>", image:"../assets/uffizi.jfif" }] constructor() { } ngOnInit(): void { } }
5c72f52a041569fa0740b61b31542dadd7cec7fc
[ "TypeScript", "HTML" ]
2
HTML
FedeBon/EsameAngular
2386b6decccce8be4a047dc4cc1daefafba49813
8f6db7e36a300d604a29cb579d2c1280c37e3879
refs/heads/master
<repo_name>vctrmn/poc-proxydata-app-engine<file_sep>/README.md # poc-proxydata-app-engine <file_sep>/app.js 'use strict'; const express = require('express'); const helmet = require('helmet'); // Protection / Creates headers that protect from attacks (security) const morgan = require('morgan'); // logs requests const { Datastore } = require('@google-cloud/datastore'); const app = express(); app.enable('trust proxy'); app.set('case sensitive routing', true); app.use(helmet()); app.use(morgan('combined')) // use 'tiny' or 'combined' // Instantiate a datastore client const datastore = new Datastore(); /** * Insert a event record into the database. * * @param {object} event The visit record to insert. */ const insertEvent = event => { return datastore.save({ key: datastore.key('event'), data: event, }); }; /** * Retrieve the event records from the database. */ const getEvents = () => { const query = datastore .createQuery('event') .order('dateSent', { descending: true }); return datastore.runQuery(query); }; // Create a event record to be stored in the database app.get('/proxydata/event', async (req, res, next) => { const event = { eventData: req.query, dateSent: Date(Date.now()) }; try { await insertEvent(event); res.status(201).type('application/json').send({ success: true, data: event }); } catch (err) { next(err); } }); // Retrieve events record stored in the database app.get('/proxydata/events', async (req, res, next) => { try { const events = await getEvents(); res.status(200).type('application/json').send(events[0]); } catch (err) { next(err); } }); // Basic 404 handler app.use((req, res, next) => { res.status(404).send({ error: 'Not Found' }); }); // 500 - Any server error app.use((err, req, res, next) => { res.status(500).send({ error: err || 'Something Broke' }); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); console.log('Press Ctrl+C to quit.'); }); module.exports = app;
5cbccee1b8e57f16fb1b27c116de49f3baa18ceb
[ "Markdown", "JavaScript" ]
2
Markdown
vctrmn/poc-proxydata-app-engine
774bdfb9cfaace5890a3efff0e14770c87f2ab9a
d5225cf9030a1ad5f214aff8015e276e87186f4c
refs/heads/master
<file_sep>names = [] surnames = [] phones = [] cities = [] emails = [] def add_to_directory(): new_name = str(input()) new_surname = str(input()) new_phone = str(input()) new_city = str(input()) new_email = str(input()) if (new_email in emails) is False: names.append(new_name) surnames.append(new_surname) phones.append(new_phone) cities.append(new_city) emails.append(new_email) else: print('дубль не был добавлен') def search(): print('По какой информации хотите искать?') request = str(input()) if request == 'name': search_name = str(input()) if search_name in names: i = names.index(search_name) print(names[i], surnames[i], phones[i], cities[i], emails[i]) elif request == 'surname': search_surname = str(input()) if search_surname in surnames: i = surnames.index(search_surname) print(names[i], surnames[i], phones[i], cities[i], emails[i]) elif request == 'phone': search_phone = str(input()) if search_phone in phones: i = phones.index(search_phone) print(names[i], surnames[i], phones[i], cities[i], emails[i]) elif request == 'city': search_city = str(input()) if search_city in cities: i = cities.index(search_city) print(names[i], surnames[i], phones[i], cities[i], emails[i]) elif request == 'e-mail': search_emails = str(input()) if search_emails in emails: i = emails.index(search_emails) print(names[i], surnames[i], phones[i], cities[i], emails[i]) def change_directory(): print('Какую информацию хотите изменить?') request = str(input()) if request == 'name': print('Какое имя изменить?') search_name = str(input()) print('Введите новое имя') change_name = str(input()) if search_name in names: i = names.index(search_name) names[i] = change_name elif request == 'surname': print('Какую фамилию изменить?') search_surname = str(input()) print('Введите новую фамилию') change_surname = str(input()) if search_surname in surnames: i = surnames.index(search_surname) surnames[i] = change_surname elif request == 'phone': print('Какой телефон изменить?') search_phone = str(input()) print('Введите новый телефон') change_phone = str(input()) if search_phone in phones: i = phones.index(search_phone) phones[i] = change_phone elif request == 'city': print('Какой город изменить?') search_city = str(input()) print('Введите новый город') change_city = str(input()) if search_city in cities: i = cities.index(search_city) cities[i] = change_city elif request == 'e-mail': print('Какой e-mail изменить?') search_email = str(input()) print('Введите новый e-mail') change_email = str(input()) if search_email in emails: i = emails.index(search_email) emails[i] = change_email def delete(): print('По какой информации удалять?') request = str(input()) if request == 'name': print('Какое имя удалить?') search_name = str(input()) if search_name in names: i = names.index(search_name) names.pop(i) surnames.pop(i) phones.pop(i) cities.pop(i) emails.pop(i) elif request == 'surname': print('Какую фамилию удалить?') search_surname = str(input()) if search_surname in surnames: i = surnames.index(search_surname) names.pop(i) surnames.pop(i) phones.pop(i) cities.pop(i) emails.pop(i) elif request == 'phone': print('Какой телефон удалить?') search_phone = str(input()) if search_phone in phones: i = phones.index(search_phone) names.pop(i) surnames.pop(i) phones.pop(i) cities.pop(i) emails.pop(i) elif request == 'city': print('Какой город удалить?') search_city = str(input()) if search_city in cities: i = phones.index(search_city) names.pop(i) surnames.pop(i) phones.pop(i) cities.pop(i) emails.pop(i) elif request == 'e-mail': print('Какой e-mail удалить?') search_email = str(input()) if search_email in emails: i = emails.index(search_email) names.pop(i) surnames.pop(i) phones.pop(i) cities.pop(i) emails.pop(i) add_to_directory() add_to_directory() add_to_directory() add_to_directory() print(names, surnames, phones, cities, emails) file = open('1.txt', 'w', encoding='utf-8') for i in range(len(names)): file.write('%s %s %s %s %s\n' % (names[i], surnames[i], phones[i],cities[i],emails[i]))
e2f9655b941646f73f5b2718f9911d902d5e7fed
[ "Python" ]
1
Python
Foxovsky-bit/Python_directory
f54937f658abb6357b4023d0000196abf326a97f
14d7e95bb3b8e4b0e6b12e2befcf9985e7ee6fbe
refs/heads/master
<repo_name>Arion9228/Automation-features-using-Selenium-Framework<file_sep>/README.md # Automation-features-using-Selenium-Framework Task 3 of GRIP Phase-2 <file_sep>/sendEmail.py #!/usr/bin/env python # # In[40]: #Importing the required Modules from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import time #Collecting the Target Mail ID mail_id = input("Please Provide the Target Mail ID: ") #Subject of Mail sub = input("Please Enter the Subject: ") #Description of Mail desp = input("Please Enter the Mail: ") #Setting up Chrome_Driver driver = webdriver.Chrome(executable_path="C:\\Users\\Acer\\Desktop\\driver\\chromedriver") #Providing the Gmail URL driver.get("http://www.gmail.com") #Inputting the Source Email ID driver.find_element_by_name("identifier").send_keys("<EMAIL>") #Clicking Next Button driver.find_element_by_xpath("//*[@id='identifierNext']/span/span").click() #Wait driver.implicitly_wait(1) #Inputting the password driver.find_element_by_name("password").send_keys("<PASSWORD>") #Delay for error Handling element = WebDriverWait(driver, 0).until( EC.invisibility_of_element_located((By.ID, "ANuIbb IdAqtf")) ) #Clicking the Next Button after Inputting Password driver.find_element_by_xpath("//*[@id='passwordNext']/span/span").click() #Wating time to completely open the Source Mail ID driver.implicitly_wait(5) #Fetching the "Compose Mail" using css_selector driver.find_element_by_css_selector(".aic .z0 div").click() #Providing the Target Mail ID driver.find_element_by_css_selector(".oj div textarea").send_keys(mail_id) #Providing the Subject driver.find_element_by_css_selector(".aoD.az6 input").send_keys(sub) #Providing Mail Description driver.find_element_by_css_selector(".Ar.Au div").send_keys(desp) #Clicking on Send Mail using css_Selector driver.find_element_by_css_selector(".T-I.J-J5-Ji.aoO.v7.T-I-atl.L3").click() #Waiting Time driver.implicitly_wait(5) #Clicking on the Source ID Profile driver.find_element_by_xpath("//*[@id='gb']/div[2]/div[3]/div/div[2]/div/a/span").click() #Waiting to check for "Sent Mail" Notification driver.implicitly_wait(3) element = WebDriverWait(driver, 0).until( EC.invisibility_of_element_located((By.ID, "J-J5-Ji")) ) #Logging Out of the Source ID driver.find_element_by_css_selector("#gb_71").click() #Waiting time for proper functioning driver.implicitly_wait(5) #Closing & Quitting Driver driver.close() driver.quit() # In[ ]: # In[ ]: <file_sep>/brokenLinks.py #!/usr/bin/env python # coding: utf-8 # In[47]: #importing the required Modules import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys #Provide the URL of the Page you want to check url = input("Enter the Url to check for Broken Links: ") print("\n") #Running the Chrome Driver driver = webdriver.Chrome(executable_path="C:\\Users\\Acer\\Desktop\\driver\\chromedriver") #Fetching the required Page driver.get(url) #Creating a list named "links" to store all the hyperlinks links = driver.find_elements_by_css_selector('a') #Intializing Counter count=0 #Searching for Broken Links for link in links: #Setting the Status Code to a variable "r" r = requests.head(link.get_attribute('href')).status_code #If status code is not equal to 200, then it implies that the link is Broken if (r != 200): #Printing the Broken Links With their respective Status Code print(link.get_attribute('href'), "Broken Link!\n", "Status Code: ", r,"\n") count+=1 #Total Broken Links Found print("Total Broken Links: ", count) #Closing and Quitting the Driver driver.close() driver.quit() # In[ ]: # In[ ]: <file_sep>/imageDownload.py #!/usr/bin/env python # coding: utf-8 # In[ ]: #importing the required modules from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC import urllib.request import json #Taking the Keyword to be searched keyword=input("Enter the Keyword: ") #Defining the number of images to download num_requested=10 #Defining the extensions type extensions = {"jpg", "jpeg", "png", "gif"} #Providing thr File Download Path file_path="C:\\Users\\Acer\\Pictures\\GRIP\\" #Providing the Driver Path driver = webdriver.Chrome(executable_path="C:\\Users\\Acer\\Desktop\\driver\\chromedriver") #Fetching the Google Images Page driver.get("https://www.google.com/imghp?hl=en") #Selecting and inputting the Keyword in the Search Bar driver.find_element_by_css_selector("#sbtc > div.SDkEP > div.a4bIc > input").send_keys(keyword) #Clicking on Search Button driver.find_element_by_css_selector("#sbtc > div.cafKYd > button").click() #Waiting Time driver.implicitly_wait(3) #Fetching the Images required and stroing them in the list called "images" images = driver.find_elements_by_xpath('//div[contains(@class,"rg_meta")]') #Defining the Initial Counter count=1 for i in range(0,num_requested): #Fetching the URL of the Image img_url = json.loads(images[i].get_attribute('innerHTML'))["ou"] #Fetching the TYPE of image img_type = json.loads(images[i].get_attribute('innerHTML'))["ity"] #Providing the Path and name of the Download Image full_path = file_path +keyword +"_" + str(count) + '.jpg' #Error Handling for HTTP Error opener=urllib.request.build_opener() opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')] urllib.request.install_opener(opener) #Retrieving the Images urllib.request.urlretrieve(img_url, full_path) #Printing the Image URL print("Image Url: "+str(img_url)) #Printing the information of the Download Image print("Download " + str(count) + " of 10 COMPLETED!"+"\n") count+=1 #Exception Handling for Invalid Extension try: if img_type not in extensions: img_type = "jpg" except Exception as e: print ("Download failed:", e) #Wait driver.implicitly_wait(10) #Closing and Quitting the Driver driver.close() driver.quit() # In[ ]: # In[ ]:
4d95326c435a80d8181b43fd66eb092f85887782
[ "Markdown", "Python" ]
4
Markdown
Arion9228/Automation-features-using-Selenium-Framework
d3b42d62327c0a2aec01a11e8aea4923652aa35b
d12b8f94eb30ead0a4089bdd279bb75d2472f141
refs/heads/master
<repo_name>djvanderlaan/kykloop<file_sep>/discord_bot/bot.js const Discord = require('discord.js'); const SerialPort = require('serialport'); const fs = require('fs'); // ========= Kykloop class ================ // Keeps track of the current pan and tilt and sends commands to the // arduino device class Kykloop { constructor(device) { this.device = device; this.pan_ = 90; this.tilt_ = 90; this.angle_max_ = 170; this.angle_min_ = 10; if (this.device != "test") { this.port = new SerialPort(this.device, {baudRate: 9600}); this.port.on('error', function(err) { console.log('Problem with sesial device: ', err.message); }); } } tilt(angle) { if (arguments.length === 0) return this.tilt_; if (angle > this.angle_max_) angle = this.angle_max_; if (angle < this.angle_min_) angle = this.angle_min_; this.tilt_ = angle; // send command to arduino let new_position = 't' + this.tilt_ + ';'; if (this.device === "test") { console.log("Command to arduino: '" + new_position + "'"); } else { this.port.write(String(new_position), function(err) { if (err) return console.log('Error on write: ', err.message); }); } return this; } change_tilt(angle) { let new_tilt = this.tilt_ + (+angle); return this.tilt(new_tilt); } pan(angle) { if (arguments.length === 0) return this.pan_; if (angle > this.angle_max_) angle = this.angle_max_; if (angle < this.angle_min_) angle = this.angle_min_; this.pan_ = angle; // send command to arduino let new_position = 'p' + this.pan_ + ';'; if (this.device === "test") { console.log("Command to arduino: '" + new_position + "'"); } else { console.log("Command to arduino: '" + new_position + "'"); this.port.write(String(new_position), function(err) { if (err) return console.log('Error on write: ', err.message); }); } return this; } change_pan(angle) { let new_pan = this.pan_ + (+angle); return this.pan(new_pan); } } // ======= Set up connection to arduino device ======= // Try to detect the port to which the arduino device is connected const possible_ports = ['/dev/ttyACM0', '/dev/ttyACM1', '/dev/ttyACM2']; let port = 'test'; for (p in possible_ports) { if (fs.existsSync(possible_ports[p])) { port = possible_ports[p]; break; } } if (port == 'test') { console.log('Could not detect serial port; running in test mode.'); } else { console.log('Connecting to ' + port + '.'); } let kykloop = new Kykloop(port); // ====== Start discord client ======== const auth = require('./auth.json'); const client = new Discord.Client(); let stored_positions = {}; if (fs.existsSync('stored_positions.json')) { stored_positions = JSON.parse( fs.readFileSync('stored_positions.json', 'utf8') ); } client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('message', msg => { try { // ===== up/down/left/right // Messages of the form "kyk left 10" const turn_re = /^kyk[ ]+([a-z]+)[ ]+([0-9]+)[ ]*$/; if (turn_re.test(msg.content)) { let res = turn_re.exec(msg.content); if (res[1] == 'up') { kykloop.change_tilt(+res[2]); } else if (res[1] == 'down') { kykloop.change_tilt(-res[2]); } else if (res[1] == 'left') { kykloop.change_pan(+res[2]); } else if (res[1] == 'right') { kykloop.change_pan(-res[2]); } else { msg.reply("Unknown direction: '" + res[1] + "'."); } msg.reply('Turning camera ' + res[1] + ' by ' + res[2] + ' degrees (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } // ====== Shorthand notation const short_re = /^([lLrRuUdD])[ ]?$/; if (short_re.test(msg.content)) { let res = short_re.exec(msg.content); if (res[1] == 'l') { kykloop.change_pan(5); msg.reply('Turning camera 5 degrees left (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'L') { kykloop.change_pan(10); msg.reply('Turning camera 10 degrees left (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'r') { kykloop.change_pan(-5); msg.reply('Turning camera 5 degrees right (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'R') { kykloop.change_pan(-10); msg.reply('Turning camera 10 degrees right (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'd') { kykloop.change_tilt(-5); msg.reply('Turning camera 5 degrees down (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'D') { kykloop.change_tilt(-10); msg.reply('Turning camera 10 degrees down (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'u') { kykloop.change_tilt(5); msg.reply('Turning camera 5 degrees up (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } else if (res[1] == 'U') { kykloop.change_tilt(10); msg.reply('Turning camera 10 degrees up (' + kykloop.pan() + ',' + kykloop.tilt() + ').'); } } // ====== store prosition // Message of the format "kyk store word" const store_re = /^kyk[ ]+store[ ]+([a-z]+)[ ]*$/; if (store_re.test(msg.content)) { let res = store_re.exec(msg.content); stored_positions[res[1]] = { 'pan' : kykloop.pan(), 'tilt': kykloop.tilt() }; fs.writeFile('stored_positions.json', JSON.stringify(stored_positions, null, 2) , 'utf-8' ); msg.reply("Stored current position in '" + res[1], "'.") } // ======= retrieve prosition // Message of the format "kyk word" const retr_re = /^kyk[ ]+([a-z]+)[ ]*$/; if (retr_re.test(msg.content)) { let res = retr_re.exec(msg.content); let pos = stored_positions[res[1]]; if (pos !== undefined && pos.tilt !== undefined && pos.pan !== undefined) { kykloop.tilt(pos.tilt).pan(pos.pan); msg.reply("Moving to '" + res[1] + "'.") } else { msg.reply("Could not find stored position '" + res[1] + "'.") } } } catch (e) { msg.reply("An error occured: " + e); } }); client.login(auth.token); <file_sep>/arduino/kykloop/kykloop.ino #include <Servo.h> // Set the pin, max and minimum angles for the pan Servo serv_pan; const int PIN_PAN = 9; const int MIN_PAN = 10; const int MAX_PAN = 170; // Set the pin, max and minimum angles for the tilt Servo serv_tilt; const int PIN_TILT = 10; const int MIN_TILT = 10; const int MAX_TILT = 170; // Inititalise servos and set initial position to 90 degrees void setup() { serv_pan.attach(PIN_PAN); serv_tilt.attach(PIN_TILT); Serial.begin(9600); serv_pan.write(90); serv_tilt.write(90); } void set_tilt(int angle) { Serial.print("Setting tilt to: "); Serial.println(angle); if (angle < MIN_TILT) angle = MIN_TILT; if (angle > MAX_TILT) angle = MAX_TILT; serv_tilt.write(angle); } void set_pan(int angle) { Serial.print("Setting pan to: "); Serial.println(angle); if (angle < MIN_PAN) angle = MIN_PAN; if (angle > MAX_PAN) angle = MAX_PAN; serv_pan.write(angle); } // In the loop we will be reading data from serial input. Reading can be in // three possible states: // RNO: we are waiting for input // RPAN: we are reading the new position for the pan; the state swithes to // this state when it finds a 'p' in the input. It finishes reading the // pan and sets the pan when a ';' is found. // RTILT: we are reading the new position for the tilt; the state swithes to // this state when it finds a 't' in the input. It finishes reading the // tilt and sets the tilt when a ';' is found. // const int RNO = 0; const int RPAN = 1; const int RTILT = 2; void loop() { static int read_num = RNO; static int value = 0; if (Serial.available()) { char ch = Serial.read(); if (ch == 'p') { read_num = RPAN; } else if (ch == 't') { read_num = RTILT; } else if (read_num != RNO) { if (ch >= '0' && ch <= '9') { value = value*10 + (ch - '0'); } else if (ch == ';') { if (read_num == RPAN) set_pan(value); else if (read_num = RTILT) set_tilt(value); value = 0; } else { Serial.print("Error: invalid character in value mode: "); Serial.println(ch); } } else { Serial.print("Error: invalid character: "); Serial.println(ch); } } } <file_sep>/readme.md Kykloop =============== Webcam that can be controlled through a Discord bot.
6d10f8b6eb9490714beb0bde1b915f78a86ee308
[ "JavaScript", "C++", "Markdown" ]
3
JavaScript
djvanderlaan/kykloop
a964cb6ea031e8ffacc5ed5fe55680a0d9fb4377
e3553c78015667b718305331d29f126dd7a0669a
refs/heads/master
<repo_name>KatsiarynaMuzyka/Parking<file_sep>/src/com/epam/service/impl/SlotServiceImplementation.java package com.epam.service.impl; import java.util.*; import com.epam.bean.entity.Slot; import com.epam.service.SlotService; public class SlotServiceImplementation implements SlotService { public List<Slot> slots = new ArrayList<>(); @Override public List<Slot> getFreeSlotsForMotoCycle() { List<Slot> freeSlots = new ArrayList<>(); for (Slot s : slots) { if ((s.isFree()) && (!s.isRegular())) { freeSlots.add(s); } else if ((s.isFree()) && (!s.isRegular())) { freeSlots.add(s); } } return freeSlots; } @Override public List<Slot> getFreeSlotsForCar() { List<Slot> freeSlots = new ArrayList<>(); for (Slot s : slots) { if ((s.isFree()) && (s.isRegular())) { freeSlots.add(s); } else if ((s.isFree()) && (s.isRegular())) { freeSlots.add(s); } } return freeSlots; } @Override public Slot createCarSlot(boolean isCovered) { Slot slot = new Slot(); slot.setCovered(isCovered); slot.setRegular(true); slot.setFree(true); slot.setNumber(slots.size() + 1); slots.add(slot); return slot; } @Override public Slot createMotoSlot(boolean isCovered) { Slot slot = new Slot(); slot.setCovered(isCovered); slot.setRegular(false); slot.setFree(true); slot.setNumber(slots.size() + 1); slots.add(slot); return slot; } @Override public void setSlots() { for (int i = 0; i < SLOTSFORCARS; i++) { createCarSlot(false); } for (int i = 0; i < SLOTSFORMOTO; i++) { createMotoSlot(false); } } @Override public Map<String, Integer> getSlotsStatistic() { Map<String, Integer> slotStat = new LinkedHashMap<>(); int slotsForCars = 0; int freeSlotsForCars = 0; int slotsForMoto = 0; int freeSlotsForMoto = 0; for (Slot slot : slots) { if (slot.isRegular()) { slotsForCars++; } if (!slot.isRegular()) { slotsForMoto++; } if (slot.isRegular() && slot.isFree()) { freeSlotsForCars++; } if (!slot.isRegular() && slot.isFree()) { freeSlotsForMoto++; } slotStat.put("All slots:", slots.size()); slotStat.put("Slots for cars:", slotsForCars); slotStat.put("Slots for moto:", slotsForMoto); slotStat.put("Reserved slots for moto:", slotsForMoto - freeSlotsForMoto); slotStat.put("Reserved slots for cars:", slotsForCars - freeSlotsForCars); } return slotStat; } @Override public void setSlotFree(Slot slot) { for (int i = 0; i < slots.size(); i++) { if (slots.get(i).getNumber() == slot.getNumber()) { slots.get(i).setFree(true); } } } @Override public void setSlotReserved(Slot slot) { for (int i = 0; i < slots.size(); i++) { if (slots.get(i).getNumber() == slot.getNumber()) { slots.get(i).setFree(false); } } } } <file_sep>/src/com/epam/bean/GetCurrentSlotReservationRequest.java package com.epam.bean; import com.epam.bean.entity.Vehicle; public class GetCurrentSlotReservationRequest extends Request { private Vehicle vehicle; public Vehicle getVehicle() { return vehicle; } public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } } <file_sep>/src/com/epam/command/impl/CreateNewSlot.java package com.epam.command.impl; import com.epam.bean.*; import com.epam.command.Command; import com.epam.command.exception.CommandException; import com.epam.service.ServiceFactory; import com.epam.service.SlotService; public class CreateNewSlot implements Command { @Override public Response execute(Request request) throws CommandException { CreateSlotRequest req = null; if (request instanceof CreateSlotRequest) { req = (CreateSlotRequest) request; } else { throw new CommandException("Wrong request"); } ServiceFactory service = ServiceFactory.getInstance(); SlotService slotService = service.getSlotService(); CreateNewSlotResponse createNewSlotResponse = new CreateNewSlotResponse(); try { if (req.getVehicle().isCar() && req.isCovered()) { createNewSlotResponse.setNewSlot(slotService.createCarSlot(true)); } if (req.getVehicle().isCar() && !req.isCovered()) { createNewSlotResponse.setNewSlot(slotService.createCarSlot(false)); } if (!req.getVehicle().isCar() && req.isCovered()) { createNewSlotResponse.setNewSlot(slotService.createMotoSlot(true)); } if (!req.getVehicle().isCar() && !req.isCovered()) { createNewSlotResponse.setNewSlot(slotService.createMotoSlot(false)); } } catch (Exception e) { throw new CommandException(); } createNewSlotResponse.setErrorStatus(false); createNewSlotResponse.setResultMessage("Vehicle is successfully created!"); return createNewSlotResponse; } } <file_sep>/src/com/epam/bean/OccupySlotResponse.java package com.epam.bean; import com.epam.bean.entity.Slot; public class OccupySlotResponse extends Response { private Slot slot; public Slot getSlot() { return slot; } public void setSlot(Slot slot) { this.slot = slot; } } <file_sep>/src/com/epam/command/impl/RegisterNewVehicle.java package com.epam.command.impl; import com.epam.bean.RegisterNewVehicleRequest; import com.epam.bean.Request; import com.epam.bean.Response; import com.epam.bean.entity.Vehicle; import com.epam.command.Command; import com.epam.command.exception.CommandException; import com.epam.service.ServiceFactory; import com.epam.service.VehicleService; public class RegisterNewVehicle implements Command { @Override public Response execute(Request request) throws CommandException { RegisterNewVehicleRequest req = null; if (request instanceof RegisterNewVehicleRequest) { req = (RegisterNewVehicleRequest) request; } else { throw new CommandException("Wrong request"); } ServiceFactory service = ServiceFactory.getInstance(); VehicleService vehicleService = service.getVehicleService(); Vehicle vehicle = new Vehicle(); vehicle.setRegNumb(req.getRegNumb()); vehicle.setCar(req.isCar()); Response response = new Response(); try { vehicleService.addVehicle(vehicle); } catch (Exception e) { throw new CommandException(); } response.setErrorStatus(false); response.setResultMessage("Vehicle is successfully registered!"); return response; } } <file_sep>/src/com/epam/service/VehicleService.java package com.epam.service; import com.epam.bean.entity.Vehicle; public interface VehicleService { void addVehicle(Vehicle vehicle); Vehicle getVehicle(String regNumb); } <file_sep>/src/com/epam/bean/CreateNewSlotResponse.java package com.epam.bean; import com.epam.bean.entity.Slot; public class CreateNewSlotResponse extends Response { Slot newSlot; public Slot getNewSlot() { return newSlot; } public void setNewSlot(Slot newSlot) { this.newSlot = newSlot; } } <file_sep>/src/com/epam/bean/entity/SlotReservation.java package com.epam.bean.entity; import java.util.*; public class SlotReservation { private Date startTime; private Date endTime; private boolean isRegular; private boolean isCovered; private String regNumber; private Integer slotNumb; private Vehicle vehicle; public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public boolean isRegular() { return isRegular; } public void setRegular(boolean regular) { isRegular = regular; } public boolean isCovered() { return isCovered; } public void setCovered(boolean covered) { isCovered = covered; } public String getRegNumber() { return regNumber; } public void setRegNumber(String regNumber) { this.regNumber = regNumber; } public Integer getSlotNumb() { return slotNumb; } public void setSlotNumb(Integer slotNumb) { this.slotNumb = slotNumb; } public Vehicle getVehicle() { return vehicle; } public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } }<file_sep>/src/com/epam/bean/entity/Vehicle.java package com.epam.bean.entity; public class Vehicle { private String regNumb; private boolean isCar; public String getRegNumb() { return regNumb; } public void setRegNumb(String regNumb) { this.regNumb = regNumb; } public boolean isCar() { return isCar; } public void setCar(boolean car) { isCar = car; } } <file_sep>/src/com/epam/service/impl/CostServiceImplementation.java package com.epam.service.impl; import org.joda.time.DateTime; import org.joda.time.Hours; import com.epam.bean.entity.SlotReservation; import com.epam.service.CostService; public class CostServiceImplementation implements CostService { private static final double CAR_COEFFICIENT = 1; private static final double MOTO_COEFFICIENT = 0.7; private static final double COVERED_PARKING_SLOT_COEFFICIENT = 1.2; private static final double NOT_COVERED_PARKING_SLOT_COEFFICIENT = 1; private static final double FIRST_DURATION_COEFFICIENT = 1.5; private static final double SECOND_DURATION_COEFFICIENT = 1.2; private static final double THIRD_DURATION_COEFFICIENT = 1; @Override public Double getOccupationCost(SlotReservation slotReservation, double basePrice, double discount) { double wholeTime; Hours hours = Hours.hoursBetween(new DateTime(slotReservation.getStartTime()), new DateTime(slotReservation.getEndTime())); wholeTime = hours.getHours(); if (wholeTime < 1) { wholeTime = 1; } if ((slotReservation.isRegular()) && (slotReservation.isCovered())) { if (wholeTime <= 4) { return FIRST_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 4 && wholeTime <= 24) { return SECOND_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 24) { return THIRD_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } } if ((slotReservation.isRegular()) && (!slotReservation.isCovered())) { if (wholeTime <= 4) { return FIRST_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 4 && wholeTime <= 24) { return SECOND_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 24) { return THIRD_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * CAR_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } } if ((!slotReservation.isRegular()) && (slotReservation.isCovered())) { if (wholeTime <= 4) { return FIRST_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 4 && wholeTime <= 24) { return SECOND_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 24) { return THIRD_DURATION_COEFFICIENT * COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } } if ((!slotReservation.isRegular()) && (!slotReservation.isCovered())) { if (wholeTime <= 4) { return FIRST_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 4 && wholeTime <= 24) { return SECOND_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } if (wholeTime > 24) { return THIRD_DURATION_COEFFICIENT * NOT_COVERED_PARKING_SLOT_COEFFICIENT * MOTO_COEFFICIENT * wholeTime * basePrice * calculateDiscount(discount); } } return null; } private double calculateDiscount(double discount) { return (1 - discount / 100); } } <file_sep>/src/com/epam/bean/SlotStatResponse.java package com.epam.bean; import java.util.HashMap; import java.util.Map; public class SlotStatResponse extends Response { //todo Map<String,Integer> statistic = new HashMap<>(); public Map<String, Integer> getStatistic() { return statistic; } public void setStatistic(Map<String, Integer> statistic) { this.statistic = statistic; } } <file_sep>/src/com/epam/command/impl/SetSlots.java package com.epam.command.impl; import com.epam.bean.Request; import com.epam.bean.Response; import com.epam.command.Command; import com.epam.command.exception.CommandException; import com.epam.service.ServiceFactory; import com.epam.service.SlotService; public class SetSlots implements Command { @Override public Response execute(Request request) throws CommandException { Request req = null; if (request instanceof Request) { req = request; } else { throw new CommandException("Wrong request"); } ServiceFactory service = ServiceFactory.getInstance(); SlotService slotService = service.getSlotService(); try { slotService.setSlots(); } catch (Exception e) { throw new CommandException(); } Response response = new Response(); response.setErrorStatus(false); response.setResultMessage("Vehicle is successfully registered!"); return response; } } <file_sep>/src/com/epam/command/impl/GetVehicle.java package com.epam.command.impl; import com.epam.bean.*; import com.epam.bean.entity.SlotReservation; import com.epam.bean.entity.Vehicle; import com.epam.command.Command; import com.epam.command.exception.CommandException; import com.epam.service.ServiceFactory; import com.epam.service.SlotReservationService; import com.epam.service.VehicleService; public class GetVehicle implements Command { @Override public Response execute(Request request) throws CommandException { GetVehicleRequest req = null; if (request instanceof GetVehicleRequest) { req = (GetVehicleRequest) request; } else { throw new CommandException("Wrong request"); } ServiceFactory service = ServiceFactory.getInstance(); VehicleService vehicleService = service.getVehicleService(); GetVehicleResponse getVehicleResponse = new GetVehicleResponse(); SlotReservationService slotReservationService = service.getSlotReservationService(); try { for (SlotReservation sr : slotReservationService.getSlotReservations()) { if (sr.getRegNumber().equals(req.getRegNumber())) { getVehicleResponse.setErrorStatus(true); getVehicleResponse.setErrorMessage("Vehicle is already exists!"); return getVehicleResponse; } } getVehicleResponse.setVehicle(vehicleService.getVehicle(req.getRegNumber())); } catch (Exception e) { throw new CommandException(); } getVehicleResponse.setErrorStatus(false); return getVehicleResponse; } } <file_sep>/src/com/epam/bean/FreeSlotsResponse.java package com.epam.bean; import java.util.ArrayList; import java.util.List; import com.epam.bean.entity.Slot; public class FreeSlotsResponse extends Response { public List<Slot> getFreeSlots() { return freeSlots; } public void setFreeSlots(List<Slot> freeSlot) { this.freeSlots = freeSlot; } private List<Slot> freeSlots = new ArrayList<>(); }
859c323da3290c3dac3b5da1801c1ac1418feb09
[ "Java" ]
14
Java
KatsiarynaMuzyka/Parking
ef5676b59fc657fc1a055ec1a5ba46b3a10a56d0
3147d8092114f8a306d82db5dbb266feee03d560
refs/heads/main
<repo_name>BaYramKad/StyleES6.github.io<file_sep>/script.js 'use strict'; let incomeAmount = document.querySelector(".income-amount"), expensesTitle = document.querySelector(".expenses-title"), expensesAmount = document.querySelector(".expenses-amount"), incomeTitle = document.querySelector(".income-title"), data = document.querySelector(".data"), inp = data.querySelectorAll("input"), inputAll = document.querySelectorAll("input"), expensesItems = document.querySelectorAll(".expenses-items"), incomeItems = document.querySelectorAll(".income-items"), addExpItem = document.querySelector(".additional_expenses-item"), targetAmout = document.querySelector(".target-amount"), checkbox = document.querySelector(".deposit-checkmark"), depositCheck = document.querySelector("#deposit-check"), income = document.querySelector(".income"), expenses = document.querySelector(".expenses"), additionalIncomeItem = document.querySelectorAll(".additional_income-item"), salaryAmount = document.querySelector(".salary-amount"), incomeBtnPlus = income.getElementsByTagName("button")[0], expensesBtnPlus = expenses.getElementsByTagName("button")[0], budGetDay = document.getElementsByClassName("budget_day-value")[0], expensesMonth = document.getElementsByClassName("expenses_month-value")[0], additionalIncomeValue = document.getElementsByClassName("additional_income-value")[0], addExpensesValue = document.getElementsByClassName("additional_expenses-value")[0], incomePeriod = document.getElementsByClassName("income_period-value")[0], targetMonth = document.getElementsByClassName("target_month-value")[0], periodSelect = document.getElementsByClassName("period-select")[0], budgetMunth = document.querySelector(".budget_month-value"), periodAmount = document.querySelector(".period-amount"), buttonStart = document.getElementById("start"), cancel = document.querySelector("#cancel"); buttonStart.style.backgroundColor = "#0c1d71"; class AppData { constructor() { this.cloneIncome; this.cloneExpenses; this.amountSelect; this.amuntValue = 1; this.income = {}; this.addIncome = []; this.expenses = {}; this.addExpenses = []; this.deposit = false; this.percentDeposit = 0; this.moneyDeposit = 0; this.period = 0; this.budget = 0; this.budgetDay = 0; this.budgetMonth = 0; this.expensesMonth = 0; } reset(){ inputAll.forEach(item => { item.removeAttribute("readonly"); item.style.backgroundColor = "rgba(255, 127, 99, 0)"; item.value = ""; }); for (let i = 0; i < incomeItems.length; i++){ if (i > 0){ incomeItems[i].remove(); } incomeBtnPlus.style.display = "inline-block"; } for (let i = 0; i < expensesItems.length; i++){ if (i > 0){ expensesItems[i].remove(); } expensesBtnPlus.style.display = "inline-block"; } depositCheck.checked = false; depositCheck.disabled = false; this.budgetMonth = 0; this.budgetDay = 0; this.budget = 0; this.addExpenses = []; this.addIncome = []; this.expenses = {}; this.income = {}; this.expensesMonth = 0; periodSelect.value = 0; periodAmount.textContent = 1; incomePeriod.value = 0; this.amountSelect = 0; this.amuntValue = 0; periodSelect.addEventListener("input", function(){ if (salaryAmount.value !== ""){ const resultAmount = 0; incomePeriod.value = +resultAmount; } else if (salaryAmount.value === ""){ periodSelect.disabled = false; } }); if (salaryAmount.value === "") { buttonStart.disabled = true; }else { buttonStart.disabled = false; } buttonStart.style.display = "inline-block"; cancel.style.display = "none"; } start(){ this.budget = +salaryAmount.value.replace(/[^0-9]+/g, ""); this.getBudget(); this.getAddIncome(); this.getAddExpenses(); this.getexpenses(); this.getExpensesMonth(); this.getIncome(); this.showResult(); inputAll = document.querySelectorAll("input"); inputAll.forEach(item => { item.setAttribute("readonly", null); item.style.backgroundColor = "#dadada"; }); depositCheck.disabled = true; buttonStart.style.display = "none"; cancel.style.display = "inline-block"; incomeBtnPlus.style.display = "none"; expensesBtnPlus.style.display = "none"; } addExpensesBlock(){ this.cloneExpenses = expensesItems[0].cloneNode(true); expensesItems[0].parentNode.insertBefore(this.cloneExpenses, expensesBtnPlus); // inp = data.querySelectorAll("input"); expensesItems = document.querySelectorAll(".expenses-items"); if (expensesItems.length === 3){ expensesBtnPlus.style.display = "none"; } } getexpenses(){ expensesItems.forEach(item => { let itemExpenses = item.querySelector(".expenses-title").value; let cashExpenses = item.querySelector(".expenses-amount").value; if(itemExpenses !== "" && cashExpenses !== ""){ this.expenses[itemExpenses] = +cashExpenses; } }); } addIncomeBlock(){ this.cloneIncome = incomeItems[0].cloneNode(true); incomeItems[0].parentNode.insertBefore(this.cloneIncome, incomeBtnPlus); // inp = data.querySelectorAll("input"); incomeItems = document.querySelectorAll(".income-items"); if(incomeItems.length === 3){ incomeBtnPlus.style.display = "none"; } } getIncome(){ incomeItems.forEach( item => { let itemIncome = item.querySelector(".income-title").value; let cashIncome = item.querySelector(".income-amount").value; if(itemIncome !== "" && cashIncome !== ""){ this.income[itemIncome] = +cashIncome; } }); } showResult(){ budgetMunth.value = +this.budget; expensesMonth.value = this.expensesMonth; budGetDay.value = Math.ceil(this.budgetDay); addExpensesValue.value = this.addExpenses.join(", "); additionalIncomeValue.value = this.addIncome.join(", "); targetMonth.value = Math.ceil(this.getTargetMonth()); incomePeriod.value = +this.budgetMunth; incomePeriod.value = +this.budgetMonth * +this.amuntValue; periodSelect.addEventListener("input", () => { if (salaryAmount.value !== ""){ const resultAmount = this.budgetMonth * +this.amuntValue; incomePeriod.value = +resultAmount; } else if (salaryAmount.value === ""){ periodSelect.disabled = false; } }); } getAddExpenses(){ const addExpenses = addExpItem.value.split(", "); addExpenses.forEach(item => { item = item.replace(/[^,a-zА-Яа-яA-Z]+/g, ""); if(item !== ""){ this.addExpenses.push(item); } }); } getAddIncome(){ additionalIncomeItem.forEach(item => { const itemValue = item.value.trim(); if (itemValue !== ""){ this.addIncome.push(itemValue); } }); } getExpensesMonth() { const sum = 0; for (let key in this.expenses) { sum+= +this.expenses[key]*1; } this.expensesMonth = +sum; } getBudget() { this.budgetMonth = +this.budget - +this.expensesMonth; this.budgetDay = this.budgetMonth / 30; } getTargetMonth() { return targetAmout.value.replace(/[^0-9]+/g, "") / this.budgetMonth; } calcSavedMoney(){ const value = +periodSelect.value; this.amuntValue = periodAmount.textContent = +value; this.amountSelect = (this.amuntValue = +periodSelect.value); return this.amountSelect; } eventListeners(){ salaryAmount.addEventListener("input", function() { if (salaryAmount.value === "") { buttonStart.disabled = true; }else { buttonStart.disabled = false; } }); buttonStart.addEventListener("click", appData.start.bind(appData)); cancel.addEventListener("click", appData.reset.bind(appData)); expensesBtnPlus.addEventListener("click", appData.addExpensesBlock.bind(appData)); incomeBtnPlus.addEventListener("click", appData.addIncomeBlock.bind(appData)); periodSelect.addEventListener("input", appData.calcSavedMoney.bind(appData)); } } const appData = new AppData(); appData.eventListeners();
a0e8fc53bc8e475efac0447e33fb4ccb9d6616fe
[ "JavaScript" ]
1
JavaScript
BaYramKad/StyleES6.github.io
1b93a94ca3a14985fe0670ce080decf999d9c4d3
f6e3fa7d16e041b9a8df96d19dd15f2fbc1ea156
refs/heads/master
<file_sep>console.log("Hello"); var audio = new Audio('Audio/notify.mp3'); var last; var count = 0; var liveFeed = ["YoungCheezy", "This site is such a good idea. I hope the donation quota is reached", "<NAME>", "Wow, Really? The javits center for laborday? YES PLZ", "<NAME>" , "I don't think this is a good idea. the parraide should stay in Flatbush" , "<NAME>" , "Oh snap! this is a Major Key", "Mr.Carter11203" , "Yeeeeerrrrrrrrr!!!!", "HungryHuffle Puff" , "Whos performing next year? Can i see that on here?", "<NAME>" , "@HungryHuffle_Puff, yeah. just click on the Performaces Tag on the top of the pg", "HungryHuffle Puff" , "@Kevin Banks, Thanks Man", "DrakeFanOVXO" , "Running through the javits center with my Woes!!!!!" , "Admin101" , "Can we take this seriously guys? Whos donating?" , "YoungCheezy" , "Me!!!", "<NAME>" , "Me!" , "<NAME>" , "thats a dub" , "Mr.Carter11203" , "i'll come but idk about donations. how do we know where the mony is going?", "DrakeFanOVXO" , "Count me in!!" , "Dj Drizzle" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Dj Drizzle" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Dj Drizzle" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Dj Drizzle" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Admin101" , "Please refrain from Spaming or else i'll be forced to take action" , "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Admin101" , "Final Warning!", "<NAME>" , "Just Block Him", "ZDragon" , "I second that motion", "Kathy" , "This isn't a court room guys", "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "<NAME>" , "Block", "ZDragon" , "Block", "HungryHuffle" , "Block", "<NAME>" , "BLOCK! BLOCK! BLOCK!!!", "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Admin101" , "<NAME> HAS BEEN BLOCKED", "DrakeFanOVXO", "Thank you, i was getting a headache", "Mr.Carter11203", "Dude was just trying to shoot his shot :D", "<NAME>", "We still talking about this guy?", "TeaLover", "XD", "TheHunchBackOfNo", "I just listened to his soundcloud. its actually pretty good", "<NAME>", "iite, we're gonna have to block @TheHunchBackOfNo too for endoresing this", "TheHunchBackOfNo" , "XD XD XD", "Admin101" , "TheHunchBackOfNo HAS BEEN BLOCKED", "<NAME>", " Wow, thats crazy. i was just joking", "Admin2", "We've offically raised $200. Thank You to our backers", "TeaLover", "*claps*", "Waldo", "Where am I?", "FlatbushKings" , "Hey you guys", "<NAME>", "Whats up!", "Brandon", "Wow, this is just like a discord server", "TwitterThommy", "Thats what i was thinking", "Kelly", "Wish we had emoji's on this", "<NAME>", "You could probably still use emojis if youre on a phone", "Admin2", "We've offically raised $250. Thank You to our backers", "Admin2", "We've offically raised $300. Thank You to our backers", "Admin2", "We've offically raised $320. Thank You to our backers", "<NAME>" , "Nice", "ZDragon" , "Oh, this is exciting", "Kathy" , "isn't the goal like 200,000?", "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "<NAME>" , "How'd he get back here", "ZDragon" , "Block", "HungryHuffle" , "Block", "<NAME>" , "BLOCK! BLOCK! BLOCK!!!", "<NAME>" , " Heard my Mix yet? https://soundcloud.com/djnonstophh/big-pun-tribute-extended", "Admin101" , "Dj Drizzle HAS BEEN reBLOCKED", "DrakeFanOVXO", "Why was he ever unblocked", "Mr.Carter11203", "LMAO", "<NAME>", "Thats what i call presistance", "YoungCheezy", "Probably a bot or something", "<NAME>", "Most likly", "<NAME>" , "Im craving Baked Ziti" , "<NAME>" , "Major Key", "Mr.Carter11203" , "Yeeeeerrrrrrrrr!!!!", "HungryHuffle Puff" , "Magic is cool", "<NAME>" , "Face Palm", "HungryHuffle Puff" , "I wonder if the presentation is still going on now", "DrakeFanOVXO" , "I hope not. im running out of comment ideas" , "Admin101" , "ikr. Its not really easy to have a fake conversation with yourself" , "YoungCheezy" , "Thats exactly what i was thinking... but you're me so i guess thats expected", "<NAME>" , "Idk if this is funny or just sad" , "<NAME>" , "hummm.... its like a middle ground between funny and sad" , "Mr.Carter11203" , "I'm gonna start randomly pressing keys for comments", "DrakeFanOVXO" , "Good idea Carter", ]; $(document).ready; function EnterComment() { var user = document.getElementById("User").value; var comment = document.getElementById("Comment").value; document.getElementById("User").value = null; document.getElementById("Comment").value = null; //document.getElementById("testWrite").value = user + " " + comment; //console.log(user + " " + comment); //last = last + " User Name: " + user + " Comment: " + comment; //document.getElementById("testWrite").innerHTML = last; if (user.length !== 0){ $(".T4").prepend('<div class="box">' + '<h1>' + '&nbsp;' + user + '</h1>' + '<p>' + '&nbsp;' + comment + '</p>' + '</div>'); }else{ $(".T4").prepend('<div class="error">' + '<h1>' + "Error" + '</h1>' + '<p>' + "No Such User Found" + '</p>' + '</div>');} //$(".T4").prepend("<div class="box"><h1> HelloLove </h1> <p> Hello To all mate</p> </div>"); //$(".T4").prepend("<h1> HelloLove2 </h1>"); } function LiveFeed(){ $(".T4").prepend('<div class="box">' + '<h1>' + '&nbsp;' + liveFeed[count] + '</h1>' + '<p>' + '&nbsp;' + liveFeed[++count] + '</p>' + '</div>'); count++; } setInterval(function() { LiveFeed(); audio.play(); }, 5 * 1000); //while(count < 30){ //window.setInterval(LiveFeed(), 2000000000000); //} $("T5").prepend("<b>Prepended text</b>");
491c1f534b1b1eaaa88a412f8df24679d6275e2e
[ "JavaScript" ]
1
JavaScript
GilbertoCanela/Awsome
e889263217f5510cdb8631a7a5fe98dc44635b23
c2d1e764b44215c0f77afdd9aae9c33005b21f30
refs/heads/master
<file_sep>package main import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Root Url", r.URL.Path[1:]) } func main() { router := gin.Default() router.Static("/", "./assets") router.get("/api/root", handler) router.Run(":8080") } <file_sep># React Assets, Go Api, Boilerplate Run Build Go api sits in the app/api folder and auto builds with the gulp command Assets build from the app/assets folder Build assets and api: gulp
627befad78be1bf68cf6a659788333582128a1d1
[ "Markdown", "Go" ]
2
Go
carsonwright/tframe
6af8640877ae69b3648c4ee4d9e74e88a28ab12c
71856be22a5a289498e0cd6aed506e90b263e612
refs/heads/main
<file_sep>'use strict'; /** * Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-controllers) * to customize this controller */ module.exports = { // find: ctx => { // const result = strapi.query('provider').find(ctx.query, [ // { path: "product" }, // { path: "metric_unit" } // ]) // return result; // }, };
a83fc20afda3e5783de0e38ea604ec6131fa20cb
[ "JavaScript" ]
1
JavaScript
deinKaiser/ozzy-backend
572ed77b26ee9dcca002fcde407ee6c0331142c6
a320ca0cd0c928049bf1a970c43f425c3747bbe7
refs/heads/master
<repo_name>Chebotin/labs<file_sep>/19-26.cpp #include "pch.h" #include <iostream> #include <cstdlib> #include <ctime> #include <chrono> #include <cstdio> using namespace std; int Search(int arr[], int requiredKey, int arrSize) { for (int i = 0; i < arrSize; i++) { if (arr[i] == requiredKey) return i; } return -1; } const int n = 100; int first, last; void quickSortRec(int *mas, int first, int last) // сортировка с рекурсией { int mid, count; int f = first, l = last; mid = mas[(f + l) / 2]; do { while (mas[f] < mid) f++; while (mas[l] > mid) l--; if (f <= l) { count = mas[f]; mas[f] = mas[l]; mas[l] = count; f++; l--; } } while (f < l); if (first < l) quickSortRec(mas, first, l); if (f < last) quickSortRec(mas, f, last); } void quickSort(int* a, int first, int last) // сортировка без рекурсии { int i, j; int lb, ub; int lbstack[2000], ubstack[2000]; long stackpos = 1; long ppos; int pivot; int temp; lbstack[1] = 0; ubstack[1] = last ; do { lb = lbstack[stackpos]; ub = ubstack[stackpos]; stackpos--; do { ppos = (lb + ub) >> 1; i = lb; j = ub; pivot = a[ppos]; do { while (a[i] < pivot) i++; while (pivot < a[j]) j--; if (i <= j) { temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } } while (i <= j); if (i < ppos) { if (i < ub) { stackpos++; lbstack[stackpos] = i; ubstack[stackpos] = ub; } ub = j; } else { if (j > lb) { stackpos++; lbstack[stackpos] = lb; ubstack[stackpos] = j; } lb = i; } } while (lb < ub); } while (stackpos != 0); } int BSearch(int arr[], int left, int right, int key) { int midle = 0; // 3 пункт while (1) // реализации в main нет, т.к. в задании об этом не сказано { midle = (left + right) / 2; if (key < arr[midle]) right = midle - 1; else if (key > arr[midle]) left = midle + 1; else return midle; if (left > right) return -1; } } void main() { const int arrSize = 10000; // 1 пункт int arr[arrSize]; int key = 0; int element = 0; srand(time(NULL)); for (int i = 0; i < arrSize; i++) { arr[i] = rand() % 2000 - 1000; } cout << "Required Key? "; cin >> key; element = Search(arr, key, arrSize); if (element != -1) cout << key << " is at [" << element << "]" << endl; else cout << "Key not found" << endl; int *Array = new int[n]; // 2 пункт cout << "Before: " << endl; for (int i = 0; i < n; i++) { Array[i] = (rand() % 21) - 10; cout << Array[i] << " "; } first = 0; last = n-1; quickSortRec(Array, first, last); // поменяйте на quickSort, чтобы проверить обычную сортировку (без рекурсии) cout << endl << "After: " << endl; for (int i = 0; i < n; i++) cout << Array[i] << " "; delete[]Array; std::clock_t start; // 4 пункт double unsortedDur; double sortedDur; start = std::clock(); for (int i = 0; i < 1000; i++) { element = Search(arr, key, arrSize); } unsortedDur = ((std::clock() - start) / (double)CLOCKS_PER_SEC); cout << endl << "Unsorted search's duration: " << unsortedDur << " ms" << endl; quickSortRec(arr, 0, 9999); start = std::clock(); // В задании про это ничего не написано, так что оба поиска были обычными (небинарными) for (int i = 0; i < 1000; i++) { element = Search(arr, key, arrSize); } sortedDur = ((std::clock() - start) / (double)CLOCKS_PER_SEC) ; cout << endl << "Sorted search's duration: " << sortedDur << " ms" << endl; if (unsortedDur < sortedDur) cout << ("Unsorted search is faster") << endl; if (unsortedDur > sortedDur) cout << ("Sorted search is faster") << endl; cin.get(); return; }
e5b03531e1e6e86b329441eda4f10b8b8865e986
[ "C++" ]
1
C++
Chebotin/labs
0acfa4d5be5d3ea7ac6d42999fa51770871bdf60
f853b4161cfd7753c6894faf85432314ce4e253d
refs/heads/main
<file_sep>import string letters_left = string.ascii_lowercase d=['d','f'] for i in d: letters_left=letters_left.replace(i,'') print(letters_left)<file_sep># hangman This is about hangman game
6967181f8957cac7cfdfdd2c87a8d8f310416fde
[ "Markdown", "Python" ]
2
Python
shubham7999/hangman
077685302c7418454509aa00c017e1c6428f1053
afe3b594b5214ba164aaebe3a227efd120ca2b5b
refs/heads/master
<file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('orders', function (Blueprint $table) { $table->increments('id'); $table->string('code')->unique(); $table->integer('seller')->unsigned(); $table->foreign('seller')->references('id')->on('users'); $table->integer('buyer')->unsigned(); $table->foreign('buyer')->references('id')->on('users'); $table->double('amount')->unsigned()->default(0); $table->double('tax')->unsigned()->default(0); $table->string('receiver_name'); $table->string('content')->nullable(); $table->string('address1'); $table->string('address2'); $table->string('phone1'); $table->string('phone2'); $table->date('ship_date'); $table->string('ship_email'); $table->enum('ship_status', ['saving', 'paying', 'delivering', 'receiving', 'cancelling']); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('orders'); } } <file_sep>#HOW TO USE DATABASE 1. Go to CMD and move to folder of project 2. Type - php artisan migrate - php artisan db:seed <file_sep>#How to do 1. Go to console CMD: - cd /d d:\Your xampp folder\htdocs - git clone <EMAIL>:webdevqn/tdc.git - cd tdc - composer install 2. Go to folder dayvahoc copy .env-example to be a new file named .env, if IDE does not show hidden files, go Google to do it. 3. Open Xampp and start Apache and MySQL to create a new database: tdc in unicode UTF8 4. Open .env and configurate suitably the database name, user name, password and save them: commonly, we use: - database: tdc - username: root - password: (do not write anything) 5. Go to Disk C > Windows > System32 > Drivers > etc. 6. Copy hosts file in etc to Desktop and configurate there, then copy back to etc folder to replace. 7. The content which is needed to change is: Add a new line to get a virtual domain tdc.vu, any name you want is ok. - The content to add is: 127.0.0.1 tdc.vu 8. Remember copy back to etc folder and surely overwrite it. 9. Stop Xampp 10. Go to Xampp > Apache > Conf > extra 11. Open file v-host and configurate it. 12. Copy 2 lines into its bottom: 1 for localhost, 1 for tdc.vu DocumentRoot "Your Path To Xampp/xampp/htdocs" ServerName localhost DocumentRoot "Your Path To Xampp/xampp/htdocs/tdc/public" ServerName tdc.vu 13. Restart Xampp 14. Open browser and open tdc.vu to get the Laravel Screen<file_sep><?php use Illuminate\Database\Seeder; class MessagesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); DB::table('messages')->truncate(); $faker = Faker\Factory::create(); for ($i = 0; $i < 28; $i++) { DB::table('messages')->insert([ 'sender' => rand(1,30), 'receiver' => rand(1,30), 'title' => $faker->name, 'content' => $faker->text(), 'attachment' => '[]', 'status' => $faker->randomElement(['read', 'unread']), 'created_at' => new DateTime, 'updated_at' => new DateTime ]); } $seeds = [ ]; DB::table('messages')->insert($seeds); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProductsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); $table->integer('category_id')->unsigned(); $table->foreign('category_id')->references('id')->on('categories'); $table->string('code')->unique(); $table->string('name'); $table->string('slug')->unique(); $table->text('description')->nullable(); $table->text('image')->nullable(); $table->double('price')->unsigned()->default(0); $table->double('weight')->unsigned()->nullable()->default(0); $table->double('length')->unsigned()->nullable()->default(0); $table->double('width')->unsigned()->nullable()->default(0); $table->double('height')->unsigned()->nullable()->default(0); $table->text('color')->nullable(); $table->date('expired_date')->nullable(); $table->text('origin')->nullable(); $table->integer('currency')->nullable(); $table->integer('per_unit')->unsigned()->nullable()->default(0); $table->integer('in_stock')->unsigned()->nullable()->default(0); $table->integer('on_order')->unsigned()->nullable()->default(0); $table->integer('sold')->unsigned()->nullable()->default(0); $table->integer('viewed')->unsigned()->nullable()->default(0); $table->integer('liked')->unsigned()->nullable()->default(0); $table->integer('followed')->unsigned()->nullable()->default(0); $table->integer('shared')->unsigned()->nullable()->default(0); $table->integer('points')->unsigned()->nullable()->default(0); $table->integer('ranked')->unsigned()->nullable()->default(0); $table->double('discount_amount')->unsigned()->nullable()->default(0); $table->date('start_date_discount')->nullable(); $table->date('end_date_discount')->nullable(); $table->text('discount_content')->nullable(); $table->enum('status', ['on', 'off']); $table->integer('created_by')->unsigned(); $table->foreign('created_by')->references('id')->on('users'); $table->integer('updated_by')->unsigned(); $table->foreign('updated_by')->references('id')->on('users'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('products'); } } <file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::statement('SET FOREIGN_KEY_CHECKS=0;'); DB::table('users')->truncate(); $faker = Faker\Factory::create(); $seeds = [ [ 'title' => $faker->title, 'first_name' => $faker->firstName, 'last_name' => $faker->lastName, 'email' => '<EMAIL>', 'password' => <PASSWORD>(<PASSWORD>), 'status' => 'active', 'role_id' => 1, 'company' => $faker->company, 'image' => $faker->imageUrl(), 'phone1' => $faker->phoneNumber, 'phone2' => $faker->phoneNumber, 'address1' => $faker->address, 'address2' => $faker->address, 'created_at' => new DateTime, 'updated_at' => new DateTime ], ]; DB::table('users')->insert($seeds); for ($i = 0; $i < 28; $i++) { DB::table('users')->insert([ //, 'title' => $faker->title, 'first_name' => $faker->firstName, 'last_name' => $faker->lastName, 'email' => $faker->unique()->email, 'password' => <PASSWORD>(<PASSWORD>), 'status' => $faker->randomElement(['active', 'banned', 'pending']), 'role_id' => rand(1,3), 'company' => $faker->company, 'image' => $faker->imageUrl(), 'phone1' => $faker->phoneNumber, 'phone2' => $faker->phoneNumber, 'address1' => $faker->address, 'address2' => $faker->address, 'created_at' => new DateTime, 'updated_at' => new DateTime ]); } DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } }
ef94354a41b9966788ae1dc772ee45921251bdf5
[ "Markdown", "PHP" ]
6
PHP
webdevqn/tdc
e8ca7d0404c9f8c952c42e1575ff000c723cca62
bcea0830bae1db7916138fd08190ff2faa7253c6
refs/heads/master
<file_sep>const express = require('express'); const bodyParser= require('body-parser'); const fs = require('fs'); const app = express(); app.use(bodyParser.json({limit:'50mb'})); app.use(bodyParser.urlencoded({limit:'50mb',extended : false})); app.post('/makePDF', function (req, res) { console.log('post api') var PDFDocument, doc; PDFDocument = require('pdfkit'); doc = new PDFDocument; var myObj = req.body.jsonObject var flag = 0 var currImageString = '' for (var i in myObj){ if (myObj[i] == ','){ var bitmap = new Buffer(currImageString, 'base64'); var photoName = makeid() fs.writeFileSync("images/" + photoName + ".jpg", bitmap); doc.image('images/' + photoName + '.jpg', 0, 0, {width: 625, height: 900}); doc.addPage() fs.unlink('./images/' + photoName + '.jpg',function(err){ if(err) return console.log(err); }); currImageString = '' } else if (myObj[i] == '}'){ flag = 0 var bitmap = new Buffer(currImageString, 'base64'); var photName = makeid() fs.writeFileSync("images/" + photName + ".jpg", bitmap); doc.image('images/' + photName + '.jpg', 0, 0, {width: 625, height: 900}); fs.unlink('./images/' + photName + '.jpg',function(err){ if(err) return console.log(err); }); } else if (flag == 1){ currImageString += myObj[i] } else if (myObj[i] == '{'){ flag = 1 } } doc.pipe(fs.createWriteStream('output.pdf')); doc.end(); res.send('hogya bhai') }) function makeid() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (var i = 0; i < 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } console.log(makeid()); app.get('/downloadPDF', function(req, res){ // Downloading file // var file = __dirname + '/output.pdf'; // res.download(file); // Rendering on Browser console.log('get api') var img = fs.readFileSync('./output.pdf'); res.writeHead(200, {'Content-Type': 'application/pdf' }); res.end(img, 'binary'); }); app.listen(5211,function(){ console.log("Server started on http://localhost:5211"); })
b18f6b28841560dcf9514d6db0dacadd2ca74e51
[ "JavaScript" ]
1
JavaScript
ayushigarg056/Image-To-PDF-
8f448ee3c38122bcfdf545bd085b3f40f5db2411
d2bca48f9fdf860e8f5b7589bf8ba93792bf11cc
refs/heads/master
<file_sep>package week1; //import edu.princeton.cs.algs4.QuickFindUF; //import edu.princeton.cs.algs4.WeightedQuickUnionUF; import edu.princeton.cs.algs4.WeightedQuickUnionUF; /** * Created by janbrusch on 29.06.15. */ public class Percolation { private int gridSize; private boolean[] openFields; //private QuickFindUF connectedSites; private WeightedQuickUnionUF connectedSites; private int virtualTopSite; private int virtualBottomSite; public Percolation(int N){ // create N-by-N grid, with all sites blocked if (N <= 0) { throw new IllegalArgumentException(); } this.gridSize = N; int numFields = (N)*(N+1); this.openFields = new boolean[numFields]; //this.connectedSites = new QuickFindUF(numFields); this.connectedSites = new WeightedQuickUnionUF(numFields); //open virtual bottom and top sites this.virtualBottomSite = 0; this.openFields[this.virtualTopSite] = true; this.virtualTopSite = this.gridSize+1; this.openFields[N+1] = true; } public void open(int i, int j) { // open site (row i, column j) if it is not open already int fieldNumber = this.xyTo1D(i,j); //System.out.println("Fied Number = " + fieldNumber); if (!this.isOpen(i,j)) { this.openFields[fieldNumber] = true; //connect field to the right if exists and is open if (this.checkInput(i+1, j) && this.isOpen(i+1, j)) { this.connectedSites.union(fieldNumber, this.xyTo1D(i+1, j)); } //connect field to the right if exists and is open if (this.checkInput(i-1, j) && this.isOpen(i-1, j)) { this.connectedSites.union(fieldNumber, this.xyTo1D(i-1, j)); } //connect field below if exists and is open if (this.checkInput(i, j+1) && this.isOpen(i, j+1)) { this.connectedSites.union(fieldNumber, this.xyTo1D(i, j+1)); } //connect field above if exists and is open if (this.checkInput(i, j-1) && this.isOpen(i, j-1)) { this.connectedSites.union(fieldNumber, this.xyTo1D(i, j-1)); } // connect to virtualbottomsite if in the last row if (i == this.gridSize) { this.connectedSites.union(fieldNumber, this.virtualTopSite); } //connect to virtualtopsite if in the top row if (i == 1) { this.connectedSites.union(fieldNumber, this.virtualBottomSite); } } } public boolean isOpen(int i, int j) { // is site (row i, column j) open? return this.openFields[this.xyTo1D(i,j)]; } public boolean isFull(int i, int j) { // is site (row i, column j) full? return this.connectedSites.connected(this.xyTo1D(i,j), virtualBottomSite); } public boolean percolates() { // does the system percolate? return this.connectedSites.connected(virtualBottomSite, virtualTopSite); } private int xyTo1D (int x, int y) { if (this.checkInput(x,y)) { return ((x - 1) * this.gridSize + (x-1)) + y; } throw new IndexOutOfBoundsException(); } private boolean checkInput (int x, int y) { return !(x < 1 || x > this.gridSize || y < 1 || y > this.gridSize); } /* private boolean isConnected (int x1, int y1, int x2, int y2) { return this.connectedSites.connected(this.xyTo1D(x1, y1), this.xyTo1D(x2, y2)); } */ }
d881626ef7c556999d7b219921260804df5dc557
[ "Java" ]
1
Java
Bruschkov/algs4
35b07adba4b1b35c1082a2b350ad94c6af06ff7b
21d37e9435f97c719665f233525151f38c775d43
refs/heads/master
<repo_name>JoacimV/FridgeBook<file_sep>/backend/src/main/java/jsonMapper/UserJson.java package jsonMapper; import entity.User; import java.util.ArrayList; import java.util.List; public class UserJson { private String username; private String pin; private List<RecipeJson> recipesCreatedByUser; private List<RecipeJson> favouriteRecipes; private List<ComestibleJson> comestibles; public UserJson(User user) { username = user.getUsername(); pin = user.getPin(); recipesCreatedByUser = new ArrayList(); favouriteRecipes = new ArrayList(); comestibles = new ArrayList(); user.getRecipesCreatedByUser().forEach(recipe -> { recipesCreatedByUser.add(new RecipeJson(recipe)); }); user.getFavouriteRecipes().forEach(recipe -> { favouriteRecipes.add(new RecipeJson(recipe)); }); user.getComestibles().forEach(comestible -> { comestibles.add(new ComestibleJson(comestible)); }); } } <file_sep>/backend/src/main/java/facade/CategoryFacade.java package facade; import entity.Category; import entity.Ingredient; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; /** * * @author joaci */ public class CategoryFacade { private final EntityManagerFactory EMF; public CategoryFacade(String persistenceUnit) { this.EMF = Persistence.createEntityManagerFactory(persistenceUnit); } private EntityManager getEntityManager() { return EMF.createEntityManager(); } public static void main(String[] args) { new CategoryFacade("PU").tester(); } public void tester() { // Category c = new Category(); // c.setIngredients(new ArrayList()); ////Økologisk hvedemel // c.setName("Hvedemel"); // createCategory(c); // c.setCategoryAmounts(new ArrayList()); // Ingredient i = new Ingredient(); // i.setBarcode("1234"); //// i.setComestible(c); // i.setImagePath("1234"); // i.setName("Øko mel"); // i.setNewIngredient(true); // new IngredientFacade("PU").createIngredient(i); Category c = getCategory(1l); System.out.println(c.getCategoryAmounts()); // c.getIngredients().add(new IngredientFacade("PU").getIngredientByName("Økologisk hvedemel")); // updateCategory(c); // updateUser(c); // System.out.println(getCategories()); } public Category getCategory(Long id) { return getEntityManager().find(Category.class, id); } public List<Category> getCategories() { return getEntityManager().createQuery("SELECT c FROM Category c", Category.class).getResultList(); } public Category createCategory(Category category) { EntityManager em = getEntityManager(); try { em.getTransaction().begin(); em.persist(category); em.getTransaction().commit(); } finally { em.close(); } return category; } public Category updateCategory(Category category) { EntityManager em = getEntityManager(); Category categoryInDB = em.find(Category.class, category.getId().longValue()); try { em.getTransaction().begin(); categoryInDB = em.merge(category); em.getTransaction().commit(); } catch (RollbackException r) { em.getTransaction().rollback(); } finally { em.close(); } return categoryInDB; } } <file_sep>/backend/src/test/java/test/UserResourceTest.java //package test; // //import com.google.gson.Gson; //import entity.User; //import facade.UserFacade; //import io.restassured.RestAssured; //import static io.restassured.RestAssured.given; //import io.restassured.parsing.Parser; //import static org.hamcrest.CoreMatchers.equalTo; //import org.junit.Test; //import org.junit.BeforeClass; // //public class UserResourceTest { // // private UserFacade USERFACADE = new UserFacade("PU"); // // @BeforeClass // public static void setUpBeforeAll() { // RestAssured.baseURI = "http://localhost"; // RestAssured.port = 8084; // RestAssured.basePath = "/FridgeBook/api/user"; // RestAssured.defaultParser = Parser.JSON; // } // // @Test // public void serverIsRunning() { // given().when().get().then().statusCode(200); // } // // @Test // public void testGetUserById() { // USERFACADE.createUser(new User("Ole", "3333")); // // given() // .pathParam("id", "Ole") // .when().get("{id}") // .then().statusCode(200) // .body("username", equalTo("Ole")); // // USERFACADE.deleteUser("Ole"); // } // // @Test // public void testCreateUser() { // User user = new User("Hans", "1212"); // given() // .contentType("application/json") // .body(new Gson().toJson(user)) // .when().post("/") // .then().statusCode(200) // .body(equalTo("Created")); // // USERFACADE.deleteUser("Hans"); // } // // @Test // public void testUpdateUser() { // USERFACADE.createUser(new User("Bob", "3221")); // // User user = USERFACADE.getUserById("Bob"); // user.setPin("1234"); // given() // .contentType("application/json") // .body(new Gson().toJson(user)) // .when().put("/") // .then().statusCode(200) // .body(equalTo("Updated")); // // USERFACADE.deleteUser("Bob"); // } // // @Test // public void testDeleteUser() { // USERFACADE.createUser(new User("Kaj", "3221")); // // given() // .pathParam("id", "Kaj") // .when().delete("{id}") // .then().statusCode(200) // .body(equalTo("Deleted")); // } //} <file_sep>/fridgenchef/components/Recipe.js import React from 'react' import {ScrollView, View, Text, Share, TouchableOpacity} from "react-native"; import ImageSlider from "./ImageSlider"; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; class Recipe extends React.Component { state = { user: {}, recipe: this.props.navigation.state.params.recipe, categories: [], ingredients: [], } componentWillUnmount() { this.props.navigation.state.params.onBack() } getCategories = async () => { let ingredients = []; fetch('https://vetterlain.dk/FridgeBook/api/category') .then(res => res.json()) .then(categories => this.setState({categories}, () => { this.state.categories.forEach(category => { category.amounts.forEach(amount => { if (amount.recipe.id === this.props.navigation.state.params.recipe.id) { for (let i = 0; i < category.ingredients.length; i++) { ingredients.push({"name": category.name, "amount": category.amounts[i].amount}); } } }) }) })) .then(() => { this.setState({ingredients}); }) } componentDidMount() { this.getCategories(); this.props.screenProps.getUser() .then(user => { this.heart(user); this.setState({user}); } ) let recipe = this.state.recipe; recipe.icon = "heart-o"; recipe.color = "gray"; this.setState({recipe}) } heart = (user) => { let recipe = this.state.recipe; recipe.icon = "heart-o"; recipe.color = "gray"; this.setState({recipe}) user.favouriteRecipes.forEach(recipe => { if (this.state.recipe.id === recipe.id) { this.state.recipe.icon = "heart"; this.state.recipe.color = "red"; } } ) } updateRecipe = async () => { const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify(this.state.recipe) } await fetch('https://vetterlain.dk/FridgeBook/api/recipe', options); } updateUserFavourites = async (hasFavourite) => { let user = {...this.state.user}; if (!hasFavourite) { // console.log("updateUserFavourites - recipe findes IKKE fav") user.favouriteRecipes.push(this.state.recipe); } else { // console.log("updateUserFavourites - recipe findes i fav") user.favouriteRecipes = user.favouriteRecipes.filter(recipe => recipe.id !== this.state.recipe.id); } this.setState({user}); const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify(user) } this.heart(user); const res = await fetch('https://vetterlain.dk/FridgeBook/api/user/', options); // console.log(res); } handleCounterChanging = async () => { if (this.state.user.favouriteRecipes.length > 0) { if (this.state.user.favouriteRecipes.filter(recipe => recipe.id === this.state.recipe.id).length === 0) { // console.log("change counter - recipe findes IKKE i fav") this.setState({recipe: {...this.state.recipe, rateCounter: this.state.recipe.rateCounter + 1}}, async () => { await this.updateRecipe() .then(this.updateUserFavourites(false)); }); } else { // console.log("change counter - recipe findes i fav") this.setState({recipe: {...this.state.recipe, rateCounter: this.state.recipe.rateCounter - 1}}, async () => { await this.updateRecipe() .then(this.updateUserFavourites(true)); }); } } else { this.setState({recipe: {...this.state.recipe, rateCounter: this.state.recipe.rateCounter + 1}}, async () => { await this.updateRecipe() .then(this.updateUserFavourites(false)); }); } } onClick = () => { Share.share({ message: 'Checkout Fridge\'N\'Chef on Google Play Store: https://play.google.com/store/apps/details?id=com.fridgenchef', // url: 'https://play.google.com/store/apps/details?isd=com.companyName.appname', // title: 'Wow, did you see that?' }, { // Android only: dialogTitle: 'Share Fridge\'N\'Chef', // iOS only: // excludedActivityTypes: [ // 'com.apple.UIKit.activity.PostToTwitter' // ] }) } renderIngredients = () => { return this.state.ingredients.map((ingredient, index) => { return ( <Text style={{fontFamily: 'fira'}} key={index}>{ingredient.name}: {ingredient.amount}</Text> ) }) } render() { return ( <ScrollView style={{flex: 1, backgroundColor: 'white'}}> <ImageSlider handleImagePress={() => this.handleCounterChanging()} images={this.state.recipe.imagePaths}/> <View style={{borderBottomWidth: .5, borderBottomColor: 'gray', flexDirection: 'row', justifyContent: 'space-between'}}> <Text style={{ fontFamily: 'fira-bold', fontSize: 34, textAlign: 'center', }}>{this.state.recipe.name}</Text> <View/> <View style={{flexDirection: 'row',paddingTop:3}}> <TouchableOpacity onPress={() => { this.handleCounterChanging().then(() => this.props.screenProps.getUser()); }}> <Icon name={"heart"} size={40} color={this.state.recipe.color}/> </TouchableOpacity> <TouchableOpacity onPress={() => { this.onClick(); }}> <Icon name="share" size={40} color="gray"/> </TouchableOpacity> </View> </View> <View style={{padding: 3}}> <Text style={{fontFamily: 'fira-bold', fontSize: 24}}>Ingredienser:</Text> {this.renderIngredients()} <Text style={{fontFamily: 'fira-bold', fontSize: 24}}>Fremgangsmåde:</Text> <Text style={{fontFamily: 'fira'}}>{this.state.recipe.text}</Text> </View> </ScrollView> ); } } export default Recipe;<file_sep>/backend/src/test/java/test/RecipeResourceTest.java //package test; // //import com.google.gson.Gson; //import entity.Ingredient; //import entity.Recipe; //import facade.RecipeFacade; //import io.restassured.RestAssured; //import static io.restassured.RestAssured.given; //import io.restassured.parsing.Parser; //import java.util.ArrayList; //import java.util.List; //import static org.hamcrest.CoreMatchers.equalTo; //import org.junit.Test; //import org.junit.BeforeClass; // //public class RecipeResourceTest { // // private RecipeFacade RECIPE_FACADE = new RecipeFacade("PU"); // // @BeforeClass // public static void setUpBeforeAll() { // RestAssured.baseURI = "http://localhost"; // RestAssured.port = 8084; // RestAssured.basePath = "/FridgeBook/api/recipe"; // RestAssured.defaultParser = Parser.JSON; // } // // @Test // public void serverIsRunning() { // given().when().get().then().statusCode(200); // } // // @Test // public void testGetIngredientById() { // List<String> imagePaths = new ArrayList(); // imagePaths.add("/image"); // imagePaths.add("/image/2"); // imagePaths.add("/image/3"); // Ingredient jordbær = new Ingredient("Jordbær", "/image"); // Ingredient choko = new Ingredient("Æg", "/image"); // List<Ingredient> ingredients = new ArrayList(); // ingredients.add(jordbær); // ingredients.add(choko); // Recipe recipe = new Recipe("Lagkage", imagePaths, "Whatever", ingredients); // RECIPE_FACADE.createRecipe(recipe); // // given() // .pathParam("id", recipe.getId()) // .when().get("{id}") // .then().statusCode(200) // .body("id", equalTo(recipe.getId())); // // RECIPE_FACADE.deleteRecipe(recipe.getId()); // } // // @Test // public void testCreateRecipe() { // List<String> imagePaths = new ArrayList(); // imagePaths.add("/image"); // imagePaths.add("/image/2"); // imagePaths.add("/image/3"); // Ingredient jordbær = new Ingredient("Jordbær", "/image"); // Ingredient choko = new Ingredient("Æg", "/image"); // List<Ingredient> ingredients = new ArrayList(); // ingredients.add(jordbær); // ingredients.add(choko); // Recipe recipe = new Recipe("Lagkage", imagePaths, "Whatever", ingredients); // RECIPE_FACADE.createRecipe(recipe); // // given() // .contentType("application/json") // .body(new Gson().toJson(recipe)) // .when().post("/") // .then().statusCode(200) // .body(equalTo("Created")); // // RECIPE_FACADE.deleteRecipe(recipe.getId()); // } // // @Test // public void testUpdateRecipe() { // List<String> imagePaths = new ArrayList(); // imagePaths.add("/image"); // imagePaths.add("/image/2"); // imagePaths.add("/image/3"); // Ingredient jordbær = new Ingredient("Jordbær", "/image"); // Ingredient choko = new Ingredient("Æg", "/image"); // List<Ingredient> ingredients = new ArrayList(); // ingredients.add(jordbær); // ingredients.add(choko); // Recipe recipe = new Recipe("Lagkage", imagePaths, "Whatever", ingredients); // RECIPE_FACADE.createRecipe(recipe); // // Recipe recipeInDB = RECIPE_FACADE.getRecipeById(recipe.getId()); // recipeInDB.setName("Iskage"); // given() // .contentType("application/json") // .body(new Gson().toJson(recipeInDB)) // .when().put("/") // .then().statusCode(200) // .body(equalTo("Updated")); // // RECIPE_FACADE.deleteRecipe(recipe.getId()); // } // // @Test // public void testDeleteRecipe() { // List<String> imagePaths = new ArrayList(); // imagePaths.add("/image"); // imagePaths.add("/image/2"); // imagePaths.add("/image/3"); // Ingredient jordbær = new Ingredient("Jordbær", "/image"); // Ingredient choko = new Ingredient("Æg", "/image"); // List<Ingredient> ingredients = new ArrayList(); // ingredients.add(jordbær); // ingredients.add(choko); // Recipe recipe = new Recipe("Lagkage", imagePaths, "Whatever", ingredients); // RECIPE_FACADE.createRecipe(recipe); // // given() // .pathParam("id", recipe.getId()) // .when().delete("{id}") // .then().statusCode(200) // .body(equalTo("Deleted")); // } //} <file_sep>/fridgenchef/components/ImageSlider.js import React, {Component} from 'react' import {Animated, View, StyleSheet, Image, Dimensions, ScrollView, TouchableHighlight} from 'react-native' const deviceWidth = Dimensions.get('window').width const deviceHeight = Dimensions.get('window').height const FIXED_BAR_WIDTH = 140 const BAR_SPACE = 20 class ImageSlider extends Component { state = { images: this.props.images } numItems = this.state.images.length itemWidth = (FIXED_BAR_WIDTH / this.numItems) - ((this.numItems - 1) * BAR_SPACE) animVal = new Animated.Value(0) handleImagePress = (e) => { const now = new Date().getTime(); if (this.lastImagePress && (now - this.lastImagePress) < 300) { delete this.lastImagePress; this.props.handleImagePress(); } else { this.lastImagePress = now; } } render() { let imageArray = [] let barArray = [] this.state.images.forEach((image, i) => { const thisImage = ( <TouchableHighlight activeOpacity={1} key={`image${i}`} onPress={() => this.handleImagePress()}> <Image source={{uri: image}} style={{width: deviceWidth, height: deviceHeight / 3}} /> </TouchableHighlight> ) imageArray.push(thisImage) const scrollBarVal = this.animVal.interpolate({ inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)], outputRange: [-this.itemWidth, this.itemWidth], extrapolate: 'clamp', }) const thisBar = ( <View key={`bar${i}`} style={[ styles.track, { width: this.itemWidth, marginLeft: i === 0 ? 0 : BAR_SPACE, }, ]} > <Animated.View style={[ styles.bar, { width: this.itemWidth, transform: [ {translateX: scrollBarVal}, ], }, ]} /> </View> ) barArray.push(thisBar) }) return ( <View style={styles.container}> <ScrollView horizontal showsHorizontalScrollIndicator={false} scrollEventThrottle={10} pagingEnabled onScroll={ Animated.event( [{nativeEvent: {contentOffset: {x: this.animVal}}}] ) } > {imageArray} </ScrollView> <View style={styles.barContainer} > {this.state.images.length > 1 ? barArray : null} </View> </View> ) } } const styles = StyleSheet.create({ container: { alignItems: 'center', justifyContent: 'center', }, barContainer: { position: 'absolute', zIndex: 2, top: 40, flexDirection: 'row', }, track: { backgroundColor: '#ccc', overflow: 'hidden', height: 2, }, bar: { backgroundColor: '#5294d6', height: 2, position: 'absolute', left: 0, top: 0, }, }) export default ImageSlider;<file_sep>/backend/src/main/java/facade/UserFacade.java package facade; import entity.User; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; public class UserFacade { private final EntityManagerFactory EMF; public UserFacade(String persistenceUnit) { this.EMF = Persistence.createEntityManagerFactory(persistenceUnit); } private EntityManager getEntityManager() { return EMF.createEntityManager(); } public User getUserById(String username) { return getEntityManager().find(User.class, username); } public List<User> getUsers() { return getEntityManager().createQuery("SELECT u FROM User u", User.class).getResultList(); } public User createUser(User user) { EntityManager em = getEntityManager(); User userInDB = null; try { em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); userInDB = em.find(User.class, user.getUsername()); } catch (RollbackException r) { // updateUser(user); em.getTransaction().rollback(); } finally { em.close(); } return userInDB; } public User updateUser(User user) { EntityManager em = getEntityManager(); User userInDB = em.find(User.class, user.getUsername()); try { em.getTransaction().begin(); userInDB = em.merge(user); em.getTransaction().commit(); } catch (RollbackException r) { // createUser(user); em.getTransaction().rollback(); } finally { em.close(); } return userInDB; } public boolean deleteUser(String username) { EntityManager em = getEntityManager(); User user = em.find(User.class, username); try { em.getTransaction().begin(); em.remove(user); em.getTransaction().commit(); } catch (RollbackException r) { em.getTransaction().rollback(); return false; } finally { em.close(); } return true; } } <file_sep>/fridgenchef/components/RecipeCard.js import React from 'react' import {Image, StyleSheet, View, Text, Dimensions, TouchableHighlight} from "react-native"; import Icon from 'react-native-vector-icons/FontAwesome'; const deviceWidth = Dimensions.get('window').width; const deviceHeight = Dimensions.get('window').height; class RecipeCard extends React.Component { openRecipe = (recipe) => { this.props.openRecipe(recipe); }; render() { return ( <View style={styles.outerContainer}> <TouchableHighlight onPress={() => {this.openRecipe(this.props.recipe)}}> <Image source={{uri: this.props.recipe.imagePaths[0]}} style={styles.image}/> </TouchableHighlight> <View style={styles.textContainer}> <View style={{flexDirection: 'row'}}> <Text style={styles.textOverhead}>OPSKRIFT </Text> <Icon name='heart' size={26} color={this.props.recipe.color}/> <Text style={styles.textOverhead}>{this.props.recipe.rateCounter}</Text> </View> <Text style={styles.textHeader}> {this.props.recipe.name}</Text> </View> </View> ); } } const styles = StyleSheet.create({ outerContainer: { flex: 1, justifyContent: 'flex-end', paddingBottom: 1, }, image: { height: deviceHeight / 1.8, width: deviceWidth, }, textContainer: { padding: 10, position: 'absolute', }, textOverhead: { color: 'white', fontFamily: 'fira-bold', fontSize: 14, borderBottomWidth: .5, borderBottomColor: 'white' }, textHeader: { color: 'white', fontFamily: 'fira-bold', fontSize: 28 }, }); export default RecipeCard;<file_sep>/fridgenchef/components/User.js import React from 'react' import {Image, View} from "react-native"; import {Button, Text} from "react-native-elements"; import {SecureStore} from 'expo'; import {NavigationActions} from 'react-navigation' class User extends React.Component { logOut = () => { SecureStore.deleteItemAsync('fbToken'); const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({routeName: 'Login'}) ] }) this.props.navigation.dispatch(resetAction) } render() { return ( <View style={{justifyContent: 'center'}}> {/*<Image source={{uri: this.props.screenProps.fbUser.picture.data.url}} style={{padding: 10, width: 80, height: 80}}/>*/} <Text style={{fontFamily: 'fira', textAlign: 'center', padding: 10}}> Hej {this.props.screenProps.fbUser.name + '!\n'} Har du noget ris/ros, eller noget andet? Send en mail til <EMAIL> </Text> <Button title={"Log ud"} icon={{name: 'exit-to-app', type: 'MaterialIcons'}} fontFamily={'fira'} buttonStyle={{backgroundColor: "#2196F3"}} onPress={() => { this.logOut() }}/> </View> ); } } export default User;<file_sep>/backend/src/main/java/rest/ImageResource.java package rest; import java.io.InputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author joaci */ @Path("imageUpload") public class ImageResource { @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadFile(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = uploadedInputStream.read(buffer)) > -1) { baos.write(buffer, 0, len); } baos.flush(); InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); InputStream is2 = new ByteArrayInputStream(baos.toByteArray()); BufferedImage image = ImageIO.read(is1); BufferedImage resized = resize(image, image.getHeight()/8, image.getWidth()/8); System.out.println("resizing"); File output = new File("/home/joacim/images/fridgebook/thumb/" + fileDetail.getFileName()); ImageIO.write(resized, "jpg", output); saveFile(is2, fileDetail.getFileName()); } catch (IOException ex) { Logger.getLogger(ImageResource.class.getName()).log(Level.SEVERE, null, ex); } return "{\"path\":\"" + fileDetail.getFileName() + "\"}"; } private static BufferedImage resize(BufferedImage img, int height, int width) { Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g2d = resized.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return resized; } private void saveFile(InputStream file, String name) { try { java.nio.file.Path path = FileSystems.getDefault().getPath("/home/joacim/images/fridgebook/" + name); // java.nio.file.Path path = FileSystems.getDefault().getPath("c:/temp/" + name); Files.copy(file, path); } catch (IOException ex) { ex.printStackTrace(); } } } <file_sep>/backend/src/main/java/rest/RecipeResource.java package rest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import entity.Recipe; import facade.RecipeFacade; import java.util.ArrayList; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.Produces; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import jsonMapper.RecipeJson; @Path("recipe") public class RecipeResource { private final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private final RecipeFacade RECIPE_FACADE = new RecipeFacade("PU"); @GET @Produces(MediaType.APPLICATION_JSON) public String getRecipes() { List<Recipe> recipes = RECIPE_FACADE.getRecipes(); List<RecipeJson> recipesJson = new ArrayList(); recipes.forEach(recipe -> { recipesJson.add(new RecipeJson(recipe)); }); return GSON.toJson(recipesJson); } @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public String getRecipeById(@PathParam("id") int id) { return GSON.toJson(new RecipeJson(RECIPE_FACADE.getRecipeById(id))); } @POST @Consumes(MediaType.APPLICATION_JSON) public String createRecipe(String content) { Recipe recipe = GSON.fromJson(content, Recipe.class); RECIPE_FACADE.createRecipe(recipe); return "Created"; } @PUT @Consumes(MediaType.APPLICATION_JSON) public String updateRecipe(String content) { Recipe recipe = GSON.fromJson(content, Recipe.class); RECIPE_FACADE.updateRecipe(recipe); return "Updated"; } @DELETE @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) public String deleteRecipe(@PathParam("id") int id) { RECIPE_FACADE.deleteRecipe(id); return "Deleted"; } } <file_sep>/backend/src/main/java/rest/CategoryResource.java package rest; import com.google.gson.Gson; import entity.Category; import facade.CategoryFacade; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import jsonMapper.CategoryJson; import jsonMapper.ComestibleJson; /** * * @author joacim */ @Path("category") public class CategoryResource { private final Gson GSON = new Gson(); private final CategoryFacade CATEGORY_FACADE = new CategoryFacade("PU"); @GET @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public String getCategoryById(@PathParam("id") Long id) { return GSON.toJson(new CategoryJson(CATEGORY_FACADE.getCategory(id))); } @GET @Produces(MediaType.APPLICATION_JSON) public String getCategories() { List<Category> categories = CATEGORY_FACADE.getCategories(); List<CategoryJson> categoriesJson = new ArrayList(); categories.forEach(category -> { categoriesJson.add(new CategoryJson(category)); }); return GSON.toJson(categoriesJson); } } <file_sep>/backend/src/main/java/entity/User.java package entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; @Entity public class User implements Serializable { private static final long serialVersionUID = 1L; @Id private String username; @Column(nullable = false) private String pin; @JoinColumn @OneToMany(fetch = FetchType.EAGER) private List<Recipe> recipesCreatedByUser; @ManyToMany(fetch = FetchType.EAGER) private List<Recipe> favouriteRecipes; @JoinColumn @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST) private List<Comestible> comestibles; public User() { } public User(String username, String pin) { this.username = username; this.pin = pin; recipesCreatedByUser = new ArrayList(); favouriteRecipes = new ArrayList(); comestibles = new ArrayList(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPin() { return pin; } public void setPin(String pin) { this.pin = pin; } public List<Recipe> getRecipesCreatedByUser() { return recipesCreatedByUser; } public void addRecipeCreatedByUser(Recipe recipe) { recipesCreatedByUser.add(recipe); } public List<Recipe> getFavouriteRecipes() { return favouriteRecipes; } public void addFavouriteRecipe(Recipe recipe) { favouriteRecipes.add(recipe); } public List<Comestible> getComestibles() { return comestibles; } public void addComestible(Comestible comestible) { comestibles.add(comestible); } @Override public String toString() { return "User{" + "username=" + username + ", pin=" + pin + ", recipesCreatedByUser=" + recipesCreatedByUser + ", favouriteRecipes=" + favouriteRecipes + ", comestibles=" + comestibles + '}'; } } <file_sep>/backend/src/main/java/facade/RecipeFacade.java package facade; import entity.Category; import entity.CategoryAmount; import entity.Ingredient; import entity.Recipe; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; public class RecipeFacade { private final EntityManagerFactory EMF; public static void main(String[] args) { new RecipeFacade("PU").start(); } public void start() { createPandekage(); // createToast(); //createCabonara(); // CategoryFacade c = new CategoryFacade("PU"); // List<String> paths = new ArrayList(); // paths.add("https://vetterlain.dk/images/fridgebook/Classic-spaghetti-carbonara.jpg"); // Recipe r = new Recipe(); // r.setImagePaths(paths); // r.setName("Spaghetti"); // List<Category> categories = new ArrayList(); // categories.add(new CategoryFacade("PU").getCategory(3l)); // r.setRecipeIngredients(categories); // r.setNote("Lækker pasta uden fløde"); // r.setText("Start med at koge spaghettien."); // r.setRateCounter(0); // Category b = c.getCategory(3l); // CategoryAmount a = new CategoryAmount(); // a.setAmount("1 pakke skiveskåret bacon"); // b.getCategoryAmounts().add(a); // a.setRecipe(createRecipe(r)); // c.updateCategory(b); } public void createToast() { CategoryFacade cat = new CategoryFacade("PU"); Recipe r = getRecipeById(3); List<String> paths = new ArrayList(); paths.add("https://vetterlain.dk/images/fridgebook/con-pariser-e-senape-725x545.jpg"); paths.add("https://vetterlain.dk/images/fridgebook/parisertoast_original.jpeg"); r.setName("Parisertoast"); r.setNote("Parisertoast kommer fra Frankrig, hvor den kendes som en croque-monsieur. Den oprindelige franske udgave består af to skiver toastbrød med ost og skinke mellem brødskiverne og stegt på en pande eller grillet i en ovn"); r.setRateCounter(0); r.setImagePaths(paths); r.setText("Skær kanterne af brødet og læg 4 skiver på en bageplade med bagepapir." + "\nLæg en skiver ost, en skiver (sammenfoldet) skinke, en skive ost og det sidste stykke brød, som låg." ); updateRecipe(r); // createRecipe(r); // CategoryAmount c1 = new CategoryAmount(); // Category ca1 = cat.getCategory(2L); // CategoryAmount c2 = new CategoryAmount(); // Category ca2 = cat.getCategory(4L); // CategoryAmount c3 = new CategoryAmount(); // Category ca3 = cat.getCategory(11L); // CategoryAmount c4 = new CategoryAmount(); // Category ca4 = cat.getCategory(12L); // CategoryAmount c5 = new CategoryAmount(); // Category ca5 = cat.getCategory(5L); // CategoryAmount c6 = new CategoryAmount(); // Category ca6 = cat.getCategory(6L); // Bacon // c1.setAmount("5g"); // c1.setRecipe(r); // ca1.getCategoryAmounts().add(c1); // cat.updateCategory(ca1); // // Parmesan // c2.setAmount("1 skive"); // c2.setRecipe(r); // ca2.getCategoryAmounts().add(c2); // cat.updateCategory(ca2); // // Salt // c3.setAmount("2 skiver"); // c3.setRecipe(r); // ca3.getCategoryAmounts().add(c3); // cat.updateCategory(ca3); // // Peber // c4.setAmount("1 skive"); // c4.setRecipe(r); // ca4.getCategoryAmounts().add(c4); // cat.updateCategory(ca4); // Spaghetti // c5.setAmount("100g"); // c5.setRecipe(r); // ca5.getCategoryAmounts().add(c5); // cat.updateCategory(ca5); // Æg // c6.setAmount("2"); // c6.setRecipe(r); // ca6.getCategoryAmounts().add(c6); // cat.updateCategory(ca6); } public void createPandekage() { CategoryFacade cat = new CategoryFacade("PU"); Recipe r = getRecipeById(1); List<String> paths = new ArrayList(); paths.add("https://vetterlain.dk/images/fridgebook/pandekage.jpg"); paths.add("https://vetterlain.dk/images/fridgebook/pan.jpg"); r.setImagePaths(paths); // r.setName("Pandekager"); //// r.setNote("Spaghetti carbonara er en traditional italiensk pastaret. Carbonara er en af de få pastaretter, hvor det ikke er fastlagt præcis hvilken pasta der skal anvendes og ud over spaghetti anvendes f.eks fettuccine, rigatoni, linguine, eller bucatini"); // CategoryAmount c1 = new CategoryAmount(); // Category ca1 = cat.getCategory(1L); // CategoryAmount c2 = new CategoryAmount(); // Category ca2 = cat.getCategory(2L); // CategoryAmount c3 = new CategoryAmount(); // Category ca3 = cat.getCategory(6L); // CategoryAmount c4 = new CategoryAmount(); // Category ca4 = cat.getCategory(7L); // CategoryAmount c5 = new CategoryAmount(); // Category ca5 = cat.getCategory(10L); //// CategoryAmount c6 = new CategoryAmount(); //// Category ca6 = cat.getCategory(6L); // c1.setAmount("50g"); // c1.setRecipe(r); // ca1.getCategoryAmounts().add(c1); // cat.updateCategory(ca1); // c2.setAmount("10g"); // c2.setRecipe(r); // ca2.getCategoryAmounts().add(c2); // cat.updateCategory(ca2); // c3.setAmount("1 stk"); // c3.setRecipe(r); // ca3.getCategoryAmounts().add(c3); // cat.updateCategory(ca3); // c4.setAmount("1 knivspids"); // c4.setRecipe(r); // ca4.getCategoryAmounts().add(c4); // cat.updateCategory(ca4); // // Spaghetti // c5.setAmount("3 dl"); // c5.setRecipe(r); // ca5.getCategoryAmounts().add(c5); // cat.updateCategory(ca5); // Æg // c6.setAmount("2"); // c6.setRecipe(r); // ca6.getCategoryAmounts().add(c6); // cat.updateCategory(ca6); // r.setText( // "Først blander du de tørre ingredienser i en skål.\n" // + "Så tilsætter du mælk lidt ad gangen. Pisk godt, så du undgår klumper. Det er nemmest og hurtigst med en elpisker.\n" // + "Tilsæt æg til sidst, og rør godt rundt, til dejen har den rette konsistens.\n" // + "Varm panden, smelt smør, og fordel den første omgang dej. Min pande tager ca. ¾-1 dl. Hvis du vil undgå, at den første bliver en mandagspandekage, skal du sørge for, at panden er ordentlig varm, inden dejen hældes på.\n" // + "Vend, når der ikke er mere “våd dej”, og steg færdig på den anden side." // ); updateRecipe(r); } public void createCabonara() { Recipe r = getRecipeById(2); List<String> paths = new ArrayList(); paths.add("https://vetterlain.dk/images/fridgebook/Classic-spaghetti-carbonara.jpg"); paths.add("https://vetterlain.dk/images/fridgebook/carb.jpg"); // r.setName("Parisertoast"); // r.setNote("Parisertoast kommer fra Frankrig, hvor den kendes som en croque-monsieur. Den oprindelige franske udgave består af to skiver toastbrød med ost og skinke mellem brødskiverne og stegt på en pande eller grillet i en ovn"); r.setRateCounter(1); r.setImagePaths(paths); // r.setText("Skær kanterne af brødet og læg 4 skiver på en bageplade med bagepapir." // + "\nLæg en skiver ost, en skiver (sammenfoldet) skinke, en skive ost og det sidste stykke brød, som låg." // ); // updateRecipe(r); // CategoryFacade cat = new CategoryFacade("PU"); // Recipe r = getRecipeById(2); r.setName("Spaghetti cabonara"); r.setNote("Spaghetti carbonara er en traditional italiensk pastaret. Carbonara er en af de få pastaretter, hvor det ikke er fastlagt præcis hvilken pasta der skal anvendes og ud over spaghetti anvendes f.eks fettuccine, rigatoni, linguine, eller bucatini"); // CategoryAmount c1 = new CategoryAmount(); // Category ca1 = cat.getCategory(3L); // CategoryAmount c2 = new CategoryAmount(); // Category ca2 = cat.getCategory(9L); // CategoryAmount c3 = new CategoryAmount(); // Category ca3 = cat.getCategory(7L); // CategoryAmount c4 = new CategoryAmount(); // Category ca4 = cat.getCategory(8L); // CategoryAmount c5 = new CategoryAmount(); // Category ca5 = cat.getCategory(5L); // CategoryAmount c6 = new CategoryAmount(); // Category ca6 = cat.getCategory(6L); //// Bacon // c1.setAmount("1 pakke"); // c1.setRecipe(r); // ca1.getCategoryAmounts().add(c1); // cat.updateCategory(ca1); // // Parmesan // c2.setAmount("Friskrevet parmesan"); // c2.setRecipe(r); // ca2.getCategoryAmounts().add(c2); // cat.updateCategory(ca2); // // Salt // c3.setAmount("1 tsk"); // c3.setRecipe(r); // ca3.getCategoryAmounts().add(c3); // cat.updateCategory(ca3); // // Peber // c4.setAmount("Masser af friskkværnet peber"); // c4.setRecipe(r); // ca4.getCategoryAmounts().add(c4); // cat.updateCategory(ca4); // // Spaghetti // c5.setAmount("100g"); // c5.setRecipe(r); // ca5.getCategoryAmounts().add(c5); // cat.updateCategory(ca5); //// Æg // c6.setAmount("2"); // c6.setRecipe(r); // ca6.getCategoryAmounts().add(c6); // cat.updateCategory(ca6); r.setText( "Sæt vand over til pasta\n\n" + "Steg bacon - når det er halvfærdigt hælder du bacon op på et stykke køkkenrulle\n\n" + "Kom salt og pasta i det kogende vand\n\n" + "bland æg, ca. 100 g parmesan, salt og peber til carbonara saucen\n\n" + "Hæld bacon tilbage i panden med løg og champignon, og hæld evt. en sjat hvidvin ved - lad det koge lidt ind\n\n" + "Når hvidvinen næsten er fordampet, slukker du for varmen og tilsætte carbonara saucen\n\n" + "Hæld vandet fra pastaen og tilsæt den færdige og afdryppede pasta til retten\n\n" + "Vend retten roligt rundt og lad evt. saucen tykne lidt" ); updateRecipe(r); } public RecipeFacade(String persistenceUnit) { this.EMF = Persistence.createEntityManagerFactory(persistenceUnit); } private EntityManager getEntityManager() { return EMF.createEntityManager(); } public Recipe getRecipeById(int id) { return getEntityManager().find(Recipe.class, id); } public List<Recipe> getRecipes() { return getEntityManager().createQuery("SELECT r FROM Recipe r", Recipe.class).getResultList(); } public Recipe createRecipe(Recipe recipe) { EntityManager em = getEntityManager(); Recipe recipeInDB = null; try { em.getTransaction().begin(); em.persist(recipe); em.getTransaction().commit(); recipeInDB = em.find(Recipe.class, recipe.getId()); } catch (RollbackException r) { em.getTransaction().rollback(); } finally { em.close(); } return recipeInDB; } public Recipe updateRecipe(Recipe recipe) { EntityManager em = getEntityManager(); Recipe recipeInDB = em.find(Recipe.class, recipe.getId()); try { em.getTransaction().begin(); recipeInDB = em.merge(recipe); em.getTransaction().commit(); } catch (RollbackException r) { em.getTransaction().rollback(); } finally { em.close(); } return recipeInDB; } public boolean deleteRecipe(int id) { EntityManager em = getEntityManager(); Recipe recipe = em.find(Recipe.class, id); try { em.getTransaction().begin(); em.remove(recipe); em.getTransaction().commit(); } catch (RollbackException r) { em.getTransaction().rollback(); return false; } finally { em.close(); } return true; } } <file_sep>/fridgenchef/components/AddComestible.js import React from 'react'; import {RefreshControl, TextInput, View, StyleSheet, TouchableOpacity, Alert, ScrollView, KeyboardAvoidingView} from "react-native"; import {Button, Icon, List, ListItem, Text, FormInput, FormLabel, Avatar} from "react-native-elements"; import DatePicker from 'react-native-datepicker'; import {NavigationActions} from "react-navigation"; class AddComestible extends React.Component { state = { name: '', amount: '', expiryDate: '', ingredient: '', ingredients: null, search: false, user: {} }; componentDidMount() { this.updateUserInState(); this.fetchIngredients() .then(() => { if (this.props.navigation.state.params.data !== undefined) { let found = false; this.state.ingredients.forEach(ingredient => { if (ingredient.barcode === this.props.navigation.state.params.data) { this.setState({name: ingredient.name, ingredient}) found = true; } }) if (!found) { this.navigateIngredient(); } } }).catch(err => { console.log(err); }) }; navigateIngredient = () => { const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName: 'AddIngredient', params: {barcode: this.props.navigation.state.params.data, fetchIngredients: this.fetchIngredients} }) ] }) this.props.navigation.dispatch(resetAction) } updateUserInState = () => { this.props.screenProps.getUser() .then(user => this.setState({user})); } fetchIngredients = async () => { const ingredients = await (await fetch('https://vetterlain.dk/FridgeBook/api/ingredient')).json(); this.setState({ingredients}); } addComestible = async () => { let comestible = { expiryDate: this.state.expiryDate, amount: this.state.amount, ingredient: { name: this.state.ingredient.name, imagePath: this.state.ingredient.imagePath } } let user = this.state.user; user.comestibles.push(comestible); const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify(user) } const res = await fetch('https:/vetterlain.dk/FridgeBook/api/user', options); } setSearching = (text) => { this.setState({search: true, name: text}) } pickIngredient = (ingredient) => { this.setState({ search: false, name: ingredient.name, ingredient: ingredient }) } render() { if (this.state.search) { let ingredientsContainingInput = this.state.ingredients; if (this.state.name.length > 0) { ingredientsContainingInput = []; this.state.ingredients.forEach(ingredient => { if (ingredient.name.toLowerCase().indexOf(this.state.name.toLowerCase()) > -1) { ingredientsContainingInput.push(ingredient); } } ) } return ( <View style={styles.container}> <FormLabel labelStyle={{fontFamily: 'fira', fontWeight: '300'}}>Vare</FormLabel> <FormInput inputStyle={{fontFamily: 'fira', fontWeight: '300'}} value={this.state.name} onChangeText={(text) => { this.setState({name: text}) }} placeholder="Navn på vare" /> <ScrollView keyboardShouldPersistTaps={'always'}> <List>{ ingredientsContainingInput.map((ingredient, index) => ( <ListItem key={index} fontFamily={'fira'} title={ingredient.name} avatar={<Avatar rounded source={{uri: 'https://vetterlain.dk/images/fridgebook/thumb/' + ingredient.imagePath}} title={ingredient.name} />} hideChevron onPress={() => this.pickIngredient(ingredient)} /> )) } <ListItem title={"Opret ny vare"} fontFamily={'fira'} onPress={() => this.navigateIngredient()} /> </List> </ScrollView> </View> ) } return ( <View style={styles.container}> <FormLabel labelStyle={{fontFamily: 'fira', fontWeight: '300'}}>Vare</FormLabel> <FormInput inputStyle={{fontFamily: 'fira', fontWeight: '300'}} value={this.state.name} placeholder="Søg efter vare..." onChangeText={text => this.setSearching(text)} onFocus={() => this.setState({search: true})} /> <FormLabel labelStyle={{fontFamily: 'fira', fontWeight: '300'}}>Mængde</FormLabel> <FormInput inputStyle={{fontFamily: 'fira', fontWeight: '300'}} keyboardType="default" placeholder="Fx 5 tomater, 250g smør eller 1 liter mælk" onChangeText={amount => this.setState({amount})} /> <Text>{"\n"}</Text> <View style={styles.buttonContainer}> <DatePicker style={{width: 200}} date={this.state.expiryDate} value={this.state.expiryDate} mode="date" placeholder="Vælg udløbsdato" format="DD/MM/YYYY" minDate="01-05-2017" maxDate="10-06-2020" confirmBtnText="Confirm" cancelBtnText="Cancel" customStyles={{ dateIcon: { position: 'absolute', left: 0, top: 4, marginLeft: 0 } }} onDateChange={(date) => { this.setState({expiryDate: date}) }} /> </View> <Text>{"\n"}</Text> <Button fontFamily={'fira'} title='OK' onPress={() => { if (this.state.name === '' || this.state.amount === '' || this.state.expiryDate === '') { Alert.alert( 'Fejl i indtastning', 'Indtast venligst vare, mængde samt udløbsdato for at fortsætte' ); } else { this.addComestible() .then(() => this.props.screenProps.getUser()) .then(() => this.props.navigation.state.params.onBack()) .then(() => this.props.navigation.state.params.setBack()) .then(() => this.props.navigation.goBack()) } } } backgroundColor={"#3B9BFF"} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#ffffff", }, buttonContainer: { flexDirection: 'row', justifyContent: 'center', } }); export default AddComestible;<file_sep>/backend/src/main/java/model/RecipeSort.java //package model; // //import entity.Category; //import entity.Ingredient; //import entity.Recipe; //import entity.User; //import facade.CategoryFacade; //import facade.IngredientFacade; //import facade.RecipeFacade; //import facade.UserFacade; //import java.util.ArrayList; //import java.util.List; // ///** // * // * @author joacim // */ //public class RecipeSort { // // RecipeFacade rFacade = new RecipeFacade("PU"); // CategoryFacade cFacade = new CategoryFacade("PU"); // IngredientFacade iFacade = new IngredientFacade("PU"); // UserFacade uFacade = new UserFacade("PU"); // // public static void main(String[] args) { // new RecipeSort().start(); // } // // public void start() { //// List<Recipe> recipes = rFacade.getRecipes(); // List<Category> categories = cFacade.getCategories(); //// List<Ingredient> ingredients = iFacade.getIngredients(); //// // User u = uFacade.getUserById("10156074410491118"); // Ingredient i = iFacade.getIngredientByName("Brunchy bacon"); // // List<String> result = new ArrayList(); // // for (Category category : categories) { // for (Ingredient ingredient : category.getIngredients()) { // if (ingredient.getName().equals(i.getName())) { // category.getCategoryAmounts().forEach(amount -> { // System.out.println( // amount.getRecipe().getName() // ); // }); //// System.out.println(category.getCategoryAmounts()); // } // } // //// for (Recipe recipe : recipes) { //// for (Category category : categories) { //// category.getIngredients().forEach(ingredient -> { //// if (ingredient.getName().equals(i.getName())) { //// System.out.println("----------------------------"); //// System.out.println("Recipe with: Økologisk hvedemel"); //// System.out.println(recipe.getName()); //// } //// }); //// category.getCategoryAmounts().forEach(amount->{ //// if(amount.recipe.getId()==i.get) //// }); // } // } // //// for (Category category : categories) { //// category.getCategoryAmounts().forEach(amount -> { //// for (Recipe recipe : recipes) { //// if (recipe.getId() == amount.getRecipe().getId()) { ////// System.out.println(recipe.getId()); //// } //// } //// }); //// for (Ingredient ingredient : category.getIngredients()) { //// System.out.println(ingredient.getName()); //// System.out.println(category.getId()); //// } //// System.out.println(category.getIngredients()); //} // //} // //} <file_sep>/backend/src/main/java/entity/Category.java package entity; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; /** * * @author joacim */ @Entity public class Category implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Boolean isNew = true; private String imageName; @OneToMany(fetch = FetchType.EAGER) private List<Ingredient> ingredients; @OneToMany(fetch = FetchType.EAGER) private List<CategoryAmount> categoryAmounts; public List<CategoryAmount> getCategoryAmounts() { return categoryAmounts; } public void setCategoryAmounts(List<CategoryAmount> categoryAmounts) { this.categoryAmounts = categoryAmounts; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsNew() { return isNew; } public void setIsNew(Boolean isNew) { this.isNew = isNew; } public List<Ingredient> getIngredients() { return ingredients; } public void setIngredients(List<Ingredient> ingredients) { this.ingredients = ingredients; } } <file_sep>/fridgenchef/components/Home.js import React from 'react' import {Avatar, Button} from "react-native-elements"; import {RefreshControl, ScrollView, TouchableOpacity, View, ActivityIndicator, FlatList, Text, Image, StyleSheet, Modal} from "react-native"; import AddComestible from "./AddComestible"; import Login from "./Login"; import {NavigationActions} from "react-navigation"; import {Permissions} from "expo"; import Card from "./Card"; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; class Home extends React.Component { static navigationOptions = ({navigation, screenProps}) => { const params = navigation.state.params || {}; return { headerLeft: params.headerLeft, headerRight: params.headerRight, } } state = { refreshing: false, user: {}, deleteVisible: false, barcode: false, modalVisible: false, refresh: false, } _setNavigationParams() { let headerLeft = <View style={{flex: 1, flexDirection: 'row'}}> <Image source={require('../assets/icon.png')} style={{width: 25, height: 25, padding: 20, paddingRight: -40}}/> <Text style={{paddingTop: 10, fontSize: 18, color: '#f0f0f0', fontFamily: 'fira-bold'}}>Fridge'N'Chef</Text> </View> let headerRight = <View style={{flexDirection: 'row'}}> <View style={{paddingTop: 18}}> <Icon name={"sort-variant"} size={24} color="#B8B8B8" onPress={() => { this.openModal() }} /> </View> <Avatar rounded containerStyle={{margin: 15}} source={{uri: this.props.screenProps.fbUser.picture.data.url}} onPress={() => this.props.navigation.navigate('User')} /> </View> this.props.navigation.setParams({ // title, headerLeft, headerRight, }); } openModal() { this.setState({modalVisible: true}); } closeModal() { this.setState({modalVisible: false}); } sortComestibles = () => { let comestibles = this.state.user.comestibles; let dateAndComestible = []; comestibles.forEach(comestible => { let str = comestible.expiryDate.split('/'); let da = new Date(str[2], str[1], str[0]); dateAndComestible.push({"date": da, "comestible": comestible}) }) dateAndComestible.sort((a, b) => { return a.date - b.date; }) let finalArray = []; dateAndComestible.forEach(comestible => { finalArray.push(comestible.comestible) }) let user = this.state.user; user.comestibles = finalArray; this.setState({user}) } sortAlphabetic = () => { let sortedComestibles = this.state.user.comestibles; sortedComestibles.sort((a, b) => { a.sorted = true; b.sorted = true; return a.ingredient.name.localeCompare(b.ingredient.name) }) let user = this.state.user; user.comestibles = sortedComestibles; this.setState({user, refresh: !this.state.refresh}, () => this.renderIngredients()) } componentWillMount() { if (this.props.screenProps.fbUser !== null) { this.updateUserInState(); this._setNavigationParams(); } else { const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({routeName: 'Login'}) ] }) this.props.navigation.dispatch(resetAction) } }; updateUserInState = () => { this.props.screenProps.getUser() .then(user => this.setState({user}, () => this.sortAlphabetic())); } onRefresh = () => { this.props.screenProps.getUser() .then(user => this.setState({user, refreshing: false})); } renderIngredients = () => { return ( <FlatList numColumns={2} data={this.state.user.comestibles} extraData={this.state.refresh} renderItem={this.renderItem} keyExtractor={this.keyExtractor} /> ) } keyExtractor = (item, index) => item.id; info = (comestible) => { this.props.navigation.navigate('Comestible', {comestible: comestible, onBack: this.updateUserInState}) } renderItem = ({item, index}) => { return <Card comestible={item} search={this.search} info={this.info} updateUser={this.updateUserInState}/> } search = (name) => { this.props.screenProps.setSearch(name); this.props.navigation.navigate('Recipes'); } render() { if (Object.keys(this.state.user).length === 0) { return ( <View style={{flex: 1, justifyContent: 'center'}}> <ActivityIndicator size={100} color="#2196F3"/> </View> ) } if (this.state.user.comestibles.length === 0) { return ( <View style={{flex: 1, backgroundColor: 'white', justifyContent: 'center'}}> <Text style={{textAlign: 'center',fontFamily:'fira'}}>Dit køleskab er tomt!</Text> <Text style={{textAlign: 'center',fontFamily:'fira'}}>Tilføj en vare ved at scanne stregkoden eller indtaste manuelt</Text> <TouchableOpacity style={{ alignItems: 'center', justifyContent: 'center', width: 70, height: 70, backgroundColor: '#ff5613', borderRadius: 100, position: 'absolute', right: '6%', bottom: '15%', elevation: 5 }} onPress={ () => { Permissions.askAsync(Permissions.CAMERA) .then(permission => { if (permission === null) { // console.log("waiting for permission") } else if (permission === false) { // console.log("no permission") } else { this.props.navigation.navigate('Barcode', {onBack: this.updateUserInState}) } }) }} > <Icon name={"barcode-scan"} size={30} color="#fff"/> </TouchableOpacity> <TouchableOpacity style={{ alignItems: 'center', justifyContent: 'center', width: 70, height: 70, backgroundColor: '#ff5613', borderRadius: 100, position: 'absolute', right: '6%', bottom: '2%', elevation: 5 }} onPress={() => { this.props.navigation.navigate('AddComestible', { onBack: this.updateUserInState, setBack: () => { } }) }} > <Icon name={"plus"} size={30} color="#fff"/> </TouchableOpacity> </View> ) } return ( <View style={{flex: 1, backgroundColor: "#ffffff"}}> <Modal transparent={true} visible={this.state.modalVisible} animationType={'fade'} onRequestClose={() => this.closeModal()} > <View style={styles.modalContainer}> <View style={styles.innerContainer}> <View style={{paddingBottom: 35, marginLeft: 120}}> <Icon name={"close"} size={50} color="#fff" onPress={() => this.closeModal()}/> </View> <Button onPress={() => { this.sortComestibles(); this.closeModal(); } } fontFamily={'fira'} buttonStyle={{backgroundColor: "#2196F3"}} title="Sorter efter dato" /> <Text>{"\n"}</Text> <Button buttonStyle={{backgroundColor: "#2196F3"}} fontFamily={'fira'} onPress={() => { this.sortAlphabetic(); this.closeModal(); }} title="Sorter alfabetisk" /> </View> </View> </Modal> <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this.onRefresh}/> }> {this.renderIngredients()} </ScrollView> <TouchableOpacity style={{ alignItems: 'center', justifyContent: 'center', width: 70, height: 70, backgroundColor: '#ff5613', borderRadius: 100, position: 'absolute', right: '6%', bottom: '15%', elevation: 5 }} onPress={ () => { Permissions.askAsync(Permissions.CAMERA) .then(permission => { if (permission === null) { // console.log("waiting for permission") } else if (permission === false) { // console.log("no permission") } else { this.props.navigation.navigate('Barcode', {onBack: this.updateUserInState}) } }) }} > <Icon name={"barcode-scan"} size={30} color="#fff"/> </TouchableOpacity> <TouchableOpacity style={{ alignItems: 'center', justifyContent: 'center', width: 70, height: 70, backgroundColor: '#ff5613', borderRadius: 100, position: 'absolute', right: '6%', bottom: '2%', elevation: 5 }} onPress={() => { this.props.navigation.navigate('AddComestible', { onBack: this.updateUserInState, setBack: () => { } }) }} > <Icon name={"plus"} size={30} color="#fff"/> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', }, modalContainer: { backgroundColor: 'rgba(0,0,0,0.2)', flex: 1, justifyContent: 'center', // backgroundColor: 'grey', }, innerContainer: { borderRadius: 1, borderColor: 'red', alignItems: 'center', }, }); export default Home;<file_sep>/backend/src/main/java/entity/Comestible.java package entity; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class Comestible implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String addedDate; private String expiryDate; private String amount; @OneToOne(cascade = CascadeType.PERSIST) private Ingredient ingredient; public Comestible() { addedDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date()); } public Comestible(String expiryDate, String amount, Ingredient ingredient) { addedDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date()); this.expiryDate = expiryDate; this.amount = amount; this.ingredient = ingredient; } public int getId() { return id; } public String getAddedDate() { return addedDate; } public String getExpiryDate() { return expiryDate; } public void setExpiryDate(String expiryDate) { this.expiryDate = expiryDate; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public Ingredient getIngredient() { return ingredient; } public void setIngredient(Ingredient ingredient) { this.ingredient = ingredient; } @Override public String toString() { return "Comestible{" + "id=" + id + ", addedDate=" + addedDate + ", expiryDate=" + expiryDate + ", amount=" + amount + ", ingredient=" + ingredient + '}'; } } <file_sep>/backend/src/main/java/jsonMapper/ComestibleJson.java package jsonMapper; import entity.Comestible; public class ComestibleJson { private int id; private String addedDate; private String expiryDate; private String amount; private IngredientJson ingredient; public ComestibleJson(Comestible comestible) { id = comestible.getId(); addedDate = comestible.getAddedDate(); expiryDate = comestible.getExpiryDate(); amount = comestible.getAmount(); ingredient = new IngredientJson(comestible.getIngredient()); } } <file_sep>/fridgenchef/components/Barcode.js import React from 'react' import {Modal, StyleSheet, Text, View} from "react-native"; import {BarCodeScanner} from "expo"; class Barcode extends React.Component { state = { read: false, } setBack = async () => { this.props.navigation.goBack(); } handleBarCodeRead = ({type, data}) => { if (!this.state.read) { this.setState({read: true}, () => { this.props.navigation.navigate('AddComestible', {data: data, onBack: this.props.navigation.state.params.onBack, setBack: this.setBack}); }) } } render() { return ( <View style={styles.container}> <BarCodeScanner onBarCodeRead={this.handleBarCodeRead} style={StyleSheet.absoluteFill} /> <View style={{backgroundColor: 'rgba(255,255,255,0.1)', flex: 1}}> <View style={{marginTop: 120, marginBottom: -120}}> <Text style={{color: 'white', textAlign: 'center', fontFamily: 'fira'}}>Vend stregkode i samme retning som mobilen{"\n"}</Text> </View> <View style={{ backgroundColor: 'rgba(0,0,0,0.1)', // position: 'absolute', flex: 1, marginTop: 140, marginBottom: 140, marginLeft: 60, marginRight: 60, borderWidth: 1, borderColor: 'white' }}> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, // alignItems: 'center', // justifyContent: 'center', // paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', } }); export default Barcode;<file_sep>/fridgenchef/components/Login.js import React from 'react' import {Dimensions, Image, Text, View} from "react-native"; import {Button} from "react-native-elements"; import {SecureStore, Facebook} from 'expo'; import {NavigationActions} from 'react-navigation'; const deviceWidth = Dimensions.get('window').width; const deviceHeight = Dimensions.get('window').height; class Login extends React.Component { login = async () => { this.logIn() .then(() => { const resetAction = NavigationActions.reset({ index: 0, // actions: [NavigationActions.navigate({routeName: 'Home',{'data':'hej'}})] actions: [NavigationActions.navigate('Home',{'data':'barcode'})] // this.props.navigation.navigate('Barcode', {onBack: this.updateUserInState}) }) this.props.navigation.dispatch(resetAction) }) }; logIn = async () => { const {type, token} = await Facebook.logInWithReadPermissionsAsync('571905333150508', { permissions: ['public_profile'], }); if (type === 'success') { await this.createUser(token) await SecureStore.setItemAsync("fbToken", token); await this.props.screenProps.fetchFromFacebook(); } } createUser = async (token) => { const response = await fetch(`https://graph.facebook.com/me?fields=id,name,picture&access_token=${token}`); response.json() .then((res) => { let dbUser = {}; dbUser.username = res.id + ""; dbUser.pin = 1234; const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST", body: JSON.stringify(dbUser) } fetch('https:/vetterlain.dk/FridgeBook/api/user', options) }) } render() { return ( <View style={{flex: 1, backgroundColor: "#2196F3", alignItems: "center", justifyContent: 'center'}}> <Text style={{color: 'white', fontSize: 34, fontFamily: 'fira-bold'}}>Fridge'N'Chef</Text> <Image source={require('../assets/splash.png')} style={{width: deviceWidth / 2, height: deviceHeight / 3}}/> {/*<Text style={{textAlign: 'center',color:'white'}}>{"\n\n"}Log venligst ind for at bruge denne app{"\n"}</Text>*/} <Button onPress={this.login} title="Login med Facebook" icon={{name: 'facebook', type: 'entypo'}} backgroundColor='#3b5998' /> </View> ); } } export default Login;<file_sep>/fridgenchef/components/CreateIngredient.js import React from 'react'; import {TextInput, View, StyleSheet, Alert, Image} from "react-native"; import {Button, Text} from "react-native-elements"; import {ImagePicker} from "expo"; import {NavigationActions} from "react-navigation"; class AddIngredient extends React.Component { state = { ingredient: {}, image: {}, barcode: '', res: null, imageTaken: false, }; componentDidMount() { if (this.props.navigation.state.params !== undefined) { this.setState({barcode: this.props.navigation.state.params.barcode}) } }; goHome = () => { const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({routeName: 'Home'}) ] }) this.props.navigation.dispatch(resetAction) } takePicture = async () => { try { let result = await ImagePicker.launchCameraAsync({ aspect: [5, 6], quality: 0.5 }); if (result.cancelled) { return; } this.setState({image: await result, imageTaken: true}, () => { this.uploadPicture() }) } catch (err) { this.goHome(); console.warn('couldn\'t start camera') } } uploadPicture = () => { let localUri = this.state.image.uri; let filename = localUri.split('/').pop(); let match = /\.(\w+)$/.exec(filename); let type = match ? `image/${match[1]}` : `image`; let formData = new FormData(); formData.append('file', {uri: localUri, name: filename, type}); return fetch("https://vetterlain.dk/FridgeBook/api/imageUpload", { method: 'POST', body: formData, header: { 'content-type': 'multipart/form-data', }, }); } renderImage = () => { return ( <Image style={{height: 200, width: 200}} source={{uri: this.state.image.uri}}/> ) } addIngredient = async () => { const ingredient = { name: this.state.ingredient.name, imagePath: this.state.image.uri.split('/').pop(), barcode: this.state.barcode } const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST", body: JSON.stringify(ingredient) } fetch('https:/vetterlain.dk/FridgeBook/api/ingredient', options) .then(() => { Alert.alert('Oprettelse godkendt', 'Varen er hermed oprettet og kan nu tilføjes til dit køleskab'); this.goHome(); }) } render() { return ( <View style={{padding: 10}}> <Text style={{fontFamily: 'fira'}}>Denne vare findes ikke i vores system - du bedes venligst oprette den ved at angive et navn, og tage et billede af varen.</Text> <TextInput style={{height: 40, fontFamily: 'fira'}} placeholder="<NAME>" value={this.state.name} onChangeText={text => this.setState({ingredient: {...this.state.ingredient, name: text}})} /> <View style={{alignItems: 'center'}}> {this.state.imageTaken ? this.renderImage() : null} <Text>{"\n"}</Text> </View> <Button iconRight={{name: 'camera', type: 'entypo'}} buttonStyle={{backgroundColor: "#2196F3"}} fontFamily={'fira'} title="Tag et billede" onPress={this.takePicture}/> <Text>{"\n"}</Text> <Button buttonStyle={{backgroundColor: "#2196F3"}} onPress={() => { if (this.state.ingredient.name === undefined) { Alert.alert( 'Fejl i indtastning', 'Indtast venligst navn på den vare du ønsker at oprette' ); } else { this.addIngredient(); } }} title="Opret" fontFamily={'fira'} /> <Text style={{fontFamily: 'fira'}}>{"\nAlle uploads bliver gennemgået, og upassende indhold vil blive fjernet"}</Text> </View> ); } } export default AddIngredient;<file_sep>/backend/src/main/java/testData/TestData.java package testData; import entity.Ingredient; import entity.Comestible; import entity.Recipe; import entity.User; import facade.IngredientFacade; import facade.RecipeFacade; import facade.UserFacade; import java.util.ArrayList; import java.util.List; public class TestData { private final UserFacade USER_FACADE = new UserFacade("PU"); private final IngredientFacade INGREDIENT_FACADE = new IngredientFacade("PU"); private final RecipeFacade RECIPE_FACADE = new RecipeFacade("PU"); public static void main(String[] args) { new TestData().populateDatabase(); } public void populateDatabase() { //User(String username, String pin) User lars = new User("Lars", "1234"); User ib = new User("Ib", "9999"); User gustav = new User("Gustav", "1111"); USER_FACADE.createUser(lars); USER_FACADE.createUser(ib); USER_FACADE.createUser(gustav); //Ingredient(String name, String imagePath) Ingredient tomat = new Ingredient("tomat", "/imagePath/tomat.jpg"); Ingredient ost = new Ingredient("ost", "/imagePath/ost.jpg"); Ingredient yoghurt = new Ingredient("yoghurt", "/imagePath/yoghurt.jpg"); Ingredient mælk = new Ingredient("mælk", "/imagePath/mælk.jpg"); Ingredient aguark = new Ingredient("aguark", "/imagePath/aguark.jpg"); INGREDIENT_FACADE.createIngredient(tomat); INGREDIENT_FACADE.createIngredient(ost); INGREDIENT_FACADE.createIngredient(yoghurt); INGREDIENT_FACADE.createIngredient(mælk); INGREDIENT_FACADE.createIngredient(aguark); //Comestible(String expiryDate, String amount, Ingredient ingredient) Comestible larsTomat = new Comestible("22/04/2018", "5", tomat); Comestible ibTomat = new Comestible("31/02/2017", "7", tomat); Comestible gustavTomat = new Comestible("11/12/2017", "3", tomat); Comestible ibMælk = new Comestible("22/04/2018", "4", mælk); Comestible larsOst = new Comestible("21/05/2018", "2", ost); Comestible gustavOst = new Comestible("19/12/2028", "1", ost); lars.addComestible(larsTomat); lars.addComestible(larsOst); ib.addComestible(ibTomat); ib.addComestible(ibMælk); gustav.addComestible(gustavTomat); gustav.addComestible(gustavOst); //Recipe(String name, List<String> imagePaths, String text, List<Ingredient> recipeIngredients List<String> imagePaths = new ArrayList(); imagePaths.add("/image"); imagePaths.add("/image/2"); imagePaths.add("/image/3"); List<Ingredient> bananIngredients = new ArrayList(); bananIngredients.add(mælk); bananIngredients.add(aguark); List<Ingredient> pandekageIngredients = new ArrayList(); pandekageIngredients.add(ost); pandekageIngredients.add(mælk); pandekageIngredients.add(aguark); List<Ingredient> drøømmekageIngredients = new ArrayList(); drøømmekageIngredients.add(ost); drøømmekageIngredients.add(yoghurt); drøømmekageIngredients.add(tomat); drøømmekageIngredients.add(aguark); // Recipe banankage = new Recipe("banankage", imagePaths, "Tag 1 liter yoghurt og bland med...", bananIngredients); // Recipe pandekage = new Recipe("pandekage", imagePaths, "Tag 1 liter mælk og bla bla bla..", pandekageIngredients); // Recipe drømmekage = new Recipe("drømmekage", imagePaths, "Beskrivelse af drømmekage", drøømmekageIngredients); // RECIPE_FACADE.createRecipe(drømmekage); // RECIPE_FACADE.createRecipe(pandekage); // RECIPE_FACADE.createRecipe(banankage); // // lars.addRecipeCreatedByUser(drømmekage); // lars.addRecipeCreatedByUser(banankage); // ib.addRecipeCreatedByUser(pandekage); // // lars.addFavouriteRecipe(drømmekage); // lars.addFavouriteRecipe(pandekage); // ib.addFavouriteRecipe(drømmekage); // gustav.addFavouriteRecipe(drømmekage); // gustav.addFavouriteRecipe(banankage); // gustav.addFavouriteRecipe(pandekage); USER_FACADE.updateUser(lars); USER_FACADE.updateUser(ib); USER_FACADE.updateUser(gustav); } } <file_sep>/backend/src/test/java/test/IngredientResourceTest.java //package test; // //import com.google.gson.Gson; //import entity.Ingredient; //import facade.IngredientFacade; //import io.restassured.RestAssured; //import static io.restassured.RestAssured.given; //import io.restassured.parsing.Parser; //import static org.hamcrest.CoreMatchers.equalTo; //import org.junit.Test; //import org.junit.BeforeClass; // //public class IngredientResourceTest { // // private IngredientFacade INGREDIENTFACADE = new IngredientFacade("PU"); // // @BeforeClass // public static void setUpBeforeAll() { // RestAssured.baseURI = "http://localhost"; // RestAssured.port = 8084; // RestAssured.basePath = "/FridgeBook/api/ingredient"; // RestAssured.defaultParser = Parser.JSON; // } // // @Test // public void serverIsRunning() { // given().when().get().then().statusCode(200); // } // // @Test // public void testGetIngredientByName() { // given() // .pathParam("id", "Mælk") // .when().get("{id}") // .then().statusCode(200) // .body("name", equalTo("Mælk")); // } // // @Test // public void testCreateIngredient() { // Ingredient ingredient = new Ingredient("Salat", "/image"); // given() // .contentType("application/json") // .body(new Gson().toJson(ingredient)) // .when().post("/") // .then().statusCode(200) // .body(equalTo("Created")); // // INGREDIENTFACADE.deleteIngredient("Salat"); // } // // @Test // public void testUpdateIngredient() { // // Ingredient mælk = INGREDIENTFACADE.getIngredientByName("Mælk"); // mælk.setImagePath("/image/mælk.png"); // given() // .contentType("application/json") // .body(new Gson().toJson(mælk)) // .when().put("/") // .then().statusCode(200) // .body(equalTo("Updated")); // // } //} <file_sep>/fridgenchef/components/Comestible.js import React from 'react' import {ScrollView, View, StyleSheet, Alert, Image, FlatList, KeyboardAvoidingView} from "react-native"; import {Button, FormInput, FormLabel, Text} from "react-native-elements"; import DatePicker from 'react-native-datepicker'; import Dimensions from 'Dimensions'; class Comestible extends React.Component { static navigationOptions = ({navigation}) => ({ title: navigation.state.params.comestible.ingredient.name, headerTitleStyle: {fontFamily: 'fira-bold', fontWeight: '300'}, tabBarVisible: false, swipeEnabled: false, }); state = { comestible: this.props.navigation.state.params.comestible, width: 100, height: 100 } updateComestible = async () => { const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify(this.state.comestible) } const res = await fetch('https://vetterlain.dk/FridgeBook/api/comestible/', options); } deleteComestible = async (id) => { const options = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "DELETE" } const res = await fetch('https://vetterlain.dk/FridgeBook/api/comestible/' + id, options); } render() { return ( <ScrollView style={styles.container}> <KeyboardAvoidingView behavior={'position'}> <View style={styles.upperContainer}> <Image style={{flex: 1, width: Dimensions.get('window').width, height: Dimensions.get('window').height / 2}} source={{uri: "https://vetterlain.dk/images/fridgebook/" + this.state.comestible.ingredient.imagePath}}/> <View style={styles.buttomContainer}> <FormLabel labelStyle={{fontFamily: 'fira', fontWeight: '300'}}>Mængde:</FormLabel><FormInput style={{height: 40}} inputStyle={{fontFamily: 'fira', fontWeight: '300'}} value={this.state.comestible.amount} onChangeText={text => this.setState({comestible: {...this.state.comestible, amount: text}})} placeholder="Mængde" /> <View style={styles.buttonContainer}> <DatePicker style={{width: 200}} date={this.state.comestible.expiryDate} value={this.state.comestible.expiryDate} mode="date" placeholder="Vælg udløbsdato" format="DD/MM/YYYY" minDate="01-05-2017" maxDate="10-06-2020" confirmBtnText="Confirm" cancelBtnText="Cancel" customStyles={{ dateIcon: { position: 'absolute', left: 0, top: 4, marginLeft: 0 } }} onDateChange={date => this.setState({comestible: {...this.state.comestible, expiryDate: date}})} /> </View> <Text>{"\n"}</Text> <View style={styles.buttonContainer}> <Button fontFamily={'fira'} title="OK" backgroundColor="#3B9BFF" onPress={() => this.updateComestible() .then(() => this.props.navigation.state.params.onBack()) .then(() => this.props.navigation.goBack())}/> <Text>{"\n"}</Text> <Button fontFamily={'fira'} title="Slet" backgroundColor="#ff0000" onPress={() => { Alert.alert( 'Slet ' + this.state.comestible.ingredient.name, `Er du sikker på at du vil slette ${this.state.comestible.ingredient.name.toLowerCase()}? Handlingen kan ikke fortrydes`, [{text: 'Annuller'}, { text: 'OK', onPress: () => { this.deleteComestible(this.state.comestible.id) .then(() => this.props.navigation.state.params.onBack()) .then(() => this.props.navigation.goBack()) } }] ); } } /> </View> </View> </View> </KeyboardAvoidingView> </ScrollView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#ffffff" }, upperContainer: { flex: 1, }, buttomContainer: { flex: 1, }, buttonContainer: { flexDirection: 'row', justifyContent: 'center', } }); export default Comestible;<file_sep>/README.md ## Main Goals - Oprette en vare - Oprette en opskrift - Se opskrifter ud fra varene i køleskabet ## Test Scenarios - Kan du logge ind - Kan du tilføje ost til dit køleskab? - Kan du redigere udløbsdatoen på ostene? - Kan du se hvor mange oste du har tilføjet? - Kan du se udløbsdatoen på dine varer? - Kan du oprette en 0.5 l vand? - Kan du finde en opskrift på pandekage? - Kan du slette en vare? - Kan du finde en Faxe Kondi vha. stregkoden på dåsen? - Kan du sortere efter udløbsdato? - Kan du sortere alfabetisk? - Hvad gør den blå bestik knap? <file_sep>/backend/src/main/java/jsonMapper/IngredientJson.java package jsonMapper; import entity.Ingredient; public class IngredientJson { private String name; private String imagePath; private String barcode; public IngredientJson(Ingredient ingredient) { name = ingredient.getName(); imagePath = ingredient.getImagePath(); barcode = ingredient.getBarcode(); } }
d895f392733b1fabafbe78ac04c85c3e15d3cf9b
[ "JavaScript", "Java", "Markdown" ]
28
Java
JoacimV/FridgeBook
f7b64009a341ba6971fc780c4cc41e1dbaa201a0
bc5d57c28b66e6405dc13bd1b68ac98eaa03ea8e
refs/heads/master
<file_sep>import { ref } from "@vue/reactivity"; import { porjectAuthentication } from '../firebase/config' const error = ref( null) const login = async ( email, password ) => { error.value = null try{ const response = await porjectAuthentication.signInWithEmailAndPassword( email, password ) if(!response){ throw new Error ( 'Invalid login') } return response } catch( err){ error.value = err.message } } const useLogin = () => { return { error, login } } export default useLogin
449a009429b8177f7347314c70bee96336a19144
[ "JavaScript" ]
1
JavaScript
herbnspice/realtme-serverless-chat
3a775e119b3df6790f818a266852ec0161e5931d
b9cee6d5af593e0c19bcf326bfa538e5313763b1
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Specialized; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using Mannex; using Mannex.Threading.Tasks; using Mannex.Web; using Newtonsoft.Json; using System.Configuration; namespace Elmah.Io { public class ErrorLog : Elmah.ErrorLog, IErrorLog { private readonly string _logId; private readonly Uri _url = new Uri("https://elmahio.azurewebsites.net/"); private readonly IWebClient _webClient; public ErrorLog(Guid logId) { _logId = logId.ToString(); _webClient = new DotNetWebClientProxy(); } public ErrorLog(IDictionary config) : this(config, new DotNetWebClientProxy()) { } public ErrorLog(IDictionary config, IWebClient webClient) { if (config == null) { throw new ArgumentNullException("config"); } if (!config.Contains("LogId") && !config.Contains("LogIdKey")) { throw new ApplicationException("Missing LogId or LogIdKey. Please specify a LogId in your web.config like this: <errorLog type=\"Elmah.Io.ErrorLog, Elmah.Io\" LogId=\"98895825-2516-43DE-B514-FFB39EA89A65\" /> or using AppSettings: <errorLog type=\"Elmah.Io.ErrorLog, Elmah.Io\" LogIdKey=\"MyAppSettingsKey\" /> where MyAppSettingsKey points to a AppSettings with the key 'MyAPpSettingsKey' and value equal LogId."); } if (config.Contains("LogId")) { Guid result; if (!Guid.TryParse(config["LogId"].ToString(), out result)) { throw new ApplicationException("Invalid LogId. Please specify a valid LogId in your web.config like this: <errorLog type=\"Elmah.Io.ErrorLog, Elmah.Io\" LogId=\"98895825-2516-43DE-B514-FFB39EA89A65\" />"); } _logId = result.ToString(); } else { var appSettingsKey = config["LogIdKey"].ToString(); var value = ConfigurationManager.AppSettings.Get(appSettingsKey); if (value == null) { throw new ApplicationException("You are trying to reference a AppSetting which is not found (key = '" + appSettingsKey + "'"); } Guid result; if (!Guid.TryParse(value, out result)) { throw new ApplicationException("Invalid LogId. Please specify a valid LogId in your web.config like this: <appSettings><add key=\"" + appSettingsKey + "\" value=\"98895825-2516-43DE-B514-FFB39EA89A65\" />"); } _logId = result.ToString(); } if (config.Contains("Url")) { Uri uri; if (!Uri.TryCreate(config["Url"].ToString(), UriKind.Absolute, out uri)) { throw new ApplicationException("Invalid URL. Please specify a valid absolute url. In fact you don't even need to specify an url, which will make the error logger use the elmah.io backend."); } _url = new Uri(config["Url"].ToString()); } _webClient = webClient; } public override string Log(Error error) { return EndLog(BeginLog(error, null, null)); } public override IAsyncResult BeginLog(Error error, AsyncCallback asyncCallback, object asyncState) { var headers = new WebHeaderCollection { { HttpRequestHeader.ContentType, "application/x-www-form-urlencoded" } }; var xml = ErrorXml.EncodeString(error); return _webClient.Post(headers, ApiUrl(), "=" + HttpUtility.UrlEncode(xml)) .ContinueWith(t => { dynamic d = JsonConvert.DeserializeObject(t.Result); return (string)d.Id; }) .Apmize(asyncCallback, asyncState); } public override string EndLog(IAsyncResult asyncResult) { return EndImpl<string>(asyncResult); } public override IAsyncResult BeginGetError(string id, AsyncCallback asyncCallback, object asyncState) { return _webClient.Get(ApiUrl(new NameValueCollection { { "id", id } })) .ContinueWith(t => { dynamic error = JsonConvert.DeserializeObject(t.Result); return MapErrorLogEntry((string) error.Id, (string) error.ErrorXml); }) .Apmize(asyncCallback, asyncState); } public override ErrorLogEntry EndGetError(IAsyncResult asyncResult) { return EndImpl<ErrorLogEntry>(asyncResult); } public override ErrorLogEntry GetError(string id) { return EndGetError(BeginGetError(id, null, null)); } public override IAsyncResult BeginGetErrors(int pageIndex, int pageSize, IList errorEntryList, AsyncCallback asyncCallback, object asyncState) { var url = ApiUrl(new NameValueCollection { { "pageindex", pageIndex.ToInvariantString() }, { "pagesize", pageSize.ToInvariantString() }, }); var task = _webClient.Get(url).ContinueWith(t => { dynamic d = JsonConvert.DeserializeObject(t.Result); var entries = from dynamic e in (IEnumerable) d.Errors select MapErrorLogEntry((string) e.Id, (string) e.ErrorXml); foreach (var entry in entries) { errorEntryList.Add(entry); } return (int) d.Total; }); return task.Apmize(asyncCallback, asyncState); } public override int EndGetErrors(IAsyncResult asyncResult) { return EndImpl<int>(asyncResult); } public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { return EndGetErrors(BeginGetErrors(pageIndex, pageSize, errorEntryList, null, null)); } private ErrorLogEntry MapErrorLogEntry(string id, string xml) { return new ErrorLogEntry(this, id, ErrorXml.DecodeString(xml)); } Uri ApiUrl(NameValueCollection query = null) { var q = new NameValueCollection { { "logId", _logId }, query ?? new NameValueCollection() }; return new Uri(_url, "api/errors" + q.ToQueryString()); } static T EndImpl<T>(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); var task = asyncResult as Task<T>; if (task == null) throw new ArgumentException(null, "asyncResult"); return task.Result; } } }
94975ccaa9d601da2b927b4547c6769307b37e94
[ "C#" ]
1
C#
teiles/elmah.io
20942af9fae8f01c72e24f15c0a66e2391460cfd
800dcbb8ca2ecfb41d0fe5eb5c5d8952866f7386
refs/heads/master
<repo_name>startspecial/yad1<file_sep>/app/src/main/java/com/example/start/yandix/Class4CL.java package com.example.start.yandix; /** * Created by start on 12.04.2017. */ public class Class4CL { private String firstName; private String lastName; private int id4Photo; // resource public Class4CL(String fName, String lName, int res) { this.firstName = fName; lastName = lName; this.id4Photo = res; } public String getFirstName() { return firstName; } public void setFirstName(String newN) { firstName = newN; } public String getLastName() { return lastName; } public void setLastName(String newN) { lastName = newN; } public int getId4Photo() { return id4Photo; } public void setId4Photo(int newN) { id4Photo = newN; } } <file_sep>/app/src/main/java/com/example/start/yandix/ClassMyAdapter.java package com.example.start.yandix; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import org.w3c.dom.Text; import java.util.List; /** * Created by start on 12.04.2017. */ public class ClassMyAdapter extends ArrayAdapter<Class4CL> { private LayoutInflater inflater; // ???? это класс, который умеет из содержимого layout-файла создать View-элемент private int layout; private List<Class4CL> contacts; public ClassMyAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Class4CL> objects) { super(context, resource, objects); this.inflater = LayoutInflater.from(context); // context = контекст, в котором используется класс. В его роли кк правило выступает класс Activity // == типа берём ИНФЛАТЕР ОТ ТУДА, чтобы при вызове инфлатер использовался тот и записывал туда // (иначе надувать будет в этом классе адаптера, а не в активити) this.layout = resource; // РЕСУРС ДЛЯ РАЗМЕТКИ ВСЕГО ИТЕМА this.contacts = objects; // набор объектов, которые будут выводиться в ListView } /* В конструкторе StateAdapter мы получаем ресурс разметки и набор объекто и сохраняем их в отдельные переменные. Кроме того, для создания объекта View по полученному ресурсу разметки потребуется объект LayoutInflater, который также сохраняется в переменную. */ public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; // класс для сохранения(держания) данных == для оптимизации // точнее для сохранения целых вьюх из каждого итема // View view = inflater.inflate(this.layout, parent, false); // надуваю лэйаут(ЭТОГО КЛАССА, полученный из конструктора) в парент, не в корень парента //НОВАЯ ОПТИМИЗИРОВАННАЯ НАДУВАЛКА if(convertView == null) { convertView = inflater.inflate(this.layout, parent, false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); // тэг это то с чем ассоциирует + может хранить данные } else { viewHolder = (ViewHolder) convertView.getTag(); // берём, заосациированный с этим вью, тэг } /* ДОРОГОЙ ПОИСК ВЬЮХ КАЖДЫЙ РАЗ ImageView contactPhoto = (ImageView) convertView.findViewById(R.id.resPhoto); // ищу по айди именно в ЭТОМ ВЬЮ TextView fName = (TextView) convertView.findViewById(R.id.fName); TextView lName = (TextView) convertView.findViewById(R.id.lName); */ Class4CL contacsObj = contacts.get(position); // ИЗ СПИСКА List<Class4CL> достаём 1 элемент который Class4CL соответственно // а это всё-равно будет происходить каждый раз // == то есть мы сохранили и не ищем постоянно место куда заливать инфу(разметку) // , но инфу заливаем каждый раз снова viewHolder.imageView.setImageResource(contacsObj.getId4Photo()); // ВОТ ОНИ МОИ ГЕТ МЕТОДЫ viewHolder.fNameView.setText(contacsObj.getFirstName()); viewHolder.lNameView.setText(contacsObj.getLastName()); return convertView; /* ну да, короче даа это адаптер 1) был класс Class4CL, объекты которого соответственно содержат всю инфу по каждому из контактов 2) сделали cl_item.xml - скелет для отображения всей этой инфы 3) ВОТ ОН ЭТОТ САМ АДАПТЕР - берёт в конструкторе (2)РАЗМЕТКУ, берёт список List<Class4CL> всех (1)ОБДЖЕКТОВ +берёт надуватель из контекста в котором нужно надувать(==пользуется чужим надувателем, который соответственно будет надувать в чужого) а в методе работает - сперва надувает пустую (2)разметку в чужого, берёт елементы разметки, а затем присовывает инфу из (1)обджекта из списка List<Class4CL> в элементы этой разметки 4) соответственно метод потом будем вызывать с перебором всех обджектов из списка */ } private class ViewHolder { final ImageView imageView; final TextView fNameView, lNameView; ViewHolder(View view) { imageView = (ImageView) view.findViewById(R.id.resPhoto); // кстати вот да - много разных элементов на одной активити будут иметь один и тот же ид // обращаться к ним через их родительское вью +файнд по ид fNameView = (TextView) view.findViewById(R.id.fName); lNameView = (TextView) view.findViewById(R.id.lName); } } } <file_sep>/app/src/main/java/com/example/start/yandix/AsyncActivity.java package com.example.start.yandix; import android.os.AsyncTask; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; /* Чтобы использовать AsyncTask, нам надо: Создать класс, производный от AsyncTask (как правило, для этого создается внутренний класс в activity или во фрагменте) Переопределить один или несколько методов AsyncTask для выполнения некоторой работы в фоновом режиме создать объект AsyncTask и вызывать его метод execute() для начала работы */ public class AsyncActivity extends AppCompatActivity { int[] integers = null; int clicks = 0; ProgressBar indicatorBar, noAsyncBar; TextView statusView, clicksView; Button progressBtn, clicksBtn, noAsyncBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_async); integers = new int[100]; //выделил память под массив с ста числами for (int i = 0; i < 100; i++) { integers[i] = i + 1; //заполнил этот массив числами, равными их порядковому номеру в массиве + 1 } indicatorBar = (ProgressBar) findViewById(R.id.indicator); statusView = (TextView) findViewById(R.id.statusView); progressBtn = (Button) findViewById(R.id.progressBtn); progressBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new ProgressTask().execute(); } }); clicksView = (TextView) findViewById(R.id.clicksView); clicksBtn = (Button) findViewById(R.id.clicksBtn); clicksBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clicks++; clicksView.setText("CLICKS: " + clicks); } }); noAsyncBar = (ProgressBar) findViewById(R.id.noAsyncIndicator); noAsyncBtn = (Button) findViewById(R.id.noAsyncBtn); noAsyncBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { noAsyncMtd(); } }); } void noAsyncMtd() { for (int i=0; i<integers.length; i++) { noAsyncBar.setProgress(i); SystemClock.sleep(10); } } /* Так как метод doInBackground() не принимает ничего и не возвращает ничего, то в качестве его параметра используется Void... - массив Void, и в качестве возвращаемого типа - тоже Void. Эти типы соответствуют первому и третьему типам в AsyncTask<Void, Integer, Void>. Метод doInBackground() перебирает массив и при каждой итерации уведомляет систему с помощью метода publishProgress(item). Так как в нашем случае для индикации используются целые числа, то параметр item должен представлять целое число. Метод onProgressUpdate(Integer... items) получает переданное выше число и применяет его для настройки текстового поля и прогрессбара. Метод onPostExecute() выполняется после завершения задачи и в качестве параметра принимает объект, возвращаемый методом doInBackground() - то есть в данном случае объект типа Void. Чтобы сигнализировать окончание работы, здесь выводится на экран всплывающее сообщение. */ class ProgressTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { for (int i=0; i<integers.length; i++) { publishProgress(i); SystemClock.sleep(100); // МЫ НЕ ВИДИМ, НО ПРИ ПОВОРОТЕ ПРОДОЛЖАЕТ РАБОТАТЬ СО СТАРОЙ АКТИВНОСТЬЮ } return null; } @Override protected void onProgressUpdate(Integer... values) { indicatorBar.setProgress(values[0]+1); statusView.setText("STATUS: " + String.valueOf(values[0]+1)); } @Override protected void onPostExecute(Void aVoid) { Toast.makeText(getApplicationContext(), "DONE", Toast.LENGTH_LONG).show(); } } } <file_sep>/app/src/main/java/com/example/start/yandix/WebActivity.java package com.example.start.yandix; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.webkit.WebViewFragment; public class WebActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); //WebView myBrowser = (WebView) findViewById(R.id.webBrowser); ////WebView myBrowser = new WebView(this); ////setContentView(myBrowser); //myBrowser.loadUrl("http://google.com"); ////myBrowser.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8"); ////myBrowser.getSettings().setJavaScriptEnabled(true); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.webContainer, new MyWebFragment()) .commit(); } } public static class MyWebFragment extends WebViewFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View result = super.onCreateView(inflater, container, savedInstanceState); getWebView().loadUrl("http://stackoverflow.com"); // Force links and redirects to open in the WebView instead of in a browser getWebView().setWebViewClient(new WebViewClient()); return(result); } } } <file_sep>/app/src/main/java/com/example/start/yandix/CalcAct.java package com.example.start.yandix; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * Created by start on 09.04.2017. */ public class CalcAct extends AppCompatActivity { EditText wField; ListView testLV; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calc_act); wField = (EditText) findViewById(R.id.editText); wField.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { TextView rField = (TextView) findViewById(R.id.textView); rField.setText(s); } @Override public void afterTextChanged(Editable s) { } }); final String[] lvContainer = getResources().getStringArray(R.array.lvhere); testLV = (ListView) findViewById(R.id.id4LV); testLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String myResult = lvContainer[position]; wField.setText(myResult); } }); Log.d("1 (TAG)", "onCreate"); } @Override protected void onStart() { super.onStart(); Log.d("2", "onStart"); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); wField.setText(savedInstanceState.getString("myMan")); Toast myToa = Toast.makeText(this, savedInstanceState.getString("myMan"), Toast.LENGTH_LONG); myToa.show(); Log.d("3", "onSaveInstanceState"); } @Override protected void onResume() { super.onResume(); Log.d("4", "onResume"); } @Override protected void onPause() { super.onPause(); Log.d("5", "onPause"); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString("myMan", wField.getText().toString()); //super.onSaveInstanceState(outState); Log.d("6", "onSaveInstanceState"); } @Override protected void onStop() { super.onStop(); Log.d("7", "onStop"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("8", "onDestroy"); } public void numClick(View view) { wField.setText("GG"); } public void opClick(View view) { Intent checkActIntent = new Intent(this, IntentTest.class); checkActIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(checkActIntent); } } <file_sep>/app/src/main/java/com/example/start/yandix/FragmentClass.java package com.example.start.yandix; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import java.util.Date; /** * Created by start on 14.04.2017. */ public class FragmentClass extends Fragment { private OnFragmentInteractionListener mListener; CheckBox host; private String curDate; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); //без этого не сохранится курДейт, но выводить в вью надо будет снова } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { // инфлейтер у каждой активности свой == свой инфлейтер надувает в свою активность == если // хочу вдуть в какую то активность - беру её инфлейтер и надуваю (разметку, в ВЬЮруппу-контейнер // , фолс чтобы не в корень) View view = inflater.inflate(R.layout.fragment_content, container, false); ////return view; добавим прослушку а потом вернём final CheckBox self = (CheckBox) view.findViewById(R.id.checkSelf); //final == Reason: if two methods see the same local variable, Java wants you to swear you // will not change it - final, in Java speak. Together with the absence of by-reference // parameters, this rule ensures that locals are only assigned in the method that they // belong to. Code is thus more readable final CheckBox caster = (CheckBox) view.findViewById(R.id.checkCaster); host = (CheckBox) view.findViewById(R.id.checkHost); Button button = (Button) view.findViewById(R.id.fButton); final TextView textView = (TextView) view.findViewById(R.id.fTextView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (self.isChecked()) { curDate = new Date().toString(); textView.setText(curDate); } if (caster.isChecked()) { updateDetail(); } } }); //после пересоздания активити setRetainInstance(true); сохранит текущее СОСТОЯНИЕ фрагмента, // но его вью пересоздастся -перевыводим засейвленный курДэйт if (curDate != null) { textView.setText(curDate); } return view; } interface OnFragmentInteractionListener { void onFragmentInteraction(String link); } @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (OnFragmentInteractionListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " должен реализовывать интерфейс OnFragmentInteractionListener"); } } public void updateDetail() { // генерируем некоторые данные curDate = new Date().toString(); // Посылаем данные Activity ЧЕРЕЗ mListener!! mListener.onFragmentInteraction(curDate); } //Фрагменты не могут напрямую взаимодействовать между собой. Для этого надо обращаться // к контексту, в качестве которого выступает класс Activity. Для обращения к activity, // как правило, создается вложенный интерфейс. В данном случае он называется // OnFragmentInteractionListener с одним методом. /* Но чтобы взаимодействовать с другим фрагментом через activity, нам надо прикрепить текущий фрагмент к activity. Для этого в классе фрагмента определен метод onAttach(Context context). В нем происходит установка объекта OnFragmentInteractionListener: */ //РОЛЬ ВТОРОГО(ПРИНИМАЮЩЕГО) ФРАГМЕНТА // обновление текстового поля public void setText(String item) { if (host.isChecked()) { TextView view = (TextView) getView().findViewById(R.id.fTextView); view.setText(item); } } }
1819a8409db5b70563433eba208f304b50d8c120
[ "Java" ]
6
Java
startspecial/yad1
4ee32f91007f545875569c186e23b12add7e382b
89ed684d25ee25b7da56bc3b1a44a678cc230dfd
refs/heads/master
<repo_name>malcolm77/PiPythonCode<file_sep>/nettest.py import os address = "192.168.1.1" ret = os.system("ping -c 3 -w 3000 " + address) if ret != 0: print "alive" <file_sep>/sunrise-sunset.py import ephem import datetime Canberra=ephem.Observer() Canberra.lat='-35.246669' Canberra.lon='149.070136' Canberra.date = datetime.datetime.now() Canberra.elevation = 605 sun = ephem.Sun() prev_sunrise = ephem.localtime(Canberra.previous_rising(sun)) prev_sunset = ephem.localtime(Canberra.previous_setting(sun)) next_sunrise = ephem.localtime(Canberra.next_rising(sun)) next_sunset = ephem.localtime(Canberra.next_setting(sun)) #print ("Test Data") #print (prev_sunset.strftime("%d/%m/%Y %H:%M:%S")) #print (next_sunrise.strftime("%d/%m/%Y %H:%M:%S")) #print ("Sunset is at " + prev_sunset.strftime("%I:%M%p %A the %d of %B ")) f = open("/var/www/html/sunrise.html", "w") f.write("<h1 style=color:White>") f.write("<table style=color:White>") f.write("<tr><td>Sunset</td>" + prev_sunset.strftime("<td>%I:%M%p</td><td>%A</td><td>%d of %B</td></tr>")) #f.write("<br>") f.write("<tr><td>Sunrise</td>" + next_sunrise.strftime("<td>%I:%M%p</td><td>%A</td><td>%d of %B</td><td></tr>")) f.write("</table>") f.write("</h1>") f.close() <file_sep>/args.py import sys print ('number of arguments:', len(sys.argv), 'arguments') print ('argument list:', str(sys.argv)) print ('turn light ',str(sys.argv[1]), ' ', str(sys.argv[2])) <file_sep>/blinkt/brightness_test.py # Pyrthon script to test / show the different brightness levels of the Pimoroni Blinkt lights import math import time from blinkt import set_pixel, show # define function for a float range def frange(start, stop, step): i = start while i < stop: yield i i += step # great loop for brightness level for i in frange(0.1, 1.0, 0.1): # use all eight lights, its in a loop, but there's no delay, so they all come on at once for x in range(0, 8): # turn on light, make it red and use options 5th parameter to set brightness set_pixel(x,0,255,0,i) show() # wait one second between brightness levels time.sleep(1.0) <file_sep>/myutils.py # from dropbox import DropboxOAuth2FlowNoRedirect import json import smtplib import os import glob import dropbox from os.path import basename from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate def send_email_attachment(email_address,subject,text,attach): fromaddr = "<EMAIL>" toaddrs = email_address print("[INFO] Emailing to {}".format(email_address)) message = 'Subject: {}\n\n{}'.format(subject, text) msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) # set attachments if attach <> 'nil': files = glob.glob(attach) print("[INFO] Number of images attached to email: {}".format(len(files))) for f in files: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) # Credentials (if needed) : EDIT THIS username = "<EMAIL>" password = "<PASSWORD>" # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() def send_email(email_address,subject,text): fromaddr = "<EMAIL>" toaddrs = email_address print("[INFO] Emailing to {}".format(email_address)) message = 'Subject: {}\n\n{}'.format(subject, text) msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) # Credentials (if needed) : EDIT THIS username = "<EMAIL>" password = "<PASSWORD>" # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() def uploadtodropbox(localfilename,dropboxfilename): # this uploads given file to dropbox client = dropbox.Dropbox("ztAk1m6GGfoAAAAAAAAAbxrjRJ4I3t35xsY8FqParQiFhtagC8nZCUahvNdSD21S") client.files_upload(open(localfilename, "rb").read(), dropboxfilename) <file_sep>/datetime.py import datetime now = datetime.datetime.now() name = now.strftime('%Y%m%d_%H%M%S.txt') print name <file_sep>/README.md use <EMAIL>:malcolm77/PiPythonCode.git to clone this repo <file_sep>/stream.py import socket import time import picamera camera = picamera.PiCamera() camera.resolution = (640,480) camera.framerate = 24 server_socket = socket.socket() server_socket.bind(('0.0.0.0',8000)) server_socket.listen(0) # to view stream from a windows PC use VLC and open # tcp/h264://192.168.1.120:8000/ # accept a single connection and make a file-like # oject out of it connection = server_socket.accept()[0].makefile('wb') try: camera.start_recording(connection, format='h264') camera.wait_recording(60) camera.stop_recording() finally: connection.close() server_socket.close() <file_sep>/utilstest.py from myutils import send_email_attachment, send_email, uploadtodropbox from os.path import basename import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('filename', help='path to file to send') args = parser.parse_args() print("localpath: "+args.filename) print("dropbox path: " + "/Temp" +"/"+basename(args.filename)) # send email with an attachment # send_email(to_email_address, subject, message, attachment(s)) # send_email_attachment('<EMAIL>','This is a test','message body',args.filename) # send email without an attachment # send_email(to_email_address, subject, message) # send_email('<EMAIL>','This is a test','message body') # upload file to dropbbox # uploadtodropbox (localfilename, dropboxfilename) # uploadtodropbox ('/home/pi/python/utils.py','/Temp/utils.py')<file_sep>/test-random.py import random n = random.randrange(1,15) print(n) <file_sep>/tempature.py import subprocess tempature = subprocess.Popen("echo $((`cat /sys/class/thermal/thermal_zone0/temp|cut -c1-2`)).$((`cat /sys/class/thermal/thermal_zone0/temp|cut -c3-5`))", shell=True, stdout=subprocess.PIPE).stdout.read() lightval = subprocess.Popen("echo $((`cat /sys/class/thermal/thermal_zone0/temp`/10000))", shell=True, stdout=subprocess.PIPE).stdout.read() print "temp is :", tempature print "temp value is :", lightval <file_sep>/timelapse/capture.sh #!/bin/bash ########################################## # # Take a series of timelapse images # # --timeout : Time (in ms) before takes picture and shuts down (if not specified, set to 5s) # --timelapse : Timelapse mode. Takes a picture every <t>ms. %d == frame number (Try: -o img_%04d.jpg) # --rotation : Set image rotation (0, 90, 180, or 270) # --output : Output filename <filename> (to write to stdout, use '-o -'). If not specified, no file is saved # # raspistill -t 30000 -tl 2000 -o image%04d.jpg # Note the %04d in the output filename: this indicates the point in the filename where you want a frame count number to appear. # So, for example, the command above will produce a capture every two seconds (2000ms), # over a total period of 30 seconds (30000ms), # named image0001.jpg, image0002.jpg, and so on, through to image0015.jpg. # # 8 hours is 28800000 milliseconds (5 zeros) # 10 minutes is 600000 milliseconds (5 zeros) # 1 minute is 60000 milliseconds (4 zeros) # 1 hour is 3600000 milliseconds (5 zeros) DATE=$(date +"%Y-%m-%d_%H%M") #raspistill -vf -hf -o $DATE.jpg # raspistill --timeout 28800000 --timelapse 60000 --output images/$DATE.jpg raspistill --timeout 600000 --timelapse 2000 --output images/image%08d.jpg #EOF <file_sep>/show_temp.py # import libraries import math import time import subprocess from blinkt import set_pixel, show # get actual tempature tempature = subprocess.Popen("echo $((`cat /sys/class/thermal/thermal_zone0/temp|cut -c1-2`)).$((`cat /sys/class/thermal/thermal_zone0/temp|cut -c3-5`))", shell=True, stdout=subprocess.PIPE).stdout.read() # get first number of tempature lightval = subprocess.Popen("echo $((`cat /sys/class/thermal/thermal_zone0/temp`/10000))", shell=True, stdout=subprocess.PIPE).stdout.read() # convert string to int temp = int(lightval) # turn on number of light equal to value of first digit in temp # if value/temp is above 60 make lights red instead of green # NOTE: 8 lights would equal a temp of 8 or 80 degress which is about the max temp it should be! for x in range(0, temp): if temp >= 6: set_pixel(x,255,0,0) else: set_pixel(x,0,255,0) show() time.sleep(0.1) # sleep for 5 seconds to keep lights on time.sleep(5.0) <file_sep>/blinkt/one.py # Blinkt Function Reference # The two Blinkt methods you'll most commonly use are `set_pixel` and `show`. Here's a simple example: import math import time from blinkt import set_pixel, show # set_pixel(4,0,255,0) # show() # `set_pixel` takes an optional fifth parameter; the brightness from 0.0 to 1.0. # # `set_pixel(pixel_no, red, green, blue, brightness)` # # You can also change the brightness with `set_brightness` from 0.0 to 1.0, for example: # from blinkt import set_brightness # # set_brightness(0.5) # show() set_pixel(3,255,255,0) show() # time.sleep(0.5) <file_sep>/blinkt/documentation/REFERENCE.md #Blinkt Function Reference The two Blinkt methods you'll most commonly use are `set_pixel` and `show`. Here's a simple example: ``` from blinkt import set_pixel, show set_pixel(0,255,0,0) show() ``` `set_pixel` takes an optional fifth parameter; the brightness from 0.0 to 1.0. `set_pixel(pixel_no, red, green, blue, brightness)` You can also change the brightness with `set_brightness` from 0.0 to 1.0, for example: ``` from blinkt import set_brightness set_brightness(0.5) show() ```
a94c3a8f4bb9b9789f6d3bc05bfa4bdd2deaafd4
[ "Markdown", "Python", "Shell" ]
15
Python
malcolm77/PiPythonCode
5e1991b16533a264cdec0ba06146ce20af2fce02
b23244c14cc6bfe8bfd174aedd370bfafe0b3516
refs/heads/main
<file_sep>#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <setjmp.h> #include <unistd.h> #include <fcntl.h> #include <wait.h> jmp_buf env; void handler(int signum) { fprintf(stderr, "read timeout in second child, killing both children.\n"); longjmp(env, 1); exit(1); } int main(int argc, char* argv[]) { signal(SIGALRM, handler); pid_t p[2]; int fid[2]; pipe(fid); if (argc == 1) { if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } else if (argc == 2 && argv[1][0] == '-') { if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", argv[1], NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } else if (argc == 2) { int inRed = open(argv[1], O_RDONLY); if (inRed == -1) { fprintf(stderr, "Input file does not exist !!\n"); exit(-1); } dup2(inRed, STDIN_FILENO); close(inRed); if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } else if (argc == 3 && argv[1][0] == '-') { int inRed = open(argv[1], O_RDONLY); if (inRed == -1) { fprintf(stderr, "Input file does not exist !!\n"); exit(-1); } dup2(inRed, STDIN_FILENO); close(inRed); if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", argv[1], NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } else if (argc == 3) { int inRed = open(argv[1], O_RDONLY); if (inRed == -1) { fprintf(stderr, "Input file does not exist !!\n"); exit(-1); } int outRed = creat(argv[2], 0644); dup2(inRed, STDIN_FILENO); dup2(outRed, STDOUT_FILENO); close(inRed); close(outRed); if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } else if (argc == 4) { int inRed = open(argv[2], O_RDONLY); if (inRed == -1) { fprintf(stderr, "Input file does not exist !!"); exit(-1); } int outRed = creat(argv[3], 0644); dup2(inRed, STDIN_FILENO); dup2(outRed, STDOUT_FILENO); close(inRed); close(outRed); if ((p[0] = fork()) == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); fprintf(stderr, "Child 1 process id : %d\n", getpid()); execl("q2", "q2", argv[1], NULL); exit(0); } if ((p[1] = fork()) == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); fprintf(stderr, "Child 2 process id : %d\n", getpid()); execl("q3", "q3", NULL); exit(0); } } if (setjmp(env) != 0) { kill(p[0], SIGTERM); kill(p[1], SIGTERM); wait(NULL); wait(NULL); exit(1); } alarm(15); close(fid[1]); close(fid[0]); wait(NULL); wait(NULL); fprintf(stderr, "Normal children exit.\n"); alarm(0); exit(0); }<file_sep>/* Main program for the virtual memory project. Make all of your modifications to this file. You may add or rearrange any code or data as you need. The header files page_table.h and disk.h explain how to use the page table and disk interfaces. */ #include "page_table.h" #include "disk.h" #include "program.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> //This variable is for accessing the page table. static int i = 0; //This variable is to determine the page replacement policy for the program. static int mode = -1; //A variable to store the total number of page faults. static int pageFaults = 0; //An array to implement the Second Chance Page replacement policy. static int* arr = 0; void page_fault_handler(struct page_table* pt, int page) { int j = 0; //We get the total number of frames and pages. int tframes = page_table_get_nframes(pt); int tpages = page_table_get_npages(pt); //Temporary variabe to store the frame number and bit. int tempf = 0; int tempb = 0; //Random page replacement policy. if (mode == 0) { //Get a random integer within 0 to max number of frames. int r = lrand48() % tframes; //We loop through the page table to determine if there is another page which is mapped to the particular frame number which we generated randomly. for (j = 0; j < tpages; j++) { page_table_get_entry(pt, j, &tempf, &tempb); //If we find one then we remove the mapping. if (tempf == r && tempb != 0) { page_table_set_entry(pt, j, r, 0); break; } } //Here we set it with the current page which is requested. page_table_set_entry(pt, page, r, PROT_READ | PROT_WRITE); //Increment the number of page faults. pageFaults++; } //FIFO page replacement policy. else if (mode == 1) { //The variable i basically keeps a track of where was the last page replacement done. We start from the top of the page table, ie. index 0 //and move one step at a time till the last frame and then in a circular fashion point to the 0th index again, hence acting like a circular array. //Here we loop through the entire page table to check if any other page is mapped to the frame pointed by the i variable. for (j = 0; j < tpages; j++) { page_table_get_entry(pt, j, &tempf, &tempb); //If we find any such page we remove it, ie. set permission bit to 0. if (tempf == i && tempb != 0) { page_table_set_entry(pt, j, i, 0); break; } } //We set the new page. page_table_set_entry(pt, page, i, PROT_READ | PROT_WRITE); //Increment the page fault counter. pageFaults++; //Increment the index variable in a circular fashion. i = (i + 1) % tframes; } //This is the Second Chance page replacement policy. Here we have an array which contains 0 or 1 depending on if the page was replaced recently or not. //If the page to be replaced has this bit = 1 , it means it was replaced recently. So we set it to 0 and move to the next frame in a circular fashion. If this bit is = 0 then we replace it. else if (mode == 2) { int k = 0; //We loop through the page table for a maximum of 2 times the total number of frames. for (k = 0; k < tframes * 2; k++) { //If the recent access bit is 1, then we make it 0 and move to next. if (arr[i] == 1) { arr[i] = 0; i = (i + 1) % tframes; } //Otherwise we replace the page as done before. else { for (j = 0; j < tpages; j++) { page_table_get_entry(pt, j, &tempf, &tempb); if (tempf == i && tempb != 0) { page_table_set_entry(pt, j, i, 0); break; } } page_table_set_entry(pt, page, i, PROT_READ | PROT_WRITE); pageFaults++; //While replacing we assign the recent access bit to be 1, which denotes that this frame was replaced recently. arr[i] = 1; i = (i + 1) % tframes; break; } } } //If we face some kind oof error during runtime. else { printf("Encountered an error. Plz try again."); exit(1); } return; } int main( int argc, char *argv[] ) { if(argc!=5) { printf("use: virtmem <npages> <nframes> <rand|fifo|custom> <sort|scan|focus>\n"); return 1; } int npages = atoi(argv[1]); int nframes = atoi(argv[2]); const char *program = argv[4]; // //Array allcation for the implementation of Second Chance Page Replacement policy. arr = (int*)calloc(nframes, sizeof(int)); //Assign the global variable according to the selected mode. if (strcmp(argv[3], "rand") == 0) mode = 0; else if (strcmp(argv[3], "fifo") == 0) mode = 1; else if (strcmp(argv[3], "custom") == 0) mode = 2; // struct disk *disk = disk_open("myvirtualdisk",npages); if(!disk) { fprintf(stderr,"couldn't create virtual disk: %s\n",strerror(errno)); return 1; } struct page_table *pt = page_table_create( npages, nframes, page_fault_handler ); if(!pt) { fprintf(stderr,"couldn't create page table: %s\n",strerror(errno)); return 1; } char *virtmem = page_table_get_virtmem(pt); //char *physmem = page_table_get_physmem(pt); if(!strcmp(program,"sort")) { sort_program(virtmem,npages*PAGE_SIZE); } else if(!strcmp(program,"scan")) { scan_program(virtmem,npages*PAGE_SIZE); } else if(!strcmp(program,"focus")) { focus_program(virtmem,npages*PAGE_SIZE); } else { fprintf(stderr,"unknown program: %s\n",argv[3]); } // //We print the total number of page faults encountered during the execution. printf("\nPage Faults : %d\n", pageFaults); // page_table_delete(pt); disk_close(disk); return 0; } <file_sep>all: webserver webserver_pool: webserver_pool.o tcp.o request.o gcc webserver_pool.o tcp.o request.o -o webserver_pool -g -lpthread webserver_pool.o: webserver_pool.c gcc -Wall -g -c webserver_pool.c -o webserver_pool.o webserver_dynamic: webserver_dynamic.o tcp.o request.o gcc webserver_dynamic.o tcp.o request.o -o webserver_dynamic -g -lpthread webserver_dynamic.o: webserver_dynamic.c gcc -Wall -g -c webserver_dynamic.c -o webserver_dynamic.o webserver: webserver.o tcp.o request.o gcc webserver.o tcp.o request.o -o webserver -g -lpthread webserver.o: webserver.c gcc -Wall -g -c webserver.c -o webserver.o tcp.o: tcp.c tcp.h gcc -Wall -g -c tcp.c -o tcp.o request.o: request.c request.h gcc -Wall -g -c request.c -o request.o clean_pool: rm -f webserver_pool.o webserver_pool clean_dynamic: rm -f webserver_dynamic.o webserver_dynamic clean: rm -f webserver.o webserver<file_sep>#include <pthread.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <ctype.h> void print_message_function( void *ptr ); void main() { pthread_t thread1, thread2; char *message1 = "Hello"; char *message2 = "World"; pthread_create(&thread1, NULL, (void *) &print_message_function, (void *) message1); pthread_create(&thread2, NULL, (void *) &print_message_function, (void *) message2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); exit(0); } void print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf("%s\n", message); pthread_exit(0); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> //This is the total number of vvalues the writer function will enter. #define MAXCOUNT 5 //These are the time in microsecond for which each thread will sleep in between their various statemest so that the other threads have the chance to execute in between. #define WRITER1 1000000 #define READER1 1000000 #define READER2 1000000 #define READER3 1000000 #define READER4 1000000 //First of all we define a data structure for the proper functioning of lock. typedef struct { //The mutex lock variable, which acts as the lock. pthread_mutex_t *mut; //Number of writers ready to write. int writers; //Number of readers ready to read. int readers; //Number of threads waiting for their turn. int waiting; //The condition variables which determine the open and close of locks. pthread_cond_t *writeOK, *readOK; } rwl; //We will get to know what each of these functions do when we reach their bodies. rwl *initlock (void); void readlock (rwl *lock, int d); void writelock (rwl *lock, int d); void readunlock (rwl *lock); void writeunlock (rwl *lock); void deletelock (rwl *lock); //A data structure which stores the process id of the reader and writer processes, the time for which each process sleeps, and the lock. Variables of this datatype is passed as argument when the thread functions are called. typedef struct { rwl *lock; int id; long delay; } rwargs; rwargs *newRWargs (rwl *l, int i, long d); void *reader (void *args); void *writer (void *args); //The global data variable which is updated by the writer and read by the readers. static int data = 1; int main (){ //First we assign 5 thereads for each process, 1 writer and 4 readers. pthread_t r1, r2, r3, r4, w1; //Now we create the variables which contain information about the processes and the lock which are passed as arguments. rwargs *a1, *a2, *a3, *a4, *a5; //We create and initialise the lock variable. rwl *lock; lock = initlock (); //In the following lines we initialise each process variable and start a thread for each of the processes. We pass the process variable as arguments to the reader and writer functions. a1 = newRWargs (lock, 1, WRITER1); pthread_create (&w1, NULL, writer, a1); a2 = newRWargs (lock, 1, READER1); pthread_create (&r1, NULL, reader, a2); a3 = newRWargs (lock, 2, READER2); pthread_create (&r2, NULL, reader, a3); a4 = newRWargs (lock, 3, READER3); pthread_create (&r3, NULL, reader, a4); a5 = newRWargs (lock, 4, READER4); pthread_create (&r4, NULL, reader, a5); //Here we wait for the completion of all the processes. pthread_join (w1, NULL); pthread_join (r1, NULL); pthread_join (r2, NULL); pthread_join (r3, NULL); pthread_join (r4, NULL); //We free up the memory since we no longer need anything. free (a1); free (a2); free (a3); free (a4); free (a5); return 0; } //This function initialises the process variable. rwargs *newRWargs (rwl *l, int i, long d) { rwargs *args; //Allocate space for the variable. args = (rwargs *)malloc (sizeof (rwargs)); //If unsuccessful return nothing. if (args == NULL) return (NULL); //Assign values. args->lock = l; args->id = i; args->delay = d; return (args); } //This function is executed by the reader threads to read the value. void *reader (void *args) { rwargs *a; int d; a = (rwargs *)args; do { //First of all the reader invokes the funtion to lock the mutex. readlock (a->lock, a->id); //Reads the data. d = data; //Sleeps. usleep (a->delay); //Invokes the funtion to unlock the lock. readunlock (a->lock); printf ("Reader %d : Data = %d\n", a->id, d); usleep (a->delay); //The loop exits when the writers has finished writing and no more values will be entered. } while (d != 0); printf ("Reader %d: Finished.\n", a->id); return (NULL); } //This is the writer function to change the data value. void *writer (void *args) { rwargs *a; int i; a = (rwargs *)args; //This loop will run MAXCOUNT number of times. for (i = 2; i < MAXCOUNT; i++) { //It invokes the function to aquire the lock. writelock (a->lock, a->id); //Changes the data. data = i; //Sleeps. usleep (a->delay); //Releases the lock. writeunlock (a->lock); printf ("Writer %d: Wrote %d\n", a->id, i); usleep (a->delay); } printf ("Writer %d: Finishing...\n", a->id); //Gets the lock for one final entry. writelock (a->lock, a->id); //Enters the terminating value. data = 0; //Invokes the function to release the mutex lock. writeunlock (a->lock); printf ("Writer %d: Finished.\n", a->id); return (NULL); } //This function initialises the mutex lock vaiable. rwl *initlock (void){ rwl *lock; //Allocate memory for the data structure. lock = (rwl *)malloc (sizeof (rwl)); //Return if unseccessfull. if (lock == NULL) return (NULL); //Allocate memory for the mutex variable. lock->mut = (pthread_mutex_t *) malloc (sizeof(pthread_mutex_t)); //Free the previously allocated memory and return if unsucessful. if (lock->mut == NULL){ free (lock); return (NULL); } //Allocate memory for the writer condition variable. lock->writeOK = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); //Free the previously allocated memory and return if unsucessful. if (lock->writeOK == NULL){ free (lock->mut); free (lock); return (NULL); } //Allocate memory for the reader condition variable. lock->readOK = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); //Free the previously allocated memory and return if unsucessful. if (lock->writeOK == NULL){ free (lock->mut); free (lock->writeOK); free (lock); return (NULL); } //Initialise the variables with default values. pthread_mutex_init (lock->mut, NULL); pthread_cond_init (lock->writeOK, NULL); pthread_cond_init (lock->readOK, NULL); lock->readers = 0; lock->writers = 0; lock->waiting = 0; return (lock); } //This function is called before the reader thread reads the value. void readlock (rwl *lock, int d) { //It aquires the lock. pthread_mutex_lock (lock->mut); //If there are no writer writing or no thread waiting then run this loop. if (lock->writers || lock->waiting) { do { printf ("reader %d blocked.\n", d); //Here the thread will release the lock and wait on the condition variavle, ie. the readOK variable. pthread_cond_wait (lock->readOK, lock->mut); printf ("reader %d unblocked.\n", d); } while (lock->writers); } //Increments the variable which stores the number of readers currently reading the data. lock->readers++; //Releases the lock. pthread_mutex_unlock (lock->mut); return; } //This function is invoked before the writer starts to edit the value. void writelock (rwl *lock, int d) { //Firstly it aquires the lock. pthread_mutex_lock (lock->mut); //Increments the number of threads waiting. lock->waiting++; //If there are are no readers or writers available then this loop is executed. while (lock->readers || lock->writers) { printf ("writer %d blocked.\n", d); //Here the thread will release the lock and wait on the condition variable, ie. the writeOK variable. pthread_cond_wait (lock->writeOK, lock->mut); printf ("writer %d unblocked.\n", d); } //Now it will decrement the number of processes waiting lock->waiting--; //Now the writer can do its intended job and so the number of writers currently working is incremented. lock->writers++; //The lock is released. pthread_mutex_unlock (lock->mut); return; } //This function is called after each reader is done reading the value. void readunlock (rwl *lock) { //It aquires the lock. pthread_mutex_lock (lock->mut); //Decrements the variable which stores the number of readers currently reading. lock->readers--; //It sends a signal to the writer thread. pthread_cond_signal (lock->writeOK); //It realeses the lock. pthread_mutex_unlock (lock->mut); } //This function is called after the writer is done editing the global data variable. void writeunlock (rwl *lock) { //It invokes the function to aquire the lock. pthread_mutex_lock (lock->mut); //Decrements the variable which stores the number of writers currently writing. lock->writers--; //This function is used to signal all the other threads, ie. all the other reader threads. Instead of using the broadcast function we can simply use 4 signal function one by one to signal all the readers individually. //pthread_cond_broadcast (lock->readOK); pthread_cond_signal(lock->readOK); pthread_cond_signal(lock->readOK); pthread_cond_signal(lock->readOK); pthread_cond_signal(lock->readOK); //We release the mutex lock. pthread_mutex_unlock (lock->mut); } //Before exiting the program this funtion frees up the memory so that it can be used for other purposes. void deletelock (rwl *lock) { pthread_mutex_destroy (lock->mut); pthread_cond_destroy (lock->readOK); pthread_cond_destroy (lock->writeOK); free (lock); return; } <file_sep># CS232_Operating-Systems-Lab 4th Semester assignments for the course Operating Systems Lab. <file_sep># include<stdio.h> int main(int argc, char* argv[]) { if (argc == 1) { return 0; } int i, f = 0; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') { printf("%s ", argv[i]); f = 1; } } if (f == 1) { printf("%c", '\n'); } return 0; }<file_sep># include<stdio.h> # include<stdlib.h> # include<fcntl.h> # include<unistd.h> # include<wait.h> int main(int argc, char* argv[]) { if (argc < 3) { fprintf(stderr, "Argument is missing !!\n"); exit(1); } int i; pid_t pid[2]; int fid[2]; pipe(fid); int inRed = open(argv[1], O_RDONLY); int outRed = creat(argv[2], 0644); if (inRed == -1) { fprintf(stderr, "Input file does not exist !!"); exit(-1); } dup2(inRed, STDIN_FILENO); dup2(outRed, STDOUT_FILENO); close(inRed); close(outRed); if (fork() == 0) { dup2(fid[1], STDOUT_FILENO); close(fid[1]); execl("q2", "q2", NULL); exit(0); } if (fork() == 0) { close(fid[1]); dup2(fid[0], STDIN_FILENO); close(fid[0]); execl("q3", "q3", NULL); exit(0); } close(fid[1]); close(fid[0]); int status; wait(&status); wait(&status); exit(0); }<file_sep>#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> void sig_handler(int signum) { if (signum == SIGTERM) { fprintf(stderr, "I've been killed"); exit(0); } if (signum == SIGPIPE) { fprintf(stderr, "I've been killed because my pipe reader died!"); exit(2); } } int main(void) { signal(SIGPIPE, sig_handler); signal(SIGTERM, sig_handler); char c[BUFSIZ] = { 0 }; int n = read(STDIN_FILENO, c, BUFSIZ); int i = 0; for (i = 0; i < n; i++) { //printf("%c", c[i]); if (c[i] <= 'z' && c[i] >= 'a') { c[i] -= 'a' - 'A'; } else if (c[i] <= 'Z' && c[i] >= 'A') { c[i] += 'a' - 'A'; } } write(STDOUT_FILENO, c, n); exit(0); }<file_sep>#include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #define MAXARG 10 #define MAXLEN 50 #define MAXCOL 45 #define MAXPATH 50 void openHelp() { printf("\n\tWELCOME TO MY SHELL HELP" "\n\tBy <NAME>, 4th Sem, 1901200" "\n\tList of Commands supported:" "\n\t>exit" "\n\t>cd" "\n\t>pwd" "\n\t>source" "\n\t>echo" "\n\t>help" "\n\t>all other general commands available in UNIX shell" "\n\t>Max 2 pipes are allowed." "\n\t>Improper spaces are handled."); return; } int ownCmd(char** cmd1) { int N = 6, i, p = -1; char* ListOfCmds[N]; char *username; char path[MAXPATH]; char *echo; int file; ListOfCmds[0] = "exit"; ListOfCmds[1] = "cd"; ListOfCmds[2] = "pwd"; ListOfCmds[3] = "source"; ListOfCmds[4] = "echo"; ListOfCmds[5] = "help"; for (i = 0; i < N; i++) { if (strcmp(cmd1[0], ListOfCmds[i]) == 0) { p = i; break; } } switch (p) { case 0: printf("\nGoodbye\n"); exit(0); case 1: chdir(cmd1[1]); return 1; case 2: getcwd(path, MAXPATH); printf("%s", path); return 1; case 3: file = open(cmd1[1], O_RDONLY); dup2(file, STDIN_FILENO); return 1; case 4: echo = cmd1[1]; printf("%s",echo); return 1; case 5: openHelp(); return 1; default: break; } return 0; } void executeBack(char **cmd1){ if(ownCmd(cmd1)) return; pid_t p1; p1 = fork(); if(p1 == -1){ perror("Error while forking."); return; } else if(p1 == 0){ if (execvp(cmd1[0], cmd1) < 0){ perror("\nCould not execute command.."); } exit(0); } else{ printf("!this!"); return; } } void execute1(char** cmd1){ if(ownCmd(cmd1)) return; pid_t p1; p1 = fork(); if(p1 == -1){ perror("Error while forking."); return; } else if(p1 == 0){ if (execvp(cmd1[0], cmd1) < 0){ perror("\nCould not execute command.."); } exit(0); } else{ wait(NULL); return; } } void checkSymExecute(char **cmd){ int i = 0; int a = 0,p = 0; char *temp; printf("?Some0?"); while(cmd[i][0] == '\0'){ if(cmd[i][0] == '&'){ a = 1; printf("?Some1?"); break; } if(cmd[i][0] == '<'){ p = -1; printf("?Some2?"); break; } if(cmd[i][0] == '>'){ p = 1; printf("?Some3?"); break; } } //if(a == 1){ printf("?Some4?"); temp = strsep(cmd, "&"); executeBack(&temp); return; //} //execute1(cmd); return; } void execute2(char** cmd1, char** cmd2){ int pipe1[2]; pid_t p1, p2; if (pipe(pipe1) < 0) { printf("\nPipe could not be initialized"); return; } p1 = fork(); if (p1 < 0) { perror("\nCould not fork"); return; } if (p1 == 0) { close(pipe1[0]); dup2(pipe1[1], STDOUT_FILENO); close(pipe1[1]); if (execvp(cmd1[0], cmd1) < 0) { printf("\nCould not execute command 1.."); exit(0); } } else{ p2 = fork(); if (p2 < 0) { printf("\nCould not fork"); return; } if (p2 == 0) { close(pipe1[1]); dup2(pipe1[0], STDIN_FILENO); close(pipe1[0]); if (execvp(cmd2[0], cmd2) < 0) { printf("\nCould not execute command 2.."); exit(0); } } else { wait(NULL); wait(NULL); } } } void execute3(char** cmd1, char** cmd2, char** cmd3){ int pipe1[2]; int pipe2[2]; if(pipe(pipe1) < 0 || pipe(pipe2) < 0){ perror("\nPipes could not be initialized"); return; } pid_t p1, p2, p3; p1 = fork(); if (p1 < 0) { printf("\nCould not fork"); return; } if (p1 == 0) { close(pipe1[0]); close(pipe2[0]); close(pipe2[1]); dup2(pipe1[1], STDOUT_FILENO); close(pipe1[1]); if (execvp(cmd1[0], cmd1) < 0) { perror("\nCould not execute command 1.."); exit(0); } } else { p2 = fork(); if (p2 < 0) { printf("\nCould not fork"); return; } if (p2 == 0) { close(pipe1[1]); close(pipe2[0]); dup2(pipe1[0], STDIN_FILENO); dup2(pipe2[1], STDOUT_FILENO); close(pipe1[0]); close(pipe2[1]); if (execvp(cmd2[0], cmd2) < 0) { printf("\nCould not execute command 2.."); exit(0); } } else{ p3 = fork(); if(p3 < 0){ printf("\nCould not fork"); return; } if(p3 == 0){ close(pipe1[1]); close(pipe1[0]); close(pipe2[1]); dup2(pipe2[0], STDIN_FILENO); close(pipe2[0]); if(execvp(cmd3[0], cmd3) < 0){ printf("\nCould not execute command 3.."); exit(0); } } else{ wait(NULL); wait(NULL); wait(NULL); } } } } void initialise(){ printf("This is the starting. Enter help to get help."); } char *readLine(void){ char *line = NULL; ssize_t bufsize = 0; int i = getline(&line, &bufsize, stdin); if (i == -1){ if (feof(stdin)) { exit(EXIT_SUCCESS); } else { perror("Readline Error."); exit(EXIT_FAILURE); } } line[i - 1] = '\0'; return line; } int parseCmd(char *str, char **cmd){ int i; for (i = 0; i < MAXARG; i++) { cmd[i] = strsep(&str, " "); if (cmd[i] == NULL) break; if (strlen(cmd[i]) == 0) i--; } } int pipeParser(char **line, char **cmd1, char **cmd2, char **cmd3){ char* pipedArg[3] = {NULL}; int pipeNo = 0, i; for(i = 0; i < 3; i++){ pipedArg[i] = strsep(line, "|"); if (pipedArg[i] == NULL){ pipeNo = i; break; } } parseCmd(pipedArg[0], cmd1); parseCmd(pipedArg[1], cmd2); parseCmd(pipedArg[2], cmd3); return pipeNo; } int sColParser(char *line, char **cmd1Raw, char **cmd2Raw){ *cmd1Raw = strsep(&line, ";"); *cmd2Raw = strsep(&line, ";"); if(*cmd2Raw == NULL) return 1; return 2; } void controller(void) { char *line; char *cmd1Raw[MAXCOL] = {NULL}; char *cmd2Raw[MAXCOL] = {NULL}; char *cmd1[MAXLEN] = {NULL}; char *cmd2[MAXLEN] = {NULL}; char *cmd3[MAXLEN] = {NULL}; int status; int m, n; initialise(); while(1){ printf("\n>>> "); line = readLine(); m = sColParser(line, cmd1Raw, cmd2Raw); n = pipeParser(cmd1Raw, cmd1, cmd2, cmd3); if(n == 1) //execute1(cmd1); checkSymExecute(cmd1); if(n == 2) execute2(cmd1, cmd2); if(n == 3) execute3(cmd1, cmd2, cmd3); if(m == 2){ n = pipeParser(cmd2Raw, cmd1, cmd2, cmd3); if(n == 1) execute1(cmd1); if(n == 2) execute2(cmd1, cmd2); if(n == 3) execute3(cmd1, cmd2, cmd3); } } } int main(){ controller(); return 0; } <file_sep>/* This is the main program for the simple webserver. Your job is to modify it to take additional command line arguments to specify the number of threads and scheduling mode, and then, using a pthread monitor, add support for a thread pool. All of your changes should be made to this file, with the possible exception that you may add items to struct request in request.h */ #include <pthread.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <sys/stat.h> #include "tcp.h" #include "request.h" //The maximum number of requests that can be put in a queue at a time. #define ALEN 10 //The mutex lock and the condition variable. pthread_mutex_t* mut; pthread_cond_t* cond; //This is the fixed sized buffer to store all the requests. We will use this as a circular array. static struct request* requests[ALEN] = { NULL }; //Two variables to store the index of the reading and writing end of the array. int w = 0; int r = 0; void* workerThreads(void* arg) { //First we detach it so that we would not need to use the join function in the main section. pthread_detach(pthread_self()); //We recieve the scheduling mode. int* m = (int*)arg; int mode = *m; //For FCFS we simply read the requests from the tail end one by one and execute them. if (mode == 1) { while (1) { pthread_mutex_lock(mut); //Wait if the buffer is empty. while (requests[r] == NULL) pthread_cond_wait(cond, mut); struct request* req = requests[r]; //After taking out the request we clean its location in the buffer. requests[r] = NULL; //Increment the pointer in a circular fashion. r = (r + 1) % ALEN; //Signal the writer, if it was waiting and release the lock. pthread_cond_signal(cond); pthread_mutex_unlock(mut); //Handle the request. printf("webserver: got request for %s\n", req->filename); request_handle(req); printf("webserver: done sending %s\n", req->filename); request_delete(req); } } //For SFF everytime we perform a sort operation according to the file size and then pick the smallest one. else if (mode == 2) { struct stat st1, st2; off_t s1, s2; struct request* treq; while (1) { pthread_mutex_lock(mut); while (requests[r] == NULL) pthread_cond_wait(cond, mut); //Sort all the existing requests. int i, j; for (i = r; i < w - 1; i++) { for (j = r; j < w - i -1; j++) { stat(requests[j]->filename, &st1); stat(requests[j + 1]->filename, &st2); s1 = st1.st_size; s2 = st2.st_size; if (s1 > s2) { //Swap. treq = request[j]; requests[j] = requests[j + 1]; requests[j + 1] = treq; } } } //Get the request with smallest size. struct request* req = requests[r]; requests[r] = NULL; r = (r + 1) % ALEN; pthread_cond_signal(cond); pthread_mutex_unlock(mut); //Handle the request. printf("webserver: got request for %s\n", req->filename); request_handle(req); printf("webserver: done sending %s\n", req->filename); request_delete(req); } } pthread_exit(NULL); } int main(int argc, char* argv[]) { if (argc < 4) { fprintf(stderr, "use: %s <port> <no of threads> <scheduling mode, FCFS or SFF>\n", argv[0]); return 1; } if (chdir("webdocs") != 0) { fprintf(stderr, "couldn't change to webdocs directory: %s\n", strerror(errno)); return 1; } int port = atoi(argv[1]); int nthreads = atoi(argv[2]); int mode = 0; //We check if the user made any mistake or not. if(strcmp(argv[3], "FCFS") == 0) mode = 1; else if (strcmp(argv[3], "SFF") == 0) mode = 2; else { fprintf(stderr, "Please enter a valid scheduling mode, ie., FCFS or SFF.\n"); return 1; } struct tcp* master = tcp_listen(port); if (!master) { fprintf(stderr, "couldn't listen on port %d: %s\n", port, strerror(errno)); return 1; } printf("webserver: waiting for requests..\n"); //Allocate memory and initialise the mutex lock and condition variable. mut = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); if (mut == NULL) { return (NULL); } cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)); if (cond == NULL) { free(mut); return (NULL); } pthread_mutex_init(mut, NULL); pthread_cond_init(cond, NULL); //Create and initialise the worker threads. pthread_t p[nthreads]; int i = 0; for (i = 0; i < nthreads; i++) { pthread_create(&p[i], NULL, workerThreads, &mode); } while (1) { struct tcp* conn = tcp_accept(master, time(0) + 300); if (conn) { printf("webserver: got new connection.\n"); struct request* req = request_create(conn); if (req) { //Get the lock. pthread_mutex_lock(mut); //Wait if buffer already full. while (requests[w] != NULL) pthread_cond_wait(cond, mut); //Add request if not full. requests[w] = req; //Increment the index in circular manner. w = (w + 1) % ALEN; //Wake up the worker threads if asleep. pthread_cond_broadcast(cond); //Release the lock. pthread_mutex_unlock(mut); } else { tcp_close(conn); } } else { printf("webserver: shutting down because idle too long\n"); break; } } return 0; }<file_sep>#include <pthread.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include "tcp.h" #include "request.h" struct node { struct request* data; struct node* next; }; struct node* head; int size = 0; void enqueue(struct request* d) { struct node* ptr, * temp; ptr = (struct node*)malloc(sizeof(struct node)); if (ptr == NULL) { printf("\nOVERFLOW"); } else { size++; ptr->data = d; if (head == NULL) { ptr->next = NULL; head = ptr; } else { temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = ptr; ptr->next = NULL; } } } struct request* remove_fcfs() { struct node* ptr; if (head == NULL) { return NULL; } else { size--; ptr = head; head = ptr->next; return ptr->data; } } struct request* remove_sff() { if (head == NULL) { return NULL; } else { int found = 0; struct node* temp = head; while (temp->next != NULL && temp->next->next != NULL) { while (strstr(temp->next->data->filename, "thumb") != NULL) { found = 1; size--; struct node* ptr; ptr = temp->next; temp->next = ptr->next; return ptr->data; } } if (found == 0) return remove_fcfs(); } return NULL; } pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int me; void* worker() { while (1) { if (size > 0) { pthread_mutex_lock(&mutex); struct request* req; if (me == 1) req = remove_fcfs(); else req = remove_sff(); pthread_mutex_unlock(&mutex); if (req != NULL) { printf("webserver: got request for %s\n", req->filename); request_handle(req); printf("webserver: done sending %s\n", req->filename); request_delete(req); } } } return NULL; } int main(int argc, char* argv[]) { if (argc < 2) { fprintf(stderr, "use: %s <port>\n", argv[0]); return 1; } if (chdir("webdocs") != 0) { fprintf(stderr, "couldn't change to webdocs directory: %s\n", strerror(errno)); return 1; } int port = atoi(argv[1]); struct tcp* master = tcp_listen(port); if (!master) { fprintf(stderr, "couldn't listen on port %d: %s\n", port, strerror(errno)); return 1; } printf("webserver: waiting for requests..\n"); if (!strcmp(argv[3], "FCFS")) me = 1; else me = 2; pthread_t t[atoi(argv[2])]; for (int i = 0; i < atoi(argv[2]); ++i) { pthread_create(&t[i], NULL, worker, NULL); } while (1) { struct tcp* conn = tcp_accept(master, time(0) + 300); if (conn) { printf("webserver: got new connection.\n"); struct request* req = request_create(conn); if (req) { pthread_mutex_lock(&mutex); if (size <= 10) enqueue(req); else printf("server full!!!\n"); pthread_mutex_unlock(&mutex); } else tcp_close(conn); } else { printf("webserver: shutting down because idle too long\n"); break; } } return 0; }<file_sep>CSE.30341.FA17: Project 06 ========================== This is the documentation for [Project 06] of [CSE.30341.FA17]. Members ------- 1. <NAME> (<EMAIL>) 2. <NAME> (<EMAIL>) Design ------ > 1. To implement `Filesystem::debug`, you will need to load the file system > data structures and report the **superblock** and **inodes**. > > - How will you read the superblock? > - How will you traverse all the inodes? > - How will you determine all the information related to an inode? > - How will you determine all the blocks related to an inode? Response. To read the superblock, we will call read(0,data) to read the data in the first block, then cast that data pointer to the Block union. Then, we can read the superblock fields through the "Super" member. To traverse all the inodes, we will first read the number of inodes from the SuperBlock. Then, we can read the inodes by, starting at block 1, iterating through the inodes by using the Inodes[] member of the union. We will determine all the information related to an inode simply by reading the fields from the struct Inode in the Inodes array. All of the blocks related to the inode are the ones in the Inode.Direct array, as well as any in the block pointed to by the Inode.Indirect field. > 2. To implement `FileSystem::format`, you will need to write the superblock > and clear the remaining blocks in the file system. > > - What pre-condition must be true before this operation can succeed? > - What information must be written into the superblock? > - How would you clear all the remaining blocks? Response. Before the operation can succeed, the disk must not be mounted already. When formatting, the magic number, number of blocks, number of inode blocks, and number of inodes must be written. We would clear all the remaining blocks by iterating across all of the inodes and setting the Valid member to zero (i.e. false) > 3. To implement `FileSystem::mount`, you will need to prepare a filesystem > for use by reading the superblock and allocating the free block bitmap. > > - What pre-condition must be true before this operation can succeed? > - What sanity checks must you perform? > - How will you record that you mounted a disk? > - How will you determine which blocks are free? Response. Before the operation can succeed, the disk must not be mounted already. We must check the following: that the magic number is correct, that the number of blocks described by the superblock is the same as the number of blocks on the disk, that the number of inode blocks is reasonable, and that the number of inodes matches the total number of inodes that would be in that many blocks. We will record that we mounted a disk by incrementing the "Mounts" member variable in the disk. We will determine which blocks are free by scanning the inodes and seeing which blocks are pointed to by valid inodes. > 4. To implement `FileSystem::create`, you will need to locate a free inode > and save a new inode into the inode table. > > - How will you locate a free inode? > - What information would you see in a new inode? > - How will you record this new inode? Response. We will locate a free inode by performing a linear scan along the inodes and finding the first one that is free. We would see in a free inode Valid set to zero. The other fields may be garbage. We would record the new inode during create by seting Valid to 1, and setting each other field of the Inode struct to its proper value (Size, filling Direct with as many pointers as needed, and setting Indirect to a block if necessary, zero otherwise). > 5. To implement `FileSystem::remove`, you will need to locate the inode and > then free its associated blocks. > > - How will you determine if the specified inode is valid? > - How will you free the direct blocks? > - How will you free the indirect blocks? > - How will you update the inode table? Response. We will determine if the specified inode is valid by checking its Valid member. We will free the direct blocks by zeroing all of the blocks pointed to by each entry of the Direct array. We will free the indirect blocks by going to the block that is pointed to by the Indirect member, and iterating through all of the pointers it contains, zeroing the data in the blocks that each pointer points to. Finally, we can clear the data members of the inode struct and set Valid to zero. > 6. To implement `FileSystem::stat`, you will need to locate the inode and > return its size. > > - How will you determine if the specified inode is valid? > - How will you determine the inode's size? Response. We will determine if the specified inode is valid by checking the Valid member of the inode struct. We will determine the inode's size by reading the Size field of the inode struct. > 7. To implement `FileSystem::read`, you will need to locate the inode and > copy data from appropriate blocks to the user-specified data buffer. > > - How will you determine if the specified inode is valid? > - How will you determine which block to read from? > - How will you handle the offset? > - How will you copy from a block to the data buffer? Response. We will determine if the specified inode is valid by checking the Valid member of the inode struct. We will determine which block(s) to read from by finding how many blocks in the specified offset would be. If that block offset is less than the number of blocks in Direct, we can simply read from the block pointed to by that entry of Direct. Otherwise, we need to scan through the indirect block for the data pointer. Once we find the data block to read from, we will handle the offset by starting the read from (offset % BLOCK_SIZE) bytes in. We will copy from a block to the data buffer using memcpy. > 8. To implement `FileSystem::write`, you will need to locate the inode and > copy data the user-specified data buffer to data blocks in the file > system. > > - How will you determine if the specified inode is valid? > - How will you determine which block to write to? > - How will you handle the offset? > - How will you know if you need a new block? > - How will you manage allocating a new block if you need another one? > - How will you copy from a block to the data buffer? > - How will you update the inode? Response. We will determine if the specified inode is valid by checking the Valid member of the inode struct. We will determine which block(s) to write to by finding how many blocks in the specified offset would be. If that block offset is less than the number of blocks in Direct, we can simply write to the block pointed to by that entry of Direct. Otherwise, we need to scan through the indirect block for the data pointer. Once we find the data block to write to, we will handle the offset by starting the read from (offset % BLOCK_SIZE) bytes in. To allocate a new block if we need one, we will add a new pointer to the Direct array if it has room, or to the indirect block if it doesn't. We will copy from a block to the data buffer using memcpy. We will update the size field of the inode if we grew the data at all (instead of overwriting), and update the Direct array if we allocated a new direct block, and the Indirect pointer if we allocated the indirect block Errata ------ > Describe any known errors, bugs, or deviations from the requirements. Extra Credit ------------ > Describe what extra credit (if any) that you implemented. [Project 06]: https://www3.nd.edu/~pbui/teaching/cse.30341.fa17/project06.html [CSE.30341.FA17]: https://www3.nd.edu/~pbui/teaching/cse.30341.fa17/ [Google Drive]: https://drive.google.com <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> void sig_handler(int signum) { fprintf(stderr, "I've been killed\n"); exit(1); } int main(int argc, char* argv[]) { signal(SIGTERM, sig_handler); char c; int j = 0; int n = 0; if (argc == 2) { n = atoi(argv[1]); //n *= -1; if (n >= 0) { fprintf(stderr, "Invalid number in the argument !!\n"); exit(2); } while ((n != 0 && (c = getchar()) != EOF)) { putchar(c); if ((c <= 'z' && c >= 'a') || (c <= 'Z' && c >= 'A')); else { j++; } n++; } } else { while ((c = getchar()) != EOF) { putchar(c); if ((c <= 'z' && c >= 'a') || (c <= 'Z' && c >= 'A')); else { j++; } } } fprintf(stderr, "%d\n", j); exit(0); } <file_sep>There is a folder called "web_server" in lab5 in the home direcory where all the necessary files are kept. In case of single threaded webserver when we execute the given example, ie. "wget -P test1 -nd -p localhost:7090/index.html" and "wget -P test2 -nd -p localhost:7090/index.html", we observe that at a time only one of the 2 requests is processed while the other has to wait. In the modified multi-threaded webserver when we execute the same example, we observe that both requests are processed simultaneouly. Currently there is an upper limit of max 10 threads, which can be easily changed as per needs. This means currently at max 10 threads can execute simultaneously. To compile and build the dynamic webserver use "make webserver_dynamic", then to run it use "./webserver_dynamic 7200". After building and executing the dynamic server, start two new sessions and then execute the examples given, ie., "wget -P test1 -nd -p localhost:7090/index.html" and "wget -P test2 -nd -p localhost:7090/index.html". It can be seen that both requests are processed simultaneously. After the completion if we wish to delete the executable file for dynamic webserver then we may use "make clean_dynamic". Similarly we can use "make weebserver_pool"to compile and build the thread pool server. to run we use "./webserver 7200 <number of threads> <scheduling mode>", available scheduling modes are FCFS and SFF. We may use the examples as used in the dynamic thread server to test this program, or directly use the shell script given. After the completion if we wish to delete the executable file for thread pool webserver then we may use "make clean_pool". The results obtained after running the test shell script file is as follows : "Total runtime dynamic with 10 parallel requests is 107.197686303 Total runtime pool with 10 parallel requests with FCFS and 5 pool threads is (1st test) 140.746285616 Total runtime pool with 10 parallel req with SFF and 5 pool threads is (2nd test) 136.123134186".<file_sep>#include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX_PROCESS 10 #define MAX_LEN 10 typedef struct s{ char name[10]; int arr; int burst; int tat; int wait; }Process; Process table[MAX_PROCESS]; int N = 0; void ReadProcessTable(char *name){ FILE *file = fopen(name, "r"); if(file == NULL) { printf("Error opening file\n"); exit(1); } int i = 0; while( fscanf(file, "%s %d %d\n", table[i].name, &table[i].arr, &table[i].burst) != EOF ) { //printf("%s %d %d\n", table[i].name, table[i].arr, table[i].burst); i++; N++; } fclose(file); } void PrintProcessTable(){ int i; for(i = 0; i < N; i++){ printf("%s %d %d\n", table[i].name, table[i].arr, table[i].burst); } } void swap(Process *x, Process *y){ Process t = *x; *x = *y; *y = t; } void PrintStats(){ int i; float t = 0.0f, w = 0.0f; printf("\nTurnaround times: "); for(i = 0; i < N; i++){ printf("%s[%d], ", table[i].name, table[i].tat); t += table[i].tat; } printf("\nWait time: "); for(i = 0; i < N; i++){ printf("%s[%d], ", table[i].name, table[i].wait); w += table[i].wait; } printf("\n\nAverage turnaround time: %.2f\nAverage wait time: %.2f\n", t/N, w/N); } void FCFS(){ printf("-------------------------------------------------\n"); printf(" First Come First Served Scheduling\n"); printf("-------------------------------------------------\n\n"); int i, j, time = 0; for(i = 0; i < N; i++){ for(j = 0; j < N - 1; j++){ if(table[j].arr > table[j + 1].arr) swap(&table[j], &table[j + 1]); } } for(i = 0; i < N; i++){ printf("[%d - %d] %s running\n", time, time + table[i].burst, table[i].name); time += table[i].burst; table[i].tat = time - table[i].arr; table[i].wait = table[i].tat - table[i].burst; } PrintStats(); } void RR(int q){ printf("-------------------------------------------------\n"); printf(" Round Robin Scheduling\n"); printf("-------------------------------------------------\n\n"); int i, j, tt = 0, qu = q; int t[N]; for(i = 0; i < N; i++){ tt += table[i].burst; } for(i = 0; i < N; i++){ for(j = 0; j < N - 1; j++){ if(table[j].arr > table[j + 1].arr) swap(&table[j], &table[j + 1]); } } for(i = 0; i < N; i++){ t[i] = 0; } i = 0; j = 0; int d = 0, time = 0; int h = 0; while(time != tt){ if(table[j].arr <= time){ t[j] = table[j].burst; j++; } if(t[i] != 0){ if(t[i] >= qu){ printf("[%d - %d] %s running\n", time, time + qu, table[i].name); time += qu; t[i] -= qu; if(t[i] == 0){ table[i].tat = time - table[i].arr; table[i].wait = table[i].tat - table[i].burst; } } else{ printf("[%d - %d] %s running\n", time, time + t[i], table[i].name); time += t[i]; t[i] = 0; table[i].tat = time - table[i].arr; table[i].wait = table[i].tat - table[i].burst; } } i = (i + 1) % N; } PrintStats(); } void SRBF(){ printf("-------------------------------------------------\n"); printf(" Shortest Remaining Burst First\n"); printf("-------------------------------------------------\n\n"); int i, j, tt = 0; int t[N]; for(i = 0; i < N; i++){ tt += table[i].burst; } for(i = 0; i < N; i++){ for(j = 0; j < N - 1; j++){ if(table[j].arr > table[j + 1].arr) swap(&table[j], &table[j + 1]); } } for(i = 0; i < N; i++){ t[i] = INT_MAX; } int time = 0, otime = 0; j = 0; i = 0; int k = 0, l = 0; while(time != tt){ if(j < N && time == table[j].arr){ t[j] = table[j].burst; j++; } else{ if(t[i] == 0){ t[i] = INT_MAX; } k = i; for(l = 0; l < N; l++){ if(t[l] < t[k]) k = l; } if(i != k){ printf("[%d - %d] %s running\n", otime, time, table[i].name); otime = time; i = k; } time++; t[i]--; if(t[i] == 0) table[i].tat = time - table[i].arr; } } printf("[%d - %d] %s running\n", otime, time, table[i].name); for(i = 0; i < N; i++) table[i].wait = table[i].tat - table[i].burst; PrintStats(); } int main(int argc, char *argv[]){ ReadProcessTable(argv[1]); int x = 1, y = 0, q; while(x != 0){ printf("-------------------------------------------------\n"); printf(" CPU Scheduling Simulation\n"); printf("-------------------------------------------------\n\n"); printf("Select the scheduling algorithm [1,2,3 or 4]:\n"); printf("1. First Come First Served (FCFS)\n"); printf("2. Round Robin (RR)\n"); printf("3. Shortest Remaining Burst First (SRBF)\n"); printf("4. Exit\n\n"); scanf("%d", &y); switch(y){ case 1: FCFS(); break; case 2: printf("Enter the time quantum: "); scanf("%d", &q); printf("\n"); RR(q); break; case 3: SRBF(); break; case 4: return 0; default: printf("Enter correct number.\n"); } printf("\nHit enter to continue ... \n"); getchar(); getchar(); } return 0; }
a5ce2d1bd135ee08999fae397af68f87e4c4e5f7
[ "Markdown", "C", "Text", "Makefile" ]
16
C
SoumyajitKarmakar/CS232_Operating-Systems-Lab
777536f9deea5cd1150a0565178fb1c0b0bfae80
08640618d0c336c1df97dd305bfa795ffc4855c4
refs/heads/master
<file_sep>package com.zhaoyan.juyou.adapter; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Color; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.view.CheckableImageView; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.AsyncPictureLoader; import com.zhaoyan.juyou.common.ImageInfo; import com.zhaoyan.juyou.common.ZYConstant.Extra; public class ImageAdapter extends BaseAdapter implements SelectInterface{ private static final String TAG = "ImageAdapter"; private LayoutInflater mInflater = null; private List<ImageInfo> mDataList; private AsyncPictureLoader pictureLoader; private boolean mIdleFlag = true; /**save status of item selected*/ private SparseBooleanArray mCheckArray; /**current menu mode,ActionMenu.MODE_NORMAL,ActionMenu.MODE_EDIT*/ private int mMenuMode = ActionMenu.MODE_NORMAL; private int mViewType = Extra.VIEW_TYPE_DEFAULT; public ImageAdapter(Context context, int viewType, List<ImageInfo> itemList){ mInflater = LayoutInflater.from(context); mDataList = itemList; pictureLoader = new AsyncPictureLoader(context); mCheckArray = new SparseBooleanArray(); mViewType = viewType; } @Override public int getCount() { return mDataList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (Extra.VIEW_TYPE_LIST == mViewType) { return getListView(convertView, position); } return getGridView(convertView, position); } private View getGridView(View convertView, int position){ View view = null; ViewHolder holder = null; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = mInflater.inflate(R.layout.image_item_grid, null); holder.imageView = (CheckableImageView) view.findViewById(R.id.iv_image_item); view.setTag(holder); } long id = mDataList.get(position).getImageId(); if (mIdleFlag) { pictureLoader.loadBitmap(id, holder.imageView); holder.imageView.setChecked(mCheckArray.get(position)); } else { if (AsyncPictureLoader.bitmapCaches.size() > 0 && AsyncPictureLoader.bitmapCaches.get(id) != null) { holder.imageView.setImageBitmap(AsyncPictureLoader.bitmapCaches .get(id).get()); } else { holder.imageView.setImageResource(R.drawable.photo_l); } holder.imageView.setChecked(mCheckArray.get(position)); } return view; } private View getListView(View convertView, int position){ View view = null; ViewHolder holder = null; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = mInflater.inflate(R.layout.image_item_list, null); holder.imageView2 = (ImageView) view.findViewById(R.id.iv_image_item); holder.nameView = (TextView) view.findViewById(R.id.tv_image_name); holder.sizeView = (TextView) view.findViewById(R.id.tv_image_size); view.setTag(holder); } long id = mDataList.get(position).getImageId(); String name = mDataList.get(position).getDisplayName(); String size = mDataList.get(position).getFormatSize(); holder.nameView.setText(name); holder.sizeView.setText(size); if (mIdleFlag) { pictureLoader.loadBitmap(id, holder.imageView2); } else { if (AsyncPictureLoader.bitmapCaches.size() > 0 && AsyncPictureLoader.bitmapCaches.get(id) != null) { holder.imageView2.setImageBitmap(AsyncPictureLoader.bitmapCaches .get(id).get()); } else { holder.imageView2.setImageResource(R.drawable.photo_l); } } updateViewBackground(position, view); return view; } public void updateViewBackground(int position, View view){ boolean selected = isChecked(position); if (selected) { view.setBackgroundResource(R.color.holo_blue_light); }else { view.setBackgroundResource(Color.TRANSPARENT); } } private class ViewHolder{ CheckableImageView imageView;//folder icon ImageView imageView2; TextView nameView; TextView sizeView; } @Override public void changeMode(int mode) { mMenuMode = mode; } @Override public boolean isMode(int mode) { return mMenuMode == mode; } @Override public void checkedAll(boolean isChecked) { int count = this.getCount(); for (int i = 0; i < count; i++) { setChecked(i, isChecked); } } @Override public void setChecked(int position, boolean isChecked) { mCheckArray.put(position, isChecked); } @Override public void setChecked(int position) { mCheckArray.put(position, !isChecked(position)); } @Override public boolean isChecked(int position) { return mCheckArray.get(position); } @Override public int getCheckedCount() { int count = 0; for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { count ++; } } return count; } @Override public List<Integer> getCheckedPosList() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(i); } } return list; } @Override public List<String> getCheckedNameList() { List<String> list = new ArrayList<String>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(mDataList.get(i).getDisplayName()); } } return list; } @Override public List<String> getCheckedPathList() { List<String> list = new ArrayList<String>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(mDataList.get(i).getPath()); } } return list; } @Override public void setIdleFlag(boolean flag) { this.mIdleFlag = flag; } } <file_sep>package com.zhaoyan.communication; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.HandlerThread; import android.os.Message; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.TrafficStaticInterface.TrafficStaticsTxListener; /** * Create server socket to send file. Send file to the connected client. * */ public class FileSender { private static final String TAG = "FileSender"; /** 3 minutes time out. */ private static final int SEND_SOCKET_TIMEOUT = 3 * 60 * 1000; /** To avoid call back to fast, set the minimum interval callback time。 */ private static final int TIME_CALLBACK_INTERVAL = 1000; private OnFileSendListener mListener; private File mSendFile; private ServerSocket mServerSocket; private SendHandlerThread mHandlerThread; private static final int MSG_UPDATE_PROGRESS = 1; private static final int MSG_FINISH = 2; private Handler mHandler; private static final String KEY_SENT_BYTES = "KEY_SENT_BYTES"; private static final String KEY_TOTAL_BYTES = "KEY_TOTAL_BYTES"; private static final int FINISH_RESULT_SUCCESS = 1; private static final int FINISH_RESULT_FAIL = 2; private Object mKey; private TrafficStaticsTxListener mTxListener = TrafficStatics.getInstance(); private boolean mCancelSendFlag = false; public FileSender() { }; public FileSender(Object key) { mKey = key; } /** * Create file send server and send file to the first connected client. * After the file is sent, the server is closed. * * @param file * @param listener * @return The server socket port. */ public int sendFile(File file, OnFileSendListener listener) { mListener = listener; mSendFile = file; mServerSocket = createServerSocket(); if (mServerSocket == null) { Log.e(TAG, "sendFile() file: " + file + ", fail. Create server socket error"); return -1; } FileSenderThread fileSenderThread = new FileSenderThread(); fileSenderThread.start(); mHandlerThread = new SendHandlerThread("HandlerThread-FileSender"); mHandlerThread.start(); mHandler = new Handler(mHandlerThread.getLooper(), mHandlerThread); return mServerSocket.getLocalPort(); } public void cancelSendFile() { mCancelSendFlag = true; } /** * Get an available port. * * @return */ private ServerSocket createServerSocket() { for (int port : SocketPort.FILE_TRANSPORT_PROT) { try { ServerSocket serverSocket = new ServerSocket(port); Log.d(TAG, "Create port successs. port number: " + port); return serverSocket; } catch (IOException e) { Log.d(TAG, "The server port is in use. port number: " + port); } } return null; } /** * A simple server socket that accepts connection and writes some data on * the stream. */ class FileSenderThread extends Thread { @Override public void run() { try { mServerSocket.setSoTimeout(SEND_SOCKET_TIMEOUT); Socket client = mServerSocket.accept(); Log.d(TAG, "Client ip: " + client.getInetAddress().getHostAddress()); Log.d(TAG, "Server: connection done"); OutputStream outputStream = client.getOutputStream(); Log.d(TAG, "server: copying files " + mSendFile.toString()); copyFile(new FileInputStream(mSendFile), outputStream); mServerSocket.close(); } catch (Exception e) { Log.e(TAG, "FileSenderThread " + e.toString()); notifyFinish(false); } Log.d(TAG, "FileSenderThread file: [" + mSendFile.getName() + "] finished"); } } class SendHandlerThread extends HandlerThread implements Callback { public SendHandlerThread(String name) { super(name); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_PROGRESS: Bundle data = msg.getData(); long sentBytes = data.getLong(KEY_SENT_BYTES); long totalBytes = data.getLong(KEY_TOTAL_BYTES); if (mListener != null) { mListener.onSendProgress(sentBytes, mSendFile, mKey); } break; case MSG_FINISH: if (mListener != null) { if (msg.arg1 == FINISH_RESULT_SUCCESS) { mListener.onSendFinished(true, mSendFile, mKey); } else { mListener.onSendFinished(false, mSendFile, mKey); } } // Quit the HandlerThread quit(); break; default: break; } return true; } } private void copyFile(InputStream inputStream, OutputStream out) { byte buf[] = new byte[4096]; int len; long sendBytes = 0; long start = System.currentTimeMillis(); long totalBytes = mSendFile.length(); long lastCallbackTime = start; long currentTime = start; mCancelSendFlag = false; try { while ((len = inputStream.read(buf)) != -1 && mCancelSendFlag == false) { out.write(buf, 0, len); sendBytes += len; currentTime = System.currentTimeMillis(); if (currentTime - lastCallbackTime >= TIME_CALLBACK_INTERVAL || sendBytes >= totalBytes) { notifyProgress(sendBytes, totalBytes); lastCallbackTime = currentTime; } mTxListener.addTxBytes(len); } if (mCancelSendFlag == true) { notifyFinish(false); } else { notifyFinish(true); } out.close(); inputStream.close(); } catch (IOException e) { notifyFinish(false); Log.d(TAG, e.toString()); } long time = System.currentTimeMillis() - start; Log.d(TAG, "Total size = " + sendBytes + "bytes time = " + time + ", speed = " + (sendBytes / time) + "KB/s"); } private void notifyProgress(long sentBytes, long totalBytes) { Message message = mHandler.obtainMessage(); message.what = MSG_UPDATE_PROGRESS; Bundle data = new Bundle(); data.putLong(KEY_SENT_BYTES, sentBytes); data.putLong(KEY_TOTAL_BYTES, totalBytes); message.setData(data); mHandler.sendMessage(message); } private void notifyFinish(boolean result) { Message message = mHandler.obtainMessage(); message.what = MSG_FINISH; if (result) { message.arg1 = FINISH_RESULT_SUCCESS; } else { message.arg1 = FINISH_RESULT_FAIL; } mHandler.sendMessage(message); } /** * Callback to get the send status. * */ public interface OnFileSendListener { /** * Every {@link #TIME_CALLBACK_INTERVAL} time, this method is invoked. * * @param sentBytes * @param file */ void onSendProgress(long sentBytes, File file, Object key); /** * The file is sent. * * @param success */ void onSendFinished(boolean success, File file, Object key); } } <file_sep>package com.zhaoyan.juyou.activity; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.View; import android.widget.TextView; import com.zhaoyan.juyou.R; public class BaseFragmentActivity extends FragmentActivity { // title view protected View mCustomTitleView; protected TextView mTitleNameView; protected void initTitle(int titleName) { mCustomTitleView = findViewById(R.id.title); // title name view mTitleNameView = (TextView) mCustomTitleView .findViewById(R.id.tv_title_name); mTitleNameView.setText(titleName); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); overridePendingTransition(0, R.anim.activity_right_out); return true; } return super.onKeyDown(keyCode, event); } } <file_sep>package com.zhaoyan.communication; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import android.annotation.SuppressLint; import android.content.Context; import android.os.IBinder; import android.os.RemoteException; import com.dreamlink.communication.aidl.HostInfo; import com.dreamlink.communication.aidl.OnCommunicationListenerExternal; import com.dreamlink.communication.aidl.PlatformManagerCallback; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.ArrayUtil; import com.zhaoyan.common.util.Log; @SuppressWarnings("unused") public class PlatformManager implements OnCommunicationListenerExternal { private int incId = 0; private ConcurrentHashMap<Integer, HostInfo> allHostList; private Map<Integer, HostInfo> createHost; private PlatformProtocol platformProtocol; private Map<Integer, ArrayList<Integer>> groupMember; private UserManager mUserManager; private SocketCommunicationManager mSocketCommunicationManager; private ProtocolCommunication mProtocolCommunication; private int appId = 115;; private String TAG = "ArbiterLiu-PlatformManagerService"; private ConcurrentHashMap<Integer, PlatformManagerCallback> callbackList; private ConcurrentHashMap<Integer, HostInfo> joinedGroup; private Context mContext; private static PlatformManager mPlatformManager; private HostNumberInterface mHostNumberInterface; public interface HostNumberInterface { public void returnHostInfo(List<HostInfo> hostList); } public void registerHostNumberInterface( HostNumberInterface hostNumberInterface) { mHostNumberInterface = hostNumberInterface; } private PlatformManager(Context context) { mContext = context; onCreate(); } /** * one app_id just allow register only one,if the new one come in ,replace * old one */ public void register(PlatformManagerCallback callback, int app_id) { callbackList.put(app_id, callback); } public void unregister(int app_id) { callbackList.remove(app_id); } public static PlatformManager getInstance(Context context) { if (mPlatformManager == null) { mPlatformManager = new PlatformManager(context); } return mPlatformManager; } public void release() { mPlatformManager = null; } @SuppressLint("UseSparseArrays") public void onCreate() { mUserManager = UserManager.getInstance(); mSocketCommunicationManager = SocketCommunicationManager.getInstance(); mProtocolCommunication = ProtocolCommunication.getInstance(); joinedGroup = new ConcurrentHashMap<Integer, HostInfo>(); allHostList = new ConcurrentHashMap<Integer, HostInfo>(); mProtocolCommunication.registerOnCommunicationListenerExternal( this, appId); platformProtocol = new PlatformProtocol(this); createHost = new HashMap<Integer, HostInfo>(); callbackList = new ConcurrentHashMap<Integer, PlatformManagerCallback>(); } /** * @param appName * 创建包名下属的名字,一个程序可能会创建很多个不同的主机,需要用此加以标示 * @param pakcageName * 创建的包名,目前这个项作用不大 * @param numberLimit * 创建人数限制 * @param app_id * 创建程序的appId,通信区分和创建区分 * */ public void createHost(String appName, String pakcageName, int numberLimit, int app_id) { HostInfo hostInfo = new HostInfo(); hostInfo.ownerID = mUserManager.getLocalUser().getUserID(); hostInfo.ownerName = mUserManager.getLocalUser().getUserName(); hostInfo.personLimit = numberLimit; hostInfo.packageName = pakcageName; hostInfo.appName = appName; hostInfo.app_id = app_id; hostInfo.personNumber = 1; if (!UserManager.isManagerServer(mUserManager.getLocalUser())) { User temUser = mUserManager.getAllUser().get(-1); if (temUser != null) { byte[] tartgetData = platformProtocol.encodePlatformProtocol( platformProtocol.CREATE_HOST_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); mProtocolCommunication.sendMessageToSingle(tartgetData, temUser, appId); } } else { requestCreateHost(hostInfo); } } public void requestCreateHost(HostInfo hostInfo) { boolean isexsit = false; if (!UserManager.isManagerServer(mUserManager.getLocalUser())) { /** this is no possible */ return; } for (Entry<Integer, HostInfo> entry : allHostList.entrySet()) { HostInfo temp = entry.getValue(); if (temp.ownerID == hostInfo.ownerID && temp.app_id == hostInfo.app_id && temp.appName.equals(hostInfo.appName) && temp.packageName.equals(hostInfo.packageName)) { /* do nothing or return the old hostInfo */ isexsit = true; if (hostInfo.ownerID == mUserManager.getLocalUser().getUserID()) { createHostAck(temp); } else { User tem = mUserManager.getAllUser().get(hostInfo.ownerID); if (tem != null) { byte[] target = platformProtocol .encodePlatformProtocol( platformProtocol.CREATE_HOST_ACK_CMD_CODE, ArrayUtil.objectToByteArray(temp)); mProtocolCommunication.sendMessageToSingle(target, tem, appId); } } } } if (!isexsit) { hostInfo.hostId = incId; incId++; hostInfo.isAlive = 1; if (UserManager.isManagerServer(mUserManager.getAllUser().get( hostInfo.ownerID))) { createHostAck(hostInfo); } else { User tem = mUserManager.getAllUser().get(hostInfo.ownerID); if (tem != null) { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.CREATE_HOST_ACK_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); mProtocolCommunication.sendMessageToSingle(target, tem, appId); } else { /** this is mean the communication has lost,do nothing */ } } } updateHostInfo(hostInfo); } private void groupUpdateForAllUser() { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GROUP_INFO_CHANGE_CMD_CODE, ArrayUtil.objectToByteArray(allHostList)); mProtocolCommunication.sendMessageToAll(target, appId); } /** 本地收到创建的ACK */ @SuppressLint("UseSparseArrays") public void createHostAck(HostInfo hostInfo) { createHost.put(hostInfo.hostId, hostInfo); if (groupMember == null) { groupMember = new HashMap<Integer, ArrayList<Integer>>(); } joinedGroup.put(hostInfo.hostId, hostInfo); ArrayList<Integer> temList = new ArrayList<Integer>(); temList.add(mUserManager.getLocalUser().getUserID()); groupMember.put(hostInfo.hostId, temList); notifyGroupCreated(hostInfo); } private void notifyGroupCreated(HostInfo hostIo) { int app_id = hostIo.app_id; PlatformManagerCallback callback = callbackList.get(app_id); if (callback != null) { try { callback.hostHasCreated(hostIo); } catch (Exception e) { e.printStackTrace(); } } } public void requestAllHost(int appID, User user) { ConcurrentHashMap<Integer, HostInfo> temMap; if (appID == 0) { temMap = allHostList; } else { temMap = new ConcurrentHashMap<Integer, HostInfo>(); for (Entry<Integer, HostInfo> entry : allHostList.entrySet()) { if (appID == entry.getValue().app_id) { temMap.put(entry.getKey(), entry.getValue()); } } } if (UserManager.isManagerServer(user)) { receiverAllHostInfo(temMap); return; } byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GROUP_INFO_CHANGE_CMD_CODE, ArrayUtil.objectToByteArray(temMap)); mProtocolCommunication.sendMessageToSingle(target, user, appId); } public void getAllHost(int appID) { if (UserManager.isManagerServer(mUserManager.getLocalUser())) { requestAllHost(appID, mUserManager.getLocalUser()); return; } User user = mUserManager.getAllUser().get(-1); if (user == null) { /** this mean no main server ,no network */ return; } byte[] tem_target = null; tem_target = ArrayUtil.int2ByteArray(appID); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GET_ALL_HOST_INFO_CMD_CODE, tem_target); mProtocolCommunication.sendMessageToSingle(target, user, appId); } public void receiverAllHostInfo( ConcurrentHashMap<Integer, HostInfo> allHostInfo) { ArrayList<HostInfo> tem = new ArrayList<HostInfo>(); for (java.util.Map.Entry<Integer, HostInfo> entry : allHostInfo .entrySet()) { HostInfo hostInfo = entry.getValue(); tem.add(hostInfo); } for (Entry<Integer, PlatformManagerCallback> entry : callbackList .entrySet()) { try { entry.getValue().hostInfoChange( ArrayUtil.objectToByteArray(tem)); } catch (Exception e) { e.printStackTrace(); } } /** for platform get all host callback */ if (mHostNumberInterface != null) mHostNumberInterface.returnHostInfo(tem); } /** * local invoke * * if the host person limit is 1 ,can not join it * */ public void joinGroup(HostInfo hostInfo) { if (hostInfo.ownerID == mUserManager.getLocalUser().getUserID() || joinedGroup.containsKey(hostInfo.hostId)) { return; } if (hostInfo.personLimit == 1) { // this should notify user join status,refuse receiverJoinAck(false, hostInfo); return; } User temUser = mUserManager.getAllUser().get(hostInfo.ownerID); if (temUser != null) { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.JOIN_GROUP_CMD_CODE, ArrayUtil.int2ByteArray(hostInfo.hostId)); mProtocolCommunication.sendMessageToSingle(target, temUser, appId); } } @SuppressLint("UseSparseArrays") public void requestJoinGroup(int hostId, User applyUser) { if (createHost != null && createHost.containsKey(hostId)) { HostInfo hostInfo = createHost.get(hostId); if (groupMember == null) { groupMember = new HashMap<Integer, ArrayList<Integer>>(); } if (!groupMember.containsKey(hostId)) { groupMember.put(hostId, new ArrayList<Integer>()); } if (hostInfo.personLimit != 1) { if (hostInfo.personNumber + 1 <= hostInfo.personLimit || hostInfo.personLimit == 0) { if (!groupMember.get(hostId) .contains(applyUser.getUserID())) { groupMember.get(hostId).add(applyUser.getUserID()); hostInfo.personNumber++; sendJoinAck(true, applyUser, hostInfo); notifyGroupInfoChangeForMember(hostInfo.hostId); prepareUpdateHostInfo(hostInfo); } } else { sendJoinAck(false, applyUser, hostInfo); } } else { sendJoinAck(false, applyUser, hostInfo); } } } private void prepareUpdateHostInfo(HostInfo hostInfo) { if (UserManager.isManagerServer(mUserManager.getLocalUser())) { updateHostInfo(hostInfo); } else { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GROUP_INFO_CHANGE_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); User tem = mUserManager.getAllUser().get(-1); if (tem == null) { Log.e(TAG, "There is no main server,check the netwok"); } else { mProtocolCommunication.sendMessageToSingle(target, tem, appId); } } } public void updateHostInfo(HostInfo hostInfo) { if (UserManager.isManagerServer(mUserManager.getLocalUser())) { if (hostInfo.isAlive == 1) { allHostList.put(hostInfo.hostId, hostInfo); } else { allHostList.remove(hostInfo.hostId); } groupUpdateForAllUser(); receiverAllHostInfo(allHostList); } else { Log.e(TAG, "Check the process ,wrong case!!!"); } } /** * group owner notify apply user,just for group person limit 0 ,or refuse * join,in network * * @param flag * is true ,agreed ,else refuse * */ private void sendJoinAck(boolean flag, User user, HostInfo hostInfo) { byte[] temp; if (flag) { temp = new byte[] { 1 }; } else { temp = new byte[] { 0 }; } temp = ArrayUtil.join(temp, ArrayUtil.objectToByteArray(hostInfo)); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.JOIN_GROUP_ACK_CMD_CODE, temp); mProtocolCommunication.sendMessageToSingle(target, user, appId); } public void receiverJoinAck(boolean flag, HostInfo hostInfo) { if (flag) { // join OK,save joined info joinedGroup.put(hostInfo.hostId, hostInfo); } PlatformManagerCallback callback = callbackList.get(hostInfo.app_id); if (callback != null) { try { callback.joinGroupResult(hostInfo, flag); } catch (Exception e) { e.printStackTrace(); } } } /** * /** notify main server and all group member when has user join or exit * ,in network */ private void notifyGroupInfoChangeForMember(int hostId) { ArrayList<Integer> temList = groupMember.get(hostId); if (temList.size() > 1) { byte[] temp = ArrayUtil.int2ByteArray(hostId); temp = ArrayUtil.join(temp, ArrayUtil.objectToByteArray(temList)); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GROUP_MEMBER_UPDATE_CMD_CODE, temp); for (int id : temList) { if (id != mUserManager.getLocalUser().getUserID()) mProtocolCommunication.sendMessageToSingle(target, mUserManager.getAllUser().get(id), appId); } } receiverGroupMemberUpdat(hostId, temList); } @SuppressLint("UseSparseArrays") public void receiverGroupMemberUpdat(int hostId, ArrayList<Integer> userList) { /** when group member update ,will receiver here */ if (!joinedGroup.containsKey(hostId)) { return; } if (groupMember == null) { groupMember = new HashMap<Integer, ArrayList<Integer>>(); } groupMember.put(hostId, userList); ArrayList<User> tem = new ArrayList<User>(); Map<Integer, User> userMap = mUserManager.getAllUser(); for (int id : userList) { tem.add(userMap.get(id)); } HostInfo hostInfo = joinedGroup.get(hostId); PlatformManagerCallback callback = callbackList.get(hostInfo.app_id); if (callback != null) { try { callback.groupMemberUpdate(hostId, ArrayUtil.objectToByteArray(tem)); } catch (Exception e) { e.printStackTrace(); } } } public void exitGroup(HostInfo hostInfo) { if (createHost != null && createHost.containsKey(hostInfo.hostId)) { /** this mean cancel the host */ cancelHost(hostInfo.hostId); return; } if (joinedGroup.containsKey(hostInfo.hostId)) { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.EXIT_GROUP_CMD_CODE, ArrayUtil.int2ByteArray(hostInfo.hostId)); User tem = mUserManager.getAllUser().get(hostInfo.ownerID); groupMember.remove(hostInfo.hostId); joinedGroup.remove(hostInfo.hostId); if (tem == null) { /** this mean the owner has disconnect */ } else { mProtocolCommunication.sendMessageToSingle(target, tem, appId); } } } public void requestExitGroup(int hostId, User applyUser) { int index = -1; if (!createHost.containsKey(hostId)) { Log.e(TAG, "this is not i create ,the hostId is " + hostId); return; } HostInfo hostInfo = createHost.get(hostId); List<Integer> userList = groupMember.get(hostId); if (userList.contains(applyUser.getUserID())) { index = userList.indexOf(applyUser.getUserID()); if (index != -1) { groupMember.get(hostId).remove(index); hostInfo.personNumber--; } byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.EXIT_GROUP_ACK_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); mProtocolCommunication.sendMessageToSingle(target, applyUser, appId); notifyGroupInfoChangeForMember(hostId); prepareUpdateHostInfo(hostInfo); } } /** * 第三方調用 专供group创建者使用,踢出某人。 * 创建者调用之后,平台从当前保存的列表中移除成员,并向该成员通讯告知其已经被踢出,并向主server更新数目变化 ,和向其他成员更新成员列表变化 * */ public void removeGroupMember(int hostId, int userId) { if (mUserManager.getLocalUser().getUserID() == userId) { Log.e(TAG, "You can not remove yourself"); return; } int index = -1; if (createHost.containsKey(hostId)) { HostInfo hostInfo = createHost.get(hostId); ArrayList<Integer> temUserList = groupMember.get(hostId); if (temUserList == null) { return; } index = temUserList.indexOf(userId); if (index != -1) { temUserList.remove(index); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.REMOVE_USER_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); User tem = mUserManager.getAllUser().get(userId); if (tem != null) mProtocolCommunication.sendMessageToSingle(target, tem, appId); hostInfo.personNumber--; notifyGroupInfoChangeForMember(hostId); prepareUpdateHostInfo(hostInfo); } } else Log.e(TAG, "you are not the host owner ,the host id is " + hostId + " or the user is not in the group. the user id is " + userId); } public void receiverRemoveUser(HostInfo hostInfo) { if (!joinedGroup.containsKey(hostInfo.hostId)) { return; } joinedGroup.remove(hostInfo.hostId); groupMember.remove(hostInfo.hostId); PlatformManagerCallback callback = callbackList.get(hostInfo.app_id); if (callback != null) { try { callback.hasExitGroup(hostInfo.hostId); } catch (Exception e) { e.printStackTrace(); } } Log.e(TAG, "you are removed by form " + hostInfo.hostId); } /** * 专供group创建者使用,取消当前group。 * 如果其中有成员,向所有成员发送group取消,向主server发送group取消,删除本地保存的创建的这个group信息。 * 主server删除此group并向网域的所有成员发送group更新信息。 * */ private void cancelHost(int hostId) { if (createHost.containsKey(hostId)) { HostInfo hostInfo = createHost.get(hostId); ArrayList<Integer> userList = groupMember.get(hostId); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.CANCEL_HOST_CMD_CODE, ArrayUtil.objectToByteArray(hostInfo)); if (userList.size() > 1) { for (int n : userList) { if (n == hostInfo.ownerID || n == -1) { continue; } User u = mUserManager.getAllUser().get(n); mProtocolCommunication.sendMessageToSingle(target, u, appId); } } mProtocolCommunication.sendMessageToSingle(target, mUserManager.getAllUser().get(-1), appId); } } private void requestCancelHost(HostInfo hostInfo, User user) { /* run in the host manager */ if (allHostList.containsKey(hostInfo.hostId) && hostInfo.ownerID == user.getUserID()) { hostInfo.isAlive = 0; prepareUpdateHostInfo(hostInfo); } else { Log.e(TAG, "you are not the owner or there is no the host "); } } public void receiverCancelHost(HostInfo hostInfo, User user) { if (joinedGroup.containsKey(hostInfo.hostId)) { joinedGroup.remove(hostInfo.hostId); groupMember.remove(hostInfo.hostId); PlatformManagerCallback callback = callbackList .get(hostInfo.app_id); if (callback != null) { try { callback.hasExitGroup(hostInfo.hostId); } catch (Exception e) { e.printStackTrace(); } } } if (mUserManager.getLocalUser().getUserID() == -1) { requestCancelHost(hostInfo, user); } } public void getGroupUser(HostInfo hostInfo) { if (!joinedGroup.containsKey(hostInfo.hostId)) { return; } if (mUserManager.getLocalUser().getUserID() == hostInfo.ownerID) { receiverGroupMemberUpdat(hostInfo.hostId, groupMember.get(hostInfo.hostId)); return; } User tempUser = mUserManager.getAllUser().get(hostInfo.ownerID); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GET_ALL_GROUP_MEMBER_CMD_CODE, ArrayUtil.int2ByteArray(hostInfo.hostId)); if (tempUser != null) { mProtocolCommunication.sendMessageToSingle(target, tempUser, appId); } else { Log.e(TAG, "the owner can not reachable"); } } public void requetsGetGroupMember(int hostId, User user) { if (createHost.containsKey(hostId)) { ArrayList<Integer> userList = groupMember.get(hostId); if (userList.contains(user.getUserID())) { byte[] tem = ArrayUtil.int2ByteArray(hostId); tem = ArrayUtil .join(tem, ArrayUtil.objectToByteArray(userList)); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.GROUP_MEMBER_UPDATE_CMD_CODE, tem); mProtocolCommunication.sendMessageToSingle(target, user, appId); } else { Log.e(TAG, "the apply user " + user.getUserID() + " is not in the group " + hostId); } } else { Log.e(TAG, "I am not the owner of the id " + hostId); } } @Override public void onReceiveMessage(byte[] arg0, User arg1) throws RemoteException { /** if join or exit ,remove .. that will know who want to do */ platformProtocol.decodePlatformProtocol(arg0, arg1); } @Override public void onUserConnected(User arg0) throws RemoteException { /* do not care this case */ } @Override public void onUserDisconnected(User arg0) throws RemoteException { int hostId = -1; if (!mSocketCommunicationManager.isConnected()) { // this mean local lost connect if (createHost != null) { createHost.clear(); } if (joinedGroup != null) { for (Entry<Integer, HostInfo> entry : joinedGroup.entrySet()) { receiverRemoveUser(entry.getValue()); } joinedGroup.clear(); if (groupMember != null) groupMember.clear(); } if (allHostList != null) allHostList.clear(); receiverAllHostInfo(allHostList); } else { for (Entry<Integer, HostInfo> entry : joinedGroup.entrySet()) { HostInfo hostInfo = entry.getValue(); if (hostInfo != null && hostInfo.ownerID == arg0.getUserID()) { Log.e(TAG, "hostInfo.ownerID == arg0.getUserID()"); hostId = hostInfo.hostId; receiverCancelHost(hostInfo, arg0); } } for (Entry<Integer, HostInfo> entry : createHost.entrySet()) { HostInfo hostInfo = entry.getValue(); if (hostInfo != null) removeGroupMember(hostInfo.hostId, arg0.getUserID()); } if (mUserManager.getLocalUser().getUserID() == -1) { for (Entry<Integer, HostInfo> entry : allHostList.entrySet()) { HostInfo hostInfo = entry.getValue(); if (hostInfo != null && hostInfo.ownerID == arg0.getUserID()) { hostId = hostInfo.hostId; receiverCancelHost(allHostList.get(hostId), arg0); } } } } } public void startGroupBusiness(int hostId) { if (createHost.containsKey(hostId)) { byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.Start_GROUP_CMD_CODE, ArrayUtil.int2ByteArray(hostId)); ArrayList<Integer> userList = groupMember.get(hostId); Map<Integer, User> userMap = mUserManager.getAllUser(); for (int id : userList) { if (id == mUserManager.getLocalUser().getUserID()) { continue; } else { mProtocolCommunication.sendMessageToSingle(target, userMap.get(id), appId); } } } } public void receiverStartGroupBusiness(int hostId) { if (joinedGroup.containsKey(hostId)) { PlatformManagerCallback callback = callbackList.get(joinedGroup .get(hostId).app_id); if (callback != null) { try { callback.startGroupBusiness(joinedGroup.get(hostId)); } catch (Exception e) { e.printStackTrace(); } } } } public void sendDataAll(byte[] data, HostInfo info) { if (!joinedGroup.containsKey(info.hostId)) { return; } Map<Integer, User> userMap = mUserManager.getAllUser(); ArrayList<Integer> userList = groupMember.get(info.hostId); for (int id : userList) { if (id == mUserManager.getLocalUser().getUserID()) { continue; } else { sendData(data, userMap.get(id), true, info); } } } public void sendDataSingle(byte[] data, HostInfo info, User targetUser) { if (!joinedGroup.containsKey(info.hostId)) { return; } ArrayList<Integer> userList = groupMember.get(info.hostId); if (userList.contains(targetUser.getUserID())) { sendData(data, targetUser, false, info); } } private void sendData(byte[] data, User user, boolean flag, HostInfo hostInfo) { byte[] allFlag; if (flag) allFlag = new byte[] { 1 }; else allFlag = new byte[] { 0 }; byte[] tempData = ArrayUtil.join(allFlag, ArrayUtil.int2ByteArray(hostInfo.hostId)); data = ArrayUtil.join(tempData, data); byte[] target = platformProtocol.encodePlatformProtocol( platformProtocol.MESSAGE_CMD_CODE, data); mProtocolCommunication.sendMessageToSingle(target, user, appId); } public void receiverData(byte[] data, User sendUser, boolean allFlag, int hostId) { if (joinedGroup.containsKey(hostId)) { PlatformManagerCallback callback = callbackList.get(joinedGroup .get(hostId).app_id); if (callback != null) { try { callback.receiverMessage(data, sendUser, allFlag, joinedGroup.get(hostId)); } catch (Exception e) { e.printStackTrace(); } } } } /** this is for application ,when they do not save the joined host */ public ArrayList<HostInfo> getJoinedHost(int appId) { ArrayList<HostInfo> temp = new ArrayList<HostInfo>(); if (appId == 0) { for (Entry<Integer, HostInfo> entry : joinedGroup.entrySet()) { temp.add(entry.getValue()); } } else { for (Entry<Integer, HostInfo> entry : joinedGroup.entrySet()) { if (entry.getValue().app_id == appId) temp.add(entry.getValue()); } } return temp; } @Override public IBinder asBinder() { return null; } } <file_sep>package com.zhaoyan.communication.connect; import android.content.Context; import android.content.Intent; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.search.DiscoveryService; import com.zhaoyan.juyou.provider.JuyouData; public class ServerCreateAndDiscovery extends Thread { private static final String TAG = "ServerCreateAndDiscovery"; private Context mContext; private DiscoveryService mDiscoveryService; private boolean mStop = false; private int mServerType; public ServerCreateAndDiscovery(Context context, int serverType) { mContext = context; mServerType = serverType; } @Override public void run() { startServerAndDiscovery(); } private void startServerAndDiscovery() { SocketCommunicationManager communicationManager = SocketCommunicationManager .getInstance(); communicationManager.startServer(mContext); mDiscoveryService = DiscoveryService.getInstance(mContext); mDiscoveryService.startDiscoveryService(); // Let server thread start first. int waitTime = 0; try { while (!mStop && !communicationManager.isServerSocketStarted() && waitTime < 5000) { Thread.sleep(200); } } catch (InterruptedException e) { // ignore } // If every thing is OK, the server is started. if (communicationManager.isServerSocketStarted()) { int networkType = 0; switch (mServerType) { case ServerCreator.TYPE_AP: networkType = JuyouData.User.NETWORK_AP; break; case ServerCreator.TYPE_LAN: networkType = JuyouData.User.NETWORK_WIFI; break; default: break; } UserManager.getInstance().addLocalServerUser(networkType); mContext.sendBroadcast(new Intent( ServerCreator.ACTION_SERVER_CREATED)); } else { Log.e(TAG, "createServerAndStartDiscoveryService timeout"); } } public void stopServerAndDiscovery() { mStop = true; UserManager userManager = UserManager.getInstance(); userManager.resetLocalUser(); SocketCommunicationManager communicationManager = SocketCommunicationManager .getInstance(); communicationManager.closeAllCommunication(); communicationManager.stopServer(); if (mDiscoveryService != null) { mDiscoveryService.stopSearch(); mDiscoveryService = null; } } } <file_sep>package com.zhaoyan.communication.protocol; public class Protocol { /** * Heart beat message. Note this message is only used by {@link #HeartBeat} */ public static final int DATA_TYPE_HEADER_HEART_BEAT = 1; public static final int DATA_SIZE_HEADER_SIZE = 4; public static final int DATA_TYPE_HEADER_SIZE = 4; public static final int LENGTH_INT = 4; // Login. public static final int DATA_TYPE_HEADER_LOGIN_REQUEST = 100; public static final int DATA_TYPE_HEADER_LOGIN_RESPOND = 101; public static final int LOGIN_RESPOND_RESULT_HEADER_SIZE = 1; // Login success. public static final byte LOGIN_RESPOND_RESULT_SUCCESS = 1; public static final int LOGIN_RESPOND_USERID_HEADER_SIZE = 4; // Login fail public static final byte LOGIN_RESPOND_RESULT_FAIL = 0; public static final int LOGIN_RESPOND_RESULT_FAIL_REASON_HEADER_SIZE = 4; public static final int LOGIN_RESPOND_RESULT_FAIL_UNKOWN = 0; public static final int LOGIN_RESPOND_RESULT_FAIL_SERVER_DISALLOW = 1; // Update all user info when user login or logout. public static final int DATA_TYPE_HEADER_UPDATE_ALL_USER = 102; public static final int UPDATE_ALL_USER_USER_TOTAL_NUMBER_HEADER_SIZE = 4; // Login forward public static final int DATA_TYPE_HEADER_LOGIN_REQUEST_FORWARD = 103; public static final int DATA_TYPE_HEADER_LOGIN_RESPOND_FORWARD = 104; public static final int LOGIN_FORWARD_USER_ID_SIZE = 4; // Send. public static final int SEND_USER_ID_HEADER_SIZE = 4; public static final int SEND_APP_ID_HEADER_SIZE = 4; public static final int DATA_TYPE_HEADER_SEND_SINGLE = 200; // Send to single public static final int DATA_TYPE_HEADER_SEND_ALL = 201; // File transport public static final int DATA_TYPE_HEADER_SEND_FILE = 300; public static final int SEND_FILE_SERVER_PORT_HEAD_SIZE = 4; public static final int SEND_FILE_SERVER_ADDRESS_HEAD_SIZE = 4; // Cancel Send File public static final int DATA_TYPE_HEADER_CANCEL_SEND_FILE = 400; // Cancel Receive File public static final int DATA_TYPE_HEADER_CANCEL_RECEIVE_FILE = 500; } <file_sep>package com.zhaoyan.communication.protocol; import java.util.Arrays; import android.util.Log; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.ArrayUtil; /** * This class is used for encode and decode send message. * */ public class SendProtocol { private static final String TAG = "SendProtocol"; public interface ISendProtocolTypeSingleCallBack { /** * Received a message. * * @param sendUserID * @param receiveUserID * @param appID * @param data */ public void onReceiveMessageSingleType(int sendUserID, int receiveUserID, int appID, byte[] data); } public interface ISendProtocolTypeAllCallBack { /** * Received a message. * * @param data * @param appID * @param sendUserID */ public void onReceiveMessageAllType(int sendUserID, int appID, byte[] data); } /** * Send message to single protocol: </br> * * [DATA_TYPE_HEADER_SEND_SINGLE][sendUser][receiveUser][appID][data] * * @param msg * @param sendUser * @param receiveUser * @param appID * @return */ public static byte[] encodeSendMessageToSingle(byte[] msg, int sendUserID, int receiveUserID, int appID) { byte[] dataTypeData = ArrayUtil .int2ByteArray(Protocol.DATA_TYPE_HEADER_SEND_SINGLE); byte[] sendUserData = ArrayUtil.int2ByteArray(sendUserID); byte[] receiveUserData = ArrayUtil.int2ByteArray(receiveUserID); byte[] appIDData = ArrayUtil.int2ByteArray(appID); msg = ArrayUtil.join(dataTypeData, sendUserData, receiveUserData, appIDData, msg); return msg; } /** * see {@link #encodeSendMessageToSingle(byte[], User, User, int)}; * * @param msg * @param callBack */ public static void decodeSendMessageToSingle(byte[] msg, ISendProtocolTypeSingleCallBack callBack) { int start = 0; int end = Protocol.SEND_USER_ID_HEADER_SIZE; byte[] sendUserIDData = Arrays.copyOfRange(msg, start, end); int sendUserID = ArrayUtil.byteArray2Int(sendUserIDData); Log.d(TAG, "decodeSendMessageToSingle: sendUserID = " + sendUserID); start = end; end += Protocol.SEND_USER_ID_HEADER_SIZE; byte[] receiveUserIDData = Arrays.copyOfRange(msg, start, end); int receiveUserID = ArrayUtil.byteArray2Int(receiveUserIDData); Log.d(TAG, "decodeSendMessageToSingle: receiveUserID = " + receiveUserID); start = end; end += Protocol.SEND_APP_ID_HEADER_SIZE; byte[] appIDData = Arrays.copyOfRange(msg, start, end); int appID = ArrayUtil.byteArray2Int(appIDData); Log.d(TAG, "decodeSendMessageToSingle: appID = " + appID); start = end; end = msg.length; byte[] data = Arrays.copyOfRange(msg, start, end); if (callBack != null) { callBack.onReceiveMessageSingleType(sendUserID, receiveUserID, appID, data); } else { Log.e(TAG, "ISendProtocolTypeSingleCallBack is null"); } } /** * Send message to all protocol: </br> * * [DATA_TYPE_HEADER_SEND_ALL][sendUser][appID][data] * * @param msg * @param sendUser * @param appID * @return */ public static byte[] encodeSendMessageToAll(byte[] msg, int sendUserID, int appID) { byte[] dataTypeData = ArrayUtil .int2ByteArray(Protocol.DATA_TYPE_HEADER_SEND_ALL); byte[] sendUserData = ArrayUtil.int2ByteArray(sendUserID); byte[] appIDData = ArrayUtil.int2ByteArray(appID); msg = ArrayUtil.join(dataTypeData, sendUserData, appIDData, msg); return msg; } /** * see {@link #encodeSendMessageToAll(byte[], User, int)}. * * @param msg * @param callBack */ public static void decodeSendMessageToAll(byte[] msg, ISendProtocolTypeAllCallBack callBack) { int start = 0; int end = Protocol.SEND_USER_ID_HEADER_SIZE; byte[] sendUserIDData = Arrays.copyOfRange(msg, start, end); int sendUserID = ArrayUtil.byteArray2Int(sendUserIDData); Log.d(TAG, "decodeSendMessageToAll: sendUserID = " + sendUserID); start = end; end += Protocol.SEND_APP_ID_HEADER_SIZE; byte[] appIDData = Arrays.copyOfRange(msg, start, end); int appID = ArrayUtil.byteArray2Int(appIDData); Log.d(TAG, "decodeSendMessageToAll: appID = " + appID); start = end; end = msg.length; byte[] data = Arrays.copyOfRange(msg, start, end); if (callBack != null) { callBack.onReceiveMessageAllType(sendUserID, appID, data); } else { Log.e(TAG, "ISendProtocolTypeAllCallBack is null"); } } } <file_sep>package com.zhaoyan.juyou.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import com.zhaoyan.common.file.FileManager; import com.zhaoyan.common.file.ZyMediaScanner; import android.content.Context; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; public class FileOperationHelper { private static final String TAG = "FileOperationHelper"; /** * current operation fileinfo list. */ private List<FileInfo> mCurFilesList = new ArrayList<FileInfo>(); /** * for mediaScanner */ private List<String> pathsList = new ArrayList<String>(); private OnOperationListener mOperationListener = null; private ZyMediaScanner mZyMediaScanner = null; private Context mContext; public static final int MSG_COPY_CUT_TO_CHILD = 0; public interface OnOperationListener{ public void onFinished(); public void onNotify(int msg); /** * @param fileName current copy file name * @param count current copy list file count * @param filesize current copy file size(bytes) * @param copysize copy size of current copy file(bytes) */ public void onRefreshFiles(String fileName, int count, long filesize, long copysize); } public void setOnOperationListener(OnOperationListener listener){ mOperationListener = listener; } public void cancelOperationListener(){ if (null != mOperationListener) { mOperationListener = null; } } public FileOperationHelper(Context context){ mContext = context; mZyMediaScanner = new ZyMediaScanner(context); } /** * record current operation fileinfos * @param files */ public void copy(List<FileInfo> files) { copyFileList(files); } private void copyFileList(List<FileInfo> files) { synchronized(mCurFilesList) { mCurFilesList.clear(); for (FileInfo f : files) { mCurFilesList.add(f); } } } /** * start copy file from old path to new path * @param newPath new path * @return */ public boolean doCopy(String newPath){ Log.d(TAG, "doCopy:" + newPath); if (TextUtils.isEmpty(newPath)) { Log.e(TAG, "doCopy:" + newPath+ " is empty"); return false; } final String _path = newPath; asnycExecute(new Runnable() { @Override public void run() { //count file nums int fileCounts = 0; File file = null; for(FileInfo f : mCurFilesList){ file = new File(f.filePath); fileCounts += count(file); } mOperationListener.onRefreshFiles(null, fileCounts, -1, -1); boolean copyToChild = false; for (FileInfo f : mCurFilesList) { if (mStopCopy) { break; } if (FileManager.containsPath(f.filePath, _path)) { //cannot copy or cut a dir to it's child dir copyToChild = true; continue; } copyFiles(f, _path); } if (copyToChild) { mOperationListener.onNotify(MSG_COPY_CUT_TO_CHILD); } clear(); } }); return true; } int copyCount = 0; private void copyFiles(FileInfo fileInfo, String path){ if (null == fileInfo || null == path) { Log.e(TAG, "copyFiles: null parameter"); return; } //copy String srcPath = fileInfo.filePath; String fileName = fileInfo.fileName; String desPath = FileManager.makePath(path, fileName); //if desFile is exist,auto rename if (new File(desPath).exists()) { fileName = FileInfoManager.autoRename(fileName); desPath = FileManager.makePath(path, fileName); } if (fileInfo.isDir) { copyFolder(srcPath, desPath); } else { copyCount ++; mOperationListener.onRefreshFiles(fileName, copyCount, new File(srcPath).length() , -1); copyFile(srcPath, desPath); } } /** * folder copy * @param srcPath source folder path * @param desPath destination folder path * @return */ private boolean copyFolder(String srcPath, String desPath) { File srcFile = new File(srcPath); String[] srcFileNameList = srcFile.list(); if (srcFileNameList.length == 0) { //copy a empty folder return new File(desPath).mkdirs(); } // create desPath folder if (!new File(desPath).mkdirs()) { return false; } File tempFile = null; for (String name : srcFileNameList) { if (srcPath.endsWith(File.separator)) { tempFile = new File(srcFile + name); } else { tempFile = new File(srcFile + File.separator + name); } if (tempFile.isFile()) { copyCount ++; mOperationListener.onRefreshFiles(name, copyCount, tempFile.length(), -1); copyFile(tempFile.getAbsolutePath(), desPath + File.separator + name); } else if (tempFile.isDirectory()) { // is a child folder copyFolder(srcPath + File.separator + name, desPath + File.separator + name); } } return true; } /** * copy single file * * @param srcPath * src file path * @param desPath * des file path * @return * @throws Exception */ private boolean copyFile(String srcPath, String desPath){ if (new File(srcPath).isDirectory()) { Log.d(TAG, "copyFile error:" + srcPath + " is a directory."); return false; } FileInputStream inputStream = null; FileOutputStream outputStream = null; try { File srcFile = new File(srcPath); if (srcFile.exists()) { inputStream = new FileInputStream(srcPath); outputStream = new FileOutputStream(desPath); byte[] buffer = new byte[1024 * 10]; int totalred = 0; int byteread = 0; while ((byteread = inputStream.read(buffer)) != -1) { if (mStopCopy) { File file = new File(desPath); if (file.exists()) { file.delete(); } break; } totalred += byteread; outputStream.write(buffer, 0, byteread); mOperationListener.onRefreshFiles(null, -1, -1, totalred); } outputStream.flush(); outputStream.close(); inputStream.close(); }else { Log.e(TAG, srcPath + " is not exist"); return false; } pathsList.add(desPath); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * start cut files to new path * @param newPath new path * @return */ public boolean doCut(String newPath) { Log.d(TAG, "doCut:" + newPath); if (TextUtils.isEmpty(newPath)) { Log.e(TAG, "doCut:" + newPath+ " is empty"); return false; } final String _path = newPath; asnycExecute(new Runnable() { @Override public void run() { //count file nums int fileCounts = 0; File file = null; for(FileInfo f : mCurFilesList){ file = new File(f.filePath); fileCounts += count(file); } mOperationListener.onRefreshFiles(null, fileCounts, -1, -1); boolean cut_to_child = false; for (FileInfo f : mCurFilesList) { if (mStopCopy) { return; } if (FileManager.containsPath(f.filePath, _path)) { //cannot copy or cut a dir to it's child dir cut_to_child = true; continue; } copyCount ++; mOperationListener.onRefreshFiles(f.fileName, copyCount, -1, -1); moveFile(f, _path); } if (cut_to_child) { mOperationListener.onNotify(MSG_COPY_CUT_TO_CHILD); } clear(); } }); return true; } private boolean moveFile(FileInfo f, String dest) { Log.v(TAG, "MoveFile >>> " + f.filePath + "," + dest); if (f == null || dest == null) { Log.e(TAG, "CopyFile: null parameter"); return false; } String fileName = f.fileName; File file = new File(f.filePath); String newPath = FileManager.makePath(dest, fileName); if (new File(newPath).exists()) { fileName = FileInfoManager.autoRename(fileName); newPath = FileManager.makePath(dest, fileName); } try { //when file.name equals newPath's name.it will return false boolean ret = file.renameTo(new File(newPath)); Log.d(TAG, "MoveFile >>> ret:" + ret); if (ret) { pathsList.add(file.getAbsolutePath()); pathsList.add(newPath); } return ret; } catch (Exception e){ e.printStackTrace(); Log.e(TAG, "Fail to move file," + e.toString()); } return false; } private void asnycExecute(Runnable r) { final Runnable _r = r; new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { synchronized (mCurFilesList) { _r.run(); } String[] filePaths = new String[pathsList.size()]; pathsList.toArray(filePaths); mZyMediaScanner.scanFile(filePaths, null); pathsList.clear(); if (mOperationListener != null) { mOperationListener.onFinished(); } return null; } }.execute(); } public void clear() { Log.d(TAG, "clear"); synchronized (mCurFilesList) { mCurFilesList.clear(); } copyCount = 0; mStopCopy = false; } private int count(File f){ int count = 0; if (f.isDirectory()) { File[] files = f.listFiles(); for(File file : files){ count += count(file); } }else { count ++; } return count; } private boolean mStopCopy = false; public void stopCopy(){ mStopCopy = true; clear(); } } <file_sep>package com.zhaoyan.juyou.provider; import android.net.Uri; import android.provider.BaseColumns; public class AppData{ public static final String DATABASE_NAME = "Appinfos.db"; public static final int DATABASE_VERSION = 1; public static final String AUTHORITY = "com.zhaoyan.juyou.provider.AppProvider"; /** * table App */ public static final class App implements BaseColumns{ public static final String TABLE_NAME = "app"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/app"); public static final Uri CONTENT_FILTER_URI = Uri.parse("content://" + AUTHORITY + "/app_filter"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/app"; public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/app"; //items /** * package name, type:String */ public static final String PKG_NAME = "pkgName"; /** * app label, type:String */ public static final String LABEL = "label"; /** * app size, type:long */ public static final String APP_SIZE = "AppSize"; /** * Version,type:String */ public static final String VERSION = "version"; /** * last modify time,mills,type:long */ public static final String DATE = "date"; /** * app type,my app or normal app,Type:int */ public static final String TYPE = "AppType"; /**app icon,Type:blob*/ public static final String ICON = "icon"; /**app path*/ public static final String PATH = "path"; /**order by label ASC*/ public static final String SORT_ORDER_LABEL = LABEL + " ASC"; } /**game table*/ public static final class AppGame implements BaseColumns{ public static final String TABLE_NAME = "game"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/game"); public static final Uri CONTENT_FILTER_URI = Uri.parse("content://" + AUTHORITY + "/game_filter"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/game"; public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/game"; } } <file_sep>package com.zhaoyan.communication.protocol; import android.content.Context; /** * This class is used for encode the message based on protocol. * */ public class ProtocolEncoder { public static byte[] encodeLoginRequest(Context context) { return LoginProtocol.encodeLoginRequest(context); } public static byte[] encodeSendMessageToSingle(byte[] msg, int sendUserID, int receiveUserID, int appID) { return SendProtocol.encodeSendMessageToSingle(msg, sendUserID, receiveUserID, appID); } public static byte[] encodeSendMessageToAll(byte[] msg, int sendUserID, int appID) { return SendProtocol.encodeSendMessageToAll(msg, sendUserID, appID); } public static void encodeUpdateAllUser(Context context) { LoginProtocol.encodeUpdateAllUser(context); } public static byte[] encodeSendFile(int sendUserID, int receiveUserID, int appID, byte[] inetAddressData, int serverPort, FileTransferInfo fileInfo) { return FileTransportProtocol.encodeSendFile(sendUserID, receiveUserID, appID, inetAddressData, serverPort, fileInfo); } } <file_sep>package com.zhaoyan.communication.recovery; import android.content.Context; public class ClientRecoveryWifi extends Recovery { private Context mContext; public ClientRecoveryWifi(Context context) { mContext = context; } @Override protected boolean doRecovery() { // TODO Auto-generated method stub return false; } @Override public void getLastSatus() { // TODO Auto-generated method stub } } <file_sep>package com.zhaoyan.communication.protocol; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.SocketCommunication; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBBase; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBType; /** * Decode and encode {@link PBBase}. Dispatch messages based on message type. * */ public class BaseProtocol extends MessageDispatcher { private static final String TAG = "BaseProtocol"; public boolean decode(byte[] msgData, SocketCommunication communication) { boolean result = false; try { PBBase pbBase = PBBase.parseFrom(msgData); PBType type = pbBase.getType(); byte[] msgDataInner = pbBase.getMessage().toByteArray(); if (dispatchMessage(type, msgDataInner, communication)) { Log.d(TAG, "dispatchMessage success. type = " + type); result = true; } else { Log.d(TAG, "dispatchMessage fail. type = " + type); result = false; } } catch (InvalidProtocolBufferException e) { Log.e(TAG, "decode " + e); } return result; } /** * Wrap message with message type. * * @param type * @param message * @return */ public static PBBase createBaseMessage(PBType type, Message message) { PBBase.Builder pbBaseBuilder = PBBase.newBuilder(); pbBaseBuilder.setType(type); pbBaseBuilder.setMessage(message.toByteString()); return pbBaseBuilder.build(); } } <file_sep>package com.zhaoyan.juyou.common; import java.io.File; import java.util.ArrayList; import java.util.List; import com.zhaoyan.common.file.FileManager; import com.zhaoyan.common.file.MultiMediaScanner; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.dialog.ZyProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; public class FileDeleteHelper { private static final String TAG = "MediaDeleteHelper"; private List<String> mCurDelList = new ArrayList<String>(); //for mediascanner List<String> mPathList = new ArrayList<String>(); private ZyProgressDialog progressDialog = null; private OnDeleteListener mOnDeleteListener = null; private Context mContext; public interface OnDeleteListener{ public void onDeleteFinished(); } public void setOnDeleteListener(OnDeleteListener listener){ mOnDeleteListener = listener; } public void cancelDeleteListener(){ if (null != mOnDeleteListener) { mOnDeleteListener = null; } } public FileDeleteHelper(Context context){ mContext = context; } /** * record current operation fileinfos * @param files */ public void setDeletePathList(List<String> paths) { copyFileList(paths); } private void copyFileList(List<String> paths) { synchronized(mCurDelList) { mCurDelList.clear(); for (String path : paths) { mCurDelList.add(path); } } } public void doDelete(){ asyncExecute(new Runnable() { @Override public void run() { for(String path: mCurDelList){ if (mStopDelete) { break; } doDeleteFiles(new File(path)); // for (int i = 0; i < mPathList.size(); i++) { // Log.d(TAG, "pathList[" + i + "]:" + mPathList.get(i)); // } } MultiMediaScanner.scanFiles(mContext, mPathList, null); clear(); } }); } private void doDeleteFiles(File file){ if (file.isFile()) { FileManager.deleteFile(file); mPathList.add(file.getAbsolutePath()); return; }else { //dir alse need to update db mPathList.add(file.getAbsolutePath()); File[] files = file.listFiles(); if (null != files) { //delete child files for(File f : files){ if (mStopDelete) { return; } if (f.isDirectory()) { doDeleteFiles(f); }else { FileManager.deleteFile(f); mPathList.add(f.getAbsolutePath()); } } } //delete dir FileManager.deleteFile(file); } } private void asyncExecute(Runnable r) { final Runnable _r = r; new AsyncTask<Void, Void, Void>() { protected void onPreExecute() { progressDialog = new ZyProgressDialog(mContext); progressDialog.setMessage(R.string.deleting); progressDialog.show(); }; @Override protected Void doInBackground(Void... params) { synchronized (mCurDelList) { _r.run(); } if (mOnDeleteListener != null) { mOnDeleteListener.onDeleteFinished(); } return null; } protected void onPostExecute(Void result) { if (null != progressDialog) { progressDialog.cancel(); progressDialog = null; } }; }.execute(); } public void clear() { Log.d(TAG, "clear"); synchronized (mCurDelList) { mCurDelList.clear(); mPathList.clear(); } mStopDelete = false; } private boolean mStopDelete = false; public void stopCopy(){ mStopDelete = true; clear(); } } <file_sep>package com.zhaoyan.juyou.activity; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Vector; import android.app.Dialog; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.common.util.IntentBuilder; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.util.SharedPreferenceUtil; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.adapter.FileInfoAdapter; import com.zhaoyan.juyou.adapter.FileInfoAdapter.ViewHolder; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.ActionMenu.ActionMenuItem; import com.zhaoyan.juyou.common.FileCategoryScanner; import com.zhaoyan.juyou.common.FileCategoryScanner.FileCategoryScanListener; import com.zhaoyan.juyou.common.FileDeleteHelper.OnDeleteListener; import com.zhaoyan.juyou.common.FileDeleteHelper; import com.zhaoyan.juyou.common.FileIconHelper; import com.zhaoyan.juyou.common.FileInfo; import com.zhaoyan.juyou.common.FileInfoManager; import com.zhaoyan.juyou.common.FileTransferUtil; import com.zhaoyan.juyou.common.MenuBarInterface; import com.zhaoyan.juyou.common.ZyStorageManager; import com.zhaoyan.juyou.common.FileTransferUtil.TransportCallback; import com.zhaoyan.juyou.dialog.ZyDeleteDialog; import com.zhaoyan.juyou.dialog.ZyAlertDialog.OnZyAlertDlgClickListener; public class FileCategoryActivity extends BaseActivity implements OnItemClickListener, OnItemLongClickListener, OnScrollListener, FileCategoryScanListener, MenuBarInterface { private static final String TAG = "FileCategoryActivity"; private ProgressBar mLoadingBar; private ListView mListView; private TextView mTipView; private ViewGroup mViewGroup; private List<FileInfo> mItemLists = new ArrayList<FileInfo>(); protected FileInfoAdapter mAdapter; protected FileInfoManager mFileInfoManager; private FileCategoryScanner mFileCategoryScanner; public static final int TYPE_DOC = 0; public static final int TYPE_ARCHIVE = 1; public static final int TYPE_APK = 2; public static final String CATEGORY_TYPE = "CATEGORY_TYPE"; private int mType = -1; private String[] filterType = null; private FileIconHelper mIconHelper; private Notice mNotice = null; private static final int MSG_UPDATE_UI = 0; private static final int MSG_UPDATE_LIST = 1; private static final int MSG_SCAN_START = 2; private static final int MSG_SCAN_COMPLETE = 3; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SCAN_START: mLoadingBar.setVisibility(View.VISIBLE); mTipView.setVisibility(View.VISIBLE); mTipView.setText(R.string.file_Category_loading); break; case MSG_SCAN_COMPLETE: mLoadingBar.setVisibility(View.INVISIBLE); mTipView.setVisibility(View.INVISIBLE); Vector<FileInfo> fileInfos = (Vector<FileInfo>) msg.obj; mAdapter.setList(fileInfos); mAdapter.selectAll(false); mAdapter.notifyDataSetChanged(); updateTitleNum(-1, fileInfos.size()); break; case MSG_UPDATE_LIST: List<FileInfo> fileList = mAdapter.getList(); updateTitleNum(-1, mAdapter.getCount()); mNotice.showToast(R.string.operator_over); List<Integer> poslist = new ArrayList<Integer>(); Bundle bundle = msg.getData(); if (null != bundle) { poslist = bundle.getIntegerArrayList("position"); // Log.d(TAG, "poslist.size=" + poslist); int removePosition; for(int i = 0; i < poslist.size() ; i++){ //remove from the last item to the first item removePosition = poslist.get(poslist.size() - (i + 1)); // Log.d(TAG, "removePosition:" + removePosition); fileList.remove(removePosition); mAdapter.notifyDataSetChanged(); } updateTitleNum(-1, fileList.size()); }else { Log.e(TAG, "bundle is null"); } break; default: break; } }; }; @Override protected void onCreate(android.os.Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.category_main); Bundle bundle = getIntent().getExtras(); mType = bundle.getInt(CATEGORY_TYPE); if (TYPE_DOC == mType) { initTitle(R.string.file_document); filterType = getResources().getStringArray(R.array.doc_file); } else if (TYPE_ARCHIVE == mType) { initTitle(R.string.file_compressed); filterType = getResources().getStringArray(R.array.archive_file); } else if (TYPE_APK == mType) { initTitle(R.string.file_apk); filterType = getResources().getStringArray(R.array.apk_file); } setTitleNumVisible(true); mListView = (ListView) findViewById(R.id.lv_Category); mListView.setOnItemClickListener(this); mListView.setOnItemLongClickListener(this); mListView.setOnScrollListener(this); mTipView = (TextView) findViewById(R.id.tv_Category_tip); mLoadingBar = (ProgressBar) findViewById(R.id.bar_loading_Category); mViewGroup = (ViewGroup) findViewById(R.id.rl_Category_main); mIconHelper = new FileIconHelper(getApplicationContext()); mAdapter = new FileInfoAdapter(getApplicationContext(), mItemLists, mIconHelper); mListView.setAdapter(mAdapter); mFileInfoManager = new FileInfoManager(); mNotice = new Notice(getApplicationContext()); initMenuBar(); ZyStorageManager zsm = ZyStorageManager.getInstance(getApplicationContext()); String[] volumnPaths = zsm.getVolumePaths(); if (volumnPaths == null) { Log.e(TAG, "No storage."); mTipView.setVisibility(View.VISIBLE); mTipView.setText(R.string.no_sdcard); mListView.setEmptyView(mTipView); } else if (volumnPaths.length == 1) { //only internal storage Log.d(TAG, "internal path:" + volumnPaths[0]); File internalFileRoot = new File(volumnPaths[0]); mFileCategoryScanner = new FileCategoryScanner(getApplicationContext(), internalFileRoot,filterType, mType); } else { //have internal & external Log.d(TAG, "internal path:" + volumnPaths[0]); Log.d(TAG, "external path:" + volumnPaths[1]); File[] rootDirs = new File[2]; rootDirs[0] = new File(volumnPaths[0]); rootDirs[1] = new File(volumnPaths[1]); mFileCategoryScanner = new FileCategoryScanner(getApplicationContext(), rootDirs,filterType, mType); //遇到的问题:万一有三张卡呢? 不会吧,如今的手机我可没见过 } if (null != mFileCategoryScanner) { long start = System.currentTimeMillis(); mFileCategoryScanner.setScanListener(this); mFileCategoryScanner.startScan(); Log.d(TAG, "mFileCategoryScanner cost time = " + (System.currentTimeMillis() - start)); } }; @Override protected void onDestroy() { super.onDestroy(); if (null != mFileCategoryScanner) { mFileCategoryScanner.cancelScan(); mFileCategoryScanner.setScanListener(null); } } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (mAdapter.isMode(ActionMenu.MODE_EDIT)) { //do nothing //doCheckAll(); return true; } else { mAdapter.changeMode(ActionMenu.MODE_EDIT); updateTitleNum(1, mAdapter.getCount()); } boolean isSelected = mAdapter.isSelected(position); mAdapter.setSelected(position, !isSelected); mAdapter.notifyDataSetChanged(); mActionMenu = new ActionMenu(getApplicationContext()); getActionMenuInflater().inflate(R.menu.filecategory_menu, mActionMenu); startMenuBar(); return true; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mAdapter.isMode(ActionMenu.MODE_EDIT)) { mAdapter.setSelected(position); mAdapter.notifyDataSetChanged(); int selectedCount = mAdapter.getSelectedItems(); updateTitleNum(selectedCount, mAdapter.getCount()); updateMenuBar(); mMenuBarManager.refreshMenus(mActionMenu); } else { // open file IntentBuilder.viewFile(this, mAdapter.getItem(position).filePath); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (TYPE_DOC == mType || TYPE_ARCHIVE == mType) { return; } switch (scrollState) { case OnScrollListener.SCROLL_STATE_FLING: mAdapter.setFlag(false); break; case OnScrollListener.SCROLL_STATE_IDLE: mAdapter.setFlag(true); mAdapter.notifyDataSetChanged(); break; case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: mAdapter.setFlag(false); break; default: break; } } @Override public void onMenuItemClick(ActionMenuItem item) { switch (item.getItemId()) { case R.id.menu_send: doTransfer(); break; case R.id.menu_delete: showDeleteDialog(); break; case R.id.menu_info: List<FileInfo> list = mAdapter.getSelectedFileInfos(); mFileInfoManager.showInfoDialog(this, list); break; case R.id.menu_select: doCheckAll(); break; case R.id.menu_rename: List<FileInfo> renameList = mAdapter.getSelectedFileInfos(); mFileInfoManager.showRenameDialog(this, renameList); mAdapter.notifyDataSetChanged(); destroyMenuBar(); break; default: break; } } @Override public void destroyMenuBar() { super.destroyMenuBar(); mAdapter.changeMode(ActionMenu.MODE_NORMAL); mAdapter.clearSelected(); mAdapter.notifyDataSetChanged(); updateTitleNum(-1, mAdapter.getCount()); } @Override public void updateMenuBar() { int selectCount = mAdapter.getSelectedItems(); updateTitleNum(selectCount, mAdapter.getCount()); ActionMenuItem selectItem = mActionMenu.findItem(R.id.menu_select); if (mAdapter.getCount() == selectCount) { selectItem.setTitle(R.string.unselect_all); selectItem.setEnableIcon(R.drawable.ic_aciton_unselect); } else { selectItem.setTitle(R.string.select_all); selectItem.setEnableIcon(R.drawable.ic_aciton_select); } if (0==selectCount) { mActionMenu.findItem(R.id.menu_send).setEnable(false); mActionMenu.findItem(R.id.menu_delete).setEnable(false); mActionMenu.findItem(R.id.menu_rename).setEnable(false); mActionMenu.findItem(R.id.menu_info).setEnable(false); }else { mActionMenu.findItem(R.id.menu_send).setEnable(true); mActionMenu.findItem(R.id.menu_delete).setEnable(true); mActionMenu.findItem(R.id.menu_rename).setEnable(true); mActionMenu.findItem(R.id.menu_info).setEnable(true); } } @Override public void doCheckAll() { int selectedCount = mAdapter.getSelectedItems(); if (mAdapter.getCount() != selectedCount) { mAdapter.selectAll(true); } else { mAdapter.selectAll(false); } updateMenuBar(); mMenuBarManager.refreshMenus(mActionMenu); mAdapter.notifyDataSetChanged(); } /** * do Tranfer files */ public void doTransfer() { ArrayList<String> checkedList = (ArrayList<String>) mAdapter .getSelectedFilePaths(); // send FileTransferUtil fileTransferUtil = new FileTransferUtil( FileCategoryActivity.this); fileTransferUtil.sendFiles(checkedList, new TransportCallback() { @Override public void onTransportSuccess() { int first = mListView.getFirstVisiblePosition(); int last = mListView.getLastVisiblePosition(); List<Integer> checkedItems = mAdapter .getSelectedItemsPos(); ArrayList<ImageView> icons = new ArrayList<ImageView>(); for (int id : checkedItems) { if (id >= first && id <= last) { View view = mListView.getChildAt(id - first); if (view != null) { ViewHolder viewHolder = (ViewHolder) view.getTag(); icons.add(viewHolder.iconView); } } } if (icons.size() > 0) { ImageView[] imageViews = new ImageView[0]; showTransportAnimation(mViewGroup, icons.toArray(imageViews)); } destroyMenuBar(); } @Override public void onTransportFail() { } }); } /** * show delete confrim dialog */ public void showDeleteDialog() { final List<FileInfo> fileList = mAdapter.getList(); final List<Integer> posList = mAdapter.getSelectedItemsPos(); ZyDeleteDialog deleteDialog = new ZyDeleteDialog(this); deleteDialog.setTitle(R.string.delete_file); String msg = ""; if (posList.size() == 1) { msg = getString(R.string.delete_file_confirm_msg, fileList.get(posList.get(0)).fileName); }else { msg = getString(R.string.delete_file_confirm_msg_file, posList.size()); } deleteDialog.setMessage(msg); deleteDialog.setPositiveButton(R.string.menu_delete, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { FileDeleteHelper deleteHelper = new FileDeleteHelper(FileCategoryActivity.this); deleteHelper.setDeletePathList(mAdapter.getSelectedFilePaths()); deleteHelper.setOnDeleteListener(new OnDeleteListener() { @Override public void onDeleteFinished() { //when delete over,send message to update ui Message message = mHandler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putIntegerArrayList("position", (ArrayList<Integer>)posList); message.setData(bundle); message.what = MSG_UPDATE_LIST; message.sendToTarget(); } }); deleteHelper.doDelete(); dialog.dismiss(); destroyMenuBar(); } }); deleteDialog.setNegativeButton(R.string.cancel, null); deleteDialog.show(); } @Override public boolean onBackKeyPressed() { if (mAdapter.isMode(ActionMenu.MODE_EDIT)) { destroyMenuBar(); return false; } return super.onBackKeyPressed(); } @Override public void onScanStart() { Log.d(TAG, "onScanStart"); mHandler.sendEmptyMessage(MSG_SCAN_START); } @Override public void onScanComplete(Vector<FileInfo> fileInfos) { Log.d(TAG, "onScanComplete"); Message message = mHandler.obtainMessage(MSG_SCAN_COMPLETE); message.obj = fileInfos; message.sendToTarget(); } @Override public void onScanCancel() { Log.d(TAG, "onScanCancel"); } } <file_sep>package com.zhaoyan.communication.protocol; import android.content.Context; import com.dreamlink.communication.aidl.User; import com.google.protobuf.InvalidProtocolBufferException; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.ProtocolCommunication; import com.zhaoyan.communication.SocketCommunication; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBBase; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBType; import com.zhaoyan.communication.protocol.pb.PBLogoutProtos.PBLogoutClient; import com.zhaoyan.communication.protocol.pb.PBLogoutProtos.PBLogoutServer; public class LogoutProtocol implements IProtocol { private static final String TAG = "LogoutProtocol"; @Override public PBType[] getMessageTypes() { return new PBType[] { PBType.LOGOUT_CLIENT, PBType.LOGOUT_SERVER }; } @Override public boolean decode(PBType type, byte[] msgData, SocketCommunication communication) { boolean result = false; if (type == PBType.LOGOUT_CLIENT) { decodeLogoutClient(msgData, communication); result = true; } else if (type == PBType.LOGOUT_SERVER) { decodeLogoutServer(msgData, communication); result = true; } return result; } public static void encodeLogoutSever(Context context) { UserManager userManager = UserManager.getInstance(); User localUser = userManager.getLocalUser(); PBLogoutServer.Builder builder = PBLogoutServer.newBuilder(); builder.setUserId(localUser.getUserID()); PBLogoutServer pbLogoutServer = builder.build(); PBBase pbBase = BaseProtocol.createBaseMessage(PBType.LOGOUT_SERVER, pbLogoutServer); SocketCommunicationManager communicationManager = SocketCommunicationManager .getInstance(); communicationManager .sendMessageToAllWithoutEncode(pbBase.toByteArray()); } private void decodeLogoutServer(byte[] msgData, SocketCommunication communication) { Log.d(TAG, "decodeLogoutServer"); UserManager userManager = UserManager.getInstance(); userManager.resetLocalUser(); SocketCommunicationManager socketCommunicationManager = SocketCommunicationManager .getInstance(); socketCommunicationManager.closeAllCommunication(); } public static void encodeLogoutClient(Context context) { UserManager userManager = UserManager.getInstance(); User localUser = userManager.getLocalUser(); PBLogoutClient.Builder builder = PBLogoutClient.newBuilder(); builder.setUserId(localUser.getUserID()); PBLogoutClient pbLogoutClient = builder.build(); PBBase pbBase = BaseProtocol.createBaseMessage(PBType.LOGOUT_CLIENT, pbLogoutClient); try { User serverUser = userManager.getServer(); SocketCommunication communication = userManager .getAllCommmunication().get(serverUser.getUserID()); communication.sendMessage(pbBase.toByteArray()); } catch (NullPointerException e) { Log.e(TAG, "encodeLogoutClient" + e); } } private void decodeLogoutClient(byte[] msgData, SocketCommunication communication) { Log.d(TAG, "decodeLogoutClient"); UserManager userManager = UserManager.getInstance(); boolean isLocalUserServer = UserManager.isManagerServer(userManager .getLocalUser()); if (!isLocalUserServer) { Log.w(TAG, "decodeLogoutClient, only server process logout of client."); return; } PBLogoutClient pbLogoutClient = null; try { pbLogoutClient = PBLogoutClient.parseFrom(msgData); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "decodeLogoutClient " + e); } if (pbLogoutClient != null) { int userId = pbLogoutClient.getUserId(); Log.d(TAG, "decodeLogoutClient userId = " + userId); // Stop SocketCommunicaton SocketCommunicationManager socketCommunicationManager = SocketCommunicationManager .getInstance(); SocketCommunication socketCommunication = userManager .getSocketCommunication(userId); if (socketCommunication != null) { socketCommunicationManager .stopCommunication(socketCommunication); } // Remove user from user manager. userManager.removeUser(userId); // Update user list. ProtocolCommunication protocolCommunication = ProtocolCommunication .getInstance(); protocolCommunication.sendMessageToUpdateAllUser(); } } } <file_sep>package com.zhaoyan.juyou.adapter; import com.zhaoyan.juyou.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class HeadChooseAdapter extends BaseAdapter { private int[] mHeadImages; private LayoutInflater mLayoutInflater; public HeadChooseAdapter(Context context, int[] images) { mHeadImages = images; mLayoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return mHeadImages.length; } @Override public Object getItem(int position) { return mHeadImages[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = mLayoutInflater.inflate(R.layout.account_setting_head_item, null); } ImageView headImageView = (ImageView) view .findViewById(R.id.iv_ashi_head); headImageView.setImageResource(mHeadImages[position]); return view; } } <file_sep>package com.zhaoyan.juyou; public interface ILogin { boolean login(); } <file_sep>package com.zhaoyan.communication.protocol; import android.content.Context; import android.util.Log; import com.zhaoyan.communication.SocketCommunication; /** * Manage all protocols. * */ public class ProtocolManager { private static final String TAG = "ProtocolManager"; private BaseProtocol mBaseProtocol; private Context mContext; public ProtocolManager(Context context) { mContext = context; } public void init() { Log.d(TAG, "init()"); mBaseProtocol = new BaseProtocol(); mBaseProtocol.addProtocol(new LoginProtocol(mContext)); mBaseProtocol.addProtocol(new UserUpdateProtocol(mContext)); mBaseProtocol.addProtocol(new MessageSendProtocol(mContext)); mBaseProtocol.addProtocol(new FileTransportProtocol(mContext)); mBaseProtocol.addProtocol(new LogoutProtocol()); } /** * Decode the message. * * @param msgData * @param communication * @return decode result whether the message is decoded. */ public boolean decode(byte[] msgData, SocketCommunication communication) { boolean result = mBaseProtocol.decode(msgData, communication); return result; } } <file_sep>package com.zhaoyan.communication.connect; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.text.TextUtils; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.net.WiFiAP; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.communication.search.WiFiNameEncryption; import com.zhaoyan.communication.search.WifiNameSuffixLoader; public class ServerCreatorAp { private static final String TAG = "ServerCreatorAp"; private Context mContext; private BroadcastReceiver mWifiApBroadcastReceiver; private boolean mIsCreated = false; private ServerCreateAndDiscovery mServerCreateAndDiscovery; public ServerCreatorAp(Context context) { mContext = context; } public void createServer() { if (mIsCreated) { return; } Log.d(TAG, "createServer"); mIsCreated = true; // Disalbe AP if needed. if (NetWorkUtil.isWifiApEnabled(mContext)) { NetWorkUtil.setWifiAPEnabled(mContext, null, false); } // Enable AP. enableAP(); mWifiApBroadcastReceiver = new WifiApBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(WiFiAP.ACTION_WIFI_AP_STATE_CHANGED); mContext.registerReceiver(mWifiApBroadcastReceiver, filter); } public void stopServer() { if (!mIsCreated) { return; } Log.d(TAG, "stopServer"); mIsCreated = false; try { mContext.unregisterReceiver(mWifiApBroadcastReceiver); } catch (Exception e) { } if (mServerCreateAndDiscovery != null) { mServerCreateAndDiscovery.stopServerAndDiscovery(); } if (NetWorkUtil.isWifiApEnabled(mContext)) { NetWorkUtil.setWifiAPEnabled(mContext, null, false); } } private void enableAP() { // Get wifi ap name. String wifiAPName = null; String wifiNameSuffix = WifiNameSuffixLoader .getWifiNameSuffix(mContext); UserInfo userInfo = UserHelper.loadLocalUser(mContext); if (TextUtils.isEmpty(wifiNameSuffix)) { wifiNameSuffix = WifiNameSuffixLoader .createNewWifiSuffixName(mContext); wifiAPName = WiFiNameEncryption.generateWiFiName(userInfo.getUser() .getUserName(), userInfo.getHeadId(), wifiNameSuffix); } else { wifiAPName = WiFiNameEncryption.generateWiFiName(userInfo.getUser() .getUserName(), userInfo.getHeadId(), wifiNameSuffix); } String wifiAPPassword = WiFiNameEncryption.getWiFiPassword(wifiAPName); NetWorkUtil .setWifiAPEnabled(mContext, wifiAPName, wifiAPPassword, true); } private class WifiApBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "onReceive, action: " + action); if (WiFiAP.ACTION_WIFI_AP_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(WiFiAP.EXTRA_WIFI_AP_STATE, WiFiAP.WIFI_AP_STATE_FAILED); handleWifiApChanged(state); } } private void handleWifiApChanged(int wifiApState) { switch (wifiApState) { case WiFiAP.WIFI_AP_STATE_ENABLED: Log.d(TAG, "WIFI_AP_STATE_ENABLED"); createServerAndStartDiscoveryService(); break; case WiFiAP.WIFI_AP_STATE_DISABLED: Log.d(TAG, "WIFI_AP_STATE_DISABLED"); stopServerAndStopDiscoveryService(); break; case WiFiAP.WIFI_AP_STATE_FAILED: Log.d(TAG, "WIFI_AP_STATE_FAILED"); break; default: Log.d(TAG, "handleWifiApchanged, unkown state: " + wifiApState); if (NetWorkUtil.isWifiApEnabled(mContext)) { Log.d(TAG, "Wifi AP is enabled."); createServerAndStartDiscoveryService(); } else { Log.d(TAG, "Wifi AP is disabled."); stopServerAndStopDiscoveryService(); } break; } } private void stopServerAndStopDiscoveryService() { if (mServerCreateAndDiscovery != null) { mServerCreateAndDiscovery.stopServerAndDiscovery(); mServerCreateAndDiscovery = null; } } private void createServerAndStartDiscoveryService() { if (mServerCreateAndDiscovery == null) { mServerCreateAndDiscovery = new ServerCreateAndDiscovery( mContext, ServerCreator.TYPE_AP); mServerCreateAndDiscovery.start(); } } } } <file_sep>package com.zhaoyan.juyou; import com.dreamlink.communication.aidl.User; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.juyou.provider.JuyouData; import android.content.Context; public class DirectLogin implements ILogin { private static final String TAG = "DirectLogin"; private Context mContext; public DirectLogin(Context context) { mContext = context; } @Override public boolean login() { Log.d(TAG, "login"); // Logout previous account. AccountHelper.logoutCurrentAccount(mContext); // Set account. AccountInfo accountInfo = AccountHelper.getTouristAccount(mContext); if (accountInfo == null) { // there is no tourist account. accountInfo = new AccountInfo(); accountInfo.setUserName(android.os.Build.MANUFACTURER); accountInfo.setHeadId(0); accountInfo.setTouristAccount(JuyouData.Account.TOURIST_ACCOUNT_TRUE); accountInfo = AccountHelper.addAccount(mContext, accountInfo); } AccountHelper.setAccountLogin(mContext, accountInfo); // Set userinfo UserInfo userInfo = UserHelper.loadLocalUser(mContext); if (userInfo == null) { // This is the first time launch. Set user info. userInfo = new UserInfo(); userInfo.setUser(new User()); userInfo.setType(JuyouData.User.TYPE_LOCAL); } userInfo.getUser().setUserName(accountInfo.getUserName()); userInfo.getUser().setUserID(0); userInfo.setHeadId(accountInfo.getHeadId()); userInfo.setHeadBitmapData(accountInfo.getHeadData()); UserHelper.saveLocalUser(mContext, userInfo); return true; } } <file_sep>package com.zhaoyan.communication.search; import java.util.List; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class ServerSearcherAndroidAP { private static final String TAG = "ServerSearcherAndroidAP"; private Context mContext; private WifiManager mWifiManager; private OnSearchListenerAP mOnSearchListener; private BroadcastReceiver mWifiBroadcastReceiver; private boolean mIsStarted; public ServerSearcherAndroidAP(Context context) { mContext = context.getApplicationContext(); mWifiManager = (WifiManager) mContext .getSystemService(Context.WIFI_SERVICE); } public void setOnSearchListener(OnSearchListenerAP listener) { mOnSearchListener = listener; } public void startSearch() { if (mIsStarted) { return; } Log.d(TAG, "startSearch"); mIsStarted = true; // close wifi ap if needed. if (NetWorkUtil.isWifiApEnabled(mContext)) { NetWorkUtil.setWifiAPEnabled(mContext, null, false); } // open wifi or start scan. if (!mWifiManager.isWifiEnabled()) { mWifiManager.setWifiEnabled(true); } else { mWifiManager.startScan(); } mWifiBroadcastReceiver = new WifiBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); mContext.registerReceiver(mWifiBroadcastReceiver, intentFilter); } public void stopSearch() { if (!mIsStarted) { return; } Log.d(TAG, "stopSearch"); mIsStarted = false; mOnSearchListener = null; try { mContext.unregisterReceiver(mWifiBroadcastReceiver); } catch (Exception e) { Log.e(TAG, "stopSearch " + e); } } private class WifiBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "onReceive, action = " + action); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { handleWifiStateChanged(intent.getIntExtra( WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)); } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) { handleScanReuslt(); } } private void handleScanReuslt() { Log.d(TAG, "handleScanReuslt()"); final List<ScanResult> results = mWifiManager.getScanResults(); if (results == null) { return; } for (ScanResult result : results) { Log.d(TAG, "handleScanReuslt, wifi: " + result.SSID); if (WiFiNameEncryption.checkWiFiName(result.SSID)) { Log.d(TAG, "handleScanReuslt, Found a matched wifi: " + result.SSID); WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); if (wifiInfo != null) { String connectedSSID = wifiInfo.getSSID(); if (connectedSSID != null) { if (connectedSSID.equals("\"" + result.SSID + "\"") || connectedSSID.equals(result.SSID)) { // Already connected to the ssid ignore. Log.d(TAG, "Already connected to the ssid ignore. " + result.SSID); continue; } } } // Add this android wifi Ap server into database if (mOnSearchListener != null) { mOnSearchListener.onFoundAPServer(result.SSID); } } } } private void handleWifiStateChanged(int wifiState) { switch (wifiState) { case WifiManager.WIFI_STATE_ENABLING: Log.d(TAG, "WIFI_STATE_ENABLING"); break; case WifiManager.WIFI_STATE_ENABLED: Log.d(TAG, "WIFI_STATE_ENABLED"); Log.d(TAG, "Start WiFi scan."); mWifiManager.startScan(); // if (mSearchServer != null) // mSearchServer.startSearch(); break; case WifiManager.WIFI_STATE_DISABLING: Log.d(TAG, "WIFI_STATE_DISABLING"); break; case WifiManager.WIFI_STATE_DISABLED: Log.d(TAG, "WIFI_STATE_DISABLED"); break; default: break; } } } public interface OnSearchListenerAP { void onFoundAPServer(String ssid); } } <file_sep>package com.zhaoyan.juyou.common; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; /** * description a file infos */ public class FileInfo implements Parcelable { public boolean isDir = false; // File name public String fileName = ""; // File Size,(bytes) public double fileSize = 0; // File Last modifed date public long fileDate; // absoulte path public String filePath; // icon public Drawable icon; // default 0:neither image nor apk; 1-->image; 2-->apk; public int type; public Object obj; // media file's play total time public long time; //how many files that in the folder public int count; public FileInfo(String filename) { this.fileName = filename; } private FileInfo(Parcel in) { readFromParcel(in); } public static final Parcelable.Creator<FileInfo> CREATOR = new Parcelable.Creator<FileInfo>() { @Override public FileInfo createFromParcel(Parcel source) { return new FileInfo(source); } @Override public FileInfo[] newArray(int size) { return new FileInfo[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(isDir ? 1 : 0); dest.writeString(fileName); dest.writeDouble(fileSize); dest.writeLong(fileDate); dest.writeString(filePath); } public void readFromParcel(Parcel in) { isDir = in.readInt() == 1 ? true : false; fileName = in.readString(); fileSize = in.readDouble(); fileDate = in.readLong(); filePath = in.readString(); } public static Comparator<FileInfo> getNameComparator() { return new NameComparator(); } public static class NameComparator implements Comparator<FileInfo> { @Override public int compare(FileInfo lhs, FileInfo rhs) { String name1 = lhs.fileName; String name2 = rhs.fileName; if (name1.compareToIgnoreCase(name2) < 0) { return -1; } else if (name1.compareToIgnoreCase(name2) > 0) { return 1; } return 0; } }; public static Comparator<FileInfo> getDateComparator() { return new DateComparator(); } /** * sort by modify date */ public static class DateComparator implements Comparator<FileInfo> { @Override public int compare(FileInfo object1, FileInfo object2) { long date1 = object1.fileDate; long date2 = object2.fileDate; if (date1 > date2) { return -1; } else if (date1 == date2) { return 0; } else { return 1; } } }; } <file_sep>package com.zhaoyan.communication.search; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; import android.content.Context; import android.util.Log; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.communication.search.SearchProtocol.OnSearchListener; /** * This class is use for search server in WiFi network in which the AP is * android WiFi hot access point.</br> * * This class is single instance, So use {@link #getInstance(Context)} to get * object.</br> * * After started, we send UDP packet to android WiFi hot AP which IP address is * 192.168.43.1 to confirm it is server or not. If the android WiFi hot AP * responds that it is a server, we found a server. </br> * */ public class SearchSeverLanAndroidAP implements Runnable { private static final String TAG = "SearchSeverLanAndroidAP"; // Socket for receive server respond. private DatagramSocket mReceiveRespondSocket; // Address for send search request. private InetAddress mSendRequestAddress; // Socket for send search request. private DatagramSocket mSendRequestSocket; private DatagramPacket mSendRequestPacket; private OnSearchListener mListener; private boolean mStopped = false; private boolean mStarted = false; private static SearchSeverLanAndroidAP mInstance; private Context mContext; public static SearchSeverLanAndroidAP getInstance(Context context) { if (mInstance == null) { mInstance = new SearchSeverLanAndroidAP(context); } return mInstance; } private SearchSeverLanAndroidAP(Context context) { mContext = context; } public void setOnSearchListener(OnSearchListener listener) { mListener = listener; } @Override public void run() { try { mReceiveRespondSocket = new DatagramSocket( Search.ANDROID_AP_RECEIVE_PORT); mReceiveRespondSocket.setSoTimeout(Search.TIME_OUT); // request ip mSendRequestAddress = InetAddress .getByName(Search.ANDROID_AP_ADDRESS); mSendRequestSocket = new DatagramSocket(); // request data byte[] request = Search.ANDROID_AP_CLIENT_REQUEST.getBytes(); mSendRequestPacket = new DatagramPacket(request, request.length, mSendRequestAddress, Search.ANDROID_AP_RECEIVE_PORT); } catch (Exception e) { Log.e(TAG, "SearchSeverAPMode error" + e); } startListenServerMessage(); if (!NetWorkUtil.isWifiApEnabled(mContext)) { while (!mStopped) { sendSearchRequest(); try { Thread.sleep(Search.ANDROID_AP_SEARCH_DELAY); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException " + e); } } } } private void sendSearchRequest() { if (mSendRequestSocket != null) { try { mSendRequestSocket.send(mSendRequestPacket); Log.d(TAG, "Send broadcast ok, data = " + new String(mSendRequestPacket.getData())); } catch (IOException e) { Log.e(TAG, "Send broadcast fail, data = " + new String(mSendRequestPacket.getData()) + " " + e); } } else { Log.e(TAG, "sendSearchRequest() fail, mSendRequestSocket is null"); } } public void startSearch() { Log.d(TAG, "Start search."); if (mStarted) { Log.d(TAG, "startSearch() ignore, search is already started."); return; } mStarted = true; Thread searchThread = new Thread(this); searchThread.start(); } public void stopSearch() { Log.d(TAG, "Stop search"); mStarted = false; mStopped = true; closeSocket(); mInstance = null; } private void closeSocket() { if (mReceiveRespondSocket != null) { mReceiveRespondSocket.close(); mReceiveRespondSocket = null; } if (mSendRequestSocket != null) { mSendRequestSocket.close(); mSendRequestSocket = null; } } /** * Listen server message. */ private void startListenServerMessage() { new Thread(new GetPacket()).start(); } /** * Get message from server. * */ class GetPacket implements Runnable { public void run() { DatagramPacket inPacket; String message; while (!mStopped) { try { inPacket = new DatagramPacket(new byte[1024], 1024); mReceiveRespondSocket.receive(inPacket); message = new String(inPacket.getData(), 0, inPacket.getLength()); Log.d(TAG, "Received broadcast, message: " + message); if (message.startsWith(Search.ANDROID_AP_SERVER_RESPOND)) { // Android AP is server. Log.d(TAG, "Android AP is server."); if (mListener != null) { mListener.onSearchSuccess(inPacket.getAddress() .getHostAddress(), message .substring(Search.ANDROID_AP_SERVER_RESPOND .length())); } } else if (message .startsWith(Search.ANDROID_AP_SERVER_REQUEST)) { Log.d(TAG, "This client is an AP. Found a server."); if (mListener != null) { mListener.onSearchSuccess(inPacket.getAddress() .getHostAddress(), message .substring(Search.ANDROID_AP_SERVER_REQUEST .length())); } } } catch (Exception e) { if (e instanceof SocketTimeoutException) { // time out, search again. Log.d(TAG, "GetPacket time out. search again."); } else { Log.e(TAG, "GetPacket error," + e.toString()); if (mListener != null) { mListener.onSearchStop(); } } } } } } } <file_sep>package com.zhaoyan.common.view; import java.util.ArrayList; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; @SuppressLint("NewApi") public class BottomBar extends LinearLayout implements OnClickListener { private ArrayList<BottomBarItem> mItems = new ArrayList<BottomBarItem>(); private OnBottomBarItemSelectChangeListener mListener; private int mLastSelectedPostion = 0; public BottomBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public BottomBar(Context context, AttributeSet attrs) { super(context, attrs); } public BottomBar(Context context) { super(context); } @Override public void onClick(View v) { for (int i = 0; i < mItems.size(); i++) { BottomBarItem item = mItems.get(i); if (v == item.getView()) { if (i != mLastSelectedPostion) { setSelectedItem(i, item); if (mListener != null) { mListener.onBottomBarItemSelectChanged(i, item); } } } } } public void setSelectedPosition(int position) { BottomBarItem item = mItems.get(position); setSelectedItem(position, item); } private void setSelectedItem(int position, BottomBarItem item) { // Update selected item and previous selected item. BottomBarItem previousItem = mItems.get(mLastSelectedPostion); previousItem.setSelected(false); item.setSelected(true); mLastSelectedPostion = position; } public void addItem(BottomBarItem item) { if (mItems.contains(item)) { return; } mItems.add(item); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1); addView(item.getView(), params); item.getView().setOnClickListener(this); } public void removeItem(BottomBarItem item) { if (mItems.contains(item)) { removeView(item.getView()); item.getView().setOnClickListener(null); mItems.remove(item); } } public void setOnBottomBarItemSelectChangeListener( OnBottomBarItemSelectChangeListener listener) { mListener = listener; } public interface OnBottomBarItemSelectChangeListener { void onBottomBarItemSelectChanged(int position, BottomBarItem item); } } <file_sep>package com.zhaoyan.juyou.adapter; import java.util.List; /** * if you want relize multi select function,you need implements thi interface * @author Yuri * */ public interface SelectInterface { /** * change current opertion mode,normal or menu edit * @param mode */ public void changeMode(int mode); /** * is current mode equals spec mode * @param mode * @return */ public boolean isMode(int mode); /** * check All or not * @param isChecked true or false */ public void checkedAll(boolean isChecked); /** * set the item is checked or not * @param position the position that clicked * @param isChecked checked or not */ public void setChecked(int position, boolean isChecked); /** * set the item checked or unselected </br> * if checked, unCheck </br> * if unChecked, check * @param position */ public void setChecked(int position); /** * get the item is checked or not * @param position * @return */ public boolean isChecked(int position); /** * get current checked items count * @return */ public int getCheckedCount(); /** * get current checked items position list * @return */ public List<Integer> getCheckedPosList(); /** * get current checked items name list * @return */ public List<String> getCheckedNameList(); /** * get current checked items file path list * @return */ public List<String> getCheckedPathList(); /** * set listview or gridview is scorll or idle * @param flag */ public void setIdleFlag(boolean flag); } <file_sep>package com.zhaoyan.juyou.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.juyou.AccountHelper; import com.zhaoyan.juyou.AccountInfo; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.common.ZYConstant; public class AccountSettingSignatureActivity extends BaseActivity implements OnClickListener { private static final String TAG = "AccountSettingNameActivity"; private Button mSaveButton; private Button mCanceButton; private EditText mSignaturEditText; private TextView mSignatureWordCount; private Notice mNotice; private static final int MAX_SIGNATURE_WORD_COUNT = 60; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_setting_signature); mNotice = new Notice(this); initTitle(R.string.account_setting_signature_title); initView(); loadSignature(); } private void loadSignature() { AccountInfo accountInfo = AccountHelper.getCurrentAccount(this); String signature = accountInfo.getSignature(); mSignaturEditText.setText(signature); mSignaturEditText.setSelection(mSignaturEditText.length()); } private void initView() { mSaveButton = (Button) findViewById(R.id.btn_save); mSaveButton.setOnClickListener(this); mCanceButton = (Button) findViewById(R.id.btn_cancel); mCanceButton.setOnClickListener(this); mSignaturEditText = (EditText) findViewById(R.id.et_as_signature); mSignaturEditText.addTextChangedListener(mTextWatcher); mSignatureWordCount = (TextView) findViewById(R.id.tv_as_signature_wordcount); setLeftWordCount(); } private void setLeftWordCount() { mSignatureWordCount.setText(String.valueOf(MAX_SIGNATURE_WORD_COUNT - getInputWordCount())); } private long getInputWordCount() { return calculateWordCount(mSignaturEditText.getText().toString()); } /** * Calculate Chinese word count. 1 Chinese word = 2 English word. * * @param c * @return */ private long calculateWordCount(CharSequence c) { double len = 0; for (int i = 0; i < c.length(); i++) { int tmp = (int) c.charAt(i); if (tmp > 0 && tmp < 127) { len += 0.5; } else { len++; } } return Math.round(len); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_save: saveAndQuit(); break; case R.id.btn_cancel: cancelAndQuit(); break; default: break; } } private void cancelAndQuit() { hideInputMethodManager(); finishWithAnimation(); } private void saveAndQuit() { hideInputMethodManager(); saveSignature(); Intent intent = new Intent(ZYConstant.CURRENT_ACCOUNT_CHANGED_ACTION); sendBroadcast(intent); finishWithAnimation(); } private void saveSignature() { AccountInfo accountInfo = AccountHelper.getCurrentAccount(this); accountInfo.setSignature(mSignaturEditText.getText().toString()); AccountHelper.saveCurrentAccount(this, accountInfo); UserInfo userInfo = UserHelper.loadLocalUser(this); userInfo.setSignature(mSignaturEditText.getText().toString()); UserHelper.saveLocalUser(this, userInfo); mNotice.showToast(R.string.account_setting_saved_message); } private void hideInputMethodManager() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow( mSignaturEditText.getWindowToken(), 0); } private TextWatcher mTextWatcher = new TextWatcher() { private int mStart; private int mEnd; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { if (calculateWordCount(s.toString()) > MAX_SIGNATURE_WORD_COUNT) { mStart = mSignaturEditText.getSelectionStart(); mEnd = mSignaturEditText.getSelectionEnd(); while (calculateWordCount(s.toString()) > MAX_SIGNATURE_WORD_COUNT) { s.delete(mStart - 1, mEnd); mStart--; mEnd--; } mSignaturEditText.setSelection(mSignaturEditText.length()); } setLeftWordCount(); } }; } <file_sep>package com.zhaoyan.common.util; import java.io.File; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.text.TextUtils; import android.widget.Toast; import com.zhaoyan.juyou.R; public class IntentBuilder { private static final String TAG = "IntentBuilder"; public static void viewFile(final Context context, final String filePath) { String type = MimeUtils.getMimeType(filePath); if (!TextUtils.isEmpty(type) && !TextUtils.equals(type, "*/*")) { /* 设置intent的file与MimeType */ Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(filePath)), type); try { context.startActivity(intent); } catch (Exception e) { Log.e(TAG, "viewFile&&&&:" + e.toString()); Toast.makeText(context, R.string.open_file_fail, Toast.LENGTH_SHORT).show(); } } else { // unknown MimeType AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); dialogBuilder.setTitle(R.string.dialog_select_type); CharSequence[] menuItemArray = new CharSequence[] { context.getString(R.string.dialog_type_text), context.getString(R.string.dialog_type_audio), context.getString(R.string.dialog_type_video), context.getString(R.string.dialog_type_image) }; dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String selectType = "*/*"; switch (which) { case 0: selectType = "text/plain"; break; case 1: selectType = "audio/*"; break; case 2: selectType = "video/*"; break; case 3: selectType = "image/*"; break; } Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(filePath)), selectType); try { context.startActivity(intent); } catch (Exception e) { Log.e(TAG, "viewFile########:" + e.toString()); Toast.makeText(context, R.string.open_file_fail, Toast.LENGTH_SHORT).show(); } } }); dialogBuilder.show(); } } } <file_sep>package com.zhaoyan.communication.protocol; import java.util.List; import java.util.Map; import android.content.Context; import com.dreamlink.communication.aidl.User; import com.google.protobuf.InvalidProtocolBufferException; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.SocketCommunication; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBBase; import com.zhaoyan.communication.protocol.pb.PBBaseProtos.PBType; import com.zhaoyan.communication.protocol.pb.PBUserUpdateProtos.PBUpdateUserId; import com.zhaoyan.communication.protocol.pb.PBUserUpdateProtos.PBUpdateUserInfo; import com.zhaoyan.juyou.provider.JuyouData; /** * Update all user after user login. Rules is below:</br> * * 1. Server send all user to all users.</br> * * 2. Send one use in one time.</br> * * 3. Send all user id first, then send all user info.</br> * * @see PBUserUpdateProtos * */ public class UserUpdateProtocol implements IProtocol { private static final String TAG = "UserUpdateProtocol"; public UserUpdateProtocol(Context context) { } @Override public PBType[] getMessageTypes() { return new PBType[] { PBType.UPDATE_USER_ID, PBType.UPDATE_USER_INFO }; } @Override public boolean decode(PBType type, byte[] msgData, SocketCommunication communication) { boolean result = true; if (type == PBType.UPDATE_USER_ID) { decodeUpdateUserId(msgData, communication); } else if (type == PBType.UPDATE_USER_INFO) { decodeUpdateUserInfo(msgData, communication); } else { result = false; } return result; } /** * Add new users. * * @param msgData * @param communication * @see #encodeUpdateUserInfo(Context); */ private void decodeUpdateUserInfo(byte[] msgData, SocketCommunication communication) { UserManager userManager = UserManager.getInstance(); PBUpdateUserInfo pbUpdateUserInfo = null; try { pbUpdateUserInfo = PBUpdateUserInfo.parseFrom(msgData); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "decodeUpdateUserInfo " + e); } if (pbUpdateUserInfo != null) { UserInfo userInfo = UserInfoUtil .pbUserInfo2UserInfo(pbUpdateUserInfo.getUserInfo()); userManager.addUpdateUser(userInfo, communication); } } /** * Clear the user not exist. * * @param msgData * @param communication * @see #encodeUpdateUserId(Context) */ private void decodeUpdateUserId(byte[] msgData, SocketCommunication communication) { PBUpdateUserId updateUserId = null; try { updateUserId = PBUpdateUserId.parseFrom(msgData); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "decodeUpdateUserId " + e); } if (updateUserId != null) { List<Integer> userIds = updateUserId.getUserIdList(); UserManager userManager = UserManager.getInstance(); for (int originalId : userManager.getAllUser().keySet()) { boolean originalUserDisconnect = true; for (int updateId : userIds) { if (updateId == originalId) { originalUserDisconnect = false; break; } } if (originalUserDisconnect) { userManager.removeUser(originalId); } } } } /** * Encode and send update user message. * * @param context * @see PBUpdateUserId * @see PBUserInfo */ public static void encodeUpdateAllUser(Context context) { encodeUpdateUserId(context); encodeUpdateUserInfo(context); } private static void encodeUpdateUserId(Context context) { PBUpdateUserId.Builder updateUserIdBuilder = PBUpdateUserId .newBuilder(); UserManager userManager = UserManager.getInstance(); Map<Integer, User> users = userManager.getAllUser(); updateUserIdBuilder.addAllUserId(users.keySet()); PBUpdateUserId updateUserId = updateUserIdBuilder.build(); PBBase pbBase = BaseProtocol.createBaseMessage(PBType.UPDATE_USER_ID, updateUserId); SocketCommunicationManager communicationManager = SocketCommunicationManager .getInstance(); communicationManager .sendMessageToAllWithoutEncode(pbBase.toByteArray()); } private static void encodeUpdateUserInfo(Context context) { SocketCommunicationManager communicationManager = SocketCommunicationManager .getInstance(); UserManager userManager = UserManager.getInstance(); Map<Integer, User> users = userManager.getAllUser(); for (Map.Entry<Integer, User> entry : users.entrySet()) { User user = entry.getValue(); UserInfo userInfo = UserHelper.getUserInfo(context, user); if (userInfo != null) { // Set type as TYPE_REMOTE. userInfo.setType(JuyouData.User.TYPE_REMOTE); PBUpdateUserInfo.Builder builder = PBUpdateUserInfo .newBuilder(); builder.setUserInfo(UserInfoUtil.userInfo2PBUserInfo(userInfo)); PBUpdateUserInfo pbUpdateUserInfo = builder.build(); PBBase pbBase = BaseProtocol.createBaseMessage( PBType.UPDATE_USER_INFO, pbUpdateUserInfo); communicationManager.sendMessageToAllWithoutEncode(pbBase .toByteArray()); } else { Log.e(TAG, "encodeUpdateAllUser getUserInfo fail. user = " + user); } } } } <file_sep>package com.zhaoyan.juyou.dialog; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.zhaoyan.juyou.R; public class DeleteDialog extends Dialog implements android.view.View.OnClickListener { private View mDeletingView; private View mPreDeleteView; private View mButtonView; private ListView mDeleteListView; private View mTitleView; private Button mButton1,mButton2, mButton3; private View mDividerOne,mDividerTwo; private List<Integer> mButtonList = new ArrayList<Integer>(); private String mBtnText1,mBtnText2,mBtnText3; private String mFilePath; private List<String> mDeleteNameList = new ArrayList<String>(); private Context mContext; private OnDelClickListener mClickListener1; private OnDelClickListener mClickListener2; private OnDelClickListener mClickListener3; public DeleteDialog(Context context, List<String> nameList){ super(context, R.style.Custom_Dialog); mContext = context; mDeleteNameList = nameList; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_delete); setTitle(R.string.delete_confirm); mDeletingView = findViewById(R.id.rl_deleting); // mPreDeleteView = findViewById(R.id.ll_pre_delete); mButtonView = findViewById(R.id.button_layout); mTitleView = findViewById(R.id.rl_title); mDeleteListView = (ListView) findViewById(R.id.lv_delete); mDividerOne = findViewById(R.id.divider_one); mDividerTwo = findViewById(R.id.divider_two); if (mButtonList.size() > 0) { mButtonView.setVisibility(View.VISIBLE); initButton(); } if (mDeleteNameList.size() > 0) { mDeleteListView.setVisibility(View.VISIBLE); ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.dialog_delete_item, mDeleteNameList); mDeleteListView.setAdapter(adapter); mDeletingView.setVisibility(View.GONE); }else { mDeletingView.setVisibility(View.VISIBLE); mDeleteListView.setVisibility(View.GONE); } } public void initButton(){ for(int whichButton : mButtonList){ switch (whichButton) { case AlertDialog.BUTTON_POSITIVE: mButton3 = (Button) findViewById(R.id.button3); mButton3.setVisibility(View.VISIBLE); mButton3.setOnClickListener(this); mButton3.setText(mBtnText3); break; case AlertDialog.BUTTON_NEUTRAL: mButton2 = (Button) findViewById(R.id.button2); mButton2.setVisibility(View.VISIBLE); mButton2.setOnClickListener(this); mButton2.setText(mBtnText2); break; case AlertDialog.BUTTON_NEGATIVE: mButton1 = (Button) findViewById(R.id.button1); mButton1.setVisibility(View.VISIBLE); mButton1.setOnClickListener(this); mButton1.setText(mBtnText1); break; default: break; } } if (mButtonList.size() == 2) { mDividerOne.setVisibility(View.VISIBLE); }else if (mButtonList.size() == 3) { mDividerTwo.setVisibility(View.VISIBLE); } } @Override public void show() { // TODO Auto-generated method stub super.show(); WindowManager windowManager = getWindow().getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.width = (int)display.getWidth() - 60; getWindow().setAttributes(lp); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: if (null != mClickListener1) { mClickListener1.onClick(v, mFilePath); }else { dismiss(); } break; case R.id.button2: if (null != mClickListener2) { mClickListener2.onClick(v, mFilePath); }else { dismiss(); } break; case R.id.button3: if (null != mClickListener3) { mClickListener3.onClick(v, mFilePath); mTitleView.setVisibility(View.GONE); mDeleteListView.setVisibility(View.GONE); mDeletingView.setVisibility(View.VISIBLE); mButtonView.setVisibility(View.GONE); }else { dismiss(); } break; default: break; } } public void setButton(int whichButton, int textResId, OnDelClickListener listener){ String text = mContext.getResources().getString(textResId); setButton(whichButton, text, listener); } public void setButton(int whichButton, String text, OnDelClickListener listener){ mButtonList.add(whichButton); switch (whichButton) { case AlertDialog.BUTTON_POSITIVE: mClickListener3 = listener; mBtnText3 = text; break; case AlertDialog.BUTTON_NEUTRAL: mClickListener2 = listener; mBtnText2 = text; break; case AlertDialog.BUTTON_NEGATIVE: mClickListener1 = listener; mBtnText1 = text; break; default: break; } } public interface OnDelClickListener{ public void onClick(View view,String path); } } <file_sep>package com.zhaoyan.communication.search; import java.util.ArrayList; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.util.Log; /** * Receive WiFi Direct sate and WiFi Direct connection info. * */ @TargetApi(14) public class WifiDirectReciver extends BroadcastReceiver { private static final String TAG = "WifiDirectReciver"; private boolean connectFlag = false; private ArrayList<WifiDirectDeviceNotify> observerList; public interface WifiDirectDeviceNotify { public void notifyDeviceChange(); public void wifiP2pConnected(); } public void registerObserver(WifiDirectDeviceNotify notify) { observerList.add(notify); notify.notifyDeviceChange(); } public void unRegisterObserver(WifiDirectDeviceNotify notify) { observerList.remove(notify); } public WifiDirectReciver() { observerList = new ArrayList<WifiDirectReciver.WifiDirectDeviceNotify>(); } @SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" }) @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); Log.d(TAG, "WIFI_STATE_CHANGED_ACTION. state = " + wifiState); } else if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // Check to see if Wi-Fi is enabled and notify appropriate activity int p2pState = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, 0); Log.d(TAG, "WIFI_P2P_STATE_CHANGED_ACTION. state = " + p2pState); } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { // Call WifiP2pManager.requestPeers() to get a list of current peers Log.d(TAG, "WIFI_P2P_PEERS_CHANGED_ACTION."); for (WifiDirectDeviceNotify f : observerList) { f.notifyDeviceChange(); } } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION .equals(action)) { NetworkInfo networkInfo = intent .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); WifiP2pInfo wifiP2pInfo = intent .getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO); Log.d(TAG, "WIFI_P2P_CONNECTION_CHANGED_ACTION, networkInfo-connect = " + networkInfo.isConnected() + ", wifiP2pInfo-groupFormed = " + wifiP2pInfo.groupFormed); if (networkInfo.isConnected()) { if (!connectFlag) { connectFlag = true; if (observerList != null) { for (WifiDirectDeviceNotify f : observerList) { f.wifiP2pConnected(); } } } } else { connectFlag = false; } } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION .equals(action)) { } } } <file_sep>package com.zhaoyan.juyou.fragment; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.Dialog; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.pm.PackageManager; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.common.file.FileManager; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.util.SharedPreferenceUtil; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.activity.AppActivity; import com.zhaoyan.juyou.adapter.AppCursorAdapter; import com.zhaoyan.juyou.adapter.AppCursorAdapter.ViewHolder; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.ActionMenu.ActionMenuItem; import com.zhaoyan.juyou.common.AppManager; import com.zhaoyan.juyou.common.FileTransferUtil; import com.zhaoyan.juyou.common.MenuBarInterface; import com.zhaoyan.juyou.common.ZYConstant; import com.zhaoyan.juyou.common.FileTransferUtil.TransportCallback; import com.zhaoyan.juyou.common.ZYConstant.Extra; import com.zhaoyan.juyou.dialog.AppDialog; import com.zhaoyan.juyou.dialog.ZyAlertDialog.OnZyAlertDlgClickListener; import com.zhaoyan.juyou.notification.NotificationMgr; import com.zhaoyan.juyou.provider.AppData; /** * use this to load app */ public class AppFragment extends BaseFragment implements OnItemClickListener, OnItemLongClickListener, MenuBarInterface { private static final String TAG = "AppFragment"; private GridView mGridView; private ListView mListView; private ProgressBar mLoadingBar; private AppCursorAdapter mAdapter = null; private AppDialog mAppDialog = null; private List<String> mUninstallList = null; private PackageManager pm = null; private Notice mNotice = null; private static final int REQUEST_CODE_UNINSTALL = 0x101; private QueryHandler mQueryHandler; private int mAppType = -1; private NotificationMgr mNotificationMgr; private boolean mIsBackupHide = false; private static final int MSG_TOAST = 0; private static final int MSG_BACKUPING = 1; private static final int MSG_BACKUP_OVER = 3; private static final int MSG_UPDATE_UI = 4; private static final int MSG_UPDATE_LIST= 5; private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_UPDATE_UI: int size = msg.arg1; count = size; updateTitleNum(-1); break; case MSG_UPDATE_LIST: Intent intent = new Intent(AppManager.ACTION_REFRESH_APP); mContext.sendBroadcast(intent); break; case MSG_TOAST: String message = (String) msg.obj; mNotice.showToast(message); break; case MSG_BACKUPING: int progress = msg.arg1; int max = msg.arg2; String name = (String) msg.obj; mNotificationMgr.updateBackupNotification(progress, max, name); break; case MSG_BACKUP_OVER: long duration = (Long) msg.obj; mNotificationMgr.appBackupOver(duration); break; default: break; } }; }; public static AppFragment newInstance(int type){ AppFragment f = new AppFragment(); Bundle args = new Bundle(); args.putInt(AppActivity.APP_TYPE, type); f.setArguments(args); return f; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAppType = getArguments() != null ? getArguments().getInt(AppActivity.APP_TYPE) : AppActivity.TYPE_APP; if (null != savedInstanceState) { mAppType = savedInstanceState.getInt(AppActivity.APP_TYPE); } mNotice = new Notice(getActivity().getApplicationContext()); pm = getActivity().getPackageManager(); mNotificationMgr = new NotificationMgr(getActivity().getApplicationContext()); Log.d(TAG, "onCreate.mViewType=" + mViewType); } @Override public void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); outState.putInt(AppActivity.APP_TYPE, mAppType); } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.app_main, container, false); mGridView = (GridView) rootView.findViewById(R.id.app_gridview); mListView = (ListView) rootView.findViewById(R.id.app_listview); Log.d(TAG, "onCreateView.mViewType=" + mViewType); if (Extra.VIEW_TYPE_LIST == mViewType) { mListView.setVisibility(View.VISIBLE); mGridView.setVisibility(View.GONE); } else { mListView.setVisibility(View.GONE); mGridView.setVisibility(View.VISIBLE); } mLoadingBar = (ProgressBar) rootView.findViewById(R.id.app_progressbar); if (isGameUI()) { initTitle(rootView.findViewById(R.id.rl_ui_app), R.string.game); }else { initTitle(rootView.findViewById(R.id.rl_ui_app), R.string.app); } initMenuBar(rootView); mQueryHandler = new QueryHandler(getActivity().getApplicationContext().getContentResolver()); mGridView.setOnItemClickListener(this); mGridView.setOnItemLongClickListener(this); mListView.setOnItemClickListener(this); mListView.setOnItemLongClickListener(this); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { mAdapter = new AppCursorAdapter(getActivity().getApplicationContext()); mAdapter.setCurrentViewType(mViewType); query(); super.onActivityCreated(savedInstanceState); } private static final String[] PROJECTION = { AppData.App._ID,AppData.App.PKG_NAME }; public void query(){ mLoadingBar.setVisibility(View.VISIBLE); //查询类型为应用的所有数据 String selectionString = AppData.App.TYPE + "=?" ; String[] args = new String[1]; if (isGameUI()) { args[0] = "" + AppManager.GAME_APP; }else { args[0] = "" + AppManager.NORMAL_APP; } mQueryHandler.startQuery(11, null, AppData.App.CONTENT_URI, PROJECTION, selectionString, args, AppData.App.SORT_ORDER_LABEL); } //query db private class QueryHandler extends AsyncQueryHandler { public QueryHandler(ContentResolver cr) { super(cr); // TODO Auto-generated constructor stub } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { Log.d(TAG, "onQueryComplete"); mLoadingBar.setVisibility(View.INVISIBLE); Message message = mHandler.obtainMessage(); if (null != cursor && cursor.getCount() > 0) { Log.d(TAG, "onQueryComplete.count=" + cursor.getCount()); mAdapter.changeCursor(cursor); if (Extra.VIEW_TYPE_LIST == mViewType) { mListView.setAdapter(mAdapter); } else { mGridView.setAdapter(mAdapter); } mAdapter.checkedAll(false); message.arg1 = cursor.getCount(); } else { message.arg1 = 0; } message.what = MSG_UPDATE_UI; message.sendToTarget(); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mAdapter.isMode(ActionMenu.MODE_EDIT)) { mAdapter.setChecked(position); mAdapter.notifyDataSetChanged(); updateMenuBar(); } else { Cursor cursor = mAdapter.getCursor(); cursor.moveToPosition(position); String packagename = cursor.getString(cursor .getColumnIndex(AppData.App.PKG_NAME)); if (ZYConstant.PACKAGE_NAME.equals(packagename)) { mNotice.showToast(R.string.app_has_started); return; } Intent intent = pm.getLaunchIntentForPackage(packagename); if (null != intent) { startActivity(intent); } else { mNotice.showToast(R.string.cannot_start_app); return; } } } @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { if (mAdapter.isMode(ActionMenu.MODE_EDIT)) { //do nothing //doCheckAll(); return true; } else { mAdapter.changeMode(ActionMenu.MODE_EDIT); updateTitleNum(1); } mAdapter.setChecked(position); mAdapter.notifyDataSetChanged(); mActionMenu = new ActionMenu(getActivity().getApplicationContext()); if (isGameUI()) { getActionMenuInflater().inflate(R.menu.game_menu, mActionMenu); }else { getActionMenuInflater().inflate(R.menu.app_menu, mActionMenu); } startMenuBar(); return true; } public void notifyUpdateUI(){ Message message = mHandler.obtainMessage(); message.arg1 = mAdapter.getCount(); message.what = MSG_UPDATE_UI; message.sendToTarget(); } @Override public void onDestroyView() { if (mAdapter != null && mAdapter.getCursor() != null) { mAdapter.getCursor().close(); mAdapter.changeCursor(null); } super.onDestroyView(); } public void reQuery() { if (null == mAdapter || mAdapter.getCursor() == null) { query(); } else { mAdapter.getCursor().requery(); notifyUpdateUI(); } } public boolean onBackPressed(){ if (null != mAdapter && mAdapter.isMode(ActionMenu.MODE_EDIT)) { destroyMenuBar(); return false; } return true; } @Override public void onMenuItemClick(ActionMenuItem item) { switch (item.getItemId()) { case R.id.menu_send: ArrayList<String> selectedList = (ArrayList<String>) mAdapter.getCheckedPathList(); //send FileTransferUtil fileTransferUtil = new FileTransferUtil(getActivity()); fileTransferUtil.sendFiles(selectedList, new TransportCallback() { @Override public void onTransportSuccess() { int first = mGridView.getFirstVisiblePosition(); int last = mGridView.getLastVisiblePosition(); List<Integer> checkedItems = mAdapter.getCheckedPosList(); ArrayList<ImageView> icons = new ArrayList<ImageView>(); for(int id : checkedItems) { if (id >= first && id <= last) { View view = mGridView.getChildAt(id - first); if (view != null) { ViewHolder viewHolder = (ViewHolder)view.getTag(); icons.add(viewHolder.iconView); } } } // if (icons.size() > 0) { ImageView[] imageViews = new ImageView[0]; showTransportAnimation(icons.toArray(imageViews)); } destroyMenuBar(); } @Override public void onTransportFail() { } }); break; case R.id.menu_uninstall: mUninstallList = mAdapter.getCheckedPkgList(); showUninstallDialog(); uninstallApp(); destroyMenuBar(); break; case R.id.menu_move_app: showMoveDialog(); break; case R.id.menu_app_info: String packageName = mAdapter.getCheckedPkgList().get(0); showInstalledAppDetails(packageName); destroyMenuBar(); break; case R.id.menu_select: doCheckAll(); break; case R.id.menu_backup: List<String> backupList = mAdapter.getCheckedPkgList(); showBackupDialog(backupList); destroyMenuBar(); break; default: break; } } public void showMoveDialog(){ final List<String> packageList = mAdapter.getCheckedPkgList(); new MoveAsyncTask(packageList).execute(); destroyMenuBar(); } private class MoveAsyncTask extends AsyncTask<Void, Void, Void>{ List<String> pkgList = new ArrayList<String>(); AppDialog dialog; MoveAsyncTask(List<String> list){ pkgList = list; } @Override protected void onPreExecute() { super.onPreExecute(); if (null == dialog) { dialog = new AppDialog(mContext, pkgList.size()); dialog.setTitle(R.string.handling); dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancel(true); } }); dialog.show(); } } @Override protected Void doInBackground(Void... params) { String label = null; for (int i = 0; i < pkgList.size(); i++) { label = AppManager.getAppLabel(pkgList.get(i), pm); dialog.updateUI(i + 1, label); doMoveTo(pkgList.get(i)); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (null != dialog) { dialog.cancel(); dialog = null; } notifyUpdateUI(); } } private void doMoveTo(String packageName){ if (isGameUI()) { moveToApp(packageName); }else { moveToGame(packageName); } } private void moveToGame(String packageName){ Log.d(TAG, "moveToGame:" + packageName); //move to game //1,将该记录的type设置为game //2,将数据插入到game表中 //3,通知GameFragment //4,重新查询数据库 ContentResolver contentResolver = getActivity().getContentResolver(); ContentValues values = null; values = new ContentValues(); values.put(AppData.App.TYPE, AppManager.GAME_APP); contentResolver.update(AppData.App.CONTENT_URI, values, AppData.App.PKG_NAME + "='" + packageName + "'", null); //insert to db values = new ContentValues(); values.put(AppData.App.PKG_NAME, packageName); contentResolver.insert(AppData.AppGame.CONTENT_URI, values); } private void moveToApp(String packageName){ // Log.d(TAG, "moveToApp:" + packageName); //move to app //1,删除game表中的数据 //2,将app表中的type改为app //3,通知AppFragment //4,重新查询数据库 ContentResolver contentResolver = getActivity().getContentResolver(); Uri uri = Uri.parse(AppData.AppGame.CONTENT_URI + "/" + packageName); contentResolver.delete(uri, null, null); //update db ContentValues values = new ContentValues(); values.put(AppData.App.TYPE, AppManager.NORMAL_APP); contentResolver.update(AppData.App.CONTENT_URI, values, AppData.App.PKG_NAME + "='" + packageName + "'", null); } @Override public void doCheckAll(){ int selectedCount1 = mAdapter.getCheckedCount(); if (mAdapter.getCount() != selectedCount1) { mAdapter.checkedAll(true); } else { mAdapter.checkedAll(false); } updateMenuBar(); mAdapter.notifyDataSetChanged(); } @Override public void destroyMenuBar() { super.destroyMenuBar(); updateTitleNum(-1); mAdapter.changeMode(ActionMenu.MODE_NORMAL); mAdapter.checkedAll(false); mAdapter.notifyDataSetChanged(); } @Override public void updateMenuBar(){ int selectCount = mAdapter.getCheckedCount(); updateTitleNum(selectCount); ActionMenuItem selectItem = mActionMenu.findItem(R.id.menu_select); if (mAdapter.getCount() == selectCount) { selectItem.setTitle(R.string.unselect_all); selectItem.setEnableIcon(R.drawable.ic_aciton_unselect); } else { selectItem.setTitle(R.string.select_all); selectItem.setEnableIcon(R.drawable.ic_aciton_select); } if (0==selectCount) { mActionMenu.findItem(R.id.menu_send).setEnable(false); mActionMenu.findItem(R.id.menu_backup).setEnable(false); mActionMenu.findItem(R.id.menu_uninstall).setEnable(false); mActionMenu.findItem(R.id.menu_move_app).setEnable(false); mActionMenu.findItem(R.id.menu_app_info).setEnable(false); } else if (1 == selectCount) { mActionMenu.findItem(R.id.menu_send).setEnable(true); mActionMenu.findItem(R.id.menu_backup).setEnable(true); mActionMenu.findItem(R.id.menu_uninstall).setEnable(true); mActionMenu.findItem(R.id.menu_move_app).setEnable(true); mActionMenu.findItem(R.id.menu_app_info).setEnable(true); } else { mActionMenu.findItem(R.id.menu_send).setEnable(true); mActionMenu.findItem(R.id.menu_backup).setEnable(true); mActionMenu.findItem(R.id.menu_uninstall).setEnable(true); mActionMenu.findItem(R.id.menu_move_app).setEnable(true); mActionMenu.findItem(R.id.menu_app_info).setEnable(false); } mMenuBarManager.refreshMenus(mActionMenu); } protected void uninstallApp(){ if (mUninstallList.size() <= 0) { mUninstallList = null; if (null != mAppDialog) { mAppDialog.cancel(); mAppDialog = null; } return; } String uninstallPkg = mUninstallList.get(0); mAppDialog.updateUI(mAppDialog.getMax() - mUninstallList.size() + 1, AppManager.getAppLabel(uninstallPkg, pm)); Uri packageUri = Uri.parse("package:" + uninstallPkg); Intent deleteIntent = new Intent(); deleteIntent.setAction(Intent.ACTION_DELETE); deleteIntent.setData(packageUri); startActivityForResult(deleteIntent, REQUEST_CODE_UNINSTALL); mUninstallList.remove(0); } @SuppressWarnings("unchecked") protected void showBackupDialog(List<String> packageList){ // Log.d(TAG, "Environment.getExternalStorageState():" + Environment.getExternalStorageState()); String path = Environment.getExternalStorageDirectory().getAbsolutePath(); if (path.isEmpty()) { mNotice.showToast(R.string.no_sdcard); return; } File file = new File(path); if (null == file.listFiles() || file.listFiles().length < 0) { mNotice.showToast(R.string.no_sdcard); return; } final BackupAsyncTask task = new BackupAsyncTask(); mAppDialog = new AppDialog(getActivity(), packageList.size()); mAppDialog.setTitle(R.string.backup_app); mAppDialog.setPositiveButton(R.string.hide, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { mIsBackupHide = true; mNotificationMgr.startBackupNotification(); updateNotification(task.currentProgress, task.size, task.currentAppLabel); dialog.dismiss(); } }); mAppDialog.setNegativeButton(R.string.cancel, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { Log.d(TAG, "showBackupDialog.onCancel"); if (null != task) { task.cancel(true); } dialog.dismiss(); } }); mAppDialog.show(); task.execute(packageList); } private class BackupAsyncTask extends AsyncTask<List<String>, Integer, Void>{ public int currentProgress = 0; public int size = 0; public String currentAppLabel; private long startTime = 0; private long endTime = 0; @Override protected Void doInBackground(List<String>... params) { startTime = System.currentTimeMillis(); size = params[0].size(); File file = new File(ZYConstant.JUYOU_BACKUP_FOLDER); if (!file.exists()){ boolean ret = file.mkdirs(); if (!ret) { Log.e(TAG, "create file fail:" + file.getAbsolutePath()); return null; } } String label = ""; String version = ""; String sourceDir = ""; String packageName = ""; for (int i = 0; i < size; i++) { if (isCancelled()) { Log.d(TAG, "doInBackground.isCancelled"); return null; } packageName = params[0].get(i); label = AppManager.getAppLabel(packageName, pm); version = AppManager.getAppVersion(packageName, pm); sourceDir = AppManager.getAppSourceDir(packageName, pm); currentAppLabel = label; currentProgress = i + 1; mAppDialog.updateName(label); String desPath = ZYConstant.JUYOU_BACKUP_FOLDER + "/" + label + "_" + version + ".apk"; if (!new File(desPath).exists()) { boolean ret = FileManager.copyFile(sourceDir, desPath); if (!ret) { Message message = mHandler.obtainMessage(); message.obj = getString(R.string.backup_fail, label); message.what = MSG_TOAST; message.sendToTarget(); } } mAppDialog.updateProgress(i + 1); if (mIsBackupHide) { updateNotification(currentProgress, size, currentAppLabel); } } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); Log.d(TAG, "onPostExecute"); if (null != mAppDialog && mAppDialog.isShowing()) { mAppDialog.cancel(); mAppDialog = null; } mNotice.showToast(R.string.backup_over); endTime = System.currentTimeMillis(); if (mIsBackupHide) { mIsBackupHide = false; Message message = mHandler.obtainMessage(); message.obj = endTime - startTime; message.what = MSG_BACKUP_OVER; message.sendToTarget(); } } } protected void showUninstallDialog(){ mAppDialog = new AppDialog(getActivity(), mUninstallList.size()); mAppDialog.setTitle(R.string.handling); mAppDialog.setNegativeButton(R.string.cancel, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { if (null != mUninstallList) { mUninstallList.clear(); mUninstallList = null; } dialog.dismiss(); } }); mAppDialog.show(); } public void updateNotification(int progress, int max, String name){ Message message = mHandler.obtainMessage(); message.arg1 = progress; message.arg2 = max; message.obj = name; message.what = MSG_BACKUPING; message.sendToTarget(); } public void showInstalledAppDetails(String packageName){ Intent intent = new Intent(); final int apiLevel = Build.VERSION.SDK_INT; if (apiLevel >= Build.VERSION_CODES.GINGERBREAD) { intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", packageName, null); intent.setData(uri); }else { intent.setAction(Intent.ACTION_VIEW); intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails"); intent.putExtra("pkg", packageName); } startActivity(intent); } private boolean isGameUI(){ return AppActivity.TYPE_GAME == mAppType; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (REQUEST_CODE_UNINSTALL == requestCode) { uninstallApp(); } } } <file_sep>package com.zhaoyan.communication.search; import android.content.Context; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.search.SearchProtocol.OnSearchListener; /** * This class is used by server for search clients.</br> * * There are two kind of lan network:</br> * * 1. No Android AP Lan.</br> * * 2. Has Android AP Lan.</br> * * In the situation 1, we use lan multicast to find clients.</br> * * In the situation 2, we use lan mulitcast and UDP communication to search * clients</br> * * This is because AP can not send or receive multicast in Android AP lan * network.</br> * * Notice: SearchClient do not get clint IP, Only client can get server IP, and * client connect server.</br> */ public class SearchClient { private static final String TAG = "SearchClient"; private OnSearchListener mListener; private boolean mStarted = false; private static SearchClient mInstance; private Context mContext; private SearchClientLanAndroidAP mSearchClientLanAndroidAP; private SearchClientLan mSearchClientLan; public static SearchClient getInstance(Context context) { if (mInstance == null) { mInstance = new SearchClient(context); } return mInstance; } private SearchClient(Context context) { mContext = context; } public void setOnSearchListener(OnSearchListener listener) { mListener = listener; if (mSearchClientLan != null) { mSearchClientLan.setOnSearchListener(listener); } if (mSearchClientLanAndroidAP != null) { mSearchClientLanAndroidAP.setOnSearchListener(listener); } } /** * start search client. */ public void startSearch() { Log.d(TAG, "Start search"); if (mStarted) { Log.d(TAG, "startSearch() igonre, search is already started."); return; } mStarted = true; NetWorkUtil.acquireWifiMultiCastLock(mContext); Log.d(TAG, "The ip is "+NetWorkUtil.getLocalIpAddress()); if (SearchUtil.isAndroidAPNetwork(mContext)) { // Android AP network. Log.d(TAG, "Android AP network."); mSearchClientLanAndroidAP = SearchClientLanAndroidAP .getInstance(mContext); mSearchClientLanAndroidAP.setOnSearchListener(mListener); mSearchClientLanAndroidAP.startSearch(); } else { Log.d(TAG, "not Android AP network."+"the ip is "+NetWorkUtil.getLocalIpAddress()); } if (!NetWorkUtil.isWifiApEnabled(mContext)) { Log.d(TAG, "This is not Android AP"); mSearchClientLan = SearchClientLan.getInstance(mContext); mSearchClientLan.setOnSearchListener(mListener); mSearchClientLan.startSearch(); } else { Log.d(TAG, "This is AP"); if (SearchUtil.isAndroidAPNetwork(mContext)) { // Android AP network. Log.d(TAG, "Android AP network."); mSearchClientLanAndroidAP = SearchClientLanAndroidAP .getInstance(mContext); mSearchClientLanAndroidAP.setOnSearchListener(mListener); mSearchClientLanAndroidAP.startSearch(); }else{ Log.e(TAG, "This ip is " + NetWorkUtil.getLocalIpAddress()); } // Android AP is enabled // Because Android AP can not send or receive Lan // multicast/broadcast,So it does not need to listen multicast. } } public void stopSearch() { Log.d(TAG, "Stop search."); StackTraceElement st[] = Thread.currentThread().getStackTrace(); for (int i = 0; i < st.length; i++) { Log.d(TAG, "trace: " + st[i].toString()); } mStarted = false; NetWorkUtil.releaseWifiMultiCastLock(); if (mSearchClientLan != null) { mSearchClientLan.stopSearch(); mSearchClientLan = null; } if (mSearchClientLanAndroidAP != null) { mSearchClientLanAndroidAP.stopSearch(); mSearchClientLanAndroidAP = null; } mInstance = null; } } <file_sep>package com.zhaoyan.juyou.adapter; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Color; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.zhaoyan.juyou.R; import com.zhaoyan.common.util.Log; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.FileIconHelper; import com.zhaoyan.juyou.common.FileInfo; import com.zhaoyan.juyou.common.FileListItem; public class FileInfoAdapter extends BaseAdapter { private static final String TAG = "FileInfoAdapter"; private List<FileInfo> mList = new ArrayList<FileInfo>(); private LayoutInflater mInflater = null; private SparseBooleanArray mIsSelected = null; private FileIconHelper iconHelper; public int mMode = ActionMenu.MODE_NORMAL; private Context mContext; public FileInfoAdapter(Context context, List<FileInfo> list, FileIconHelper iconHelper) { mInflater = LayoutInflater.from(context); this.mList = list; mIsSelected = new SparseBooleanArray(); this.iconHelper = iconHelper; mContext = context; } /** * Select All or not * * @param isSelected * true or false */ public void selectAll(boolean isSelected) { int count = this.getCount(); Log.d(TAG, "selectALl.count=" + count); for (int i = 0; i < count; i++) { setSelected(i, isSelected); } } /** * set selected or not * * @param position * the position that clicked * @param isSelected * checked or not */ public void setSelected(int position, boolean isSelected) { mIsSelected.put(position, isSelected); } public void setSelected(int position) { mIsSelected.put(position, !isSelected(position)); } public void clearSelected() { for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { setSelected(i, false); } } } /** * return current position checked or not * * @param position * current position * @return checked or not */ public boolean isSelected(int position) { return mIsSelected.get(position); } /** * get how many item that has cheked * * @return checked items num. */ public int getSelectedItems() { int count = 0; for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { count++; } } return count; } /** * get selected items fileinfo list * @return */ public List<FileInfo> getSelectedFileInfos() { List<FileInfo> fileList = new ArrayList<FileInfo>(); for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { fileList.add(mList.get(i)); } } return fileList; } /** * get selected items filepath list * @return */ public List<String> getSelectedFilePaths() { List<String> pathList = new ArrayList<String>(); for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { pathList.add(mList.get(i).filePath); } } return pathList; } /** * get selected items position list * @return */ public List<Integer> getSelectedItemsPos() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { list.add(mIsSelected.keyAt(i)); } } return list; } /** * check if there is dir selected in selected list * @return */ public boolean hasDirSelected(){ for (int i = 0; i < mIsSelected.size(); i++) { if (mIsSelected.valueAt(i)) { if (mList.get(i).isDir) { return true; } } } return false; } /** * set scroll is idle or not * * @param flag */ public void setFlag(boolean flag) { // this.mIdleFlag = flag; } /** * This method changes the display mode of adapter between MODE_NORMAL, * MODE_EDIT * * @param mode * the mode which will be changed to be. */ public void changeMode(int mode) { mMode = mode; } /** * This method checks that current mode equals to certain mode, or not. * * @param mode * the display mode of adapter * @return true for equal, and false for not equal */ public boolean isMode(int mode) { return mMode == mode; } public List<FileInfo> getList() { return mList; } public void setList(List<FileInfo> fileList) { mList = fileList; } /** * This method gets index of certain fileInfo(item) in fileInfoList * * @param fileInfo * the fileInfo which wants to be located. * @return the index of the item in the listView. */ public int getPosition(FileInfo fileInfo) { Log.d(TAG, "getPosition:" + fileInfo.filePath); for (int i = 0; i < mList.size(); i++) { if (fileInfo.filePath.equals(mList.get(i).filePath)) { return i; } } return mList.indexOf(fileInfo); } @Override public int getCount() { return mList.size(); } @Override public FileInfo getItem(int position) { if (mList.size() <= 0) { return null; } return mList.get(position); } @Override public long getItemId(int position) { return position; } public class ViewHolder { public ImageView iconView; TextView nameView; TextView countView; TextView dateAndSizeView; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; ViewHolder holder = null; if (null == convertView || null == convertView.getTag()) { holder = new ViewHolder(); view = mInflater.inflate(R.layout.file_item, parent, false); holder.iconView = (ImageView) view .findViewById(R.id.file_icon_imageview); // holder.nameView = (TextView) view // .findViewById(R.id.tv_filename); // holder.countView = (TextView) view.findViewById(R.id.tv_filecount); // holder.dateAndSizeView = (TextView) view // .findViewById(R.id.tv_fileinfo); view.setTag(holder); } else { view = convertView; holder = (ViewHolder) view.getTag(); } FileInfo fileInfo = mList.get(position); //20131128 yuri:use new way to load file icon FileListItem.setupFileListItemInfo(mContext, view, fileInfo, iconHelper); if (isMode(ActionMenu.MODE_EDIT) || isMode(ActionMenu.MODE_COPY)) { updateListViewBackground(position, view, R.color.holo_blue_light); } else if (isMode(ActionMenu.MODE_CUT)) { updateListViewBackground(position, view, R.color.holo_blue_light_transparent); }else { view.setBackgroundResource(Color.TRANSPARENT); } return view; } private void updateListViewBackground(int position, View view, int colorId) { if (isSelected(position)) { view.setBackgroundResource(colorId); } else { view.setBackgroundResource(Color.TRANSPARENT); } } } <file_sep>package com.zhaoyan.communication.protocol; import java.util.Arrays; import java.util.Map; import android.content.Context; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.ArrayUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.CallBacks.ILoginRequestCallBack; import com.zhaoyan.communication.CallBacks.ILoginRespondCallback; import com.zhaoyan.communication.SocketCommunication; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.protocol.FileTransportProtocol.OnReceiveFileCallback; import com.zhaoyan.communication.protocol.LoginProtocol.DecodeLoginRequestForwardResult; import com.zhaoyan.communication.protocol.LoginProtocol.DecodeLoginRespondForwardResult; import com.zhaoyan.communication.protocol.SendProtocol.ISendProtocolTypeAllCallBack; import com.zhaoyan.communication.protocol.SendProtocol.ISendProtocolTypeSingleCallBack; /** * This class is used for decode the message based on protocol. * */ public class ProtocolDecoder implements ISendProtocolTypeSingleCallBack, ISendProtocolTypeAllCallBack, ILoginRespondCallback, OnReceiveFileCallback { private static final String TAG = "ProtocolDecoder"; private UserManager mUserManager; private SocketCommunicationManager mCommunicationManager; /** * Call back for SocketCommunicationManager */ private ILoginRequestCallBack mLoginRequestCallBack; /** * Call back for SocketCommunicationManager */ private ILoginRespondCallback mLoginRespondCallback; private Context mContext; public ProtocolDecoder(Context context) { mContext = context; mUserManager = UserManager.getInstance(); mCommunicationManager = SocketCommunicationManager.getInstance(); } public void setLoginRequestCallBack(ILoginRequestCallBack callback) { mLoginRequestCallBack = callback; } public void setLoginRespondCallback(ILoginRespondCallback callback) { mLoginRespondCallback = callback; } /** * Decode message. * * @param msg * @param communication * @return */ public byte[] decode(byte[] msg, SocketCommunication communication) { int dataType = ArrayUtil.byteArray2Int(Arrays.copyOfRange(msg, 0, Protocol.DATA_TYPE_HEADER_SIZE)); byte[] data = Arrays.copyOfRange(msg, Protocol.DATA_TYPE_HEADER_SIZE, msg.length); switch (dataType) { case Protocol.DATA_TYPE_HEADER_LOGIN_REQUEST: Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_REQUEST."); handleLoginRequest(data, communication); break; case Protocol.DATA_TYPE_HEADER_LOGIN_RESPOND: Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_RESPOND"); handleLoginRespond(data, communication); break; case Protocol.DATA_TYPE_HEADER_UPDATE_ALL_USER: Log.d(TAG, "DATA_TYPE_HEADER_UPDATE_ALL_USER"); handleLoginUpdateAllUser(data, msg, communication); break; case Protocol.DATA_TYPE_HEADER_LOGIN_REQUEST_FORWARD: Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_REQUEST_FORWARD"); handleLoginRequestForward(data, communication); break; case Protocol.DATA_TYPE_HEADER_LOGIN_RESPOND_FORWARD: Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_RESPOND_FORWARD"); handleLoginRespondForward(data, communication); break; case Protocol.DATA_TYPE_HEADER_SEND_SINGLE: Log.d(TAG, "DATA_TYPE_HEADER_SEND_SINGLE"); handleSendSingle(data); break; case Protocol.DATA_TYPE_HEADER_SEND_ALL: Log.d(TAG, "DATA_TYPE_HEADER_SEND_ALL"); handleSendAll(data); break; case Protocol.DATA_TYPE_HEADER_SEND_FILE: Log.d(TAG, "DATA_TYPE_HEADER_SEND_FILE"); handleSendFile(data); break; case Protocol.DATA_TYPE_HEADER_CANCEL_SEND_FILE: Log.d(TAG, "DATA_TYPE_HEADER_CANCEL_SEND_FILE"); // For Later break; case Protocol.DATA_TYPE_HEADER_CANCEL_RECEIVE_FILE: Log.d(TAG, "DATA_TYPE_HEADER_CANCEL_RECEIVE_FILE"); // For Later break; default: Log.d(TAG, "Unkown data type: " + dataType); break; } return data; } private void handleSendFile(byte[] data) { FileTransportProtocol.decodeSendFile(data, this); } /** * Protocol.DATA_TYPE_HEADER_SEND_ALL * * @param data */ private void handleSendAll(byte[] data) { SendProtocol.decodeSendMessageToAll(data, this); } /** * Protocol.DATA_TYPE_HEADER_SEND_SINGLE * * @param data */ private void handleSendSingle(byte[] data) { SendProtocol.decodeSendMessageToSingle(data, this); } /** * Protocol.DATA_TYPE_HEADER_LOGIN_RESPOND_FORWARD * * @param data * @param communication */ private void handleLoginRespondForward(byte[] data, SocketCommunication communication) { // TODO Because of wifi direct is not used, this is not used already. DecodeLoginRespondForwardResult decodeRespondResult = LoginProtocol .decodeLoginRespondForward(data); int userLocalIDRespond = decodeRespondResult.getUserLocalID(); boolean loginResult = decodeRespondResult.isLoginResult(); int userID = decodeRespondResult.getUserID(); byte[] loginRespond = LoginProtocol.encodeLoginRespond(loginResult, userID); SocketCommunication communication2 = mCommunicationManager .getLocalCommunicaiton(userLocalIDRespond); if (communication2 != null) { mCommunicationManager.sendMessage(communication2, loginRespond); mUserManager.addLocalCommunication(userID, communication2); mCommunicationManager.removeLocalCommunicaiton(userLocalIDRespond); } else { Log.e(TAG, "communication2 is null"); } } /** * Protocol.DATA_TYPE_HEADER_LOGIN_REQUEST_FORWARD * * @param data * @param communication */ private void handleLoginRequestForward(byte[] data, SocketCommunication communication) { // TODO Because of wifi direct is not used, this is not used already. User localUser = mUserManager.getLocalUser(); if (UserManager.isManagerServer(localUser)) { DecodeLoginRequestForwardResult decodeRequestResult = LoginProtocol .decodeLoginRequestForward(data); User user = decodeRequestResult.getUser(); int userLocalID = decodeRequestResult.getUserID(); Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_REQUEST user = " + user); boolean isAdded = mUserManager.addUser(user, communication); Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_REQUEST send add users' info to all, isAdded = " + isAdded); byte[] respond = LoginProtocol.encodeLoginRespondForward(isAdded, user, userLocalID); Log.d(TAG, "DATA_TYPE_HEADER_LOGIN_REQUEST respond length = " + respond.length); mCommunicationManager.sendMessage(communication, respond); if (isAdded) { // sendMessageToUpdateAllUser(); } } else { // TODO This condition is not supported yet. } } /** * Protocol.DATA_TYPE_HEADER_UPDATE_ALL_USER * * @param data * @param originMessage * @param communication */ private void handleLoginUpdateAllUser(byte[] data, byte[] originMessage, SocketCommunication communication) { LoginProtocol.decodeUpdateAllUser(data, communication); // TODO Because of wifi direct is not used, code below is not used // already. // send all user data to other user in my local network. for (SocketCommunication communication2 : mCommunicationManager .getCommunications()) { if (communication != communication2) { mCommunicationManager .sendMessage(communication2, originMessage); } } } /** * Protocol.DATA_TYPE_HEADER_LOGIN_RESPOND * * @param data * @param communication */ private void handleLoginRespond(byte[] data, SocketCommunication communication) { LoginProtocol.decodeLoginRespond(data, mContext, communication, this); } /** * Protocol.DATA_TYPE_HEADER_LOGIN_REQUEST * * @param data * @param communication */ private void handleLoginRequest(byte[] data, SocketCommunication communication) { User localUser = mUserManager.getLocalUser(); if (UserManager.isManagerServer(localUser)) { Log.d(TAG, "This is manager server, process login request."); UserInfo userInfo = LoginProtocol.decodeLoginRequest(data); // Let call back to handle the request. if (mLoginRequestCallBack != null) { mLoginRequestCallBack.onLoginRequest(userInfo, communication); } } else { // TODO Because of wifi direct is not used, this is not used // already. // Log.d(TAG, "This is not manager server, need forward."); // This login request need forward. // int id = // mCommunicationManager.addLocalCommunicaiton(communication); // User user = LoginProtocol.decodeLoginRequest(data); // byte[] loginReqestData = LoginProtocol.encodeLoginRequestForward( // user, id); // // Send the message to other user except the login requester. // for (SocketCommunication communication2 : mCommunicationManager // .getCommunications()) { // if (communication2 != communication) { // mCommunicationManager.sendMessage(communication2, // loginReqestData); // Log.d(TAG, "login forward success."); // } // } } } @Override public void onReceiveMessageSingleType(int sendUserID, int receiveUserID, int appID, byte[] data) { Log.d(TAG, "onReceiveMessageSingleType senUserID = " + sendUserID + ", receiveUserID = " + receiveUserID + ", appID = " + appID); User localUser = mUserManager.getLocalUser(); if (receiveUserID == localUser.getUserID()) { Log.d(TAG, "This message is for me"); mCommunicationManager.notifyReceiveListeners(sendUserID, appID, data); } else { Log.d(TAG, "This message is not for me"); SocketCommunication communication = mUserManager .getSocketCommunication(receiveUserID); byte[] originalMsg = SendProtocol.encodeSendMessageToSingle(data, sendUserID, receiveUserID, appID); communication.sendMessage(originalMsg); } } @Override public void onReceiveMessageAllType(int sendUserID, int appID, byte[] data) { Log.d(TAG, "onReceiveMessageAllType sendUserID = " + sendUserID + ", appID = " + appID); if (sendUserID == mUserManager.getLocalUser().getUserID()) { // When the client connected to the server but is not login success, // the client can receive the message, and the client will send the // message to other communications which user ID is not the same as // the message from. So the client will send the message back to the // server. So this message should ignore. // TODO This condition should avoid in the future. Log.d(TAG, "onReceiveMessageAllType, This message is sent by me, ignore."); return; } mCommunicationManager.notifyReceiveListeners(sendUserID, appID, data); byte[] msg = SendProtocol.encodeSendMessageToAll(data, sendUserID, appID); Map<Integer, SocketCommunication> communications = mUserManager .getAllCommmunication(); for (SocketCommunication communication : mCommunicationManager .getCommunications()) { if (communications.get(sendUserID) != communication) { mCommunicationManager.sendMessage(communication, msg); Log.d(TAG, "Send to communication: " + communication.getConnectedAddress()); } else { Log.d(TAG, "Ignore, the communication is the message comes from."); } } } @Override public void onLoginSuccess(User localUser, SocketCommunication communication) { if (mLoginRespondCallback != null) { mLoginRespondCallback.onLoginSuccess(localUser, communication); } else { Log.d(TAG, "mLoginReusltCallback is null"); } } @Override public void onLoginFail(int failReason, SocketCommunication communication) { if (mLoginRespondCallback != null) { mLoginRespondCallback.onLoginFail(failReason, communication); } else { Log.d(TAG, "mLoginReusltCallback is null"); } } @Override public void onReceiveFile(int sendUserID, int receiveUserID, int appID, byte[] serverAddress, int serverPort, FileTransferInfo fileInfo) { Log.d(TAG, "onReceiveFile senUserID = " + sendUserID + ", receiveUserID = " + receiveUserID + ", appID = " + appID + ", serverPort = " + serverPort + ", file = " + fileInfo.mFileName); User localUser = mUserManager.getLocalUser(); if (receiveUserID == localUser.getUserID()) { Log.d(TAG, "onReceiveFile This file is for me"); // mCommunicationManager.notfiyFileReceiveListeners(sendUserID, appID, // serverAddress, serverPort, fileInfo); } else { Log.d(TAG, "onReceiveFile This file is not for me"); SocketCommunication communication = mUserManager .getSocketCommunication(receiveUserID); byte[] originalMsg = ProtocolEncoder.encodeSendFile(sendUserID, receiveUserID, appID, serverAddress, serverPort, fileInfo); communication.sendMessage(originalMsg); } } } <file_sep>package com.zhaoyan.communication.search; import java.lang.reflect.Method; import java.util.ArrayList; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.util.Log; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.search.WifiDirectReciver.WifiDirectDeviceNotify; /** * Manage WiFi direct to search peers and connect peers. * */ @TargetApi(14) public class WifiDirectManager implements WifiDirectDeviceNotify { private static final String TAG = "WifiDirectManager"; @SuppressLint("NewApi") private WifiP2pManager mWifiP2pManager; private WifiManager mWifiManager; private boolean serverFlag = false; public Channel channel; private Context context; private ArrayList<ManagerP2pDeivce> observerList; public interface ManagerP2pDeivce { public void deviceChange(ArrayList<WifiP2pDevice> list); public void hasConnect(WifiP2pInfo info); }; public WifiDirectManager(Context context) { this.context = context; mWifiP2pManager = (WifiP2pManager) context .getSystemService(Context.WIFI_P2P_SERVICE); mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); setDeviceName(mWifiP2pManager, channel, UserHelper.getUserName(context), null); if (mWifiManager.isWifiEnabled()) { channel = mWifiP2pManager.initialize(context, context.getMainLooper(), null); observerList = new ArrayList<WifiDirectManager.ManagerP2pDeivce>(); } } public WifiDirectManager(Context context, boolean flag) { this.serverFlag = flag; this.context = context; mWifiP2pManager = (WifiP2pManager) context .getSystemService(Context.WIFI_P2P_SERVICE); mWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); if (mWifiManager.isWifiEnabled()) { channel = mWifiP2pManager.initialize(context, context.getMainLooper(), null); observerList = new ArrayList<WifiDirectManager.ManagerP2pDeivce>(); } if (flag) { setDeviceName( mWifiP2pManager, channel, WiFiNameEncryption.generateWiFiName("DreamLink" + UserHelper.getUserName(context)), null); } } @SuppressLint({ "NewApi", "NewApi" }) public void discover() { mWifiP2pManager.discoverPeers(channel, null); } private void setDeviceName(WifiP2pManager manager, Channel channel, String name, ActionListener listener) { try { Method method = manager.getClass().getMethod("setDeviceName", Channel.class, String.class, ActionListener.class); method.invoke(manager, channel, name, listener); } catch (Exception e) { Log.e(TAG, "setDeviceName fail: " + e); } } /** * @param serverFlag * ,if true as the group owner,else as the client * */ public void searchDirect(Context context, boolean server) { serverFlag = server; discover(); } @SuppressLint({ "NewApi", "NewApi" }) public void stopSearch() { mWifiP2pManager.stopPeerDiscovery(channel, null); } public void stopConnect() { try { mWifiP2pManager.cancelConnect(channel, null); mWifiP2pManager.removeGroup(channel, null); } catch (Exception e) { Log.e(TAG, "stopConnect()" + e); } } public void registerObserver(ManagerP2pDeivce notify) { observerList.add(notify); } public void unRegisterObserver(ManagerP2pDeivce notify) { observerList.remove(notify); } public void connect(WifiP2pConfig config) { mWifiP2pManager.connect(channel, config, null); } @Override public void wifiP2pConnected() { notifyConnect(); } private void getPeerDevice(final boolean flag) { final ArrayList<WifiP2pDevice> serverList = new ArrayList<WifiP2pDevice>(); mWifiP2pManager.requestPeers(channel, new PeerListListener() { @SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" }) public void onPeersAvailable(WifiP2pDeviceList peers) { if (!flag) { for (WifiP2pDevice device : peers.getDeviceList()) { if (WiFiNameEncryption.checkWiFiName(device.deviceName)) { serverList.add(device); } } } if (observerList != null) { for (ManagerP2pDeivce f : observerList) { f.deviceChange(serverList); } } } }); } private void notifyConnect() { mWifiP2pManager.requestConnectionInfo(this.channel, new ConnectionInfoListener() { public void onConnectionInfoAvailable(WifiP2pInfo info) { if (observerList != null) { for (ManagerP2pDeivce f : observerList) { f.hasConnect(info); } } } }); } @Override public void notifyDeviceChange() { getPeerDevice(serverFlag); } public void setServerFlag(boolean flag) { if (serverFlag == flag) { return; } this.serverFlag = flag; this.stopSearch(); if (serverFlag) { setDeviceName(mWifiP2pManager, channel, WiFiNameEncryption.generateWiFiName(UserHelper .getUserName(context)), null); } else { setDeviceName(mWifiP2pManager, channel, UserHelper.getUserName(context), null); } this.discover(); getPeerDevice(serverFlag); } } <file_sep>package com.zhaoyan.communication.search; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketTimeoutException; import android.content.Context; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.search.ServerSearcherLan.OnSearchListenerLan; /** * This class is use for search server in Wifi network in which the AP is not * android WiFi hot access point.</br> * * This class is single instance, So use {@link #getInstance(Context)} to get * object.</br> * * After started, we listen the mulitcast message in the network. The message is * the server IP, so when get the message, found a server. </br> * */ public class ServerSearcherLanWifi implements Runnable { private static final String TAG = "SearchServerLanWifi"; // multicast address. private InetAddress mMulticastAddress; // Socket for receive multicast message. private MulticastSocket mReceiveSocket; // Read socket packet thread private GetPacket mGetPacketRunnable; private OnSearchListenerLan mListener; private boolean mStarted = false; private Context mContext; public ServerSearcherLanWifi(Context context) { mContext = context; } public void setOnSearchListener(OnSearchListenerLan listener) { mListener = listener; } @Override public void run() { try { mReceiveSocket = new MulticastSocket(Search.MULTICAST_RECEIVE_PORT); mReceiveSocket.setSoTimeout(Search.TIME_OUT); mMulticastAddress = InetAddress.getByName(Search.MULTICAST_IP); } catch (Exception e) { Log.e(TAG, "Create mReceiveSocket fail." + e); } join(mMulticastAddress); startListenServerMessage(); } public void startSearch() { if (mStarted) { Log.d(TAG, "startSearch() ignore, search is already started."); return; } Log.d(TAG, "Start search."); mStarted = true; NetWorkUtil.acquireWifiMultiCastLock(mContext); Thread searchThread = new Thread(this); searchThread.start(); } public void stopSearch() { if (!mStarted) { Log.d(TAG, "stopSearch() ignore, search is not started."); return; } Log.d(TAG, "Stop search"); mStarted = false; if (mGetPacketRunnable != null) { mGetPacketRunnable.stop(); mGetPacketRunnable = null; } leaveGroup(mMulticastAddress); NetWorkUtil.releaseWifiMultiCastLock(); closeSocket(); } private void closeSocket() { if (mReceiveSocket != null) { mReceiveSocket.close(); mReceiveSocket = null; } } /** * Join broadcast group. */ private void join(InetAddress groupAddr) { try { // Join broadcast group. mReceiveSocket.joinGroup(groupAddr); } catch (Exception e) { Log.e(TAG, "Join group fail. " + e.toString()); } } /** * Leave broadcast group. */ private void leaveGroup(InetAddress groupAddr) { try { // leave broadcast group. mReceiveSocket.leaveGroup(groupAddr); } catch (Exception e) { Log.e(TAG, "leave group fail. " + e.toString()); } } /** * Listen server message. */ private void startListenServerMessage() { if (mGetPacketRunnable != null) { mGetPacketRunnable.stop(); } mGetPacketRunnable = new GetPacket(); new Thread(mGetPacketRunnable).start(); } /** * Get message from server. * */ class GetPacket implements Runnable { private boolean mStop = false; public void stop() { mStop = true; } @Override public void run() { DatagramPacket inPacket; while (!mStop) { try { inPacket = new DatagramPacket(new byte[1024], 1024); mReceiveSocket.receive(inPacket); byte[] data = inPacket.getData(); SearchProtocol.decodeSearchLan(data, mListener); } catch (Exception e) { if (e instanceof SocketTimeoutException) { // time out, search again. } else { if (!mStop) { Log.e(TAG, "GetPacket error," + e.toString()); } if (mListener != null) { mListener.onSearchLanStop(); } } } } } } } <file_sep>package com.zhaoyan.juyou.dialog; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.util.ZYUtils; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.common.HistoryManager; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; /** * use for view copy or move ui dialog * @author Yuri */ public class CopyMoveDialog extends ZyAlertDialog{ private static final String TAG = "CopyMoveDialog"; private TextView mMessageView; private TextView mFileCountView; private TextView mFileCountPercentView; private TextView mFileSizeView; private TextView mFileSizePercentView; private ProgressBar mFileCountBar; private ProgressBar mFileSizeBar; /** * the path that copy or move to directory */ private String mDespath; /** * current copy or move file count */ private int mTotalCount; private long mSingleFileTotalSize; private long mCopySize; float mCountPrev = 0; private float mSizePrev = 0; private String mTotalSizeStr; private String mProgressSizeStr; private static final int MSG_UPDATE_PROGRESS_COUNT = 0; private static final int MSG_UPDATE_PROGRESS_SIZE = 1; private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_UPDATE_PROGRESS_COUNT: if (mSingleFileTotalSize == -1) { mFileSizeBar.setVisibility(View.GONE); } int count = msg.arg1; String fileName = msg.obj.toString(); mMessageView.setText(fileName + "->" + mDespath); mFileCountView.setText(count + "/" + mTotalCount); float per = (float) count / mTotalCount; if (mCountPrev != per * 100) { mFileCountBar.setProgress((int)(per * 100)); mFileCountPercentView.setText(HistoryManager.nf.format(per)); mCountPrev = per * 100; } break; case MSG_UPDATE_PROGRESS_SIZE: float percent = (float)mCopySize / mSingleFileTotalSize; if (mSizePrev != percent * 100) { mFileSizeBar.setProgress((int)(percent * 100)); // mFileSizePercentView.setText(HistoryManager.nf.format(percent)); // mFileSizeView.setText(mProgressSizeStr + "/" + mTotalSizeStr); mSizePrev = percent * 100; } break; default: break; } }; }; public CopyMoveDialog(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub View view = getLayoutInflater().inflate(R.layout.dialog_copy, null); mMessageView = (TextView) view.findViewById(R.id.tv_copy_msg); mFileCountView = (TextView) view.findViewById(R.id.tv_file_count); mFileCountPercentView = (TextView) view.findViewById(R.id.tv_file_count_percent); mFileCountBar = (ProgressBar) view.findViewById(R.id.bar_copy_one); mFileCountBar.setMax(100); mFileSizeView = (TextView) view.findViewById(R.id.tv_file_size); mFileSizePercentView = (TextView) view.findViewById(R.id.tv_file_size_percent); mFileSizeBar = (ProgressBar) view.findViewById(R.id.bar_copy_two); mFileSizeBar.setMax(100); setCustomView(view); super.onCreate(savedInstanceState); } public void setDesPath(String despath){ this.mDespath = despath; } public void setTotalCount(int totalCount){ this.mTotalCount = totalCount; } public void setSignleFileTotalSize(long size){ this.mSingleFileTotalSize = size; } public void updateMessage(String fileName){ } public void updateCountProgress(String fileName, int count, long filesize){ this.mSingleFileTotalSize = filesize; if (filesize == -1) { //is move operation }else { mTotalSizeStr = ZYUtils.getFormatSize(filesize); } Message message = mHandler.obtainMessage(); message.arg1 = count; message.obj = fileName; message.what = MSG_UPDATE_PROGRESS_COUNT; message.sendToTarget(); } public void updateSingleFileProgress(long copysize){ mCopySize = copysize; mProgressSizeStr = ZYUtils.getFormatSize(copysize); Message message = mHandler.obtainMessage(); message.what = MSG_UPDATE_PROGRESS_SIZE; message.sendToTarget(); } } <file_sep>package com.zhaoyan.juyou.common; import java.util.ArrayList; import java.util.List; import com.zhaoyan.common.util.Log; import android.content.Context; public class ActionMenu{ private static final String TAG = "ActionMenu"; public static final int ACTION_MENU_OPEN = 0x01; public static final int ACTION_MENU_SEND = 0x02; public static final int ACTION_MENU_DELETE = 0x03; public static final int ACTION_MENU_INFO = 0x04; public static final int ACTION_MENU_MORE = 0x05; public static final int ACTION_MENU_PLAY = 0x06; public static final int ACTION_MENU_RENAME = 0x07; public static final int ACTION_MENU_SELECT = 0x08; public static final int ACTION_MENU_UNINSTALL = 0x09; public static final int ACTION_MENU_MOVE_TO_GAME = 0x10; public static final int ACTION_MENU_MOVE_TO_APP = 0x11; public static final int ACTION_MENU_BACKUP = 0x12; public static final int ACTION_MENU_CANCEL = 0x13; public static final int ACTION_MENU_CLEAR_HISTORY = 0x14; public static final int ACTION_MENU_CLEAR_HISTORY_AND_FILE = 0x15; public static final int ACTION_MENU_COPY = 0x16; public static final int ACTION_MENU_PASTE = 0x17; public static final int ACTION_MENU_CUT = 0x18; public static final int ACTION_MENU_CREATE_FOLDER = 0x19; public static final int ACTION_MENU_CANCEL_TRANSFER = 0x20; public static final int ACTION_MENU_CANCEL_SEND = 0x21; public static final int ACTION_MENU_CANCEL_RECEIVE = 0x22; public static final int ACTION_MENU_CAPTURE = 0x23; public static final int ACTION_MENU_PICK_PICTURE = 0x24; //action menu mode,edit is menu mode public static final int MODE_NORMAL = 0; public static final int MODE_EDIT = 1; public static final int MODE_COPY = 2; public static final int MODE_CUT = 3; private List<ActionMenuItem> items = new ArrayList<ActionMenu.ActionMenuItem>(); private Context mContext; public ActionMenu(Context context){ mContext = context; } public ActionMenuItem addItem(int itemId){ ActionMenuItem item = new ActionMenuItem(itemId); items.add(item); return item; } public void addItem(int id, int iconId, String title){ ActionMenuItem item = new ActionMenuItem(id, iconId, title); items.add(item); } public void addItem(int id, int iconId, int title_redId){ String title = mContext.getResources().getString(title_redId); addItem(id, iconId, title); } public int size(){ return items.size(); } public ActionMenuItem getItem(int index){ try { return items.get(index); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Out of bound,the size is " + size() + ",index is " + index); return null; } } public ActionMenuItem findItem(int id){ for(ActionMenuItem item : items){ if (id == item.getItemId()) { return item; } } return null; } public class ActionMenuItem{ int id; int iconId; int enableIconId; int disableIconId; String title; boolean enable = true; int text_color; ActionMenuItem(int itemid){ id = itemid; text_color = mContext.getResources().getColor(android.R.color.black); } ActionMenuItem(int id, int iconid, String title){ this.id = id; this.iconId = iconid; this.title = title; text_color = mContext.getResources().getColor(android.R.color.black); } public int getItemId(){ return id; } public void setTitle(String title){ this.title = title; } public void setTitle(int resId){ String title = mContext.getResources().getString(resId); setTitle(title); } public String getTitle(){ return title; } public void setTextColor(int color_id){ this.text_color = color_id; } public int getTextColor(){ return text_color; } public void setIcon(int iconId){ this.iconId = iconId; } public int getIcon(){ return iconId; } public void setEnableIcon(int iconId){ this.enableIconId = iconId; } public int getEnableIcon(){ return enableIconId == 0 ? iconId : enableIconId; } public void setDisableIcon(int iconId){ this.disableIconId = iconId; } public int getDisableIcon(){ return disableIconId == 0 ? iconId : disableIconId; } public void setEnable(boolean enable){ this.enable = enable; } public boolean isEnable(){ return enable; } } } <file_sep>package com.zhaoyan.juyou.adapter; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.util.SparseBooleanArray; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.view.CheckableImageView; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.async.ImageLoadAsync; import com.zhaoyan.juyou.async.MediaAsync; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.AsyncPictureLoader; import com.zhaoyan.juyou.common.ImageInfo; import com.zhaoyan.juyou.common.ZYConstant.Extra; public class ImageGridAdapter extends BaseAdapter implements SelectInterface{ private static final String TAG = "ImageGridAdapter"; private LayoutInflater mInflater = null; private List<ImageInfo> mDataList; private boolean mIdleFlag = true; /**save status of item selected*/ private SparseBooleanArray mCheckArray; /**current menu mode,ActionMenu.MODE_NORMAL,ActionMenu.MODE_EDIT*/ private int mMenuMode = ActionMenu.MODE_NORMAL; //List or Grid private int mViewType = Extra.VIEW_TYPE_DEFAULT; private int mWidth; private Context mContext; public ImageGridAdapter(Context context, int viewType, List<ImageInfo> itemList){ mContext = context; mInflater = LayoutInflater.from(context); mDataList = itemList; mCheckArray = new SparseBooleanArray(); mViewType = viewType; Display display = ((Activity)mContext).getWindowManager().getDefaultDisplay(); mWidth = display.getWidth(); // deprecated Log.d(TAG, "mWidth=" + mWidth); } @Override public int getCount() { return mDataList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (Extra.VIEW_TYPE_LIST == mViewType) { return getListView(convertView, position); } return getGridView(convertView, position); } private View getGridView(View convertView, int position){ View view = null; ViewHolder holder = null; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = mInflater.inflate(R.layout.image_item_grid, null); holder.imageView = (CheckableImageView) view.findViewById(R.id.iv_image_item); view.setTag(holder); } LayoutParams imageParams = (LayoutParams) holder.imageView.getLayoutParams(); imageParams.width = mWidth/3; imageParams.height = mWidth/3; holder.imageView.setLayoutParams(imageParams); // long id = mDataList.get(position).getImageId(); String path = mDataList.get(position).getPath(); ImageLoadAsync loadAsync = new ImageLoadAsync(mContext, holder.imageView, mWidth / 3); loadAsync.executeOnExecutor(MediaAsync.THREAD_POOL_EXECUTOR, path); // if (mIdleFlag) { // pictureLoader.loadBitmap(id, holder.imageView); // holder.imageView.setChecked(mCheckArray.get(position)); // } else { // if (AsyncPictureLoader.bitmapCaches.size() > 0 // && AsyncPictureLoader.bitmapCaches.get(id) != null) { // holder.imageView.setImageBitmap(AsyncPictureLoader.bitmapCaches // .get(id).get()); // } else { // holder.imageView.setImageResource(R.drawable.photo_l); // } // holder.imageView.setChecked(mCheckArray.get(position)); // } holder.imageView.setChecked(mCheckArray.get(position)); return view; } private View getListView(View convertView, int position){ View view = null; ViewHolder holder = null; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = mInflater.inflate(R.layout.image_item_list, null); holder.imageView2 = (ImageView) view.findViewById(R.id.iv_image_item); holder.nameView = (TextView) view.findViewById(R.id.tv_image_name); holder.sizeView = (TextView) view.findViewById(R.id.tv_image_size); view.setTag(holder); } LayoutParams imageParams = (LayoutParams) holder.imageView2.getLayoutParams(); imageParams.width = mWidth / 4; imageParams.height = mWidth / 4; holder.imageView2.setLayoutParams(imageParams); // long id = mDataList.get(position).getImageId(); String name = mDataList.get(position).getDisplayName(); String size = mDataList.get(position).getFormatSize(); String path = mDataList.get(position).getPath(); holder.nameView.setText(name); holder.sizeView.setText(size); ImageLoadAsync loadAsync = new ImageLoadAsync(mContext, holder.imageView2, mWidth / 4); loadAsync.executeOnExecutor(MediaAsync.THREAD_POOL_EXECUTOR, path); // if (mIdleFlag) { // pictureLoader.loadBitmap(id, holder.imageView2); // } else { // if (AsyncPictureLoader.bitmapCaches.size() > 0 // && AsyncPictureLoader.bitmapCaches.get(id) != null) { // holder.imageView2.setImageBitmap(AsyncPictureLoader.bitmapCaches // .get(id).get()); // } else { // holder.imageView2.setImageResource(R.drawable.photo_l); // } // } updateViewBackground(position, view); return view; } public void updateViewBackground(int position, View view){ boolean selected = isChecked(position); if (selected) { view.setBackgroundResource(R.color.holo_blue_light); }else { view.setBackgroundResource(Color.TRANSPARENT); } } private class ViewHolder{ CheckableImageView imageView;//folder icon ImageView imageView2; TextView nameView; TextView sizeView; } @Override public void changeMode(int mode) { mMenuMode = mode; } @Override public boolean isMode(int mode) { return mMenuMode == mode; } @Override public void checkedAll(boolean isChecked) { int count = this.getCount(); for (int i = 0; i < count; i++) { setChecked(i, isChecked); } } @Override public void setChecked(int position, boolean isChecked) { mCheckArray.put(position, isChecked); } @Override public void setChecked(int position) { mCheckArray.put(position, !isChecked(position)); } @Override public boolean isChecked(int position) { return mCheckArray.get(position); } @Override public int getCheckedCount() { int count = 0; for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { count ++; } } return count; } @Override public List<Integer> getCheckedPosList() { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(i); } } return list; } @Override public List<String> getCheckedNameList() { List<String> list = new ArrayList<String>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(mDataList.get(i).getDisplayName()); } } return list; } @Override public List<String> getCheckedPathList() { List<String> list = new ArrayList<String>(); for (int i = 0; i < mCheckArray.size(); i++) { if (mCheckArray.valueAt(i)) { list.add(mDataList.get(i).getPath()); } } return list; } @Override public void setIdleFlag(boolean flag) { this.mIdleFlag = flag; } } <file_sep>package com.zhaoyan.juyou.common; import java.io.File; import com.zhaoyan.common.util.ZYUtils; import android.os.Parcel; import android.os.Parcelable; public class ImageInfo implements Parcelable{ /**sdcard中图片在数据库中保存的id*/ private long image_id; /**image path*/ private String path; private String dispalyName; /**bucket dispaly name*/ private String bucketDisplayName; /**width*/ private long width; /**height*/ private long height; public static final Parcelable.Creator<ImageInfo> CREATOR = new Parcelable.Creator<ImageInfo>() { @Override public ImageInfo createFromParcel(Parcel source) { return new ImageInfo(source); } @Override public ImageInfo[] newArray(int size) { return new ImageInfo[size]; } }; public ImageInfo(){} public ImageInfo(long id){ this.image_id = id; } private ImageInfo(Parcel in) { readFromParcel(in); } public long getImageId() { return image_id; } public void setImageId(long image_id) { this.image_id = image_id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getDisplayName(){ return dispalyName; } public void setDisplayName(String name){ this.dispalyName = name; } public String getBucketDisplayName() { return bucketDisplayName; } public void setBucketDisplayName(String bucketDisplayName) { this.bucketDisplayName = bucketDisplayName; } public long getWidth(){ return width; } public void setWidth(long width){ this.width = width; } public long getHeight(){ return height; } public void setHeight(long height){ this.height = height; } public String getName(){ File file = new File(path); return file.getName(); } public long getDate(){ File file = new File(path); return file.lastModified(); } public String getFormatDate(){ return ZYUtils.getFormatDate(getDate()); } public String getFormatSize(){ long size = new File(path).length(); return ZYUtils.getFormatSize(size); } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeLong(image_id); dest.writeString(path); dest.writeString(bucketDisplayName); dest.writeLong(width); dest.writeLong(height); } public void readFromParcel(Parcel in){ image_id = in.readLong(); path = in.readString(); bucketDisplayName = in.readString(); width = in.readLong(); height = in.readLong(); } } <file_sep>package com.zhaoyan.communication; import java.net.Socket; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; import com.dreamlink.communication.lib.util.Notice; /** * This class is a AsyncTask, used for creating client socket and connecting to * server.</br> * * After connected server, start communication with server socket.</br> * */ @SuppressLint("UseValueOf") public class SocketClientTask extends AsyncTask<String, Void, Socket> { private static final String TAG = "SocketClientTask"; public interface OnConnectedToServerListener { /** * Connected to server. * * @param socket */ void onConnectedToServer(Socket socket); } private Context mContext; private ProgressDialog progressDialog; private Notice notice; private SocketClient client; private OnConnectedToServerListener mOnConnectedToServerListener; public SocketClientTask(Context context) { this.mContext = context; client = new SocketClient(); notice = new Notice(mContext); } public void setOnConnectedToServerListener( OnConnectedToServerListener listener) { mOnConnectedToServerListener = listener; } @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(mContext); progressDialog.setTitle("Server"); progressDialog.setMessage("Connecting to server..."); progressDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Stop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancel(true); progressDialog.dismiss(); } }); progressDialog.setCancelable(false); // progressDialog.show(); } @Override protected Socket doInBackground(String... arg) { return client.startClient(arg[0], new Integer(arg[1])); } @Override protected void onPostExecute(Socket result) { super.onPostExecute(result); closeDialog(); if (result == null) { notice.showToast("Connect to server fail."); } else { if (mOnConnectedToServerListener != null) { mOnConnectedToServerListener.onConnectedToServer(result); } } } private void closeDialog() { if (progressDialog != null && progressDialog.isShowing()) { try { progressDialog.dismiss(); } catch (Exception e) { Log.e(TAG, "closeDialog(), " + e); // There is exception sometimes. } } } }<file_sep>package com.zhaoyan.communication.search; import java.lang.reflect.Method; import java.util.ArrayList; import android.annotation.SuppressLint; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.os.Binder; import android.os.IBinder; import android.util.Log; import com.dreamlink.communication.aidl.User; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.search.SearchProtocol.OnSearchListener; import com.zhaoyan.communication.search.WifiDirectReciver.WifiDirectDeviceNotify; /** * use this create wifi-direct server and find wifi-direct server to connect. * </br> you should implements the {@link DeviceNotify} interface to know the * device change and connect status.</br> normally , application start this * service only once at the same time,so please remember unbind it. * */ @SuppressLint({ "NewApi", "NewApi" }) public class DirectSearchService extends Service { private WifiP2pManager wifiP2pManager; private WifiDirectReciver wifiDirectReceiver; private Channel channel; private boolean flag; private IntentFilter mWifiDirectIntentFilter; private String TAG = "Direct Service"; private User user; private ArrayList<DeviceNotify> list; private IntentFilter filter; private OnSearchListener onSearchListener; private boolean register_flag = false; /** * this interface will notify you that the wifi-direct device update and * connect info */ public interface DeviceNotify { public void deviceChange(ArrayList<WifiP2pDevice> list); public void hasConnect(WifiP2pInfo info); } @Override public IBinder onBind(Intent arg0) { if (myBinder == null) { myBinder = new DirectBinder(); } return myBinder; } @Override public boolean onUnbind(Intent intent) { wifiP2pManager.stopPeerDiscovery(channel, null); unregisterReceiver(wifiDirectReceiver); if (register_flag) { unregisterReceiver(server_reciver); register_flag = false; } stopSelf(); return super.onUnbind(intent); } @Override public void onCreate() { Log.d(TAG, "onCreate()"); super.onCreate(); initReceiver(); } @Override public void onDestroy() { Log.d(TAG, "onDestroy()"); myBinder = null; super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } public class DirectBinder extends Binder { public DirectSearchService getService() { return DirectSearchService.this; } } public void stopSearch() { if (wifiP2pManager != null) { wifiP2pManager.stopPeerDiscovery(channel, null); } } private DirectBinder myBinder; public void regitserListener(DeviceNotify deviceNotify) { if (list == null) { list = new ArrayList<DirectSearchService.DeviceNotify>(); } list.add(deviceNotify); } public void unregitserListener(DeviceNotify deviceNotify) { if (list != null && list.contains(deviceNotify)) { list.remove(deviceNotify); if (list.size() == 0) { if (wifiP2pManager != null) { stopServer(); } } } } /** * start wifi-direct server or search direct device * * @param flag * true,start server;else search device * @param user * the client will connect to,if null ,show all devices which * name conform the rule */ @SuppressLint("NewApi") public void startDirect(boolean flag, User user, OnSearchListener onSearchListener) { this.flag = flag; this.user = user; this.onSearchListener = onSearchListener; final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { startDirectServer(); } else { wifiManager.setWifiEnabled(true); registerReceiver(server_reciver, filter); register_flag = true; } } private void startDirectServer() { wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = wifiP2pManager.initialize(getApplicationContext(), getMainLooper(), null); this.registerReceiver(wifiDirectReceiver, mWifiDirectIntentFilter); if (flag) { setDeviceName(wifiP2pManager, channel, WiFiNameEncryption.generateWiFiName(UserHelper .getUserName(getApplicationContext())), null); } else { setDeviceName(wifiP2pManager, channel, UserHelper.getUserName(getApplicationContext()), null); } wifiP2pManager.discoverPeers(channel, null); wifiDirectReceiver.registerObserver(new WifiDeviceNotify()); notifyServerCreated(); } private class WifiDeviceNotify implements WifiDirectDeviceNotify { @SuppressLint({ "NewApi", "NewApi" }) @Override public void notifyDeviceChange() { if (!flag) { /* if server need not to know the device change */ wifiP2pManager.requestPeers(channel, new PeerListListener() { @SuppressLint("NewApi") @Override public void onPeersAvailable(WifiP2pDeviceList peers) { ArrayList<WifiP2pDevice> serverList = new ArrayList<WifiP2pDevice>(); for (WifiP2pDevice device : peers.getDeviceList()) { Log.e("ArbiterLiu", "just test ,not error : " + device.deviceName); if (WiFiNameEncryption .checkWiFiName(device.deviceName)) { if (user != null) { /** * this mean connect to the user which the * server ask */ connectToDevice(device); return; } else { /** * this mean search all that name conform * the rule */ serverList.add(device); ServerInfo info = new ServerInfo(); info.setServerType(ConnectHelper.SERVER_TYPE_WIFI_DIRECT); info.setServerDevice(device); info.setServerName(device.deviceName); onSearchListener.onSearchSuccess(info); } } } } }); } } @Override public void wifiP2pConnected() { wifiP2pManager.requestConnectionInfo(channel, new ConnectionInfoListener() { public void onConnectionInfoAvailable(WifiP2pInfo info) { if (info.isGroupOwner) { SocketCommunicationManager.getInstance().startServer( getApplicationContext()); } else { SocketCommunicationManager.getInstance() .connectServer( getApplicationContext(), info.groupOwnerAddress .getHostAddress()); } if (list != null) { for (DeviceNotify f : list) { f.hasConnect(info); } } if (!info.isGroupOwner) { stopServer(); } } }); } } private void initReceiver() { mWifiDirectIntentFilter = new IntentFilter(); mWifiDirectIntentFilter .addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); mWifiDirectIntentFilter .addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mWifiDirectIntentFilter .addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mWifiDirectIntentFilter .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mWifiDirectIntentFilter .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); wifiDirectReceiver = new WifiDirectReciver(); filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); } @SuppressLint("NewApi") private void setDeviceName(WifiP2pManager manager, Channel channel, String name, ActionListener listener) { try { Method method = manager.getClass().getMethod("setDeviceName", Channel.class, String.class, ActionListener.class); method.invoke(manager, channel, name, listener); } catch (Exception e) { Log.e(TAG, "setDeviceName fail: " + e); } } private void connectToDevice(WifiP2pDevice device) { String userName = device.deviceName.substring(0, device.deviceName.indexOf("@")); if (userName.equals(user.getUserName())) { WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.groupOwnerIntent = 0; wifiP2pManager.connect(channel, config, null); } } public void stopServer() { wifiP2pManager.stopPeerDiscovery(channel, null); DirectSearchService.this.getApplicationContext().unregisterReceiver( wifiDirectReceiver); wifiDirectReceiver = null; channel = null; wifiP2pManager = null; } private BroadcastReceiver server_reciver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) { int wifiState = intent.getIntExtra( WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); if (wifiState == WifiManager.WIFI_STATE_ENABLED) { startDirectServer(); } } } }; public boolean connectToServer(ServerInfo info) { if (info == null || !info.getServerType().equals( ConnectHelper.SERVER_TYPE_WIFI_DIRECT)) { return false; } WifiP2pDevice device = info.getServerDevice(); WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.groupOwnerIntent = 0; wifiP2pManager.connect(channel, config, null); return true; } public void notifyServerCreated() { this.sendBroadcast(new Intent(ConnectHelper.ACTION_SERVER_CREATED)); } } <file_sep>package com.zhaoyan.juyou.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import com.zhaoyan.common.util.Log; public class JuyouProvider extends ContentProvider { private static final String TAG = "ZhaoyanProvider"; private SQLiteDatabase mSqLiteDatabase; private DatabaseHelper mDatabaseHelper; public static final int HISTORY_COLLECTION = 10; public static final int HISTORY_SINGLE = 11; public static final int HISTORY_FILTER = 12; public static final int TRAFFIC_STATICS_RX_COLLECTION = 20; public static final int TRAFFIC_STATICS_RX_SINGLE = 21; public static final int TRAFFIC_STATICS_TX_COLLECTION = 22; public static final int TRAFFIC_STATICS_TX_SINGLE = 23; public static final int USER_COLLECTION = 30; public static final int USER_SINGLE = 31; public static final int ACCOUNT_COLLECTION = 40; public static final int ACCOUNT_SINGLE = 41; public static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(JuyouData.AUTHORITY, "history", HISTORY_COLLECTION); uriMatcher.addURI(JuyouData.AUTHORITY, "history/*", HISTORY_SINGLE); uriMatcher.addURI(JuyouData.AUTHORITY, "history_filter/*", HISTORY_FILTER); uriMatcher.addURI(JuyouData.AUTHORITY, "trafficstatics_rx", TRAFFIC_STATICS_RX_COLLECTION); uriMatcher.addURI(JuyouData.AUTHORITY, "trafficstatics_rx/#", TRAFFIC_STATICS_RX_SINGLE); uriMatcher.addURI(JuyouData.AUTHORITY, "trafficstatics_tx", TRAFFIC_STATICS_TX_COLLECTION); uriMatcher.addURI(JuyouData.AUTHORITY, "trafficstatics_tx/#", TRAFFIC_STATICS_TX_SINGLE); uriMatcher.addURI(JuyouData.AUTHORITY, "user", USER_COLLECTION); uriMatcher.addURI(JuyouData.AUTHORITY, "user/#", USER_SINGLE); uriMatcher.addURI(JuyouData.AUTHORITY, "account", ACCOUNT_COLLECTION); uriMatcher.addURI(JuyouData.AUTHORITY, "account/#", ACCOUNT_SINGLE); } @Override public boolean onCreate() { mDatabaseHelper = new DatabaseHelper(getContext()); return (mDatabaseHelper == null) ? false : true; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); String table; switch (uriMatcher.match(uri)) { case HISTORY_COLLECTION: table = JuyouData.History.TABLE_NAME; break; case HISTORY_SINGLE: table = JuyouData.History.TABLE_NAME; String segment2 = uri.getPathSegments().get(1); if (selection != null && segment2.length() > 0) { selection = "_id=" + segment2 + " AND (" + selection + ")"; } else { // 由于segment是个string,那么需要给他加个'',如果是int型的就不需要了 // selection = "pkg_name='" + segment + "'"; } break; case TRAFFIC_STATICS_RX_SINGLE: table = JuyouData.TrafficStaticsRX.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case TRAFFIC_STATICS_RX_COLLECTION: table = JuyouData.TrafficStaticsRX.TABLE_NAME; break; case TRAFFIC_STATICS_TX_SINGLE: table = JuyouData.TrafficStaticsTX.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case TRAFFIC_STATICS_TX_COLLECTION: table = JuyouData.TrafficStaticsTX.TABLE_NAME; break; case USER_SINGLE: table = JuyouData.User.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case USER_COLLECTION: table = JuyouData.User.TABLE_NAME; break; case ACCOUNT_SINGLE: table = JuyouData.Account.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case ACCOUNT_COLLECTION: table = JuyouData.Account.TABLE_NAME; break; default: throw new IllegalArgumentException("UnKnow Uri:" + uri); } int count = mSqLiteDatabase.delete(table, selection, selectionArgs); if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case HISTORY_COLLECTION: return JuyouData.History.CONTENT_TYPE; case HISTORY_SINGLE: return JuyouData.History.CONTENT_TYPE_ITEM; case TRAFFIC_STATICS_TX_COLLECTION: return JuyouData.TrafficStaticsRX.CONTENT_TYPE; case TRAFFIC_STATICS_RX_SINGLE: return JuyouData.TrafficStaticsRX.CONTENT_TYPE_ITEM; case USER_COLLECTION: return JuyouData.User.CONTENT_TYPE; case USER_SINGLE: return JuyouData.User.CONTENT_TYPE_ITEM; case ACCOUNT_COLLECTION: return JuyouData.Account.CONTENT_TYPE; case ACCOUNT_SINGLE: return JuyouData.Account.CONTENT_TYPE_ITEM; default: throw new IllegalArgumentException("Unkonw uri:" + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { Log.v(TAG, "insert db"); mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); String table; Uri contentUri; switch (uriMatcher.match(uri)) { case HISTORY_COLLECTION: case HISTORY_SINGLE: table = JuyouData.History.TABLE_NAME; contentUri = JuyouData.History.CONTENT_URI; break; case TRAFFIC_STATICS_RX_SINGLE: case TRAFFIC_STATICS_RX_COLLECTION: table = JuyouData.TrafficStaticsRX.TABLE_NAME; contentUri = JuyouData.TrafficStaticsRX.CONTENT_URI; break; case TRAFFIC_STATICS_TX_SINGLE: case TRAFFIC_STATICS_TX_COLLECTION: table = JuyouData.TrafficStaticsTX.TABLE_NAME; contentUri = JuyouData.TrafficStaticsTX.CONTENT_URI; break; case USER_SINGLE: case USER_COLLECTION: table = JuyouData.User.TABLE_NAME; contentUri = JuyouData.User.CONTENT_URI; break; case ACCOUNT_SINGLE: case ACCOUNT_COLLECTION: table = JuyouData.Account.TABLE_NAME; contentUri = JuyouData.Account.CONTENT_URI; break; default: throw new IllegalArgumentException("Unknow uri:" + uri); } long rowId = mSqLiteDatabase.insertWithOnConflict(table, "", values, SQLiteDatabase.CONFLICT_REPLACE); if (rowId > 0) { Uri rowUri = ContentUris.withAppendedId(contentUri, rowId); getContext().getContentResolver().notifyChange(uri, null); Log.v(TAG, "insertDb.rowId=" + rowId); return rowUri; } throw new IllegalArgumentException("Cannot insert into uri:" + uri); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch (uriMatcher.match(uri)) { case HISTORY_COLLECTION: qb.setTables(JuyouData.History.TABLE_NAME); break; case HISTORY_SINGLE: qb.setTables(JuyouData.History.TABLE_NAME); qb.appendWhere("_id="); qb.appendWhere(uri.getPathSegments().get(1)); break; case HISTORY_FILTER: break; case TRAFFIC_STATICS_RX_SINGLE: qb.setTables(JuyouData.TrafficStaticsRX.TABLE_NAME); qb.appendWhere("_id=" + uri.getPathSegments().get(1)); break; case TRAFFIC_STATICS_RX_COLLECTION: qb.setTables(JuyouData.TrafficStaticsRX.TABLE_NAME); break; case TRAFFIC_STATICS_TX_SINGLE: qb.setTables(JuyouData.TrafficStaticsTX.TABLE_NAME); qb.appendWhere("_id=" + uri.getPathSegments().get(1)); break; case TRAFFIC_STATICS_TX_COLLECTION: qb.setTables(JuyouData.TrafficStaticsTX.TABLE_NAME); break; case USER_SINGLE: qb.setTables(JuyouData.User.TABLE_NAME); qb.appendWhere("_id=" + uri.getPathSegments().get(1)); break; case USER_COLLECTION: qb.setTables(JuyouData.User.TABLE_NAME); break; case ACCOUNT_SINGLE: qb.setTables(JuyouData.Account.TABLE_NAME); qb.appendWhere("_id=" + uri.getPathSegments().get(1)); break; case ACCOUNT_COLLECTION: qb.setTables(JuyouData.Account.TABLE_NAME); break; default: throw new IllegalArgumentException("Unknow uri:" + uri); } mSqLiteDatabase = mDatabaseHelper.getReadableDatabase(); Cursor ret = qb.query(mSqLiteDatabase, projection, selection, selectionArgs, null, null, sortOrder); if (ret != null) { ret.setNotificationUri(getContext().getContentResolver(), uri); } return ret; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int match = uriMatcher.match(uri); mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); String table; switch (match) { case HISTORY_SINGLE: table = JuyouData.History.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case HISTORY_COLLECTION: table = JuyouData.History.TABLE_NAME; break; case TRAFFIC_STATICS_RX_SINGLE: table = JuyouData.TrafficStaticsRX.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case TRAFFIC_STATICS_RX_COLLECTION: table = JuyouData.TrafficStaticsRX.TABLE_NAME; break; case TRAFFIC_STATICS_TX_SINGLE: table = JuyouData.TrafficStaticsTX.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case TRAFFIC_STATICS_TX_COLLECTION: table = JuyouData.TrafficStaticsTX.TABLE_NAME; break; case USER_SINGLE: table = JuyouData.User.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case USER_COLLECTION: table = JuyouData.User.TABLE_NAME; break; case ACCOUNT_SINGLE: table = JuyouData.Account.TABLE_NAME; selection = "_id=" + uri.getPathSegments().get(1); selectionArgs = null; break; case ACCOUNT_COLLECTION: table = JuyouData.Account.TABLE_NAME; break; default: throw new UnsupportedOperationException("Cannot update uri:" + uri); } int count = mSqLiteDatabase.update(table, values, selection, null); getContext().getContentResolver().notifyChange(uri, null); return count; } private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, JuyouData.DATABASE_NAME, null, JuyouData.DATABASE_VERSION); Log.d(TAG, "DatabaseHelper"); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "DatabaseHelper.onCreate"); // create history table db.execSQL("create table " + JuyouData.History.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + JuyouData.History.FILE_PATH + " TEXT, " + JuyouData.History.FILE_NAME + " TEXT, " + JuyouData.History.FILE_SIZE + " LONG, " + JuyouData.History.SEND_USERNAME + " TEXT, " + JuyouData.History.RECEIVE_USERNAME + " TEXT, " + JuyouData.History.PROGRESS + " LONG, " + JuyouData.History.DATE + " LONG, " + JuyouData.History.STATUS + " INTEGER, " + JuyouData.History.MSG_TYPE + " INTEGER, " + JuyouData.History.FILE_TYPE + " INTEGER, " + JuyouData.History.FILE_ICON + " BLOB, " + JuyouData.History.SEND_USER_HEADID + " INTEGER, " + JuyouData.History.SEND_USER_ICON + " BLOB);"); // create traffic statics rx table. db.execSQL("create table " + JuyouData.TrafficStaticsRX.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + JuyouData.TrafficStaticsRX.DATE + " TEXT UNIQUE, " + JuyouData.TrafficStaticsRX.TOTAL_RX_BYTES + " LONG);"); // create traffic statics tx table. db.execSQL("create table " + JuyouData.TrafficStaticsTX.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + JuyouData.TrafficStaticsTX.DATE + " TEXT UNIQUE, " + JuyouData.TrafficStaticsTX.TOTAL_TX_BYTES + " LONG);"); // create user table db.execSQL("create table " + JuyouData.User.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + JuyouData.User.USER_NAME + " TEXT, " + JuyouData.User.USER_ID + " INTEGER, " + JuyouData.User.HEAD_ID + " INTEGER, " + JuyouData.User.THIRD_LOGIN + " INTEGER, " + JuyouData.User.HEAD_DATA + " BLOB, " + JuyouData.User.IP_ADDR + " TEXT, " + JuyouData.User.STATUS + " INTEGER, " + JuyouData.User.TYPE + " INTEGER, " + JuyouData.User.SSID + " TEXT, " + JuyouData.User.NETWORK + " INTEGER, " + JuyouData.User.SIGNATURE + " TEXT);"); // create account table db.execSQL("create table " + JuyouData.Account.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + JuyouData.Account.USER_NAME + " TEXT, " + JuyouData.Account.HEAD_ID + " INTEGER, " + JuyouData.Account.HEAD_DATA + " BLOB, " + JuyouData.Account.ACCOUNT_ZHAOYAN + " TEXT, " + JuyouData.Account.PHONE_NUMBER + " TEXT, " + JuyouData.Account.EMAIL + " TEXT, " + JuyouData.Account.ACCOUNT_QQ + " TEXT, " + JuyouData.Account.ACCOUNT_RENREN + " TEXT, " + JuyouData.Account.ACCOUNT_SINA_WEIBO + " TEXT, " + JuyouData.Account.ACCOUNT_TENCENT_WEIBO + " TEXT, " + JuyouData.Account.SIGNATURE + " TEXT, " + JuyouData.Account.LOGIN_STATUS + " INTEGER, " + JuyouData.Account.TOURIST_ACCOUNT + " INTEGER, " + JuyouData.Account.LAST_LOGIN_TIME + " LONG);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + JuyouData.History.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + JuyouData.TrafficStaticsRX.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + JuyouData.TrafficStaticsTX.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + JuyouData.User.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + JuyouData.Account.TABLE_NAME); onCreate(db); } } } <file_sep>package com.zhaoyan.juyou.activity; import android.os.Bundle; import com.zhaoyan.juyou.R; public class RegisterAccountActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_account); initTitle(R.string.register); initView(); } private void initView() { } } <file_sep>package com.zhaoyan.communication.search; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import android.content.Context; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.UserManager; /** * This class is use for search client in Android AP network.</br> * * There are two situation:</br> * * 1. This server is AP.</br> * * 2. This server is STA.</br> * * In situation 1, just wait and receive request from client, and tell them * "Yes, I am server."</br> * * In situation 2, send message to AP, tell him * "I am server, IP: 192.168.43.xxx". And also listen message from client in * case of there are other servers<br> * */ public class DiscoveryServiceLanAP { private static final String TAG = "SearchClientLanAndroidAP"; private SendMessageToAPThread mSendMessageToAPThread; private TellClientThisIsServerThread mTellClientThisIsServerThread; private boolean mStarted = false; private static DiscoveryServiceLanAP mInstance; private Context mContext; public static DiscoveryServiceLanAP getInstance(Context context) { if (mInstance == null) { mInstance = new DiscoveryServiceLanAP(context); } return mInstance; } private DiscoveryServiceLanAP(Context context) { mContext = context; } public void startSearch() { if (mStarted) { Log.d(TAG, "startSearch() igonre, search is already started."); return; } Log.d(TAG, "Start search"); mStarted = true; if (!NetWorkUtil.isWifiApEnabled(mContext)) { // In Android soft AP network. And this server is a STA. Log.d(TAG, "In Android soft AP network. And this server is a STA"); if (mSendMessageToAPThread != null) { mSendMessageToAPThread.quit(); } mSendMessageToAPThread = new SendMessageToAPThread(); mSendMessageToAPThread.start(); } else { // In Android soft AP network. And this server is a AP. if (mTellClientThisIsServerThread != null) { mTellClientThisIsServerThread.quit(); } mTellClientThisIsServerThread = new TellClientThisIsServerThread(); mTellClientThisIsServerThread.start(); } } public void stopSearch() { if (!mStarted) { Log.d(TAG, "stopSearch() igonre, search is not started."); return; } Log.d(TAG, "Stop search."); mStarted = false; closeSocket(); mInstance = null; } private void closeSocket() { if (mTellClientThisIsServerThread != null) { mTellClientThisIsServerThread.quit(); mTellClientThisIsServerThread = null; } if (mSendMessageToAPThread != null) { mSendMessageToAPThread.quit(); mSendMessageToAPThread = null; } } /** * Respond client search request, and tell it that "Yes, I am the server you * find." */ class TellClientThisIsServerThread extends Thread { private boolean mStop = false; private DatagramSocket mSocket; public TellClientThisIsServerThread() { try { mSocket = new DatagramSocket(Search.ANDROID_AP_RECEIVE_PORT); } catch (SocketException e) { Log.e(TAG, "TellClientThisIsServerThread create socket fail. " + e); } } public void run() { DatagramPacket inPacket; String message; Log.d(TAG, "GetClientPacket started. Waiting for client..."); while (!mStop) { if (mSocket == null) { break; } try { inPacket = new DatagramPacket(new byte[1024], 1024); mSocket.receive(inPacket); message = new String(inPacket.getData(), 0, inPacket.getLength()); Log.d(TAG, "Received message: " + message); if (message.equals(Search.ANDROID_AP_CLIENT_REQUEST)) { // Got a client search request. Log.d(TAG, "Got a client search request"); sendRespond(inPacket.getAddress()); } else if (message .startsWith(Search.ANDROID_AP_SERVER_REQUEST)) { // Got another server. Log.d(TAG, "Got another server."); } } catch (Exception e) { if (e instanceof SocketTimeoutException) { // time out, search again. Log.d(TAG, "GetPacket time out. search again."); } else { Log.e(TAG, "GetPacket error," + e.toString()); break; } } } } public void quit() { mStop = true; if (mSocket != null) { mSocket.close(); mSocket = null; } } /** * Send "Yes, I am the server you find." respond to client. * * @param clientAddress */ private void sendRespond(InetAddress clientAddress) { Log.d(TAG, "sendRespond to " + clientAddress.getHostAddress()); try { DatagramSocket socket = new DatagramSocket(); byte[] respond = (Search.ANDROID_AP_SERVER_RESPOND + UserManager .getInstance().getLocalUser().getUserName()).getBytes(); DatagramPacket inPacket = new DatagramPacket(respond, respond.length, clientAddress, Search.ANDROID_AP_RECEIVE_PORT); socket.send(inPacket); socket.close(); Log.d(TAG, "Send respond ok."); } catch (SocketException e) { Log.e(TAG, "Send respond fail." + e); } catch (IOException e) { Log.e(TAG, "Send respond fail." + e); } } } /** * Send packet to Android AP to tell "I am server."; This is only used when * this server is a WiFi STA. */ class SendMessageToAPThread extends Thread { // Socket for send packet to tell Android soft AP "I am server."; private DatagramSocket mSendToClientSocket; private DatagramPacket mSearchPacket = null; private boolean mStop = false; public SendMessageToAPThread() { try { mSendToClientSocket = new DatagramSocket(); InetAddress androidAPAddress = InetAddress .getByName(Search.ANDROID_AP_ADDRESS); // search data like: "I am server. IP: 192.168.43.169" byte[] searchData = (Search.ANDROID_AP_SERVER_REQUEST + UserManager .getInstance().getLocalUser().getUserName()).getBytes(); mSearchPacket = new DatagramPacket(searchData, searchData.length, androidAPAddress, Search.ANDROID_AP_RECEIVE_PORT); } catch (UnknownHostException e) { Log.e(TAG, "SendMessageToAPThread." + e); } catch (SocketException e) { Log.e(TAG, "SendMessageToAPThread." + e); } } @Override public void run() { while (!mStop) { if (mSendToClientSocket != null) { try { mSendToClientSocket.send(mSearchPacket); } catch (IOException e) { Log.e(TAG, "sendSearchRequest, data = " + new String(mSearchPacket.getData()) + " " + e); } } try { Thread.sleep(Search.ANDROID_AP_SEARCH_DELAY); } catch (InterruptedException e) { } } } public void quit() { mStop = true; if (mSendToClientSocket != null) { mSendToClientSocket.close(); mSendToClientSocket = null; } } } } <file_sep>package com.zhaoyan.communication; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import com.dreamlink.communication.aidl.HostInfo; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.ArrayUtil; import com.zhaoyan.common.util.Log; public class PlatformProtocol { private PlatformManager mPlatformManager; /** * 下面这些CMD不一定全部都会用 * * 一下CMD代码全部在网络通信中使用 * */ public final String CMD_HEAD = "PlatformManager@"; public final int GROUP_INFO_CHANGE_CMD_CODE = 0; public final int CREATE_HOST_CMD_CODE = 1; public final int CREATE_HOST_ACK_CMD_CODE = -1; public final int JOIN_GROUP_CMD_CODE = 2; public final int JOIN_GROUP_ACK_CMD_CODE = -2; public final int REMOVE_USER_CMD_CODE = 3; public final int REMOVE_USER_ACK_CMD_CODE = -3; public final int EXIT_GROUP_CMD_CODE = 4; public final int EXIT_GROUP_ACK_CMD_CODE = -4; public final int Start_GROUP_CMD_CODE = 5; public final int FINISH_GROUP_BUSINESS_CMD_CODE = 6; public final int CANCEL_HOST_CMD_CODE = 7; public final int CANCEL_HOST_ACK_CMD_CODE = -7; public final int REGISTER_ACK_CMD_CODE = -8; public final int REGISTER_CMD_CODE = 8; public final int UNREGISTER_ACK_CMD_CODE = -9; public final int UNREGISTER_CMD_CODE = 9; public final int GET_ALL_HOST_INFO_CMD_CODE = 10; public final int GROUP_MEMBER_UPDATE_CMD_CODE = 11; public final int GET_ALL_GROUP_MEMBER_CMD_CODE = 12; public final int MESSAGE_CMD_CODE = 13; private final String TAG="ArbiterLiu-PlatformProtocol"; public PlatformProtocol(PlatformManager platformManagerService) { mPlatformManager = platformManagerService; } public boolean decodePlatformProtocol(byte[] sourceData, User user) { int leng = CMD_HEAD.getBytes().length; String tem_head = new String(Arrays.copyOfRange(sourceData, 0, leng)); if (!CMD_HEAD.equals(tem_head)) { return false; } byte[] cmdByte = Arrays.copyOfRange(sourceData, leng, leng + 4); leng += 4; int cmdCode = ArrayUtil.byteArray2Int(cmdByte); Log.d(TAG, "receiver cmd code is" + cmdCode); byte[] data = Arrays.copyOfRange(sourceData, leng, sourceData.length); switch (cmdCode) { case GROUP_INFO_CHANGE_CMD_CODE: if (UserManager.getInstance().getLocalUser().getUserID() == -1) { /** group owner send group change to host manager */ hostChangeForManager(data); } else { /** host manager send to all user the host info change */ hostChangeForUser(data); } break; case CREATE_HOST_CMD_CODE: createHost(data); break; case CREATE_HOST_ACK_CMD_CODE: createHostAck(data); break; case CANCEL_HOST_CMD_CODE: cancelHost(data, user); break; case CANCEL_HOST_ACK_CMD_CODE: break; case JOIN_GROUP_CMD_CODE: joinGroup(data, user); break; case JOIN_GROUP_ACK_CMD_CODE: recevierJoinAck(data); break; case REMOVE_USER_CMD_CODE: removeUser(data); break; case REMOVE_USER_ACK_CMD_CODE: break; case EXIT_GROUP_CMD_CODE: exitGroup(data, user); break; case EXIT_GROUP_ACK_CMD_CODE: break; case Start_GROUP_CMD_CODE: startGameCmd(data); break; case REGISTER_ACK_CMD_CODE: break; case REGISTER_CMD_CODE: break; case GET_ALL_HOST_INFO_CMD_CODE: getAllHostInfo(data, user); break; case GROUP_MEMBER_UPDATE_CMD_CODE: groupMemberUpdate(data); break; case GET_ALL_GROUP_MEMBER_CMD_CODE: getGroupMember(data, user); break; case FINISH_GROUP_BUSINESS_CMD_CODE: break; case MESSAGE_CMD_CODE: groupMessageCommunication(data, user); break; default: break; } return true; } private void joinGroup(byte[] data, User user) { int hostId = ArrayUtil.byteArray2Int(data); mPlatformManager.requestJoinGroup(hostId, user); } /** * 信息格式:cmdCode+info.信息长度在传送的时候会编码,这里避免这些数据重复 * */ public byte[] encodePlatformProtocol(int cmdCode, byte[] sourceData) { Log.d(TAG, "encodePlatformProtocol cmd code is "+cmdCode); byte[] target = ArrayUtil.int2ByteArray(cmdCode); if (sourceData != null) target = ArrayUtil.join(target, sourceData); target = ArrayUtil.join(CMD_HEAD.getBytes(), target); return target; } private void createHost(byte[] data) { try { HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(data); if (hostInfo != null) { mPlatformManager.requestCreateHost(hostInfo); } else { Log.e(TAG, "createHost receiver data is exception"); } } catch (Exception e) { } } private void createHostAck(byte[] data) { HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(data); if (hostInfo != null) { mPlatformManager.createHostAck(hostInfo); } else { Log.e(TAG, "createHostAck receiver data is exception"); } } private void hostChangeForManager(byte[] data) { try { HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(data); if (hostInfo != null) { mPlatformManager.updateHostInfo(hostInfo); } else { Log.e(TAG, "hostChangeForManager receiver data is exception"); } } catch (Exception e) { } } private void hostChangeForUser(byte[] data) { @SuppressWarnings("unchecked") ConcurrentHashMap<Integer, HostInfo> allHostInfo = (ConcurrentHashMap<Integer, HostInfo>) ArrayUtil .byteArrayToObject(data); if (allHostInfo != null) { mPlatformManager.receiverAllHostInfo(allHostInfo); } else { Log.e(TAG, "hostChangeForUser receiver data is exception"); } } private void getAllHostInfo(byte[] data, User user) { int appId = ArrayUtil.byteArray2Int(data); mPlatformManager.requestAllHost(appId, user); } private void recevierJoinAck(byte[] data) { byte flag = data[0]; HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(Arrays .copyOfRange(data, 1, data.length)); if (flag == 1) { mPlatformManager.receiverJoinAck(true, hostInfo); } else { mPlatformManager.receiverJoinAck(false, hostInfo); } } private void groupMemberUpdate(byte[] data) { int hostId = ArrayUtil.byteArray2Int(Arrays.copyOfRange(data, 0, 4)); @SuppressWarnings("unchecked") ArrayList<Integer> userList = (ArrayList<Integer>) ArrayUtil .byteArrayToObject(Arrays.copyOfRange(data, 4, data.length)); if (userList != null) { mPlatformManager.receiverGroupMemberUpdat(hostId, userList); } else { Log.e(TAG, "groupMemberUpdate receiver data is exception"); } } private void cancelHost(byte[] data, User user) { try { HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(data); mPlatformManager.receiverCancelHost(hostInfo, user); } catch (Exception e) { } } private void removeUser(byte[] data) { try { HostInfo hostInfo = (HostInfo) ArrayUtil.byteArrayToObject(data); mPlatformManager.receiverRemoveUser(hostInfo); } catch (Exception e) { } } private void exitGroup(byte[] data, User user) { try { int hostId = ArrayUtil.byteArray2Int(data); mPlatformManager.requestExitGroup(hostId, user); } catch (Exception e) { Log.e(TAG, "" + e.toString()); } } private void getGroupMember(byte[] data, User user) { try { int hostId = ArrayUtil.byteArray2Int(data); mPlatformManager.requetsGetGroupMember(hostId, user); } catch (Exception e) { } } private void groupMessageCommunication(byte[] data, User user) { byte flag = data[0]; int hostId = ArrayUtil.byteArray2Int(Arrays.copyOfRange(data, 1, 5)); byte[] targetData = Arrays.copyOfRange(data, 5, data.length); if (flag == 1) { mPlatformManager .receiverData(targetData, user, true, hostId); } else { mPlatformManager.receiverData(targetData, user, false, hostId); } } private void startGameCmd(byte[] data) { int hostId = ArrayUtil.byteArray2Int(data); mPlatformManager.receiverStartGroupBusiness(hostId); } } <file_sep>package com.zhaoyan.juyou.common; import java.lang.ref.SoftReference; import java.util.HashMap; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.widget.ImageView; import com.zhaoyan.juyou.adapter.ImageItemAdapter; public class AsyncPictureLoader { // SoftReference是软引用,是为了更好的为了系统回收变量 public static HashMap<Long, SoftReference<Bitmap>> bitmapCaches; private ContentResolver contentResolver = null; public AsyncPictureLoader(Context context) { bitmapCaches = new HashMap<Long, SoftReference<Bitmap>>(); contentResolver = context.getContentResolver(); } public Bitmap loadBitmap(final long id, final ILoadImagesCallback videoCallback) { if (bitmapCaches.containsKey(id)) { // 从缓存中获取 SoftReference<Bitmap> softReference = bitmapCaches.get(id); Bitmap bitmap = softReference.get(); if (null != bitmap) { return bitmap; } } final Handler handler = new Handler() { public void handleMessage(Message message) { videoCallback.onObtainBitmap((Bitmap) message.obj, id); } }; new Thread() { @Override public void run() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = false;//采用默认值 options.inPreferredConfig = Bitmap.Config.ARGB_8888;//采用默认值 // get images thumbail Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(contentResolver, id, Images.Thumbnails.MICRO_KIND, options); bitmapCaches.put(id, new SoftReference<Bitmap>(bitmap)); Message message = handler.obtainMessage(0, bitmap); handler.sendMessage(message); } }.start(); return null; } public Bitmap loadBitmap(final long id, final ImageView imageView) { if (!ImageItemAdapter.USE_VIEW_CACHE) { if (bitmapCaches.containsKey(id)) { // 从缓存中获取 SoftReference<Bitmap> softReference = bitmapCaches.get(id); Bitmap bitmap = softReference.get(); if (null != bitmap) { imageView.setImageBitmap(bitmap); return bitmap; } } } final Handler handler = new Handler() { public void handleMessage(Message message) { Bitmap bitmap = (Bitmap)message.obj; imageView.setImageBitmap(bitmap); } }; new Thread() { @Override public void run() { BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = false;//采用默认值 options.inPreferredConfig = Bitmap.Config.ARGB_8888;//采用默认值 // get images thumbail Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(contentResolver, id, Images.Thumbnails.MICRO_KIND, options); if (!ImageItemAdapter.USE_VIEW_CACHE) { bitmapCaches.put(id, new SoftReference<Bitmap>(bitmap)); } Message message = handler.obtainMessage(0, bitmap); handler.sendMessage(message); } }.start(); return null; } /** * 异步加载的回调接口 */ public interface ILoadImagesCallback { public void onObtainBitmap(Bitmap bitmap, long id); } } <file_sep>package com.zhaoyan.juyou.dialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.zhaoyan.juyou.R; public class AppDialog extends ZyAlertDialog implements android.view.View.OnClickListener { private TextView mNameView; private TextView mNumView; private ProgressBar mProgressBar; private int progress; private String mName; private int max; private static final int MSG_UPDATE_PROGRESS = 0x10; private Handler mHandler = new Handler(){ public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_UPDATE_PROGRESS: mProgressBar.setProgress(progress); mNameView.setText(mName); mNumView.setText(progress + "/" + max); break; default: break; } }; }; public AppDialog(Context context, int size){ super(context); max = size; } @Override protected void onCreate(Bundle savedInstanceState) { View view = getLayoutInflater().inflate(R.layout.app_dialog, null); mProgressBar = (ProgressBar) view.findViewById(R.id.bar_move); mProgressBar.setMax(max); mNameView = (TextView) view.findViewById(R.id.name_view); mNumView = (TextView) view.findViewById(R.id.num_view); setCustomView(view); super.onCreate(savedInstanceState); setCancelable(false); } public void updateName(String name){ this.mName = name; mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_PROGRESS)); } public void updateProgress(int progress){ this.progress = progress; mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_PROGRESS)); } public void updateUI(int progress, String fileName){ this.progress = progress; this.mName = fileName; mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_PROGRESS)); } public int getMax(){ return max; } } <file_sep>package com.zhaoyan.communication.search; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.UnknownHostException; import android.content.Context; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.ArrayUtil; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.ArraysCompat; import com.zhaoyan.common.util.BitmapUtilities; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.communication.search.ServerSearcherLan.OnSearchListenerLan; import com.zhaoyan.juyou.provider.JuyouData; public class SearchProtocol { private static final String TAG = "SearchProtocol"; private static final int LENGTH_WRITE_ONE_TIME = 1024 * 4; private static final int LENGTH_INT = 4; private static final int IP_ADDRESS_HEADER_SIZE = 4; /** * Search packet protocol:</br> * * [server ip] * * @return */ public static byte[] encodeSearchLan() { byte[] localIPAddresss = NetWorkUtil.getLocalIpAddressBytes(); return localIPAddresss; } /** * see {@link #encodeSearchLan()} * * @param data * @throws UnknownHostException */ public static void decodeSearchLan(byte[] data, OnSearchListenerLan listener) throws UnknownHostException { if (data.length < SearchProtocol.IP_ADDRESS_HEADER_SIZE) { // Data format error. Log.e(TAG, "decodeSearchLan. Data format error, received data length = " + data.length); return; } // server ip. int start = 0; int end = SearchProtocol.IP_ADDRESS_HEADER_SIZE; byte[] serverIpData = ArraysCompat.copyOfRange(data, start, end); String serverIP = InetAddress.getByAddress(serverIpData) .getHostAddress(); Log.d(TAG, "Found server ip = " + serverIP); if (!serverIP.equals(NetWorkUtil.getLocalIpAddress())) { if (listener != null) { listener.onFoundLanServer(serverIP); } } } public static void encodeLanServerInfo(Context context, DataOutputStream outputStream) { UserInfo userInfo = UserHelper.loadLocalUser(context); try { byte[] name = userInfo.getUser().getUserName().getBytes(); byte[] nameLength = ArrayUtil.int2ByteArray(name.length); byte[] headImageId = ArrayUtil.int2ByteArray(userInfo.getHeadId()); outputStream.write(nameLength); outputStream.write(name); outputStream.write(headImageId); // If head is user customized, send head image. if (userInfo.getHeadId() == UserInfo.HEAD_ID_NOT_PRE_INSTALL) { byte[] headImage = BitmapUtilities.bitmapToByteArray(userInfo .getHeadBitmap()); byte[] headImageLength = ArrayUtil .int2ByteArray(headImage.length); outputStream.write(headImageLength); // If the head image is too large, write it in multiple // times. if (headImage.length <= LENGTH_WRITE_ONE_TIME) { outputStream.write(headImage); } else { int start = 0; int end = start + LENGTH_WRITE_ONE_TIME; int sentLength = 0; int totalLength = headImage.length; while (sentLength < totalLength) { outputStream.write(ArraysCompat.copyOfRange(headImage, start, end)); sentLength += end - start; start = end; if (totalLength - sentLength <= LENGTH_WRITE_ONE_TIME) { end = totalLength; } else { end += LENGTH_WRITE_ONE_TIME; } } } } outputStream.flush(); } catch (Exception e) { Log.e(TAG, "encodeLanServerInfo " + e); } } public static void decodeLanServerInfo(Context context, DataInputStream inputStream, String serverIp) { try { // name byte[] nameLengthData = new byte[LENGTH_INT]; inputStream.readFully(nameLengthData); byte[] nameData = new byte[ArrayUtil.byteArray2Int(nameLengthData)]; inputStream.readFully(nameData); String name = new String(nameData); // head image id byte[] headImageIdData = new byte[LENGTH_INT]; inputStream.readFully(headImageIdData); int headImageId = ArrayUtil.byteArray2Int(headImageIdData); // head image byte[] headImageData = null; if (headImageId == UserInfo.HEAD_ID_NOT_PRE_INSTALL) { byte[] headImageLengthData = new byte[LENGTH_INT]; inputStream.readFully(headImageLengthData); headImageData = new byte[ArrayUtil .byteArray2Int(headImageLengthData)]; inputStream.readFully(headImageData); } // Save server info to database. UserInfo userInfo = new UserInfo(); User user = new User(); user.setUserName(name); userInfo.setUser(user); userInfo.setHeadId(headImageId); if (headImageId == UserInfo.HEAD_ID_NOT_PRE_INSTALL && headImageData != null) { userInfo.setHeadBitmap(BitmapUtilities .byteArrayToBitmap(headImageData)); } userInfo.setType(JuyouData.User.TYPE_REMOTE_SEARCH_LAN); userInfo.setIpAddress(serverIp); UserHelper.addRemoteUserToDatabase(context, userInfo); Log.d(TAG, "decodeLanServerInfo add into database userInfo = " + userInfo); } catch (Exception e) { Log.e(TAG, "decodeLanServerInfo " + e); } } } <file_sep>package com.zhaoyan.juyou.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.dreamlink.communication.aidl.User; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.UserManager.OnUserChangedListener; import com.zhaoyan.communication.connect.ServerCreator; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.fragment.ConnectedInfoFragment; import com.zhaoyan.juyou.fragment.SearchConnectFragment; public class ConnectFriendsActivity extends BaseFragmentActivity implements OnUserChangedListener { private static final String TAG = "ConnectFriendsActivity"; private SocketCommunicationManager mCommunicationManager; private UserManager mUserManager; private FragmentManager mFragmentManager; private SearchConnectFragment mSearchAndConnectFragment; private ConnectedInfoFragment mConnectedInfoFragment; private static final String FRAGMENT_TAG_SEARCH_CONNECT = "SearchConnectFragment"; private static final String FRAGMENT_TAG_CONNECTED_INFO = "ConnectedInfoFragment"; private String mCurrentFragmentTag; private static final int MSG_SHOW_LOGIN_DIALOG = 1; private static final int MSG_UPDATE_NETWORK_STATUS = 2; private static final int MSG_UPDATE_USER = 3; private Handler mHandler; private BroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.connect_friends); mHandler = new UiHandler(); mCommunicationManager = SocketCommunicationManager.getInstance(); mUserManager = UserManager.getInstance(); mUserManager.registerOnUserChangedListener(this); mFragmentManager = getSupportFragmentManager(); initTitle(R.string.connect_friends); initFragment(savedInstanceState); updateFragment(); mReceiver = new CreateServerReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(ServerCreator.ACTION_SERVER_CREATED); registerReceiver(mReceiver, filter); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString("fragment", mCurrentFragmentTag); super.onSaveInstanceState(outState); } private void initFragment(Bundle savedInstanceState) { mSearchAndConnectFragment = (SearchConnectFragment) mFragmentManager .findFragmentByTag(FRAGMENT_TAG_SEARCH_CONNECT); if (mSearchAndConnectFragment == null) { mSearchAndConnectFragment = new SearchConnectFragment(); } mConnectedInfoFragment = (ConnectedInfoFragment) mFragmentManager .findFragmentByTag(FRAGMENT_TAG_CONNECTED_INFO); if (mConnectedInfoFragment == null) { mConnectedInfoFragment = new ConnectedInfoFragment(); } // Restore from save instance. if (savedInstanceState != null) { mCurrentFragmentTag = savedInstanceState.getString("fragment"); if (FRAGMENT_TAG_CONNECTED_INFO.equals(mCurrentFragmentTag)) { if (mSearchAndConnectFragment.isAdded()) { mFragmentManager.beginTransaction() .hide(mSearchAndConnectFragment).commit(); } } else if (FRAGMENT_TAG_SEARCH_CONNECT.equals(mCurrentFragmentTag)) { if (mConnectedInfoFragment.isAdded()) { mFragmentManager.beginTransaction() .hide(mSearchAndConnectFragment).commit(); } } } } private void updateFragment() { if (mCommunicationManager.isConnected() || mCommunicationManager.isServerAndCreated()) { transactTo(mConnectedInfoFragment, FRAGMENT_TAG_CONNECTED_INFO); } else { transactTo(mSearchAndConnectFragment, FRAGMENT_TAG_SEARCH_CONNECT); } } private void transactTo(Fragment fragment, String tag) { if (tag.equals(mCurrentFragmentTag)) { return; } Fragment currentFragment = mFragmentManager .findFragmentByTag(mCurrentFragmentTag); FragmentTransaction transaction = mFragmentManager.beginTransaction(); if (currentFragment != null) { transaction.hide(currentFragment); } try { if (!fragment.isAdded()) { transaction.add(R.id.fl_cf_container, fragment, tag).commitAllowingStateLoss(); } else { transaction.show(fragment).commitAllowingStateLoss(); } } catch (Exception e) { Log.e(TAG, "transactTo " + e); } mCurrentFragmentTag = tag; } @Override public void onUserConnected(User user) { mHandler.sendEmptyMessage(MSG_UPDATE_NETWORK_STATUS); mHandler.sendEmptyMessage(MSG_UPDATE_USER); } @Override public void onUserDisconnected(User user) { mHandler.sendEmptyMessage(MSG_UPDATE_NETWORK_STATUS); mHandler.sendEmptyMessage(MSG_UPDATE_USER); } private class UiHandler extends Handler { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_SHOW_LOGIN_DIALOG: break; case MSG_UPDATE_NETWORK_STATUS: updateFragment(); break; case MSG_UPDATE_USER: break; default: break; } } }; @Override protected void onDestroy() { mUserManager.unregisterOnUserChangedListener(this); try { unregisterReceiver(mReceiver); } catch (Exception e) { Log.e(TAG, "onDestroy " + e); } mReceiver = null; mHandler = null; super.onDestroy(); } private class CreateServerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ServerCreator.ACTION_SERVER_CREATED.equals(action)) { updateFragment(); } } }; } <file_sep>package com.zhaoyan.juyou.activity; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.fragment.FileBrowserFragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.Window; public class FileBrowserActivity extends FragmentActivity{ private FileBrowserFragment mBrowserFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); mBrowserFragment= new FileBrowserFragment(); getSupportFragmentManager().beginTransaction().replace( android.R.id.content, mBrowserFragment).commit(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { boolean ret = mBrowserFragment.onBackPressed(); if (ret) { finish(); overridePendingTransition(0, R.anim.activity_right_out); return true; }else { return false; } } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (null != mBrowserFragment) { mBrowserFragment = null; } super.onDestroy(); } } <file_sep>package com.zhaoyan.juyou.common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import android.os.Environment; import com.zhaoyan.common.util.Log; import com.zhaoyan.juyou.common.DevMountInfo.DevInfo; /** * 判断sdcard位置 * */ public class DevMountInfo implements IDev { private static final String TAG = "DevMountInfo"; public final String HEAD = "dev_mount"; public final String LABEL = "<label>"; public final String MOUNT_POINT = "<mount_point>"; public final String PATH = "<part>"; public final String SYSFS_PATH = "<sysfs_path1...>"; /** * Label for the volume */ private final int NLABEL = 1; /** * Partition */ private final int NPATH = 2; /** * Where the volume will be mounted */ private final int NMOUNT_POINT = 3; private final int NSYSFS_PATH = 4; private final int DEV_INTERNAL = 0; private final int DEV_EXTERNAL = 1; private ArrayList<String> cache = new ArrayList<String>(); private static DevMountInfo dev; private DevInfo info; private final File VOLD_FSTAB = new File(Environment.getRootDirectory() .getAbsoluteFile() + File.separator + "etc" + File.separator + "vold.fstab"); public static DevMountInfo getInstance() { if (null == dev) dev = new DevMountInfo(); return dev; } private DevInfo getInfo(final int device) { if (null == info) info = new DevInfo(); try { initVoldFstabToCache(); } catch (IOException e) { e.printStackTrace(); } String[] exterSinfo = null; String[] interSinfo = null; if (1 >= cache.size()) { exterSinfo = cache.get(0).split(" "); info.setInterPath(MountManager.NO_INTERNAL_SDCARD); } else { interSinfo = cache.get(0).split(" "); exterSinfo = cache.get(1).split(" "); info.setInterPath(interSinfo[NPATH]); } Log.d(TAG, "getInfo.cache.size=" + cache.size()); Log.d(TAG, "device=" + device + "\n" + exterSinfo[NPATH]); info.setLabel(exterSinfo[NLABEL]); info.setMount_point(exterSinfo[NMOUNT_POINT]); info.setPath(exterSinfo[NPATH]); info.setExterPath(exterSinfo[NPATH]); info.setSysfs_path(exterSinfo[NSYSFS_PATH]); return info; } /** * init the words into the cache array * @throws IOException */ private void initVoldFstabToCache() throws IOException { cache.clear(); BufferedReader br = new BufferedReader(new FileReader(VOLD_FSTAB)); String tmp = null; while ((tmp = br.readLine()) != null) { // the words startsWith "dev_mount" are the SD info Log.i(TAG, "tmp:" + tmp); if (tmp.startsWith(HEAD)) { cache.add(tmp); } } br.close(); cache.trimToSize(); } public class DevInfo { private String label, mount_point, path, inter_path, exter_path, sysfs_path; /** * return the label name of the SD card * @return */ public String getLabel() { return label; } private void setLabel(String label) { this.label = label; } /** * the mount point of the SD card * @return */ public String getMount_point() { return mount_point; } private void setMount_point(String mount_point) { this.mount_point = mount_point; } /** * SD mount path * @return */ public String getPath() { return path; } private void setPath(String path) { this.path = path; } public String getExterPath(){ return exter_path; } private void setExterPath(String path){ this.exter_path = path; } public String getInterPath(){ return inter_path; } private void setInterPath(String path){ this.inter_path = path; } /** * "unknow" * @return */ public String getSysfs_path() { return sysfs_path; } private void setSysfs_path(String sysfs_path) { this.sysfs_path = sysfs_path; } } @Override public DevInfo getInternalInfo() { return getInfo(DEV_INTERNAL); } @Override public DevInfo getExternalInfo() { return getInfo(DEV_EXTERNAL); } @Override public DevInfo getDevInfo() { return getInfo(DEV_EXTERNAL); } @Override public boolean isExistExternal() { return VOLD_FSTAB.exists(); } } interface IDev { DevInfo getInternalInfo(); DevInfo getExternalInfo(); DevInfo getDevInfo(); /**is exist external sdcard*/ boolean isExistExternal(); } <file_sep>package com.zhaoyan.communication.recovery; import com.dreamlink.communication.aidl.User; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.communication.UserManager; import com.zhaoyan.juyou.provider.JuyouData; import android.content.Context; import android.util.Log; public class ClientRecovery extends Recovery { private static final String TAG = "ClientRecovery"; private Context mContext; private ClientRecoveryAp mClientRecoveryAp; private ClientRecoveryWifi mClientRecoveryWifi; public ClientRecovery(Context context) { mContext = context; } @Override protected boolean doRecovery() { boolean result = false; if (mClientRecoveryAp != null) { result = mClientRecoveryAp.attemptRecovery(); } else if (mClientRecoveryWifi != null) { result = mClientRecoveryWifi.attemptRecovery(); } Log.d(TAG, "doRecovery() result = " + result); return result; } @Override public void getLastSatus() { UserManager userManager = UserManager.getInstance(); User server = userManager.getServer(); UserInfo serverInfo = UserHelper.getUserInfo(mContext, server); int networkType = serverInfo.getNetworkType(); if (networkType == JuyouData.User.NETWORK_AP) { mClientRecoveryAp = new ClientRecoveryAp(mContext); mClientRecoveryAp.getLastSatus(); } else if (networkType == JuyouData.User.NETWORK_WIFI) { mClientRecoveryWifi = new ClientRecoveryWifi( mContext); mClientRecoveryWifi.getLastSatus(); } } } <file_sep>package com.zhaoyan.communication.recovery; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.juyou.provider.JuyouData; import android.content.Context; public class ServerRecovery extends Recovery { private Context mContext; public ServerRecovery(Context context) { mContext = context; } @Override protected boolean doRecovery() { boolean result = false; UserInfo localUserInfo = UserHelper.loadLocalUser(mContext); int networkType = localUserInfo.getNetworkType(); if (networkType == JuyouData.User.NETWORK_AP) { ServerRecoveryAp serverRecoveryAP = new ServerRecoveryAp(mContext); result = serverRecoveryAP.attemptRecovery(); } else if (networkType == JuyouData.User.NETWORK_WIFI) { ServerRecoveryWifi serverRecoveryWifi = new ServerRecoveryWifi( mContext); result = serverRecoveryWifi.attemptRecovery(); } return result; } @Override public void getLastSatus() { // TODO Auto-generated method stub } } <file_sep>package com.zhaoyan.communication.search; import com.zhaoyan.communication.SocketPort; public class Search { public static final String MULTICAST_IP = "172.16.58.3"; /** timeout:10 seconds */ public static final int TIME_OUT = 10 * 1000; public static final int MULTICAST_SEND_PORT = SocketPort.MULTICAST_SEND_PORT; public static final int MULTICAST_RECEIVE_PORT = SocketPort.MULTICAST_RECEIVE_PORT; public static final long MULTICAST_DELAY_TIME = 2000; public static final String EXTRA_IP = "ip"; public static final String ANDROID_AP_ADDRESS = "192.168.43.1"; public static final String ANDROID_STA_ADDRESS_START = "192.168.43."; /** This message is only used when AP is server. */ public static final String ANDROID_AP_CLIENT_REQUEST = "Are you server?"; /** This message is only used when AP is server. */ public static final String ANDROID_AP_SERVER_RESPOND = "Yes, AP is server."; /** This message is only used when AP is client. */ public static final String ANDROID_AP_SERVER_REQUEST = "I am server. IP: "; public static final int ANDROID_AP_SEND_PORT = SocketPort.ANDROID_AP_SEND_PORT; public static final int ANDROID_AP_RECEIVE_PORT = SocketPort.ANDROID_AP_RECEIVE_PORT; /** Search request send delay time (second) */ public static final long ANDROID_AP_SEARCH_DELAY = 2000; } <file_sep>package com.zhaoyan.communication.recovery; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.juyou.provider.JuyouData; import android.content.Context; import android.database.ContentObserver; import android.os.Handler; import android.os.Message; public class ServerSearchObserver extends ContentObserver { private Handler mHandler; private Context mContext; private UserInfo mUserInfo; public ServerSearchObserver(Context context, Handler handler, UserInfo userInfo) { super(handler); mContext = context; mHandler = handler; mUserInfo = userInfo; } @Override public void onChange(boolean selfChange) { String selection = JuyouData.User.USER_NAME + "='" + mUserInfo.getUser().getUserName() + "'"; UserInfo userInfo = UserHelper.getUserInfo(mContext, selection); if (userInfo != null) { Message message = mHandler.obtainMessage(); message.obj = userInfo; message.sendToTarget(); } } } <file_sep>package com.zhaoyan.communication.search; import android.content.Context; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; /** * This class is used by server for search clients.</br> * * There are two kind of lan network:</br> * * 1. No Android AP Lan.</br> * * 2. Has Android AP Lan.</br> * * In the situation 1, we use lan multicast to find clients.</br> * * In the situation 2, we use lan mulitcast and UDP communication to search * clients</br> * * This is because AP can not send or receive multicast in Android AP lan * network.</br> * * Notice: SearchClient do not get clint IP, Only client can get server IP, and * client connect server.</br> */ public class DiscoveryService { private static final String TAG = "DiscoveryService"; private boolean mStarted = false; private static DiscoveryService mInstance; private Context mContext; private DiscoveryServiceLanAP mSearchClientLanAndroidAP; private DiscoveryServiceLanWifi mSearchClientLan; private SendServerInfoSocket mSendServerInfoSocket; public static DiscoveryService getInstance(Context context) { if (mInstance == null) { mInstance = new DiscoveryService(context); } return mInstance; } private DiscoveryService(Context context) { mContext = context; } /** * start deamon client. */ public void startDiscoveryService() { if (mStarted) { Log.d(TAG, "startDiscoveryService() igonre, search is already started."); return; } Log.d(TAG, "startDiscoveryService."); mStarted = true; NetWorkUtil.acquireWifiMultiCastLock(mContext); Log.d(TAG, "The ip is " + NetWorkUtil.getLocalIpAddress()); if (SearchUtil.isAndroidAPNetwork(mContext)) { Log.d(TAG, "Android AP network."); if (!NetWorkUtil.isWifiApEnabled(mContext)) { Log.d(TAG, "This is not Android AP"); mSearchClientLan = new DiscoveryServiceLanWifi(); mSearchClientLan.startSearch(); } mSearchClientLanAndroidAP = DiscoveryServiceLanAP .getInstance(mContext); mSearchClientLanAndroidAP.startSearch(); } else { Log.d(TAG, "not Android AP network."); mSearchClientLan = new DiscoveryServiceLanWifi(); mSearchClientLan.startSearch(); } mSendServerInfoSocket = SendServerInfoSocket.getInstance(); mSendServerInfoSocket.startServer(mContext); } public void stopSearch() { Log.d(TAG, "Stop search."); StackTraceElement st[] = Thread.currentThread().getStackTrace(); for (int i = 0; i < st.length; i++) { Log.d(TAG, "trace: " + st[i].toString()); } mStarted = false; NetWorkUtil.releaseWifiMultiCastLock(); if (mSearchClientLan != null) { mSearchClientLan.stopSearch(); mSearchClientLan = null; } if (mSearchClientLanAndroidAP != null) { mSearchClientLanAndroidAP.stopSearch(); mSearchClientLanAndroidAP = null; } if (mSendServerInfoSocket != null) { mSendServerInfoSocket.stopServer(); } mInstance = null; } } <file_sep>package com.zhaoyan.juyou.common; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zhaoyan.common.util.ZYUtils; import com.zhaoyan.juyou.R; public class FileListItem { public static void setupFileListItemInfo(Context context, View view, FileInfo fileInfo, FileIconHelper fileIcon) { setText(view, R.id.tv_filename, fileInfo.fileName); setText(view, R.id.tv_filecount, fileInfo.isDir ? "(" + fileInfo.count + ")" : ""); String size = ZYUtils.getFormatSize(fileInfo.fileSize); String date = ZYUtils.getFormatDate(fileInfo.fileDate); setText(view, R.id.tv_fileinfo, fileInfo.isDir ? date : date + " | " + size); ImageView lFileImage = (ImageView) view.findViewById(R.id.file_icon_imageview); if (fileInfo.isDir) { lFileImage.setImageResource(R.drawable.icon_folder); } else { fileIcon.setIcon(fileInfo, lFileImage); } } private static boolean setText(View view, int resId, String text){ TextView textView = (TextView) view.findViewById(resId); if (textView == null) return false; textView.setText(text); return true; } } <file_sep>package com.zhaoyan.communication; import java.io.File; import java.net.InetAddress; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import com.dreamlink.communication.aidl.OnCommunicationListenerExternal; import com.dreamlink.communication.aidl.User; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.FileSender.OnFileSendListener; import com.zhaoyan.communication.UserManager.OnUserChangedListener; import com.zhaoyan.communication.protocol.FileTransportProtocol; import com.zhaoyan.communication.protocol.LoginProtocol; import com.zhaoyan.communication.protocol.LogoutProtocol; import com.zhaoyan.communication.protocol.MessageSendProtocol; import com.zhaoyan.communication.protocol.ProtocolManager; import com.zhaoyan.communication.protocol.UserUpdateProtocol; import com.zhaoyan.communication.protocol.FileTransportProtocol.FileInfo; import com.zhaoyan.juyou.R; import android.content.Context; import android.os.RemoteException; /** * This class provide common interface for protocols. * * 1. use protocols to communicate.</br> * * 2. notify protocols' events to listeners. * */ public class ProtocolCommunication implements OnUserChangedListener { private static final String TAG = "ProtocolCommunication"; private static ProtocolCommunication mInstance; private Context mContext; /** Used for Login confirm UI */ private ILoginRequestCallBack mLoginRequestCallBack; private ILoginRespondCallback mLoginRespondCallback; private UserManager mUserManager; private Notice mNotice; private ProtocolManager mProtocolManager; /** * Map for OnFileTransportListener and appID management. When an application * register to SocketCommunicationManager, record it in this map. When * received a message, notify the related applications base on the * appID.</br> * * Map structure</br> * * key: listener, value: app ID. */ private ConcurrentHashMap<OnFileTransportListener, Integer> mOnFileTransportListener = new ConcurrentHashMap<OnFileTransportListener, Integer>(); /** * Map for OnCommunicationListenerExternal and appID management. When an * application register to SocketCommunicationManager, record it in this * map. When received a message, notify the related applications base on the * appID.</br> * * Map structure</br> * * key: listener, value: app ID. */ private ConcurrentHashMap<OnCommunicationListenerExternal, Integer> mOnCommunicationListenerExternals = new ConcurrentHashMap<OnCommunicationListenerExternal, Integer>(); private ProtocolCommunication() { } public static synchronized ProtocolCommunication getInstance() { if (mInstance == null) { mInstance = new ProtocolCommunication(); } return mInstance; } public void init(Context context) { mContext = context; mUserManager = UserManager.getInstance(); mUserManager.registerOnUserChangedListener(this); mNotice = new Notice(mContext); mProtocolManager = new ProtocolManager(mContext); mProtocolManager.init(); } public void release() { mInstance = null; if (mUserManager != null) { mUserManager.unregisterOnUserChangedListener(this); } } public void decodeMessage(byte[] msg, SocketCommunication socketCommunication) { long start = System.currentTimeMillis(); mProtocolManager.decode(msg, socketCommunication); long end = System.currentTimeMillis(); Log.i(TAG, "decodeMessage() takes time: " + (end - start)); } public void registerOnCommunicationListenerExternal( OnCommunicationListenerExternal listener, int appID) { Log.d(TAG, "registerOnCommunicationListenerExternal() appID = " + appID); mOnCommunicationListenerExternals.put(listener, appID); } public void unregisterOnCommunicationListenerExternal( OnCommunicationListenerExternal listener) { if (listener == null) { Log.e(TAG, "the params listener is null"); } else { if (mOnCommunicationListenerExternals.containsKey(listener)) { int appID = mOnCommunicationListenerExternals.remove(listener); Log.d(TAG, "registerOnCommunicationListenerExternal() appID = " + appID); } else { Log.e(TAG, "there is no this listener in the map"); } } } public void unregisterOnCommunicationListenerExternal(int appId) { for (Entry<OnCommunicationListenerExternal, Integer> entry : mOnCommunicationListenerExternals .entrySet()) { if (entry.getValue() == appId) { mOnCommunicationListenerExternals.remove(entry.getKey()); } } } public void setLoginRequestCallBack(ILoginRequestCallBack callback) { mLoginRequestCallBack = callback; } public void setLoginRespondCallback(ILoginRespondCallback callback) { mLoginRespondCallback = callback; } public void notifyLoginSuccess(User localUser, SocketCommunication communication) { if (mLoginRespondCallback != null) { mLoginRespondCallback.onLoginSuccess(localUser, communication); } } public void notifyLoginFail(int failReason, SocketCommunication communication) { if (mLoginRespondCallback != null) { mLoginRespondCallback.onLoginFail(failReason, communication); } } public void notifyLoginRequest(UserInfo user, SocketCommunication communication) { Log.d(TAG, "onLoginRequest()"); if (mLoginRequestCallBack != null) { mLoginRequestCallBack.onLoginRequest(user, communication); } } /** * client login server directly. */ public void sendLoginRequest() { LoginProtocol.encodeLoginRequest(mContext); } /** * Respond to the login request. If login is allowed, send message to update * user list. * * @param userInfo * @param communication * @param isAllow */ public void respondLoginRequest(UserInfo userInfo, SocketCommunication communication, boolean isAllow) { // TODO If the server disallow the login request, may be stop the socket // communication. But we should check the login request is from the WiFi // direct server or a client. Let this be done in the future. boolean loginResult = false; if (isAllow) { loginResult = mUserManager.addNewLoginedUser(userInfo, communication); } else { loginResult = false; } LoginProtocol.encodeLoginRespond(loginResult, userInfo.getUser() .getUserID(), communication); Log.d(TAG, "longin result = " + loginResult + ", userInfo = " + userInfo); if (loginResult) { UserUpdateProtocol.encodeUpdateAllUser(mContext); } } public void logout() { Log.d(TAG, "logout()"); SocketCommunicationManager socketCommunicationManager = SocketCommunicationManager .getInstance(); boolean isServer = socketCommunicationManager.isServerAndCreated(); boolean isConnectedToServer = socketCommunicationManager.isConnected(); if (isServer) { LogoutProtocol.encodeLogoutSever(mContext); } else if (isConnectedToServer) { LogoutProtocol.encodeLogoutClient(mContext); } UserManager userManager = UserManager.getInstance(); userManager.resetLocalUser(); } public void registerOnFileTransportListener( OnFileTransportListener listener, int appID) { Log.d(TAG, "registerOnFileTransportListener() appID = " + appID); mOnFileTransportListener.put(listener, appID); } public void unregisterOnFileTransportListener( OnFileTransportListener listener) { if (null == listener) { Log.e(TAG, "the params listener is null"); } else { if (mOnFileTransportListener.containsKey(listener)) { int appID = mOnFileTransportListener.remove(listener); Log.d(TAG, "mOnFileTransportListener() appID = " + appID); } else { Log.e(TAG, "there is no this listener in the map"); } } } // @Snow.Tian, Cancel Send File public void cancelSendFile(User receiveUser, int appID) { Log.d(TAG, "cancelSendFile: " + receiveUser.getUserName() + ", appID = " + appID); boolean result = FileTransportProtocol.encodeCancelSend(receiveUser, appID); if (result) { mNotice.showToast(R.string.cancel_send); } else { mNotice.showToast("cancelSendFile: Communcation Null!"); } } // @Snow.Tian, Cancel Receive File public void cancelReceiveFile(User sendUser, int appID) { Log.d(TAG, "cancelReceiveFile: " + sendUser.getUserName() + ", appID = " + appID); boolean result = FileTransportProtocol.encodeCancelReceive(sendUser, appID); if (result) { mNotice.showToast(R.string.cancel_receive); } else { mNotice.showToast("cancelReceiveFile: Communcation Null!"); } } /** * Send file to the receive user. * * @param file * @param listener * @param receiveUser * @param appID */ public void sendFile(File file, OnFileSendListener listener, User receiveUser, int appID) { sendFile(file, listener, receiveUser, appID, null); } /** * Send file to the receive user. * * @param file * @param listener * @param receiveUser * @param appID * @param key * Key is used for marking different FileSenders. * @return */ public FileSender sendFile(File file, OnFileSendListener listener, User receiveUser, int appID, Object key) { Log.d(TAG, "sendFile() file = " + file.getName() + ", receive user = " + receiveUser.getUserName() + ", appID = " + appID); FileSender fileSender = null; if (key == null) { fileSender = new FileSender(); } else { fileSender = new FileSender(key); } int serverPort = fileSender.sendFile(file, listener); if (serverPort == -1) { Log.e(TAG, "sendFile error, create socket server fail. file = " + file.getName()); return fileSender; } InetAddress inetAddress = NetWorkUtil.getLocalInetAddress(); if (inetAddress == null) { Log.e(TAG, "sendFile error, get inet address fail. file = " + file.getName()); return fileSender; } FileTransportProtocol.encodeSendFile(receiveUser, appID, serverPort, file, mContext); return fileSender; } /** * Notify all registered file receive listener.</br> * * This is used by {@link FileTransportProtocol}. When receive a file from * {@link FileTransportProtocol}, this method will be called. * * @param sendUserID * @param appID * @param serverAddress * @param serverPort * @param fileInfo */ public void notfiyFileReceiveListeners(int sendUserID, int appID, byte[] serverAddress, int serverPort, FileInfo fileInfo) { for (Map.Entry<OnFileTransportListener, Integer> entry : mOnFileTransportListener .entrySet()) { if (entry.getValue() == appID) { User sendUser = mUserManager.getAllUser().get(sendUserID); if (sendUser == null) { Log.e(TAG, "notfiyFileReceiveListeners cannot find send user, send user id = " + sendUserID); return; } FileReceiver fileReceiver = new FileReceiver(sendUser, serverAddress, serverPort, fileInfo); entry.getKey().onReceiveFile(fileReceiver); } } } /** * Notify all listeners that we received a message sent by the user with the * ID sendUserID for us. * * This is used by ProtocolDecoder. * * @param sendUserID * @param appID * @param data */ public void notifyMessageReceiveListeners(int sendUserID, int appID, byte[] data) { for (Map.Entry<OnCommunicationListenerExternal, Integer> entry : mOnCommunicationListenerExternals .entrySet()) { if (entry.getValue() == appID) { try { entry.getKey().onReceiveMessage(data, mUserManager.getAllUser().get(sendUserID)); } catch (RemoteException e) { Log.e(TAG, "notifyReceiveListeners error." + e); } } } } /** * Send message to the receiver. * * @param msg * @param receiveUser * @param appID */ public void sendMessageToSingle(byte[] msg, User receiveUser, int appID) { int localUserID = mUserManager.getLocalUser().getUserID(); int receiveUserID = receiveUser.getUserID(); MessageSendProtocol.encodeSendMessageToSingle(msg, localUserID, receiveUserID, appID); } /** * Send message to all users in the network. * * @param msg */ public void sendMessageToAll(byte[] msg, int appID) { Log.d(TAG, "sendMessageToAll.msg.=" + new String(msg)); int localUserID = mUserManager.getLocalUser().getUserID(); MessageSendProtocol.encodeSendMessageToAll(msg, localUserID, appID); } /** * Update user when user connect and disconnect. */ public void sendMessageToUpdateAllUser() { UserUpdateProtocol.encodeUpdateAllUser(mContext); } @Override public void onUserConnected(User user) { for (Map.Entry<OnCommunicationListenerExternal, Integer> entry : mOnCommunicationListenerExternals .entrySet()) { try { entry.getKey().onUserConnected(user); } catch (RemoteException e) { Log.e(TAG, "onUserConnected error." + e); } } } @Override public void onUserDisconnected(User user) { for (Map.Entry<OnCommunicationListenerExternal, Integer> entry : mOnCommunicationListenerExternals .entrySet()) { try { entry.getKey().onUserDisconnected(user); } catch (RemoteException e) { Log.e(TAG, "onUserDisconnected error." + e); } } } /** * Call back interface for login activity. * */ public interface ILoginRequestCallBack { /** * When a client requests login, this method will notify the server. * * @param userInfo * @param communication */ void onLoginRequest(UserInfo userInfo, SocketCommunication communication); } /** * Call back interface for login activity. * */ public interface ILoginRespondCallback { /** * When the server responds the login request and allows login, this * method will notify the request client. * * @param localUser * @param communication */ void onLoginSuccess(User localUser, SocketCommunication communication); /** * When the server responds the login request and disallow login, this * method will notify the request client. * * @param failReason * @param communication */ void onLoginFail(int failReason, SocketCommunication communication); } public interface OnFileTransportListener { void onReceiveFile(FileReceiver fileReceiver); } public String getOnFileTransportListenerStatus() { StringBuffer status = new StringBuffer(); status.append("Total size: " + mOnFileTransportListener.size() + "\n"); status.append(mOnFileTransportListener.toString() + "\n"); return status.toString(); } public String getOnCommunicationListenerExternalStatus() { StringBuffer status = new StringBuffer(); status.append("Total size: " + mOnCommunicationListenerExternals.size() + "\n"); status.append(mOnCommunicationListenerExternals.toString() + "\n"); return status.toString(); } } <file_sep>package com.zhaoyan.communication.search; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; /** * This is a discovery service and WiFi AP is not Android AP.</br> * * Send multicast socket to all clients, and wait for client connection.</br> */ public class DiscoveryServiceLanWifi implements Runnable { private static final String TAG = "DiscoveryServiceLanWifi"; // Socket for send muticast message. private DatagramSocket mSendMessageSocket; private boolean mStopped = false; private boolean mStarted = false; @Override public void run() { // multicast our message. try { mSendMessageSocket = new DatagramSocket(Search.MULTICAST_SEND_PORT); } catch (SocketException e) { Log.e(TAG, "Create multicast packet error. " + e); } String ip = NetWorkUtil.getLocalIpAddress(); DatagramPacket packet = getSearchPacket(); while (!mStopped) { if (ip == null || ip.equals("")) { // illegal ip, ignore. } else if (ip.endsWith(NetWorkUtil.getLocalIpAddress())) { // ip is not changed. sendDataToClient(packet); } else { // ip is changed. ip = NetWorkUtil.getLocalIpAddress(); packet = getSearchPacket(); sendDataToClient(packet); } try { Thread.sleep(Search.MULTICAST_DELAY_TIME); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException " + e); } } } /** * Search packet protocol:</br> * * [server ip][server name size][server name] * * @return */ private DatagramPacket getSearchPacket() { byte[] searchMessage = SearchProtocol.encodeSearchLan(); DatagramPacket packet = null; try { packet = new DatagramPacket(searchMessage, searchMessage.length, InetAddress.getByName(Search.MULTICAST_IP), Search.MULTICAST_RECEIVE_PORT); } catch (UnknownHostException e) { Log.e(TAG, "getSearchPacket error." + e); } return packet; } private void sendDataToClient(DatagramPacket packet) { if (mSendMessageSocket == null) { Log.e(TAG, "startBroadcastData() fail, mSocket is null"); return; } try { mSendMessageSocket.send(packet); Log.d(TAG, "Send broadcast ok, data = " + new String(packet.getData())); } catch (IOException e) { Log.e(TAG, "Send broadcast fail, data = " + new String(packet.getData()) + " " + e); } } public void startSearch() { if (mStarted) { Log.d(TAG, "startSearch() igonre, search is already started."); return; } Log.d(TAG, "Start search"); mStarted = true; mStopped = false; Thread searchThread = new Thread(this); searchThread.start(); } public void stopSearch() { if (!mStarted) { Log.d(TAG, "stopSearch() igonre, search is not started."); return; } Log.d(TAG, "Stop search."); mStarted = false; mStopped = true; closeSocket(); } private void closeSocket() { if (mSendMessageSocket != null) { mSendMessageSocket.close(); } } } <file_sep>package com.zhaoyan.common.util; import android.content.Context; import android.content.SharedPreferences; public class SharedPreferenceUtil { public static final String NAME = "zhaoyan"; public static final String DEFAULT_SAVE_PATH = "DEFAULT_SAVE_PATH"; public static final String SDCARD_PATH = "sdcard_path"; public static final String INTERNAL_PATH = "internal_path"; public static SharedPreferences getSharedPreference(Context context) { return context.getSharedPreferences(NAME, Context.MODE_PRIVATE); } } <file_sep>package com.zhaoyan.juyou.adapter; import java.io.File; import android.app.Dialog; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.content.ContentUris; import android.os.Bundle; import android.content.Intent; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.common.file.FileManager; import com.zhaoyan.common.file.SingleMediaScanner; import com.zhaoyan.common.util.IntentBuilder; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.util.ZYUtils; import com.zhaoyan.communication.UserHelper; import com.zhaoyan.communication.UserInfo; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.common.ActionMenuInterface.OnMenuItemClickListener; import com.zhaoyan.juyou.common.AsyncImageLoader; import com.zhaoyan.juyou.common.ActionMenu.ActionMenuItem; import com.zhaoyan.juyou.common.AsyncImageLoader.ILoadImageCallback; import com.zhaoyan.juyou.common.ActionMenu; import com.zhaoyan.juyou.common.FileTransferUtil; import com.zhaoyan.juyou.common.HistoryManager; import com.zhaoyan.juyou.dialog.ContextMenuDialog; import com.zhaoyan.juyou.dialog.SingleChoiceDialog; import com.zhaoyan.juyou.dialog.ZyAlertDialog; import com.zhaoyan.juyou.dialog.ZyAlertDialog.OnZyAlertDlgClickListener; import com.zhaoyan.juyou.provider.JuyouData; import com.zhaoyan.juyou.provider.JuyouData.History; import com.zhaoyan.communication.FileTransferService; import com.zhaoyan.juyou.common.ZYConstant; public class HistoryCursorAdapter extends CursorAdapter { private static final String TAG = "HistoryCursorAdapter"; private LayoutInflater mLayoutInflater = null; private Notice mNotice = null; private Context mContext; private AsyncImageLoader bitmapLoader = null; private boolean mIdleFlag = true; private MsgOnClickListener mClickListener = new MsgOnClickListener(); private ListView mListView; private UserInfo mLocalUserInfo = null; public HistoryCursorAdapter(Context context, ListView listView) { super(context, null, true); this.mContext = context; mListView = listView; mNotice = new Notice(context); mLayoutInflater = LayoutInflater.from(context); bitmapLoader = new AsyncImageLoader(context); mLocalUserInfo = UserHelper.loadLocalUser(context); } @Override public Object getItem(int position) { return super.getItem(position); } @Override public int getItemViewType(int position) { Cursor cursor = (Cursor) getItem(position); int type = cursor.getInt(cursor .getColumnIndex(JuyouData.History.MSG_TYPE)); if (HistoryManager.TYPE_RECEIVE == type) { return 0; } else { return 1; } } @Override public int getViewTypeCount() { // 如果你的list中有不同的视图类型,就一定要重写这个方法,并配合getItemViewType一起使用 //if you ui have two type views,you must overrid this function,add relize in getItemViewType return 2; } public void setIdleFlag(boolean flag) { this.mIdleFlag = flag; } @Override public void bindView(View view, Context arg1, Cursor cursor) { // Log.d(TAG, "bindView.count=" + cursor.getCount()); ViewHolder holder = (ViewHolder) view.getTag(); holder.position = cursor.getPosition(); int id = cursor.getInt(cursor.getColumnIndex(JuyouData.History._ID)); // Log.d(TAG, "bindView: pos = " + holder.position + ", id = " + id); int type = cursor.getInt(cursor .getColumnIndex(JuyouData.History.MSG_TYPE)); long time = cursor.getLong(cursor .getColumnIndex(JuyouData.History.DATE)); String filePath = cursor.getString(cursor .getColumnIndex(JuyouData.History.FILE_PATH)); String fileName = cursor.getString(cursor .getColumnIndex(JuyouData.History.FILE_NAME)); String sendUserName = cursor.getString(cursor .getColumnIndex(JuyouData.History.SEND_USERNAME)); ; String reveiveUserName; long fileSize = cursor.getLong(cursor .getColumnIndex(JuyouData.History.FILE_SIZE)); double progress = cursor.getDouble(cursor .getColumnIndex(JuyouData.History.PROGRESS)); int status = cursor.getInt(cursor .getColumnIndex(JuyouData.History.STATUS)); int fileType = cursor.getInt(cursor .getColumnIndex(JuyouData.History.FILE_TYPE)); int headId; byte[] headIcon; if (HistoryManager.TYPE_SEND == type) { reveiveUserName = cursor.getString(cursor .getColumnIndex(JuyouData.History.RECEIVE_USERNAME)); holder.contentTitleView.setText(mContext.getString( R.string.sending, reveiveUserName)); headId = mLocalUserInfo.getHeadId(); if (UserInfo.HEAD_ID_NOT_PRE_INSTALL != headId) { holder.userHeadView .setImageResource(UserHelper.HEAD_IMAGES[headId]); } else { headIcon = mLocalUserInfo.getHeadBitmapData(); Bitmap headIconBitmap = BitmapFactory.decodeByteArray(headIcon, 0, headIcon.length); if (headIconBitmap != null) { holder.userHeadView.setImageBitmap(headIconBitmap); } else { holder.userHeadView .setImageResource(UserHelper.HEAD_IMAGES[0]); } } } else { headId = cursor.getInt(cursor .getColumnIndex(JuyouData.History.SEND_USER_HEADID)); if (UserInfo.HEAD_ID_NOT_PRE_INSTALL != headId) { holder.userHeadView .setImageResource(UserHelper.HEAD_IMAGES[headId]); } else { headIcon = cursor.getBlob(cursor .getColumnIndex(JuyouData.History.SEND_USER_ICON)); Bitmap headIconBitmap = BitmapFactory.decodeByteArray(headIcon, 0, headIcon.length); if (headIconBitmap != null) { holder.userHeadView.setImageBitmap(headIconBitmap); } else { holder.userHeadView .setImageResource(UserHelper.HEAD_IMAGES[0]); } } } holder.userNameView.setText(sendUserName); holder.fileIconView.setTag(filePath); holder.dateView.setText(ZYUtils.getFormatDate(time)); holder.fileNameView.setText(fileName); holder.fileSizeView.setTextColor(Color.BLACK); MsgData msgData = new MsgData(id, fileName, filePath, type, status); holder.msgLayout.setTag(msgData); byte[] fileIcon = cursor.getBlob(cursor.getColumnIndex(JuyouData.History.FILE_ICON)); if(fileIcon == null || fileIcon.length == 0) { // There is no file icon, use default setIconView(holder, holder.fileIconView, filePath, fileType); } else { Bitmap fileIconBitmap = BitmapFactory.decodeByteArray(fileIcon, 0, fileIcon.length); if (fileIconBitmap != null) { holder.fileIconView.setImageBitmap(fileIconBitmap); } } setSendReceiveStatus(holder, status, fileSize, progress); } private void setSendReceiveStatus(ViewHolder holder, int status, long fileSize, double progress) { // Log.d(TAG, "setSendReceiveStatus.status=" + status); String statusStr = ""; int color = Color.BLACK; String fileSizeStr = ZYUtils.getFormatSize(fileSize); String percentStr = HistoryManager.nf.format(progress / fileSize); int bar_progress = (int) ((progress / fileSize) * 100); boolean showBar = false; switch (status) { case HistoryManager.STATUS_PRE_SEND: statusStr = mContext.getString(R.string.transfer_wait); color = Color.RED; break; case HistoryManager.STATUS_SENDING: case HistoryManager.STATUS_RECEIVING: showBar = true; statusStr = percentStr; fileSizeStr = ZYUtils.getFormatSize(progress) + "/" + fileSizeStr; break; case HistoryManager.STATUS_SEND_SUCCESS: case HistoryManager.STATUS_RECEIVE_SUCCESS: statusStr = mContext.getString(R.string.transfer_ok); color = mContext.getResources().getColor(R.color.holo_blue_light); break; case HistoryManager.STATUS_SEND_FAIL: statusStr = mContext.getString(R.string.send_fail); color = Color.RED; fileSizeStr = ZYUtils.getFormatSize(progress) + "/" + fileSizeStr; break; case HistoryManager.STATUS_RECEIVE_FAIL: statusStr = mContext.getString(R.string.receive_fail); color = Color.RED; fileSizeStr = ZYUtils.getFormatSize(progress) + "/" + fileSizeStr; break; default: Log.e(TAG, "setSendReceiveStatus.Error.status=" + status); break; } holder.transferBar.setVisibility(showBar ? View.VISIBLE : View.INVISIBLE); if (showBar) { holder.transferBar.setProgress(bar_progress); } holder.sendStatusView.setText(statusStr); holder.sendStatusView.setTextColor(color); holder.fileSizeView.setText(fileSizeStr); } /** * use async thread loader bitmap. * * @param iconView * @param filePath * @param fileType */ private void setIconView(ViewHolder holder, final ImageView iconView, final String filePath, int fileType) { // Log.d(TAG, "scroll flag=" + mIdleFlag); switch (fileType) { case FileManager.IMAGE: case FileManager.VIDEO: if (!mIdleFlag) { if (AsyncImageLoader.bitmapCache.size() > 0 && AsyncImageLoader.bitmapCache.get(filePath) != null) { iconView.setImageBitmap(AsyncImageLoader.bitmapCache.get( filePath).get()); } else { setImageViewIcon(iconView, fileType); } return; } else { Bitmap bitmap = bitmapLoader.loadImage(filePath, fileType, new ILoadImageCallback() { @Override public void onObtainBitmap(Bitmap bitmap, String url) { ImageView imageView = (ImageView) mListView .findViewWithTag(filePath); if (null != bitmap && null != imageView) { imageView.setImageBitmap(bitmap); } } }); if (null == bitmap) { setImageViewIcon(iconView, fileType); } else { iconView.setImageBitmap(bitmap); } } break; default: setImageViewIcon(iconView, fileType); break; } } @Override public View newView(Context arg0, Cursor cursor, ViewGroup arg2) { int type = cursor.getInt(cursor .getColumnIndex(JuyouData.History.MSG_TYPE)); View view = null; ViewHolder holder = new ViewHolder(); if (HistoryManager.TYPE_RECEIVE == type) { view = mLayoutInflater.inflate(R.layout.history_item_rev, null); } else { view = mLayoutInflater.inflate(R.layout.history_item_send, null); holder.contentTitleView = (TextView) view .findViewById(R.id.tv_send_title_msg); } holder.transferBar = (ProgressBar) view .findViewById(R.id.bar_progressing); holder.transferBar.setMax(100); holder.fileIconView = (ImageView) view .findViewById(R.id.iv_send_file_icon); holder.dateView = (TextView) view.findViewById(R.id.tv_sendtime); holder.userNameView = (TextView) view.findViewById(R.id.tv_username); holder.userHeadView = (ImageView) view.findViewById(R.id.iv_userhead); holder.fileNameView = (TextView) view .findViewById(R.id.tv_send_file_name); holder.fileSizeView = (TextView) view .findViewById(R.id.tv_send_file_size); holder.sendStatusView = (TextView) view .findViewById(R.id.tv_send_status); holder.msgLayout = (LinearLayout) view .findViewById(R.id.layout_chatcontent); holder.msgLayout.setOnClickListener(mClickListener); view.setTag(holder); return view; } private void setImageViewIcon(ImageView imageView, int type) { switch (type) { case FileManager.IMAGE: imageView.setImageResource(R.drawable.icon_image); break; case FileManager.VIDEO: imageView.setImageResource(R.drawable.icon_video); break; case FileManager.AUDIO: imageView.setImageResource(R.drawable.icon_audio); break; case FileManager.EBOOK: imageView.setImageResource(R.drawable.icon_txt); break; case FileManager.ARCHIVE: imageView.setImageResource(R.drawable.icon_rar); break; case FileManager.WORD: imageView.setImageResource(R.drawable.icon_doc); break; case FileManager.PPT: imageView.setImageResource(R.drawable.icon_ppt); break; case FileManager.EXCEL: imageView.setImageResource(R.drawable.icon_xls); break; case FileManager.PDF: imageView.setImageResource(R.drawable.icon_pdf); break; default: imageView.setImageResource(R.drawable.icon_file); break; } } class ViewHolder { ProgressBar transferBar; TextView dateView; TextView userNameView; ImageView userHeadView; TextView fileNameView; TextView fileSizeView; TextView contentTitleView; TextView sendStatusView; ImageView fileIconView; // msg layout LinearLayout msgLayout; int position; } class MsgData { int itemID; String fileName; String filePath; int type; int status; public MsgData(int itemID, String fileName, String filePath, int type, int status) { this.itemID = itemID; this.fileName = fileName; this.filePath = filePath; this.type = type; this.status = status; } } /** * Cancel sending data. * * @param id The storage identifier. * * @return void */ private void cancelSending(int id) { String uri = ContentUris.withAppendedId(JuyouData.History.CONTENT_URI, id).toString(); Log.d(TAG, "cancelSending: uri = " + uri); Intent intent = new Intent(mContext, FileTransferService.class); intent.setAction(ZYConstant.CANCEL_SEND_ACTION); Bundle bundle = new Bundle(); bundle.putString(HistoryManager.HISTORY_URI, uri); intent.putExtras(bundle); mContext.startService(intent); } /** * Cancel receiving data. * * @param id The storage identifier. * * @return void */ private void cancelReceiving(int id) { String uri = ContentUris.withAppendedId(JuyouData.History.CONTENT_URI, id).toString(); Log.d(TAG, "cancelReceiving: uri = " + uri); Intent intent = new Intent(mContext, FileTransferService.class); intent.setAction(ZYConstant.CANCEL_RECEIVE_ACTION); Bundle bundle = new Bundle(); bundle.putString(HistoryManager.HISTORY_URI, uri); intent.putExtras(bundle); mContext.startService(intent); } class MsgOnClickListener implements OnClickListener { @Override public void onClick(View v) { MsgData data = (MsgData) v.getTag(); final int id = data.itemID; final String filePath = data.filePath; String fileName = data.fileName; final int type = data.type; int status = data.status; ActionMenu actionMenu = new ActionMenu(mContext); switch (status) { case HistoryManager.STATUS_PRE_SEND: actionMenu.addItem(ActionMenu.ACTION_MENU_SEND, 0, R.string.send_file); actionMenu.addItem(ActionMenu.ACTION_MENU_OPEN, 0, R.string.open_file); break; case HistoryManager.STATUS_SENDING: actionMenu.addItem(ActionMenu.ACTION_MENU_SEND, 0, R.string.send_file); actionMenu.addItem(ActionMenu.ACTION_MENU_OPEN, 0, R.string.open_file); actionMenu.addItem(ActionMenu.ACTION_MENU_CANCEL_SEND, 0, R.string.cancel_send); break; case HistoryManager.STATUS_SEND_SUCCESS: case HistoryManager.STATUS_RECEIVE_SUCCESS: actionMenu.addItem(ActionMenu.ACTION_MENU_SEND, 0, R.string.send_file); actionMenu.addItem(ActionMenu.ACTION_MENU_OPEN, 0, R.string.open_file); actionMenu.addItem(ActionMenu.ACTION_MENU_DELETE, 0, R.string.delete_history); actionMenu.addItem(ActionMenu.ACTION_MENU_CLEAR_HISTORY, 0, R.string.clear_history); break; case HistoryManager.STATUS_SEND_FAIL: actionMenu.addItem(ActionMenu.ACTION_MENU_SEND, 0, R.string.send_file); actionMenu.addItem(ActionMenu.ACTION_MENU_OPEN, 0, R.string.open_file); actionMenu.addItem(ActionMenu.ACTION_MENU_CANCEL, 0, R.string.delete_history); actionMenu.addItem(ActionMenu.ACTION_MENU_CLEAR_HISTORY, 0, R.string.clear_history); break; case HistoryManager.STATUS_PRE_RECEIVE: //do nothing return; case HistoryManager.STATUS_RECEIVING: actionMenu.addItem(ActionMenu.ACTION_MENU_CANCEL_RECEIVE, 0, R.string.cancel_receive); break; case HistoryManager.STATUS_RECEIVE_FAIL: actionMenu.addItem(ActionMenu.ACTION_MENU_CANCEL, 0, R.string.delete_history); actionMenu.addItem(ActionMenu.ACTION_MENU_CLEAR_HISTORY, 0, R.string.clear_history); break; default: Log.e(TAG, "MsgOnClickListener.STATUS_ERROR:" + status); break; } ContextMenuDialog contextdialog = new ContextMenuDialog(mContext, actionMenu); contextdialog.setTitle(fileName); contextdialog .setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public void onMenuItemClick( ActionMenuItem actionMenuItem) { File file = new File(filePath); switch (actionMenuItem.getItemId()) { case ActionMenu.ACTION_MENU_SEND: if (!file.exists()) { showFileNoExistDialog(id); break; } else { FileTransferUtil fileSendUtil = new FileTransferUtil( mContext); fileSendUtil.sendFile(filePath); } break; case ActionMenu.ACTION_MENU_DELETE: showDeleteDialog(file, id, type); break; case ActionMenu.ACTION_MENU_OPEN: if (!file.exists()) { showFileNoExistDialog(id); break; } else { IntentBuilder.viewFile(mContext, filePath); } break; case ActionMenu.ACTION_MENU_CANCEL: String selection = JuyouData.History._ID + "=" + id; mContext.getContentResolver().delete( JuyouData.History.CONTENT_URI, selection, null); break; case ActionMenu.ACTION_MENU_CLEAR_HISTORY: // delete history // delete history table showClearDialog(); break; case ActionMenu.ACTION_MENU_CANCEL_SEND: cancelSending(id); break; case ActionMenu.ACTION_MENU_CANCEL_RECEIVE: cancelReceiving(id); break; } } }); contextdialog.show(); } } /** * Delete the transfer record in DB. * * @param id * the transfer record id id db */ private void deleteHistory(int id) { // Do not delete file current. Log.d(TAG, "deleteHistory: id = " + id); String selection = JuyouData.History._ID + "=" + id; int result = mContext.getContentResolver().delete( JuyouData.History.CONTENT_URI, selection, null); if (result > 0) { mNotice.showToast("已刪除记录"); } else { mNotice.showToast("刪除记录失败"); } } /** * Delete the tranfser record in DB and delelte the file * * @param file * the file that need to delete * @param id * the transfer record id id db */ private void deleteFileAndHistory(File file, int id) { deleteHistory(id); boolean ret = false; if (file.exists()) { ret = file.delete(); if (!ret) { mNotice.showToast("删除文件失败:" + file.getAbsolutePath()); } } } /** * show delete transfer record dialog</br> if the record is send to * others,user only can delete record</br> if the record is receive from * others,user can delete record and delete file in system * * @param file * @param id * @param type * send or receive */ public void showDeleteDialog(final File file, final int id, int type) { ActionMenu actionMenu = new ActionMenu(mContext); actionMenu.addItem(1, 0, R.string.delete_history); actionMenu.addItem(2, 0, R.string.delete_history_and_file); if (HistoryManager.TYPE_SEND == type) { actionMenu.findItem(2).setEnable(false); } final SingleChoiceDialog choiceDialog = new SingleChoiceDialog(mContext, 0, actionMenu); choiceDialog.setTitle(R.string.delete_history); choiceDialog.setPositiveButton(R.string.ok, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { int itemId = choiceDialog.getChoiceItemId(); switch (itemId) { case 1: //delete_history deleteHistory(id); break; case 2: //delete_history_and_file deleteFileAndHistory(file, id); break; } //re-init dialog.dismiss(); } }); choiceDialog.setNegativeButton(R.string.cancel, null); choiceDialog.show(); } public void showFileNoExistDialog(final int id) { ZyAlertDialog dialog = new ZyAlertDialog(mContext); dialog.setTitle(R.string.file_no_exist_delete); dialog.setMessage(R.string.delete_history_or_not); dialog.setNeutralButton(R.string.cancel, null); dialog.setPositiveButton(R.string.menu_delete, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { deleteHistory(id); dialog.dismiss(); } }); dialog.setNegativeButton(R.string.cancel, null); dialog.setCanceledOnTouchOutside(true); dialog.show(); } public void showClearDialog(){ ActionMenu actionMenu = new ActionMenu(mContext); actionMenu.addItem(1, 0, R.string.clear_history); actionMenu.addItem(2, 0, R.string.clear_history_file); final SingleChoiceDialog choiceDialog = new SingleChoiceDialog(mContext, 0, actionMenu); choiceDialog.setTitle(R.string.clear_history); choiceDialog.setPositiveButton(R.string.ok, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { int itemId = choiceDialog.getChoiceItemId(); switch (itemId) { case 1: //clear_history showClearTipDialog(true); break; case 2: //clear_history_file showClearTipDialog(false); break; } dialog.dismiss(); } }); choiceDialog.setNegativeButton(R.string.cancel, null); choiceDialog.show(); } /** * show clear tip dialog * @param clearHistoryOnly true:clear history only,false:clear history and file */ public void showClearTipDialog(final boolean clearHistoryOnly){ ZyAlertDialog dialog = new ZyAlertDialog(mContext); dialog.setTitle(R.string.wenxi_tip); if (clearHistoryOnly) { dialog.setMessage(R.string.clear_history_tip); }else { dialog.setMessage(R.string.clear_history_file_tip); } dialog.setNeutralButton(R.string.cancel, null); dialog.setPositiveButton(R.string.ok, new OnZyAlertDlgClickListener() { @Override public void onClick(Dialog dialog) { if (clearHistoryOnly) { mContext.getContentResolver().delete( History.CONTENT_URI, null, null); }else { Cursor cursor = getCursor(); if (cursor.moveToFirst()) { String filePath; int type; File file = null; do { type = cursor.getInt(cursor .getColumnIndex(History.MSG_TYPE)); // just delete the file that received from friends if (HistoryManager.TYPE_RECEIVE == type) { filePath = cursor.getString(cursor .getColumnIndex(History.FILE_PATH)); file = new File(filePath); if (file.delete()) { // if delete file success,update mediaProvider new SingleMediaScanner(mContext, file); } } } while (cursor.moveToNext()); } cursor.close(); mContext.getContentResolver().delete( History.CONTENT_URI, null, null); } dialog.dismiss(); } }); dialog.setNegativeButton(R.string.cancel, null); dialog.setCanceledOnTouchOutside(true); dialog.show(); } } <file_sep>package com.zhaoyan.juyou.provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import com.zhaoyan.common.util.Log; public class AppProvider extends ContentProvider { private static final String TAG = "AppProvider"; private SQLiteDatabase mSqLiteDatabase; private DatabaseHelper mDatabaseHelper; public static final int GAME_COLLECTION = 1; public static final int GAME_SINGLE = 2; public static final int GAME_FILTER = 5; public static final int APP_COLLECTION = 10; public static final int APP_SINGLE = 11; public static final int APP_FILTER = 12; public static final UriMatcher uriMatcher; static{ uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AppData.AUTHORITY, "game", GAME_COLLECTION); uriMatcher.addURI(AppData.AUTHORITY, "game/*", GAME_SINGLE); uriMatcher.addURI(AppData.AUTHORITY, "game_filter/*", GAME_FILTER); uriMatcher.addURI(AppData.AUTHORITY, "app", APP_COLLECTION); uriMatcher.addURI(AppData.AUTHORITY, "app/*", APP_SINGLE); uriMatcher.addURI(AppData.AUTHORITY, "app_filter/*", APP_FILTER); } @Override public boolean onCreate() { mDatabaseHelper = new DatabaseHelper(getContext()); return (mDatabaseHelper == null) ? false : true; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); int count = 0; switch (uriMatcher.match(uri)) { case GAME_COLLECTION: count = mSqLiteDatabase.delete(AppData.AppGame.TABLE_NAME, selection, selectionArgs); break; case GAME_SINGLE: String segment = uri.getPathSegments().get(1); if (selection != null && segment.length() > 0) { //根据ID删除 selection = "_id=" + segment + " AND (" + selection + ")"; }else { //由于segment是个string,那么需要给他加个'',如果是int型的就不需要了 //根据包名删除 selection = AppData.App.PKG_NAME + "='" + segment + "'"; } count = mSqLiteDatabase.delete(AppData.AppGame.TABLE_NAME, selection, selectionArgs); break; case APP_COLLECTION: count = mSqLiteDatabase.delete(AppData.App.TABLE_NAME, selection, selectionArgs); break; case APP_SINGLE: String segment2 = uri.getPathSegments().get(1); if (selection != null && segment2.length() > 0) { selection = "_id=" + segment2 + " AND (" + selection + ")"; }else { //由于segment是个string,那么需要给他加个'',如果是int型的就不需要了 Log.d(TAG, "delete packagename=" + segment2); selection = AppData.App.PKG_NAME + "='" + segment2 + "'"; } count = mSqLiteDatabase.delete(AppData.App.TABLE_NAME, selection, selectionArgs); break; default: throw new IllegalArgumentException("UnKnow Uri:" + uri); } if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case GAME_COLLECTION: return AppData.AppGame.CONTENT_TYPE; case GAME_SINGLE: return AppData.AppGame.CONTENT_TYPE_ITEM; default: throw new IllegalArgumentException("Unkonw uri:" + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { // Log.d(TAG, "insert db"); mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); long rowId = 0; switch (uriMatcher.match(uri)) { case GAME_COLLECTION: case GAME_SINGLE: rowId = mSqLiteDatabase.insertWithOnConflict(AppData.AppGame.TABLE_NAME, "", values, SQLiteDatabase.CONFLICT_REPLACE); if (rowId > 0) { Uri rowUri = ContentUris.withAppendedId(AppData.AppGame.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(uri, null); return rowUri; } throw new IllegalArgumentException("Cannot insert into uri:" + uri); case APP_COLLECTION: case APP_SINGLE: rowId = mSqLiteDatabase.insertWithOnConflict(AppData.App.TABLE_NAME, "", values, SQLiteDatabase.CONFLICT_REPLACE); if (rowId > 0) { Uri rowUri = ContentUris.withAppendedId(uri, rowId); getContext().getContentResolver().notifyChange(uri, null); // Log.i(TAG, "insertDb.rowId=" + rowId); return rowUri; } throw new IllegalArgumentException("Cannot insert into uri:" + uri); default: throw new IllegalArgumentException("Unknow uri:" + uri); } } @Override public int bulkInsert(Uri uri, ContentValues[] values) { // TODO Auto-generated method stub mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); int numValues = 0; mSqLiteDatabase.beginTransaction(); try { numValues = values.length; for (int i = 0; i < values.length; i++) { insert(uri, values[i]); } } catch (Exception e) { Log.e(TAG, "insert error:" + e.toString()); } finally{ mSqLiteDatabase.setTransactionSuccessful(); mSqLiteDatabase.endTransaction(); } return numValues; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch (uriMatcher.match(uri)) { case GAME_COLLECTION: qb.setTables(AppData.AppGame.TABLE_NAME); break; case GAME_SINGLE: qb.setTables(AppData.AppGame.TABLE_NAME); qb.appendWhere("_id="); qb.appendWhere(uri.getPathSegments().get(1)); break; case GAME_FILTER: qb.setTables(AppData.AppGame.TABLE_NAME); qb.appendWhere(AppData.App.PKG_NAME + " like \'%" + uri.getPathSegments().get(1) + "%\'"); break; case APP_COLLECTION: qb.setTables(AppData.App.TABLE_NAME); break; case APP_SINGLE: qb.setTables(AppData.App.TABLE_NAME); qb.appendWhere("_id="); qb.appendWhere(uri.getPathSegments().get(1)); break; case APP_FILTER: break; default: throw new IllegalArgumentException("Unknow uri:" + uri); } mSqLiteDatabase = mDatabaseHelper.getReadableDatabase(); // Log.i(TAG, "selection:" + selection + ",args:" + selectionArgs.toString()); Cursor ret = qb.query(mSqLiteDatabase, projection, selection, selectionArgs, null, null, sortOrder); if (ret != null) { ret.setNotificationUri(getContext().getContentResolver(), uri); } return ret; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count; long rowId = 0; int match = uriMatcher.match(uri); mSqLiteDatabase = mDatabaseHelper.getWritableDatabase(); switch (match) { case GAME_SINGLE: String segment1 = uri.getPathSegments().get(1); rowId = Long.parseLong(segment1); count = mSqLiteDatabase.update(AppData.AppGame.TABLE_NAME, values, "_id=" + rowId, null); break; case GAME_COLLECTION: count = mSqLiteDatabase.update(AppData.AppGame.TABLE_NAME, values, selection, null); break; case APP_SINGLE: String segment2 = uri.getPathSegments().get(1); rowId = Long.parseLong(segment2); count = mSqLiteDatabase.update(AppData.App.TABLE_NAME, values, "_id=" + rowId, null); break; case APP_COLLECTION: count = mSqLiteDatabase.update(AppData.App.TABLE_NAME, values, selection, null); break; default: throw new UnsupportedOperationException("Cannot update uri:" + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } private static class DatabaseHelper extends SQLiteOpenHelper{ public DatabaseHelper(Context context) { super(context, AppData.DATABASE_NAME, null, AppData.DATABASE_VERSION); Log.d(TAG, "DatabaseHelper"); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "DatabaseHelper.onCreate"); //create game table db.execSQL("create table " + AppData.AppGame.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + AppData.App.PKG_NAME + " TEXT);" ); //create APP table db.execSQL("create table " + AppData.App.TABLE_NAME + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT, " + AppData.App.PKG_NAME + " TEXT, " + AppData.App.LABEL + " TEXT, " + AppData.App.APP_SIZE + " LONG, " + AppData.App.VERSION + " TEXT, " + AppData.App.DATE + " LONG, " + AppData.App.TYPE + " INTEGER, " + AppData.App.ICON + " BLOB, " + AppData.App.PATH + " TEXT);" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + AppData.AppGame.TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + AppData.App.TABLE_NAME); onCreate(db); } } } <file_sep>package com.zhaoyan.juyou.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.zhaoyan.juyou.R; public class GuangChangFragment extends BaseFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View viweRoot = inflater.inflate(R.layout.guangchang_fragment, container, false); initTitle(viweRoot, R.string.guang_chang); return viweRoot; } }<file_sep>package com.zhaoyan.communication.search; import java.util.Random; import com.zhaoyan.communication.UserInfo; /** * This class is used for generate encrypted WiFi name and check WiFi name</br> * * WiFi name naming rule: userName@wifiName.</br> * * userName is the user name.</br> * * wifiName is the encrypted WiFi name.</br> * */ public class WiFiNameEncryption { public static final String WIFI_NAME_SUFFIX_KEY = "WLAN"; public static final int WIFI_NAME_SUFFIX_LENGTH = 10; public static final int USER_HEAD_ID_LENGHT = 2; /** * Generate a encrypted name. * * @param userName * @return */ public static String generateWiFiName(String userName) { int headId = UserInfo.HEAD_ID_NOT_PRE_INSTALL; return generateWiFiName(userName, headId); } /** * Generate a encrypted name. * * @param userName * @return */ public static String generateWiFiName(String userName, int headId) { return generateWiFiName(userName, headId, generateWiFiNameSuffix()); } /** * Generate a WiFi name suffix. * * @return */ public static String generateWiFiNameSuffix() { Random random = new Random(); // Get a random position for WIFI_NAME_SUFFIX_KEY. int wifiNameKeyPosition = random.nextInt(WIFI_NAME_SUFFIX_LENGTH - WIFI_NAME_SUFFIX_KEY.length() - 1); // Get the WiFi name suffix. StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(generateRandomUperCaseChar(wifiNameKeyPosition)); stringBuilder.append(WIFI_NAME_SUFFIX_KEY); stringBuilder.append(generateRandomUperCaseChar(WIFI_NAME_SUFFIX_LENGTH - wifiNameKeyPosition - WIFI_NAME_SUFFIX_KEY.length())); // Get the encrypted WiFi name suffix. return Encryption.encrypt(stringBuilder.toString()); } /** * Generate WiFi name with user name and an exist suffix. * * @param userName * @param suffix * @return */ public static String generateWiFiName(String userName, String suffix) { int headId = UserInfo.HEAD_ID_NOT_PRE_INSTALL; return generateWiFiName(userName, headId, suffix); } /** * Generate WiFi name with user name and an exist suffix. * * @param userName * @param suffix * @return */ public static String generateWiFiName(String userName, int headId, String suffix) { String headIdString = String.valueOf(headId); if (headIdString.length() < USER_HEAD_ID_LENGHT) { while (headIdString.length() < USER_HEAD_ID_LENGHT) { headIdString = "0" + headIdString; } } else if (headIdString.length() > USER_HEAD_ID_LENGHT) { throw new IllegalArgumentException( "WiFiNameEncryption generateWiFiName() headId is too large"); } return userName + headIdString + "@" + suffix; } /** * Get user name from WiFi name. * * @param wifiName * @return */ public static String getUserName(String wifiName) { return wifiName.substring(0, wifiName.length() - WIFI_NAME_SUFFIX_LENGTH - 1 - USER_HEAD_ID_LENGHT); } public static int getUserHeadId(String wifiName) { int start = wifiName.length() - WIFI_NAME_SUFFIX_LENGTH - 1 - USER_HEAD_ID_LENGHT; int end = wifiName.length() - WIFI_NAME_SUFFIX_LENGTH - 1; int headId = UserInfo.HEAD_ID_NOT_PRE_INSTALL; if (start >= 0) { String headIdString = wifiName.substring(start, end); try { headId = Integer.valueOf(headIdString); } catch (NumberFormatException e) { e.printStackTrace(); } } return headId; } /** * Get suffix from WiFi name. * * @return */ public static String getSuffix(String wifiName) { return wifiName.substring(wifiName.length() - WIFI_NAME_SUFFIX_LENGTH, wifiName.length()); } /** * Check WiFi name whether is our WiFi AP or WiFi direct. * * @param wifiName * @return */ public static boolean checkWiFiName(String wifiName) { // Check total length. if (wifiName == null || wifiName.length() < WIFI_NAME_SUFFIX_LENGTH) { return false; } // Check WiFi name suffix whether all chars are from 'A' to 'Z'. String wifiNameSuffix = wifiName.substring(wifiName.length() - WIFI_NAME_SUFFIX_LENGTH, wifiName.length()); for (int i = 0; i < wifiNameSuffix.length(); i++) { if (wifiNameSuffix.charAt(i) < 'A' || wifiNameSuffix.charAt(i) > 'Z') { return false; } } // Decrypt the WiFi name and check it whether contains // WIFI_NAME_SUFFIX_KEY. String wifiNameSuffixDecrypted = Encryption.decrypt(wifiNameSuffix); if (wifiNameSuffixDecrypted.contains(WIFI_NAME_SUFFIX_KEY)) { return true; } else { return false; } } private static char[] generateRandomUperCaseChar(int n) { Random random = new Random(); char[] array = new char[n]; for (int i = 0; i < n; i++) { array[i] = (char) ('A' + random.nextInt(25)); } return array; } /** * Get a WiFi password base on WiFi name. * * @param wifiName * Name of wiFi AP, and it must be checked by * {@link #checkWiFiName(String)}. * @return */ // Get the last WIFI_PASSWORD_LENGTH string. public static String getWiFiPassword(String wifiName) { return Encryption.encrypt(getSuffix(wifiName)); } } <file_sep>package com.zhaoyan.communication.search; import com.zhaoyan.common.util.SharedPreferenceUtil; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * This class is used for fixing a bug: If we generate a new WiFi AP name suffix * every time when create a WiFi AP server, it may happen that we get the old * WiFi AP when do WiFi scan, but actually, the old WiFi AP is not exist. Since * the old WiFi AP name is different from the new one, we can not distinguish * whether they are established from the same user. So the old WiFi AP and the * new WiFi AP is show in server list both. That is not we want.</br> * * The solution is that we make the WiFi AP name not change in the duration of * one application launch. When application is launched, create a new WiFi AP * name suffix use {@link #createNewWifiSuffixName(Context)}. When create * server, get the WiFi AP name use {@link #getWifiNameSuffix(Context)}. * */ public class WifiNameSuffixLoader { private static final String WIFI_NAME_SUFFIX = "wifi_name_suffix"; /** * create a new WiFi AP name suffix * * @param context */ public static String createNewWifiSuffixName(Context context) { SharedPreferences preferences = SharedPreferenceUtil .getSharedPreference(context); Editor editor = preferences.edit(); String wifiNameSuffix = WiFiNameEncryption.generateWiFiNameSuffix(); editor.putString(WIFI_NAME_SUFFIX, wifiNameSuffix); editor.commit(); return wifiNameSuffix; } /** * Get WiFi AP name suffix from shared preference. * * @param context * @return */ public static String getWifiNameSuffix(Context context) { SharedPreferences preferences = SharedPreferenceUtil .getSharedPreference(context); String wifiNameSuffix = preferences.getString(WIFI_NAME_SUFFIX, ""); return wifiNameSuffix; } } <file_sep>ZhaoYanJuYou ============ 如果你发现代码中有乱码,请在Properites中将编码格式改成UTF-8 if you found LuanMa in code,Please modify encode to UTF-8 in Properites <file_sep>package com.zhaoyan.juyou.dialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.zhaoyan.juyou.R; /** * Custom ALert dialog,make 2.3os, can have 4.0 dialog ui */ public class ZyAlertDialog extends Dialog implements android.view.View.OnClickListener { private String mTitle; private String mMessage; private TextView mTitleTV, mMessageTV; private View mTitleView; private View mDivideOneView, mDivideTwoView; private Button mNegativeBtn, mPositiveBtn, mNeutralBtn; private boolean mHasMessage = false; private boolean mShowTitle = false; private boolean mShowNegativeBtn = false; private boolean mShowPositiveBtn = false; private boolean mShowNeutralBtn = false; private String mNegativeMessage,mPositiveMessage,mNeutralMessage; private OnZyAlertDlgClickListener mNegativeListener; private OnZyAlertDlgClickListener mPositiveListener; private OnZyAlertDlgClickListener mNeutralListener; private LinearLayout mContentLayout; private LinearLayout mButtonLayout; private View mCustomeView; private Context mContext; private int padding_left = 0; private int padding_right = 0; private int padding_top = 10; private int padding_bottom = 10; public ZyAlertDialog(Context context){ super(context, R.style.Custom_Dialog); mContext = context; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_alertdialog); if (mShowTitle) { mTitleView = findViewById(R.id.rl_dialog_title); mTitleView.setVisibility(View.VISIBLE); mTitleTV = (TextView) findViewById(R.id.tv_dialog_title); mTitleTV.setText(mTitle); } if (mHasMessage) { mMessageTV = (TextView) findViewById(R.id.tv_dialog_msg); mMessageTV.setVisibility(View.VISIBLE); mMessageTV.setText(mMessage); } mContentLayout = (LinearLayout) findViewById(R.id.ll_content); LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); lp.setMargins(padding_left, padding_top, padding_right, padding_bottom); mContentLayout.setLayoutParams(lp); if (null != mCustomeView) { mContentLayout.addView(mCustomeView); } mButtonLayout = (LinearLayout) findViewById(R.id.ll_button); if (!mShowNegativeBtn && !mShowPositiveBtn && !mShowNeutralBtn) { mButtonLayout.setVisibility(View.GONE); }else { if (mShowNegativeBtn) { mNegativeBtn = (Button) findViewById(R.id.btn_negative); mNegativeBtn.setText(mNegativeMessage); mNegativeBtn.setOnClickListener(this); mNegativeBtn.setVisibility(View.VISIBLE); } if (mShowNeutralBtn) { mNeutralBtn = (Button) findViewById(R.id.btn_neutral); mNeutralBtn.setText(mNeutralMessage); mNeutralBtn.setOnClickListener(this); mNeutralBtn.setVisibility(View.VISIBLE); } if (mShowPositiveBtn) { mPositiveBtn = (Button) findViewById(R.id.btn_positive); mPositiveBtn.setText(mPositiveMessage); mPositiveBtn.setOnClickListener(this); mPositiveBtn.setVisibility(View.VISIBLE); } if (mShowNegativeBtn && mShowNeutralBtn) { mDivideOneView = findViewById(R.id.divider_one); mDivideOneView.setVisibility(View.VISIBLE); } if (mShowNeutralBtn && mShowPositiveBtn) { mDivideTwoView = findViewById(R.id.divider_two); mDivideTwoView.setVisibility(View.VISIBLE); } if (mShowNegativeBtn && mShowPositiveBtn) { mDivideOneView = findViewById(R.id.divider_one); mDivideOneView.setVisibility(View.VISIBLE); } } } @Override public void setTitle(CharSequence title) { mTitle = title.toString(); mShowTitle = true; } @Override public void setTitle(int titleId) { String title = mContext.getString(titleId); setTitle(title); } public void setMessage(String message) { mHasMessage = true; mMessage = message; } public void setMessage(int messageId) { String msg = mContext.getString(messageId); setMessage(msg); } public void setCustomView(View view) { mCustomeView = view; } /** * allow to define customview margis * @param left * @param top * @param right * @param bottom */ public void setCustomViewMargins(int left, int top, int right, int bottom){ this.padding_left = left; this.padding_top = top; this.padding_right = right; this.padding_bottom = bottom; } @Override public void show() { super.show(); WindowManager windowManager = getWindow().getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.width = (int)display.getWidth() - 40; getWindow().setAttributes(lp); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_negative: if (null == mNegativeListener) { dismiss(); }else { mNegativeListener.onClick(this); } break; case R.id.btn_positive: if (null == mPositiveListener) { dismiss(); }else { mPositiveListener.onClick(this); } break; case R.id.btn_neutral: if (null == mNeutralListener) { dismiss(); }else { mNeutralListener.onClick(this); } break; default: break; } } public interface OnZyAlertDlgClickListener{ void onClick(Dialog dialog); } public void setNegativeButton(String text, OnZyAlertDlgClickListener listener){ mNegativeMessage = text; mShowNegativeBtn = true; mNegativeListener = listener; } public void setNegativeButton(int textId, OnZyAlertDlgClickListener listener){ String text = mContext.getString(textId); setNegativeButton(text, listener); } public void setPositiveButton(String text, OnZyAlertDlgClickListener listener){ mPositiveMessage = text; mShowPositiveBtn = true; mPositiveListener = listener; } public void setPositiveButton(int textId, OnZyAlertDlgClickListener listener){ String text = mContext.getString(textId); setPositiveButton(text, listener); } public void setNeutralButton(String text, OnZyAlertDlgClickListener listener){ mNeutralMessage = text; mShowNeutralBtn = true; mNeutralListener = listener; } public void setNeutralButton(int textId, OnZyAlertDlgClickListener listener){ String text = mContext.getString(textId); setPositiveButton(text, listener); } } <file_sep>package com.zhaoyan.juyou.common; import java.io.File; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.Settings; import com.zhaoyan.common.util.Log; import com.zhaoyan.juyou.provider.AppData; public class AppManager { private static final String TAG = "AppManager"; public static final int NORMAL_APP = 0; public static final int GAME_APP = 1; public static final int ZHAOYAN_APP = 2; public static final int ERROR_APP = -1; public static final String ACTION_REFRESH_APP = "intent.aciton.refresh.app"; public static final String ACTION_SEND_TO_APP = "intent.aciton.send.to.app"; public static final String ACTION_ADD_MYGAME = "intent.cation.add.mygame"; public static final String ACTION_REMOVE_MYGAME = "intent.action.remove.mygame"; public static final String ACTION_SEND_TO_GAME = "intent.aciton.send.to.game"; public static final String NORMAL_APP_SIZE = "normal_app_size"; public static final String GAME_APP_SIZE = "game_app_size"; public static final String EXTRA_INFO = "info"; public static final int NORMAL_APP_MENU = 0x00; public static final int GAME_APP_MENU_XX = 0x01; public static final int GAME_APP_MENU_MY = 0x02; public static int menu_type = -1; public static final int MENU_INFO = 0x10; public static final int MENU_SHARE = 0x11; public static final int MENU_UNINSTALL = 0x12; public static final int MENU_MOVE = 0x13; public static List<ApplicationInfo> getAllApps(PackageManager pm) { List<ApplicationInfo> allApps = pm.getInstalledApplications(0); return allApps; } /** * accord package name to get is game app from game db * @param pkgName package name * @return true,is game app </br>false, is normal app */ public static boolean isGameApp(Context context, String pkgName){ String selectionString = AppData.App.PKG_NAME + "=?" ; String args[] = {pkgName}; boolean ret = false; Cursor cursor = context.getContentResolver().query(AppData.AppGame.CONTENT_URI, null, selectionString, args, null); if (cursor.getCount() <= 0) { ret = false; }else { ret = true; } cursor.close(); return ret; } public static boolean isMyApp(Context context, String packageName, PackageManager pm){ //get we app Intent appIntent = new Intent(ZYConstant.APP_ACTION); appIntent.addCategory(Intent.CATEGORY_DEFAULT); // 通过查询,获得所有ResolveInfo对象. List<ResolveInfo> resolveInfos = pm.queryIntentActivities(appIntent, 0); for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.packageName; // 获得应用程序的包名 if (packageName.equals(pkgName)) { return true; } } return false; } public static ContentValues getValuesByAppInfo(AppInfo appInfo){ ContentValues values = new ContentValues(); values.put(AppData.App.PKG_NAME, appInfo.getPackageName()); values.put(AppData.App.LABEL, appInfo.getLabel()); values.put(AppData.App.VERSION, appInfo.getVersion()); values.put(AppData.App.APP_SIZE, appInfo.getAppSize()); values.put(AppData.App.DATE, appInfo.getDate()); values.put(AppData.App.TYPE, appInfo.getType()); values.put(AppData.App.ICON, appInfo.getIconBlob()); values.put(AppData.App.PATH, appInfo.getInstallPath()); return values; } /** * accord package name to get the app entry and position * @param packageName * @return int[0]:(0,normal app;1:game app) * </br> * int[1]:(the position in the list) */ public static int[] getAppInfo(String packageName, List<AppInfo> normalAppList, List<AppInfo> gameAppList, List<AppInfo> myAppList){ int[] result = new int[2]; for (int i = 0; i < normalAppList.size(); i++) { AppInfo appInfo = normalAppList.get(i); if (packageName.equals(appInfo.getPackageName())) { //is normal app result[0] = AppManager.NORMAL_APP; result[1] = i; return result; } } for (int i = 0; i < gameAppList.size(); i++) { AppInfo appInfo = gameAppList.get(i); if (packageName.equals(appInfo.getPackageName())) { //is game app result[0] = AppManager.GAME_APP; result[1] = i; return result; } } for (int i = 0; i < myAppList.size(); i++) { AppInfo appInfo = myAppList.get(i); if (packageName.equals(appInfo.getPackageName())) { //is my app result[0] = AppManager.ZHAOYAN_APP; result[1] = i; return result; } } return null; } /**return the position according to packagename*/ public static int getAppPosition(String packageName, List<AppInfo> list){ for (int i = 0; i < list.size(); i++) { AppInfo appInfo = list.get(i); if (packageName.equals(appInfo.getPackageName())) { return i; } } return -1; } public static void installApk(Context context, String apkFilePath) { if (apkFilePath.endsWith(".apk")) { installApk(context, new File(apkFilePath)); } } public static void installApk(Context context, File file) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); Uri uri = Uri.fromFile(file); intent.setDataAndType(uri, "application/vnd.android.package-archive"); context.startActivity(intent); } public static void uninstallApp(Context context, String packageName){ Uri packageUri = Uri.parse("package:" + packageName); Intent deleteIntent = new Intent(); deleteIntent.setAction(Intent.ACTION_DELETE); deleteIntent.setData(packageUri); context.startActivity(deleteIntent); } public static String getAppLabel(String packageName, PackageManager pm){ ApplicationInfo applicationInfo = null; try { applicationInfo = pm.getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { Log.e(TAG, "getAppLabel.name not found:" + packageName); Log.e(TAG, e.toString()); return null; } return applicationInfo.loadLabel(pm).toString(); } public static String getAppVersion(String packageName, PackageManager pm){ String version = ""; try { version = pm.getPackageInfo(packageName, 0).versionName; } catch (NameNotFoundException e) { Log.e(TAG, "getAppVersion.name not found:" + packageName); e.printStackTrace(); } return version; } public static String getAppSourceDir(String packageName, PackageManager pm){ ApplicationInfo applicationInfo = null; try { applicationInfo = pm.getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { Log.e(TAG, "getAppSourceDir:" + packageName + " name not found."); e.printStackTrace(); } return applicationInfo.sourceDir; } } <file_sep>package com.zhaoyan.communication; import java.util.Vector; import com.zhaoyan.common.util.Log; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class ScreenMonitor extends Service { private static final String TAG = "ScreenMonitorService"; private SocketCommunicationManager mCommunicationManager; private ScreenMonitorBroadcastReceiver mReceiver; @Override public void onCreate() { super.onCreate(); mCommunicationManager = SocketCommunicationManager.getInstance(); mReceiver = new ScreenMonitorBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_SCREEN_ON); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(mReceiver, intentFilter); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } @Override public IBinder onBind(Intent intent) { return null; } private class ScreenMonitorBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_SCREEN_ON.equals(action)) { Log.d(TAG, "ACTION_SCREEN_ON"); Vector<SocketCommunication> communications = mCommunicationManager .getCommunications(); for (SocketCommunication communication : communications) { communication.setScreenOn(); } } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { Log.d(TAG, "ACTION_SCREEN_OFF"); Vector<SocketCommunication> communications = mCommunicationManager .getCommunications(); for (SocketCommunication communication : communications) { communication.setScreenOff(); } } } } } <file_sep>package com.zhaoyan.communication.search; import java.net.InetAddress; import java.net.UnknownHostException; import com.dreamlink.communication.lib.util.ArrayUtil; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.ArraysCompat; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.UserManager; public class SearchProtocol { private static final String TAG = "SearchProtocol"; public interface OnSearchListener { /** * Search server success and found a server</br> * * Be careful:</br> * * This method is not in activity main thread.</br> * * @param serverIP * The server IP address. */ void onSearchSuccess(String serverIP, String name); void onSearchSuccess(ServerInfo serverInfo); /** * Search server stop</br> * * Be careful:</br> * * This method is not in activity main thread.</br> * */ void onSearchStop(); } // [4 bytes ][4 bytes][n bytes ] // [server ip][server name size][server name] public static final int IP_ADDRESS_HEADER_SIZE = 4; public static final int SERVER_NAME_HEADER_SIZE = 4; /** * Search packet protocol:</br> * * [server ip][server name size][server name] * * @return */ public static byte[] encodeSearchLan() { byte[] localIPAddresss = NetWorkUtil.getLocalIpAddressBytes(); byte[] localUserName = UserManager.getInstance().getLocalUser() .getUserName().getBytes(); byte[] localUserNameSize = ArrayUtil .int2ByteArray(localUserName.length); byte[] searchMessage = ArrayUtil.join(localIPAddresss, localUserNameSize, localUserName); return searchMessage; } /** * see {@link #encodeSearchLan()} * * @param data * @throws UnknownHostException */ public static void decodeSearchLan(byte[] data, OnSearchListener listener) throws UnknownHostException { if (data.length < SearchProtocol.IP_ADDRESS_HEADER_SIZE + SearchProtocol.SERVER_NAME_HEADER_SIZE) { // Data format error. Log.e(TAG, "GetMulticastPacket, Data format error, received data length = " + data.length); return; } // server ip. int start = 0; int end = SearchProtocol.IP_ADDRESS_HEADER_SIZE; byte[] serverIpData = ArraysCompat.copyOfRange(data, start, end); String serverIP = InetAddress.getByAddress(serverIpData) .getHostAddress(); // server name size. start = end; end += SearchProtocol.SERVER_NAME_HEADER_SIZE; byte[] serveraNameSizeData = ArraysCompat.copyOfRange(data, start, end); int serverNameSize = ArrayUtil.byteArray2Int(serveraNameSizeData); // server name. if (serverNameSize < 0 || data.length < SearchProtocol.IP_ADDRESS_HEADER_SIZE + SearchProtocol.SERVER_NAME_HEADER_SIZE + serverNameSize) { // Data format error. Log.e(TAG, "GetMulticastPacket, Data format error, received data length = " + data.length + ", server name length = " + serverNameSize); start = 0; end = 16; serverIpData = ArraysCompat.copyOfRange(data, start, end); serverIP = ""; serverIP = InetAddress.getByAddress(serverIpData).getHostAddress(); // server name size. start = end; end += SearchProtocol.SERVER_NAME_HEADER_SIZE; serveraNameSizeData = ArraysCompat.copyOfRange(data, start, end); serverNameSize = ArrayUtil.byteArray2Int(serveraNameSizeData); Log.e("ArbiterLiu", serverNameSize + ""); if (serverNameSize < 0 || data.length < SearchProtocol.IP_ADDRESS_HEADER_SIZE + SearchProtocol.SERVER_NAME_HEADER_SIZE + serverNameSize) { // Data format error. Log.e(TAG, "GetMulticastPacket, Data format error, received data length = " + data.length + ", server name length = " + serverNameSize); return; } } start = end; end += serverNameSize; byte[] serverNameData = ArraysCompat.copyOfRange(data, start, end); String serverName = new String(serverNameData); Log.d(TAG, "Found server ip = " + serverIP + ", name = " + serverName); if (serverIP.equals(NetWorkUtil.getLocalIpAddress())) { // ignore. } else { // Got another server. because client will not broadcast // message. if (listener != null) { listener.onSearchSuccess(serverIP, serverName); } } } } <file_sep>package com.zhaoyan.common.view; import java.util.ArrayList; import com.zhaoyan.juyou.R; import android.content.Context; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; public class TableTitleView extends LinearLayout implements OnClickListener { private Context mContext; private ArrayList<TextView> mTableTitles = new ArrayList<TextView>(); private LinearLayout mTabHost; private ImageView mCursorImageView; private int mLastSelectPostion; private OnTableSelectChangeListener mListener; public TableTitleView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; setOrientation(VERTICAL); } public TableTitleView(Context context) { super(context); mContext = context; setOrientation(VERTICAL); } public void initTitles(String[] tableTitles) { LayoutParams tableHostParams = new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mTabHost = new LinearLayout(mContext); mTabHost.setOrientation(LinearLayout.HORIZONTAL); addView(mTabHost, tableHostParams); LayoutParams tableTitleParams = new LayoutParams(0, LayoutParams.MATCH_PARENT); tableTitleParams.weight = 1; tableTitleParams.gravity = Gravity.CENTER; TextView tableTitleTextView; final int paddingTop = ViewUtil.dp2px(mContext, 20); final int paddingBottom = paddingTop; for (String title : tableTitles) { tableTitleTextView = new TextView(mContext); tableTitleTextView.setText(title); tableTitleTextView.setTextSize(12); tableTitleTextView.setTextColor(mContext.getResources().getColor( R.color.table_title_unselected)); tableTitleTextView.setGravity(Gravity.CENTER); tableTitleTextView.setPadding(0, paddingTop, 0, paddingBottom); tableTitleTextView.setClickable(true); tableTitleTextView.setOnClickListener(this); mTableTitles.add(tableTitleTextView); mTabHost.addView(tableTitleTextView, tableTitleParams); } if (mTableTitles.size() > 0) { mTableTitles.get(0).setTextColor( mContext.getResources().getColor( R.color.table_title_selected)); } LinearLayout cursorLinearLayout = new LinearLayout(mContext); cursorLinearLayout.setOrientation(LinearLayout.HORIZONTAL); LayoutParams cursorParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); addView(cursorLinearLayout, cursorParams); mCursorImageView = new ImageView(mContext); mCursorImageView.setImageResource(R.drawable.table_title_cursor); mCursorImageView.setScaleType(ScaleType.FIT_XY); View cursorBlankView = new View(mContext); cursorParams = new LayoutParams(0, LayoutParams.WRAP_CONTENT); cursorParams.weight = 1; cursorLinearLayout.addView(mCursorImageView, cursorParams); cursorParams = new LayoutParams(0, 0); cursorParams.weight = tableTitles.length - 1; cursorLinearLayout.addView(cursorBlankView, cursorParams); View bottomLineView = new View(mContext); LayoutParams bottomLineParams = new LayoutParams( LayoutParams.MATCH_PARENT, 2); bottomLineView.setBackgroundColor(mContext.getResources().getColor( R.color.table_title_selected)); addView(bottomLineView, bottomLineParams); } public void setSelectedPostion(int position) { if (position != mLastSelectPostion) { if (position >= mTableTitles.size()) { position = mTableTitles.size() - 1; } setCurrentItem(position); } } public String getTableTitle(int position) { return mTableTitles.get(position).getText().toString(); } public void setTableTitle(int position, String title) { mTableTitles.get(position).setText(title); } @Override public void onClick(View v) { for (int i = 0; i < mTableTitles.size(); i++) { if (v == mTableTitles.get(i)) { if (mLastSelectPostion != i) { setCurrentItem(i); if (mListener != null) { mListener.onTableSelect(i); } } } } } private void setCurrentItem(int position) { float animStart = (float) mLastSelectPostion / mTabHost.getChildCount(); float animEnd = (float) position / mTabHost.getChildCount(); TranslateAnimation translateAnimation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, animStart, Animation.RELATIVE_TO_PARENT, animEnd, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0); translateAnimation.setFillAfter(true); translateAnimation.setDuration(300); mCursorImageView.startAnimation(translateAnimation); mTableTitles.get(position).setTextColor( mContext.getResources().getColor(R.color.table_title_selected)); mTableTitles.get(mLastSelectPostion).setTextColor( mContext.getResources() .getColor(R.color.table_title_unselected)); mLastSelectPostion = position; } public void setOnTableSelectChangeListener( OnTableSelectChangeListener listener) { mListener = listener; } public interface OnTableSelectChangeListener { void onTableSelect(int position); } } <file_sep>package com.zhaoyan.juyou.fragment; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.ProtocolCommunication; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.connect.ServerCreator; import com.zhaoyan.communication.search.SearchUtil; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.adapter.ConnectedUserAdapter; import com.zhaoyan.juyou.provider.JuyouData; public class ConnectedInfoFragment extends ListFragment implements OnClickListener, LoaderCallbacks<Cursor> { private static final String TAG = "ConnectedInfoFragment"; private Button mDisconnectButton; private Context mContext; private ServerCreator mServerCreator; private ListView mListView; private ConnectedUserAdapter mAdapter; protected static final String[] PROJECTION = { JuyouData.User._ID, JuyouData.User.USER_NAME, JuyouData.User.USER_ID, JuyouData.User.HEAD_ID, JuyouData.User.THIRD_LOGIN, JuyouData.User.HEAD_DATA, JuyouData.User.IP_ADDR, JuyouData.User.STATUS, JuyouData.User.TYPE, JuyouData.User.SSID, JuyouData.User.SIGNATURE }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView"); mContext = getActivity(); mServerCreator = ServerCreator.getInstance(mContext); View rootView = inflater.inflate(R.layout.connected_info, container, false); initView(rootView); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mListView = getListView(); mAdapter = new ConnectedUserAdapter(mContext, null, true); mListView.setAdapter(mAdapter); getLoaderManager().initLoader(0, null, this); } @Override public void onDestroyView() { Log.d(TAG, "onDestroyView"); super.onDestroyView(); mAdapter.swapCursor(null); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { String selection = JuyouData.User.STATUS + "=" + JuyouData.User.STATUS_SERVER_CREATED + " or " + JuyouData.User.STATUS + "=" + JuyouData.User.STATUS_CONNECTED; return new CursorLoader(mContext, JuyouData.User.CONTENT_URI, PROJECTION, selection, null, JuyouData.User.SORT_ORDER_DEFAULT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_ci_disconnect: disconnect(); break; default: break; } } private void initView(View rootView) { mDisconnectButton = (Button) rootView .findViewById(R.id.btn_ci_disconnect); mDisconnectButton.setOnClickListener(this); } private void disconnect() { ProtocolCommunication protocolCommunication = ProtocolCommunication .getInstance(); protocolCommunication.logout(); // Stop search if this is server. // Stop all communication if this is client. if (mServerCreator.isCreated()) { mServerCreator.stopServer(); } else { SocketCommunicationManager manager = SocketCommunicationManager .getInstance(); manager.closeAllCommunication(); } // close WiFi AP if WiFi AP is enabled. if (NetWorkUtil.isWifiApEnabled(mContext)) { NetWorkUtil.setWifiAPEnabled(mContext, null, false); } // disconnect current network if connected to the WiFi AP created by // our application. SearchUtil.clearWifiConnectHistory(mContext); } } <file_sep>package com.zhaoyan.juyou.common; import java.util.HashMap; import android.content.Context; import android.widget.ImageView; import com.zhaoyan.common.file.FileManager; import com.zhaoyan.common.util.Log; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.common.FileCategoryHelper.FileCategory; import com.zhaoyan.juyou.common.FileIconLoader.IconLoadFinishListener; public class FileIconHelper implements IconLoadFinishListener { private static final String TAG = "FileIconHelper"; private static HashMap<String, Integer> fileExtToIcons = new HashMap<String, Integer>(); private FileIconLoader mIconLoader; static { addItem(FileCategoryHelper.AUDIO_EXTS, R.drawable.icon_audio); addItem(FileCategoryHelper.VIDEO_EXTS, R.drawable.icon_video); addItem(FileCategoryHelper.IMAGE_EXTS, R.drawable.icon_image); addItem(FileCategoryHelper.EBOOK_EXTS, R.drawable.icon_txt); addItem(FileCategoryHelper.WORD_EXTS, R.drawable.icon_doc); addItem(FileCategoryHelper.PPT_EXTS, R.drawable.icon_ppt); addItem(FileCategoryHelper.EXCEL_EXTS, R.drawable.icon_xls); addItem(FileCategoryHelper.APK_EXTS, R.drawable.icon_apk); addItem(FileCategoryHelper.ARCHIVE_EXTS, R.drawable.icon_rar); addItem(FileCategoryHelper.PDF_EXTS, R.drawable.icon_pdf); } public FileIconHelper(Context context) { mIconLoader = new FileIconLoader(context, this); } private static void addItem(String[] exts, int resId) { if (exts != null) { for (String ext : exts) { fileExtToIcons.put(ext.toLowerCase(), resId); } } } public static int getFileIcon(String ext) { Integer i = fileExtToIcons.get(ext.toLowerCase()); if (i != null) { return i.intValue(); } else { return R.drawable.icon_file; } } public void setIcon(FileInfo fileInfo, ImageView fileImage) { String filePath = fileInfo.filePath; String ext = FileManager.getExtFromFilename(fileInfo.fileName); FileCategory fc = FileCategoryHelper.getCategoryByName(fileInfo.fileName); boolean set = false; int id = getFileIcon(ext); fileImage.setImageResource(id); mIconLoader.cancelRequest(fileImage); switch (fc) { case Apk: set = mIconLoader.loadIcon(fileImage, filePath, fc); if (!set) { fileImage.setImageResource(R.drawable.icon_apk); set = true; } break; case Image: case Video: set = mIconLoader.loadIcon(fileImage, filePath, fc); if (!set){ fileImage.setImageResource(fc == FileCategory.Image ? R.drawable.icon_image : R.drawable.icon_video); set = true; } break; default: set = true; break; } if (!set) fileImage.setImageResource(R.drawable.icon_file); } @Override public void onIconLoadFinished(ImageView view) { Log.d(TAG, "onIconLoadFinished"); } public void stopLoader(){ mIconLoader.cancelAllRequest(); } } <file_sep>package com.zhaoyan.juyou.activity; import java.lang.ref.WeakReference; import android.annotation.SuppressLint; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.dreamlink.communication.lib.util.Notice; import com.zhaoyan.common.util.Log; import com.zhaoyan.common.util.ZYUtils; import com.zhaoyan.communication.FileTransferService; import com.zhaoyan.juyou.R; import com.zhaoyan.juyou.adapter.HistoryCursorAdapter; import com.zhaoyan.juyou.provider.JuyouData; public class HistoryActivity extends BaseActivity implements OnScrollListener, OnItemClickListener { private static final String TAG = "HistoryActivityTest"; private Context mContext; // view private TextView mStorageTV; private ListView mHistoryMsgLV; private ProgressBar mLoadingBar; // adapter private HistoryCursorAdapter mAdapter; private HistoryContent mHistoryContent = null; private Notice mNotice; // msg private static final int MSG_UPDATE_UI = 1; private QueryHandler queryHandler = null; private static final int HISTORY_QUERY_TOKEN = 11; private static final String[] PROJECTION = { JuyouData.History._ID, JuyouData.History.FILE_PATH, JuyouData.History.FILE_NAME, JuyouData.History.FILE_SIZE, JuyouData.History.SEND_USERNAME, JuyouData.History.RECEIVE_USERNAME, JuyouData.History.PROGRESS, JuyouData.History.DATE, JuyouData.History.STATUS, JuyouData.History.MSG_TYPE, JuyouData.History.FILE_TYPE, JuyouData.History.FILE_ICON, JuyouData.History.SEND_USER_HEADID, JuyouData.History.SEND_USER_ICON}; private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_UPDATE_UI: int num = msg.arg1; updateTitleNum(-1, num); break; default: break; } }; }; class HistoryContent extends ContentObserver { public HistoryContent(Handler handler) { super(handler); // TODO Auto-generated constructor stub } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); int count = mAdapter.getCount(); updateUI(count); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.history_main); mContext = this; mNotice = new Notice(getApplicationContext()); initTitle(R.string.history); mTitleNumView.setVisibility(View.VISIBLE); initView(); queryHandler = new QueryHandler(getApplicationContext().getContentResolver(), this); mHistoryContent = new HistoryContent(new Handler()); getApplicationContext().getContentResolver().registerContentObserver( JuyouData.History.CONTENT_URI, true, mHistoryContent); } @Override protected void onResume() { super.onResume(); query(); //notify hide badgeview Intent intent = new Intent( FileTransferService.ACTION_NOTIFY_SEND_OR_RECEIVE); intent.putExtra(FileTransferService.EXTRA_BADGEVIEW_SHOW, false); sendBroadcast(intent); } @Override protected void onDestroy() { if (mAdapter != null && mAdapter.getCursor() != null) { mAdapter.getCursor().close(); mAdapter.swapCursor(null); } if (mHistoryContent != null) { getApplicationContext().getContentResolver().unregisterContentObserver(mHistoryContent); mHistoryContent = null; } if (queryHandler != null) { queryHandler.cancelOperation(HISTORY_QUERY_TOKEN); queryHandler = null; } super.onDestroy(); } public void query() { // String selection = JuyouData.History.STATUS + "!=?"; // String[] selectionArgs = {HistoryManager.STATUS_PRE_SEND +""}; // queryHandler.startQuery(HISTORY_QUERY_TOKEN, null, JuyouData.History.CONTENT_URI, // PROJECTION, selection, selectionArgs, JuyouData.History.SORT_ORDER_DEFAULT); queryHandler.startQuery(HISTORY_QUERY_TOKEN, null, JuyouData.History.CONTENT_URI, PROJECTION, null, null, JuyouData.History.SORT_ORDER_DEFAULT); } @SuppressLint("NewApi") private void initView() { mStorageTV = (TextView) findViewById(R.id.tv_storage); String space = getResources().getString( R.string.storage_space, ZYUtils.getFormatSize(Environment.getExternalStorageDirectory() .getTotalSpace()), ZYUtils.getFormatSize(Environment.getExternalStorageDirectory() .getFreeSpace())); mStorageTV.setText(space); mLoadingBar = (ProgressBar) findViewById(R.id.pb_history_loading); mHistoryMsgLV = (ListView) findViewById(R.id.lv_history_msg); mHistoryMsgLV.setOnScrollListener(this); mHistoryMsgLV.setOnItemClickListener(this); mAdapter = new HistoryCursorAdapter(mContext, mHistoryMsgLV); mHistoryMsgLV.setAdapter(mAdapter); mHistoryMsgLV.setSelection(0); } // query db private static class QueryHandler extends AsyncQueryHandler { WeakReference<HistoryActivity> mActivity; public QueryHandler(ContentResolver cr, HistoryActivity activity) { super(cr); mActivity = new WeakReference<HistoryActivity>(activity); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { Log.d(TAG, "onQueryComplete"); HistoryActivity historyActivity = mActivity.get(); historyActivity.mLoadingBar.setVisibility(View.INVISIBLE); int num = 0; if (null != cursor) { Log.d(TAG, "onQueryComplete.count=" + cursor.getCount()); historyActivity.mAdapter.swapCursor(cursor); num = cursor.getCount(); } historyActivity.updateUI(num); } } private void updateUI(int num) { Message message = mHandler.obtainMessage(); message.arg1 = num; message.what = MSG_UPDATE_UI; message.sendToTarget(); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mNotice.showToast(position + "" + ",view = " + view); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_FLING: mAdapter.setIdleFlag(false); break; case OnScrollListener.SCROLL_STATE_IDLE: mAdapter.setIdleFlag(true); mAdapter.notifyDataSetChanged(); break; case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: mAdapter.setIdleFlag(false); break; default: break; } } } <file_sep>package com.zhaoyan.communication.protocol; import java.util.Arrays; import com.dreamlink.communication.lib.util.ArrayUtil; public class FileTransportProtocol { public static byte[] encodeSendFile(int sendUserID, int receiveUserID, int appID, byte[] inetAddressData, int serverPort, FileTransferInfo fileInfo) { byte[] result = null; byte[] headData = ArrayUtil .int2ByteArray(Protocol.DATA_TYPE_HEADER_SEND_FILE); byte[] sendUserData = ArrayUtil.int2ByteArray(sendUserID); byte[] receiveUserData = ArrayUtil.int2ByteArray(receiveUserID); byte[] appIDData = ArrayUtil.int2ByteArray(appID); byte[] serverPortData = ArrayUtil.int2ByteArray(serverPort); byte[] fileInfoData = ArrayUtil.objectToByteArray(fileInfo); result = ArrayUtil.join(headData, sendUserData, receiveUserData, appIDData, inetAddressData, serverPortData, fileInfoData); return result; } public static void decodeSendFile(byte[] data, OnReceiveFileCallback callback) { int start = 0; int end = Protocol.SEND_USER_ID_HEADER_SIZE; // get send user ID. byte[] sendUserIDData = Arrays.copyOfRange(data, start, end); int sendUserID = ArrayUtil.byteArray2Int(sendUserIDData); // get receive user ID. start = end; end += Protocol.SEND_USER_ID_HEADER_SIZE; byte[] receiveUserIDData = Arrays.copyOfRange(data, start, end); int receiveUserID = ArrayUtil.byteArray2Int(receiveUserIDData); // get appID. start = end; end += Protocol.SEND_APP_ID_HEADER_SIZE; byte[] appIDData = Arrays.copyOfRange(data, start, end); int appID = ArrayUtil.byteArray2Int(appIDData); // get server address start = end; end += Protocol.SEND_FILE_SERVER_ADDRESS_HEAD_SIZE; byte[] serverAddress = Arrays.copyOfRange(data, start, end); // get server port. start = end; end += Protocol.SEND_FILE_SERVER_PORT_HEAD_SIZE; byte[] serverPortData = Arrays.copyOfRange(data, start, end); int serverPort = ArrayUtil.byteArray2Int(serverPortData); // get file info. start = end; end = data.length; byte[] fileInfoData = Arrays.copyOfRange(data, start, end); FileTransferInfo fileInfo = (FileTransferInfo) ArrayUtil .byteArrayToObject(fileInfoData); if (callback != null) { callback.onReceiveFile(sendUserID, receiveUserID, appID, serverAddress, serverPort, fileInfo); } } /** * This interface is used by {@code ProtocolDecoder}. * */ public interface OnReceiveFileCallback { /** * Received a file which is sent by the user with id of sendUserID. * * @param sendUserID * @param receiveUserID * @param appID * @param serverAddress * @param serverPort * @param fileInfo */ void onReceiveFile(int sendUserID, int receiveUserID, int appID, byte[] serverAddress, int serverPort, FileTransferInfo fileInfo); } } <file_sep>package com.zhaoyan.juyou.common; import java.text.NumberFormat; import java.util.Comparator; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import com.zhaoyan.common.util.Log; import com.zhaoyan.juyou.provider.JuyouData; public class HistoryManager { //status public static final int STATUS_DEFAULT = 0; public static final int STATUS_PRE_SEND = 10; public static final int STATUS_SENDING = 11; public static final int STATUS_SEND_SUCCESS = 12; public static final int STATUS_SEND_FAIL = 13; public static final int STATUS_PRE_RECEIVE = 21; public static final int STATUS_RECEIVING = 22; public static final int STATUS_RECEIVE_SUCCESS = 23; public static final int STATUS_RECEIVE_FAIL = 24; public static final String HISTORY_URI = "history_uri"; public static final NumberFormat nf = NumberFormat.getPercentInstance(); public static final int TYPE_SEND = 0; public static final int TYPE_RECEIVE = 1; public static final String ME = "ME"; private Context mContext; public Comparator<HistoryInfo> getDateComparator() { return new DateComparator(); } /** * Perform alphabetical comparison of application entry objects. */ public static class DateComparator implements Comparator<HistoryInfo> { @Override public int compare(HistoryInfo object1, HistoryInfo object2) { long date1 = object1.getDate(); long date2 = object2.getDate(); if (date1 > date2) { return -1; } else if (date1 == date2) { return 0; } else { return 1; } } }; public HistoryManager(Context context){ mContext = context; } public synchronized void insertToDb(HistoryInfo historyInfo){ InsertThread insertThread = new InsertThread(historyInfo); insertThread.start(); } public void deleteItemFromDb(int id){ Uri uri = Uri.parse(JuyouData.History.CONTENT_URI + "/" + id); mContext.getContentResolver().delete(uri, null, null); } class InsertThread extends Thread{ HistoryInfo historyInfo = null; InsertThread(HistoryInfo historyInfo){ this.historyInfo = historyInfo; } @Override public void run() { ContentValues values = new ContentValues(); values.put(JuyouData.History.FILE_PATH, historyInfo.getFile().getAbsolutePath()); values.put(JuyouData.History.FILE_NAME, historyInfo.getFile().getName()); values.put(JuyouData.History.FILE_SIZE, historyInfo.getFile().length()); values.put(JuyouData.History.SEND_USERNAME, historyInfo.getSendUserName()); values.put(JuyouData.History.RECEIVE_USERNAME, historyInfo.getReceiveUser().getUserName()); values.put(JuyouData.History.PROGRESS, historyInfo.getProgress()); values.put(JuyouData.History.DATE, historyInfo.getDate()); values.put(JuyouData.History.STATUS, historyInfo.getStatus()); values.put(JuyouData.History.MSG_TYPE, historyInfo.getMsgType()); mContext.getContentResolver().insert(JuyouData.History.CONTENT_URI, values); } } public ContentValues getInsertValues(HistoryInfo historyInfo){ ContentValues values = new ContentValues(); values.put(JuyouData.History.FILE_PATH, historyInfo.getFile().getAbsolutePath()); values.put(JuyouData.History.FILE_NAME, historyInfo.getFile().getName()); values.put(JuyouData.History.FILE_SIZE, historyInfo.getFileSize()); values.put(JuyouData.History.SEND_USERNAME, historyInfo.getSendUserName()); values.put(JuyouData.History.RECEIVE_USERNAME, historyInfo.getReceiveUser().getUserName()); values.put(JuyouData.History.PROGRESS, historyInfo.getProgress()); values.put(JuyouData.History.DATE, historyInfo.getDate()); values.put(JuyouData.History.STATUS, historyInfo.getStatus()); values.put(JuyouData.History.MSG_TYPE, historyInfo.getMsgType()); values.put(JuyouData.History.FILE_TYPE, historyInfo.getFileType()); values.put(JuyouData.History.FILE_ICON, historyInfo.getIcon()); values.put(JuyouData.History.SEND_USER_HEADID, historyInfo.getSendUserHeadId()); values.put(JuyouData.History.SEND_USER_ICON, historyInfo.getSendUserIcon()); return values; } /** * when app finish,modfiy all pre(pre_send/pre_receive) status to fail * status that file transfer history in history stable */ public static void modifyHistoryDb(Context context) { try { ContentValues values = new ContentValues(); // 更新两次,第一次将pre_send,改为send_fail values.put(JuyouData.History.STATUS, HistoryManager.STATUS_SEND_FAIL); String where = JuyouData.History.STATUS + "=" + HistoryManager.STATUS_PRE_SEND + " or " + JuyouData.History.STATUS + "=" + HistoryManager.STATUS_SENDING; context.getContentResolver().update( JuyouData.History.CONTENT_URI, values, where, null); // 第二次,将pre_receive,改为receive_fail values.put(JuyouData.History.STATUS, HistoryManager.STATUS_RECEIVE_FAIL); where = JuyouData.History.STATUS + "=" + HistoryManager.STATUS_PRE_RECEIVE + " or " + JuyouData.History.STATUS + "=" + HistoryManager.STATUS_RECEIVING; context.getContentResolver().update( JuyouData.History.CONTENT_URI, values, where , null); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.zhaoyan.juyou; import android.app.Application; import android.content.Context; import android.content.Intent; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.zhaoyan.common.net.NetWorkUtil; import com.zhaoyan.common.util.Log; import com.zhaoyan.communication.FileTransferService; import com.zhaoyan.communication.ProtocolCommunication; import com.zhaoyan.communication.SocketCommunicationManager; import com.zhaoyan.communication.TrafficStatics; import com.zhaoyan.communication.UserManager; import com.zhaoyan.communication.connect.ServerConnector; import com.zhaoyan.communication.connect.ServerCreator; import com.zhaoyan.communication.search.SearchUtil; import com.zhaoyan.communication.search.ServerSearcher; public class JuYouApplication extends Application { private static final String TAG = "JuYouApplication"; private static boolean mIsInit = false; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); initApplication(getApplicationContext()); } /** * Notice, call this not only in application's {@link #onCreate()}, but also * in the first activity's onCreate(). Because application's * {@link #onCreate()} will not be call every time when we launch first * activity. * * @param context */ public static synchronized void initApplication(Context context) { if (mIsInit) { return; } Log.d(TAG, "initApplication"); mIsInit = true; initImageLoader(context); // Start save log to file. Log.startSaveToFile(); // Initialize TrafficStatics TrafficStatics.getInstance().init(context); // Initialize SocketCommunicationManager SocketCommunicationManager.getInstance().init(context); // Initialize ProtocolCommunication ProtocolCommunication.getInstance().init(context); } public static synchronized void quitApplication(Context context) { if (!mIsInit) { return; } Log.d(TAG, "quitApplication"); mIsInit = false; logout(context); stopServerSearch(context); stopServerCreator(context); stopCommunication(context); stopFileTransferService(context); // Release ProtocolCommunication ProtocolCommunication.getInstance().release(); // Release SocketCommunicationManager SocketCommunicationManager.getInstance().release(); // Release TrafficStatics TrafficStatics.getInstance().quit(); // Logout account logoutAccount(context); // Stop record log and close log file. Log.stopAndSave(); releaseStaticInstance(context); } private static void logoutAccount(Context context) { AccountHelper.logoutCurrentAccount(context); } private static void logout(Context context) { ProtocolCommunication protocolCommunication = ProtocolCommunication .getInstance(); protocolCommunication.logout(); } private static void releaseStaticInstance(Context context) { ServerConnector serverConnector = ServerConnector.getInstance(context); serverConnector.release(); } private static void stopServerCreator(Context context) { ServerCreator serverCreator = ServerCreator.getInstance(context); serverCreator.stopServer(); serverCreator.release(); } private static void stopServerSearch(Context context) { ServerSearcher serverSearcher = ServerSearcher.getInstance(context); serverSearcher.stopSearch(ServerSearcher.SERVER_TYPE_ALL); serverSearcher.release(); } private static void stopFileTransferService(Context context) { Intent intent = new Intent(); intent.setClass(context, FileTransferService.class); context.stopService(intent); } private static void stopCommunication(Context context) { UserManager.getInstance().resetLocalUser(); SocketCommunicationManager manager = SocketCommunicationManager .getInstance(); manager.closeAllCommunication(); manager.stopServer(); // Disable wifi AP. NetWorkUtil.setWifiAPEnabled(context, null, false); // Clear wifi connect history. SearchUtil.clearWifiConnectHistory(context); } public static void initImageLoader(Context context) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( context).threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) .tasksProcessingOrder(QueueProcessingType.LIFO) .writeDebugLogs() // remove it when release app .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } }
6aa0d889ebf29d81998fec87f767345965b3d0f2
[ "Markdown", "Java" ]
78
Java
liangxiaofei1100/ZhaoYanJuYou
57e80e477c687d422cc8558d2d1d7f13665277fd
de57c05180c20fb3e91719a0d7ac581242ab33c1
refs/heads/master
<file_sep>/* Copyright 2017 Vector Creations Ltd 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. */ 'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var classNames = require('classnames'); var sdk = require('matrix-react-sdk'); var FormattingUtils = require('matrix-react-sdk/lib/utils/FormattingUtils'); var RoomNotifs = require('matrix-react-sdk/lib/RoomNotifs'); var AccessibleButton = require('matrix-react-sdk/lib/components/views/elements/AccessibleButton'); module.exports = React.createClass({ displayName: 'RoomSubListHeader', propTypes: { label: React.PropTypes.string.isRequired, tagName: React.PropTypes.string, roomCount: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), collapsed: React.PropTypes.bool.isRequired, isInvited: React.PropTypes.bool, roomNotificationCount: React.PropTypes.array, hidden: React.PropTypes.bool, onClick: React.PropTypes.func, onHeaderClick: React.PropTypes.func }, getDefaultProps: function() { return { onHeaderClick: function() {} // NOP }; }, render: function() { var TintableSvg = sdk.getComponent("elements.TintableSvg"); var notifications = this.props.roomNotification; var notificationCount = notifications[0]; var notifyHighlight = notifications[1]; var chevronClasses = classNames({ 'mx_RoomSubList_chevron': true, 'mx_RoomSubList_chevronRight': this.props.hidden, 'mx_RoomSubList_chevronDown': !this.props.hidden }); var badgeClasses = classNames({ 'mx_RoomSubList_badge': true, 'mx_RoomSubList_badgeHighlight': notifyHighlight }); var badge; if (notificationCount > 0) { badge = <div className={badgeClasses}>{ FormattingUtils.formatCount(notificationCount) }</div>; } else if (notifyHighlight) { badge = <div className={badgeClasses}>!</div>; } var title; var roomCount = this.props.roomCount; if (this.props.collapsed) { title = this.props.label; if (roomCount !== '') { title += " [" + roomCount + "]"; } } var invited; if (this.props.isInvited) { var IncomingCallBox = sdk.getComponent("voip.IncomingCallBox"); invited = <IncomingCallBox className="mx_RoomSubList_invited" invited={ this.props.invited }/>; } return ( <div ref="header" className="mx_RoomSubList_labelContainer" title={ title } > <AccessibleButton onClick={ this.props.onClick } className="mx_RoomSubList_label" tabIndex="0" > { this.props.collapsed ? '' : this.props.label } <div className="mx_RoomSubList_roomCount" > { roomCount } </div> <div className={chevronClasses} /> { badge } { invited } </AccessibleButton> </div> ); } });
23b7df64e8add513801208248854152b73d02e66
[ "JavaScript" ]
1
JavaScript
jamieabc/riot-web
67150662eba68c946e4f5dc7f51e1b82da0cb70c
fcfa5ef2a70c8048958b886d55263ae4c3d96ddb
refs/heads/master
<file_sep>/* generator DKA za 1. labos iz afjjp */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int kodiraj_stanje (int *parovi, int broj_parova, int m) { int i, kod; for (kod=0, i=0 ; i<broj_parova ; ++i) { if (fabs(parovi[i])>m) return pow (2 * m + 1, broj_parova); kod += (parovi[i] + m) * pow (2 * m + 1, i); } return kod; } void dekodiraj_stanje (int kod, int *parovi, int n, int m) { int tmp_kod, i; tmp_kod = kod; for (i=0 ; i<n ; ++i) { parovi[i] = (tmp_kod % (2 * m + 1)) - m; tmp_kod /= 2 * m + 1; } } int main () { FILE *in, *out; int m, n, i, stanje, *parovi, broj_stanja; char ch, *s = NULL; if ((in = fopen ("ulaz.dat", "r")) == NULL) { perror ("ulaz.dat"); exit (EXIT_FAILURE); } fscanf (in, "%d\n", &m); n = 0; while (fscanf (in, " %c-", &ch) != EOF) { s = (char *) realloc (s, ++n); *(s + n - 1) = ch; } *(s + n) = '\0'; fclose (in); n /= 2; parovi = (int *) malloc (n); broj_stanja = pow ((2 * m + 1), n); printf ("Broj generiranih stanja: %d\n", broj_stanja + 1); if ((out = fopen ("tablica.dat", "w")) == NULL) { perror ("izlaz.dat"); exit (EXIT_FAILURE); } fprintf (out, "%d\n", broj_stanja + 1); fprintf (out, "%d\n", n * 2); fprintf (out, "%s\n", s); for (stanje=0 ; stanje<broj_stanja ; ++stanje) { for (i=0 ; i<strlen(s) ; ++i) { dekodiraj_stanje (stanje, parovi, n, m); if (i%2) --parovi[i/2]; else ++parovi[i/2]; fprintf (out, "%d ", kodiraj_stanje (parovi, n, m)); } fprintf (out, "%d\n", stanje); } for (i=0 ; i<strlen(s) + 1 ; ++i) fprintf (out, "%d ", broj_stanja); fprintf (out, "\n"); fclose (out); return EXIT_SUCCESS; } <file_sep>/* dekker.c - iskljucivanje niti Dekkerovim algoritmom * Labos iz Operacijskih Sustava * * (C) 2005 <NAME> <<EMAIL>> * * Prevesti sa: gcc -lpthread -D_REENTRANT dekker.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define THREADS_NUM 2 int access_right = 0; int flags[THREADS_NUM] = {0}; void lock_state (int i, int j) { flags[i] = 1; while (flags[j]) { if (access_right == j) { flags[i] = 0; while (access_right == j); flags[i] = 1; } } } void unlock_state (int i, int j) { access_right = j; flags[i] = 0; } void *thread_function (void *i) { int k, m; for (k=1 ; k<=5 ; ++k) { lock_state (*((int *) i), 1 - *((int *) i)); for (m=1 ; m<=5 ; ++m) { printf ("%d ", * ((int *) i)); printf ("%d ", k); printf ("%d\n", m); sleep (1); } unlock_state (*((int *) i), 1 - *((int *) i)); } return NULL; } int main () { int i = 0, j = 1; pthread_t thread1_id, thread2_id; if (pthread_create (&thread1_id, NULL, &thread_function, &i)) { perror ("pthread_create"); exit (EXIT_FAILURE); } if (pthread_create (&thread2_id, NULL, &thread_function, &j)) { perror ("pthread_create"); exit (EXIT_FAILURE); } if (pthread_join (thread1_id, NULL)) { perror ("pthread_join"); exit (EXIT_FAILURE); } if (pthread_join (thread2_id, NULL)) { perror ("pthread_join"); exit (EXIT_FAILURE); } return EXIT_SUCCESS; } <file_sep>/* txtstat - statistical analysis of text files * Copyright (C) 2003 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <getopt.h> #include <stdlib.h> #define VERSION "1.1.2" void display_usage (FILE *stream, int exit_code) { fprintf (stream, "Usage: txtstat [options] [file(s)]\n" " -h --help Display this usage information\n" " -o --output file Write output to file\n" " -s --stream Use stdin instead of input file\n" " -v --verbose Display verbose messages\n" " -V --version Display program version\n"); fprintf (stream, "\nReport bugs to <<EMAIL>>\n"); exit (exit_code); } int main (int argc, char **argv) { FILE *in, *out; char *output; int next_option; int verbose = 0, stream = 0, have_output_file = 0; /* getopt_long() data */ const char *short_options = "ho:svV"; const struct option long_options[] = { {"help", 0, NULL, 'h'}, {"output", 1, NULL, 'o'}, {"stream", 0, NULL, 's'}, {"verbose", 0, NULL, 'v'}, {"version", 0, NULL, 'V'}, {NULL, 0, NULL, 0} }; if (argc == 1) display_usage (stdout, 0); do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { /* --help or -h */ case 'h': display_usage (stdout, EXIT_SUCCESS); break; /* --output or -o */ case 'o': have_output_file = 1; output = optarg; break; /* --stream or -s */ case 's': /* switch stream input on */ stream = 1; break; /* --verbose or -v */ case 'v': /* switch verbose messages on */ verbose = 1; break; /* --version or -u */ case 'V': printf ("txtstat version %s\n", VERSION); exit (EXIT_SUCCESS); break; /* Invalid option */ case '?': display_usage (stderr, EXIT_FAILURE); break; /* Parsing finished? */ case -1: break; /* An error occured */ default: abort (); } } while (next_option != -1); /* No stream and no files specified */ if (!stream && !argv[optind]) display_usage (stderr, EXIT_FAILURE); /* Open output stream if neccessary */ if (have_output_file) { if ((out = fopen (output, "w")) == NULL) { fprintf (stderr, "Could not open file for writting: %s\n", output); exit (EXIT_FAILURE); } } else out = stdout; if (stream) { if (verbose) fprintf (stderr, "Verbose option has no effect with -s option\n"); analyze (stdin); } else { while (optind < argc) { if (verbose) fprintf (stderr, "Processing file: %s\n", argv[optind]); if ((in = fopen (argv[optind], "r")) == NULL) { fprintf (stderr, "Could not open file for reading: %s\n", argv[optind]); exit (EXIT_FAILURE); } analyze (in); ++optind; } } display_graph (out); display_stats (out); return EXIT_SUCCESS; } <file_sep>// Primjer koristenja STL-a (liste, sort i iteratori) za sortiranje stringova // (C) 2005 <NAME> <<EMAIL>> #include <list> #include <string> #include <iostream> #include <iterator> using namespace std; int main (int argc, char **argv) { string tmp; list<string> input; while (cin >> tmp) input.push_back (tmp); input.sort(); ostream_iterator<string> out_iter_string (cout, " "); copy (input.begin(), input.end(), out_iter_string); cout << endl; return 0; } <file_sep># displays current playing song in xmms (xchat script) # (C) 2005 <NAME> <<EMAIL>> import xchat from xmms import get_playlist_title, get_playlist_pos __module_name__ = "nowPlaying" __module_version__ = "1.0" __module_description__ = "Displays what song is currently playing in Xmms" song = get_playlist_title (get_playlist_pos()) try: xchat.command ("me plays: " + song) except TypeError: xchat.prnt ("Xmms is not running") <file_sep>/* dka.c - deterministicki konacni automat * * (C) 2004 <NAME> <<EMAIL>> * * Neka je zadan jezik L nad skupom dekadskih znamenaka {0, 1, ..., 9}. * Niz se promatra kao cjelobrojna vrijednost. Niz je u jeziku L ako je * njegova cjelobrojna vrijednost djeljiva s tri, L = {e, 0, 3, 6, ...} * Implementirati DKA koji prihvaca zadani jezik L. */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #define STATES 3 #define TRANSITIONS 10 int main () { int in, q; /* tablica prijelaza */ int tt[STATES][TRANSITIONS] = { {0, 1, 2, 0, 1, 2, 0, 1, 2, 0}, {1, 2, 0, 1, 2, 0, 1, 2, 0, 1}, {2, 0, 1, 2, 0, 1, 2, 0, 1, 2} }; /* Prazni niz je po definiciji prihvatljiv */ q = 0; printf ("Unesi niz: "); while ((in = fgetc(stdin)) != EOF && in != '\n') { if (!(isdigit (in))) { fprintf (stderr, "Zadani niz sadrzi znakova izvan abecede\n"); exit (EXIT_FAILURE); } /* prijelaz u novo stanje */ q = tt[q][in - '0']; } if (q == 0) printf ("Niz je unutar jezika\n"); else printf ("Niz nije unutar jezika\n"); return EXIT_SUCCESS; } <file_sep>/* stablo_listom - implementacija binarnog stabla pomocu liste. * * (C) 2003 <NAME> <<EMAIL>> * * Podaci za cvorove se unose iz datoteke "ulaz.dat", zatim se formira * stablo, te ispisu podaci koristeci inorder, preorder i postorder prolazak * kroz stablo. Podaci su cjelobrojni brojevi odvojeni razmakom. */ #include <stdio.h> #include <stdlib.h> struct node_t { int key; struct node_t *left, *right; }; typedef struct node_t node; node *dodaj_cvor (node *root, int key) { if (root == NULL) { root = (node *) malloc (sizeof (node)); if (root) { root->key = key; root->left = root->right = NULL; } } else { if (key < root->key) { root->left = dodaj_cvor (root->left, key); } else if (key > root->key) { root->right = dodaj_cvor (root->right, key); } else { printf ("Podatak vec postoji\n"); } } return root; } void inorder (node *root) { if (root) { inorder (root->left); printf ("%d ", root->key); inorder (root->right); } } void postorder (node *root) { if (root) { postorder (root->left); postorder (root->right); printf ("%d ", root->key); } } void preorder (node *root) { if (root) { printf ("%d ", root->key); preorder (root->left); preorder (root->right); } } int main () { FILE *in; int x; node *root = NULL; if ((in = fopen ("ulaz.dat", "r")) == NULL) { fprintf (stderr, "Ulazna datoteka ne postoji\n"); exit (EXIT_FAILURE); } while (fscanf (in, "%d", &x) != EOF) root = dodaj_cvor (root, x); printf ("Preorder prolaz: "); preorder (root); printf ("\nInorder prolaz: "); inorder (root); printf ("\nPostorder prolaz: "); postorder (root); printf ("\n"); return 0; } <file_sep>/* bin_search.c - binarno pretrazivanje * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* vraca indeks u polju gdje se nalazi element (-1 ako ga nema) */ /* polje MORA biti sortirano */ int bin_search (int x, int *polje, int n) { int pos, lpos, rpos; pos = n / 2; lpos = 0; rpos = n; while (lpos != rpos - 1) { if (x > polje[pos]) { lpos = pos; pos = (pos + rpos) / 2; } else if (x < polje[pos]) { rpos = pos; pos = (pos + lpos) / 2; } else return pos; } return -1; } void shell_sort (int *a, int n) { int i, j, step, tmp; for (step=n/2 ; step>0 ; step /= 2) for (i=step ; i<n ; i++) { tmp = a[i]; for (j=i ; j>=step && a[j-step]>tmp; j-=step) a[j] = a[j-step]; a[j] = tmp; } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; /* polje MORA biti sortirano */ printf ("Sortitam polje...\n"); shell_sort (polje, n); for (i=0 ; i<n ; ++i) printf ("%d ", polje[i]); printf ("\n"); printf ("Unesi broj koji treba pronaci: "); scanf ("%d", &i); i = bin_search (i, polje, n); if (i == -1) printf ("Nema takvog elementa"); else printf ("Element je na mjestu %d", i+1); printf ("\n"); return 0; } <file_sep>/* posix_sem.c - thread synchronization with POSIX semaphores * * (C) 2003 <NAME> <<EMAIL>> */ #include <malloc.h> #include <pthread.h> #include <semaphore.h> struct node { int key; struct node *next; } *head; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t node_count; /* process jobs until list becomes emptry */ void *thread_function(void *unused) { struct node *next_node; while (1) { /* wait for new job */ sem_wait(&node_count); /* lock mutex */ pthread_mutex_lock(&mutex); /* there is no need to check if queue is empty as semaphore guaranties that */ next_node = head; head = head->next; /* release mutex */ pthread_mutex_unlock(&mutex); /* Ubaciti neki kod za obradu cvora next_node */ printf("%d\n", next_node->key); free(next_node); } return NULL; } void initialize_list () { head = NULL; sem_init(&node_count, 0, 0); } void add_node(int key) { struct node *t; /* alocate new node */ t = (struct node *) malloc(sizeof (struct node)); t->key = key; pthread_mutex_lock(&mutex); t->next = head; head = t; /* signal that there is a new node available) */ sem_post(&node_count); pthread_mutex_unlock(&mutex); } int main() { int i; pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); for (i = 0 ; i < 10 ; i++) add_node(i); return 0; } <file_sep>/* ls.c - list files in current directory * * (C) 2004 <NAME> <<EMAIL>> */ #include <malloc.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <dirent.h> #include <sys/types.h> void list_dir(char *initial_dir) { DIR *current_dir; struct dirent *current_entry; if ((current_dir = opendir (initial_dir)) == NULL) { perror(initial_dir); exit(EXIT_FAILURE); } while ((current_entry = readdir(current_dir)) != NULL) { printf("Inode: %d\t", current_entry->d_ino); printf("Length: %u\t", current_entry->d_reclen); switch (current_entry->d_type) { case 4: printf("Type: dir\t"); break; case 8: printf("Type: file\t"); break; } printf("%s\n", current_entry->d_name); } printf("\n"); } int main(int argc, char **argv) { char *initial_dir; if (argc == 1) initial_dir = (char *) get_current_dir_name (); else initial_dir = strdup (argv[1]); list_dir(initial_dir); return EXIT_SUCCESS; } <file_sep>/* bubble_sort.c - mjehuricasto sortiranje * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* zamjeni varijable a i b */ void swap (int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } void bubble_sort (int *polje, size_t n) { int i, j; for (i=0 ; i<n-1 ; i++) for (j=i+1 ; j<n ; j++) if (polje[i] > polje[j]) swap (&polje[i], &polje[j]); } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); bubble_sort (polje, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>#!/usr/bin/python import sys, os, getopt import md5, sha program_version = '0.1.1' verbose_messages = False digest_algorithm = 'md5' def usage(): """Display program usage and exit""" print 'psyncdir version %s' % program_version print 'Usage: psyncdir [options] URL1 URL2\n' print 'Options are:' print ' -d, --digest Select one of hash algorithms: md5(default), sha1' print ' -r --recursive Recursive directory syncronization' print ' -h, --help Display this usage information' print ' -v, --verbose Display verbose messages' print ' -V, --version Display program version' sys.exit() def calculate_hash(filename, algorithm = 'md5'): """Return hash for given file using on of the hash algorithms""" try: f = file(filename) except IOError: print 'No such file: %s' % filename sys.exit(1) if algorithm == 'md5': hash = md5.new() elif algorithm == 'sha1': hash = sha.new() elif algorithm == 'hmac': hash = hmac.new() else: print 'No such algorith: %s' % algorithm sys.exit(1) for line in f: hash.update(line) f.close() return hash.digest() def get_files(path, recursive = True): """Returns list of files within directory""" files = [] if path[-1] == os.sep: path = path[:-1] items = os.listdir(path) for item in items: if item in ('.', '..'): continue new_path = path + os.sep + item if os.path.isdir(new_path) and recursive: files.extend(get_files(new_path, True)) else: files.append(path + os.sep + item) return files def main(): short_options = 'd:vhv' long_options = ['digest=', 'verbose', 'help', 'version'] try: opts, args = getopt.getopt(sys.argv[1:], short_options, long_options) except getopt.GetoptError: usage() for option, arg in opts: if option in ('-d', '--digest'): if arg not in ('sha1', 'md5'): print 'No such hash algorithm: %s' % arg sys.exit(1) digest_algorithm = arg if option in ('-v', '--verbose'): verbose_messages = True if option in ('-h', '--help'): usage() if option in ('-V', '--version'): print "psyncdir version %s" % program_version sys.exit() if __name__ == '__main__': for f in get_files('work'): print f.ljust(60), calculate_hash(f) #main() <file_sep>import random def quickselect(array, k): pivot = array[len(array) / 2] less_than = [e for e in array if e < pivot] more_than = [e for e in array if e > pivot] if k <= len(less_than): return quickselect(less_than, k) elif k > len(array) - len(more_than): return quickselect(more_than, k - (len(array) - len(more_than))) else: return pivot <file_sep>/* hanoi.c - problem Hanojskih tornjeva * * (C) 2003 <NAME> <<EMAIL>> * * Problem: * Zadana su tri stapa (1, 2 i 3). Na stapu 1 nalazi se n diskova razlicite * velicine smjestenih tako da se manji disk nalazi uvijek iznad veceg diska. * Treba preseliti sve diskove sa stapa 1 na 3, jedan po jedan, tako da manji * disk uvijek dolazi na veci disk * * Opis algoritma: * 1. Ignorirati donji (najveci) disk i rijesiti problem za n-1 diskova * sa stapa 1 na stap 2 koristeci stap 3 kao pomocni * 2. Najveci disk se nalazi na stapu 1, ostalih n-1 se nalazi na stapu 2 * 3. Preseliti najveci disk sa 1 na 3 * 4. Preseliti n-1 disk sa stapa 2 na stap 3 koristeci stap 1 kao pomocni */ #include <stdio.h> /* Rekurzivno rjesenje problema. Ispisuje poredak potrebnih prebacivanja */ void hanoi (char src, char dest, char temp, int n) { if (n > 0) { hanoi (src, temp, dest, n-1); printf ("%c --> %c\n", src, dest); hanoi (temp, dest, src, n-1); } } int main () { int n; printf ("Unesi broj diskova: "); scanf ("%d", &n); hanoi ('S', 'D', 'T', n); return 0; } <file_sep>#!/usr/bin/python import sys import urllib import xml.etree.ElementTree as et if len(sys.argv) < 2: print "Usage: %s keywords..." % sys.argv[0] sys.exit(1) search_url = 'http://search.twitter.com/search.atom?' search_url += 'q=' + urllib.quote(' '.join(sys.argv[1:])) search_url += '&since=2010-01-01' search_url += '&rpp=100' feed = urllib.urlopen(search_url) tree = et.parse(feed) feed.close() for e in tree.getiterator(): if e.tag.endswith('published'): print e.text <file_sep>/* stog_listom.c - implementacija stoga pomocu jednostruko povezane liste * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> struct node { int key; struct node *next; }; void stack_init (struct node **head) { *head = (struct node *) malloc (sizeof (struct node)); } /* Stavi podatak na stog */ void push (struct node **head, int key) { struct node *new_node; new_node = (struct node *) malloc (sizeof (struct node)); new_node->key = key; new_node->next = (*head)->next; (*head)->next = new_node; } /* Uzmi podatak sa stoga */ int pop (struct node **head) { int ret_val; struct node *tmp; /* Da li je stog prazan? Vrati -1 ako je */ if ((*head)->next == NULL) return -1; tmp = (*head)->next; ret_val = tmp->key; (*head)->next = (*head)->next->next; free (tmp); return ret_val; } int main () { struct node *head; int val, ret_val; stack_init (&head); /* Generiraj pseudoslucajne brojeve. Ako je generiran parni broj * stavi ga na stog, ako je neparan uzmi podataka sa stoga. Prekini * ako je stog prazan. */ /* Inicijaliziraj generator pseudoslucajnih brojeva */ srand ((unsigned) time (NULL)); while (1) { val = 1 + (int)(100.0 * rand() / (RAND_MAX + 1.0)); /* Neparan */ if (val % 2) { ret_val = pop (&head); if (ret_val == -1) { printf ("Stog je prazan\n"); exit (0); } printf ("Pop = %d\n", ret_val); } else { /* Paran */ push (&head, val); printf ("Push (%d)\n", val); } } return 0; } <file_sep>/* listener.c - simple network server program * * (C) 2005 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> const char *welcome_msg = "Welcome to simple network listener v1.0 \n(C) 2005 <NAME> <<EMAIL>>\nType 'quit' or 'exit' to terminate connection\n"; int main(int argc, char **argv) { int server_socket_fd, client_socket_fd, port; struct sockaddr_in server_address, client_address; if (argc != 2) { fprintf(stderr, "Usage: server [port]\n"); exit(EXIT_FAILURE); } sscanf(argv[1], "%d", &port); server_socket_fd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(port); bind(server_socket_fd, (struct sockaddr *) &server_address, sizeof (server_address)); listen(server_socket_fd, 1); printf("Started server on port %d\n", port); while (1) { char buffer[256]; int len, msg_len, client_active = 1; printf("Server waiting for connections...\n"); len = sizeof (client_address); client_socket_fd = accept(server_socket_fd, (struct sockaddr *) &client_address, &len); write(client_socket_fd, welcome_msg, strlen (welcome_msg)); printf("==> Connection from: %s\n", inet_ntoa(client_address.sin_addr)); while (client_active) { msg_len = read(client_socket_fd, buffer, 256); buffer[msg_len] = '\0'; if (msg_len > 0) printf("==> Read: %s", buffer); if (!strncmp (buffer, "quit", 4) || !strncmp (buffer, "exit", 4)) client_active = 0; } close(client_socket_fd); } return EXIT_SUCCESS; } <file_sep>// vim: ts=4 #include <cmath> #include "chromosome.h" using namespace std; Chromosome::Chromosome(int val) { value = val; // binary_val = static_cast<double> ((val - min_value) / value_range * (pow(2.0, n) - 1)); binary_val = static_cast<unsigned int>((static_cast<double> (val - min_value) / value_range * (pow(2.0, n) - 1))); } void Chromosome::calculate_value() { // value = min_value + (static_cast<double> (binary_val)) / (pow(2.0, n) - 1) * value_range; value = min_value + (static_cast<double>(binary_val)) / (pow(2.0, n) - 1) * value_range; } int Chromosome::n = static_cast<int>(ceil(log(value_range * pow(10.0, precision) + 1.0) / log(2.0))); <file_sep>/* zombie.c - example on creating a zombie process * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t pid = fork(); if (pid) { /* Parent */ sleep(30); } else { /* Child process. Exit normally, so exit status will "hang" as parent is sleeping and it's not able to collect our exit status. You may see that child is in "zombie" state with ps command */ exit(0); } return 0; } <file_sep>/* kraljice.c - problem osam kraljica * * (C) 2004 <NAME> <<EMAIL>> * * Problem: * Smjestit osam kraljica na sahovsku plocu tako da se one medjusobno * ne napadaju. (Postoji tocno 92 razlicita rjesenja) * * Opis algoritma: * 1. Promatramo stupce od prvog prema zadnjem * 2. U svaki stupac postavljamo jednu kraljicu * 3. Promatramo plocu kada je vec postavljeno i kraljica (u i razlicitih * stupaca) koje se medjusobno ne napadaju * 4. Postavljamo i+1 kraljicu tako da ona ne napada niti jednu od vec * postavljenih kraljica i da se ostale kraljice mogu postaviti uz * uvjet nenapadanja */ #include <stdio.h> /* Ispituje da li se kraljice na pozicijama (x1, y1) i (x2, y2) napadaju. * Vraca 1 ako se napadaju, 0 ako se ne napadaju */ int atacked (int x1, int y1, int x2, int y2) { int t = 0; if (x1 == x2) t = 1; if (y1 == y2) t = 1; if (x1 + y2 == x2 + y1) t = 1; if (x1 - y2 == x2 - y1) t = 1; return t; } int q8 (int *queens, int i, int n) { int a, b; int good; if (i == n) return 1; for (a=0 ; a < n ; a++) { good = 1; for (b=0 ; b<i ; b++) { if (atacked (b+1, queens[b]+1, i+1, a+1)) { good = 0; break; } } if (good) { queens[i] = a; if (q8 (queens, i+1, n) == 1) return 1; } } return 0; } int main () { int i; int queens[8] = {0}; q8 (queens, 0, 8); for (i=0 ; i<8 ; i++) printf ("(%d, %d)\n", i+1, queens[i]+1); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_PROC_LINE 256 static __inline__ unsigned long long rdtsc(void) { unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ((unsigned long long) lo) | (((unsigned long long) hi) << 32); } float get_proc_speed(void) { FILE *proc; char buff[MAX_PROC_LINE]; float speed; if ((proc = fopen("/proc/cpuinfo", "rb")) == NULL) { perror("fopen"); exit(EXIT_FAILURE); } while (fgets(buff, MAX_PROC_LINE, proc)) { if (strstr(buff, "cpu MHz")) { sscanf(buff, "cpu MHz : %f", &speed); return speed; } } return 0; } int main() { unsigned long long tsc = rdtsc(); printf("TSC: %llu (%3.2f days)\n", tsc, tsc/(get_proc_speed()*10e5)/24.0/60/60); return EXIT_SUCCESS; } <file_sep>/* Jednostavni OpenGL demo * (C) 2003 <NAME> <<EMAIL>> */ #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 500.0f #define WINDOW_HEIGHT 500.0f #define X_START_POSITION ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define Y_START_POSITION ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) float xdelta = 0.01; float ydelta = 0.05; void init_gl () { glShadeModel (GL_SMOOTH); glClearColor (0.0f, 0.0f, 0.0f, 0.5f); glClearDepth (1.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); glEnable (GL_COLOR_MATERIAL); glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene () { static float theta = 0; float x, y, t; glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity (); glTranslatef (0.0f, 0.0f, -5.0f); glRotatef (theta, 1.0f, 0.5f, 0.25f); glColor3f (0.0f, 1.0f, 0.0f); glBegin(GL_QUADS); glColor3f (0.0f, 1.0f, 0.0f); glVertex3i(-1, 1, 0); glColor3f (1.0f, 0.0f, 0.0f); glVertex3i(1, 1, 0); glColor3f (0.0f, 0.0f, 1.0f); glVertex3i(1, -1, 0); glColor3f (1.0f, 0.0f, 0.0f); glVertex3i(-1, -1, 0); glEnd(); glBegin(GL_QUADS); glColor3f (0.0f, 1.0f, 0.0f); glVertex3i(-1, 1, 1); glColor3f (1.0f, 0.0f, 0.0f); glVertex3i(1, 1, 1); glColor3f (0.0f, 0.0f, 1.0f); glVertex3i(1, -1, 1); glColor3f (1.0f, 0.0f, 0.0f); glVertex3i(-1, -1, 1); glEnd(); theta += 0.45; glutSwapBuffers (); } void resize_scene (int width, int height) { glViewport (0, 0, width, height); glMatrixMode (GL_PROJECTION); glLoadIdentity (); if (height == 0) ++height; gluPerspective (80, (float) width / height, 1.0f, 5000.0f); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); } void keyboard_handler (unsigned char key, int x, int y) { switch (key) { case 27: case 'q': case 'Q': exit (0); } } void special_keys_handler (int key, int x, int y) { switch (key) { case GLUT_KEY_UP: glutFullScreen (); break; case GLUT_KEY_DOWN: glutReshapeWindow (WINDOW_WIDTH, WINDOW_HEIGHT); break; } } int main (int argc, char **argv) { glutInit (&argc, argv); init_gl (); glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize (WINDOW_WIDTH, WINDOW_HEIGHT); glutInitWindowPosition (X_START_POSITION, Y_START_POSITION); glutCreateWindow (argv[0]); glutDisplayFunc (draw_scene); glutIdleFunc (draw_scene); glutReshapeFunc (resize_scene); glutKeyboardFunc (keyboard_handler); glutSpecialFunc (special_keys_handler); glutMainLoop (); return 0; } <file_sep>/* mkstemp.c - create an unique temporary file by using mkstemp system call * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> int main() { int fd; char filename_template[] = "tempXXXXXX"; fd = mkstemp(filename_template); printf("Temporary filename: %s\n", filename_template); return 0; } <file_sep>#!/usr/bin/python # izbacivanje beskorisnih (mrtvih i nedohvatljivih) # znakova iz kontekstno neovisne gramatike # # (C) 2004 <NAME> <<EMAIL>> from sys import argv, exit produkcije = {} def izbaci_mrtve_znakove (): nova_lista_zivih = [] stara_lista_zivih = [] for nezavrsni_znak in produkcije.keys (): for desna_strana_produkcije in produkcije[nezavrsni_znak]: if desna_strana_produkcije == '$' or desna_strana_produkcije.islower(): nova_lista_zivih.append (nezavrsni_znak) break while stara_lista_zivih <> nova_lista_zivih: stara_lista_zivih = nova_lista_zivih[:] for nezavrsni_znak in produkcije.keys(): for desna_strana_produkcije in produkcije[nezavrsni_znak]: znak_ziv = 1 for ch in desna_strana_produkcije: if ch.isupper() and ch not in nova_lista_zivih: znak_ziv = 0 break if znak_ziv: if nezavrsni_znak not in nova_lista_zivih: nova_lista_zivih.append (nezavrsni_znak) for nezavrsni_znak in produkcije.keys(): if nezavrsni_znak not in nova_lista_zivih: del produkcije[nezavrsni_znak] else: for desna_strana in produkcije[nezavrsni_znak]: for znak in desna_strana: if znak.isupper() and znak not in nova_lista_zivih: produkcije[nezavrsni_znak].remove(desna_strana) def izbaci_nedohvatljive_znakove (): stara_lista_dohvatljivih = [] nova_lista_dohvatljivih = ['S'] while stara_lista_dohvatljivih <> nova_lista_dohvatljivih: stara_lista_dohvatljivih = nova_lista_dohvatljivih[:] for nezavrsni_znak in produkcije.keys(): for dohvatljiv_znak in stara_lista_dohvatljivih: for desna_strana_produkcije in produkcije[dohvatljiv_znak]: if nezavrsni_znak in desna_strana_produkcije: if nezavrsni_znak not in nova_lista_dohvatljivih: nova_lista_dohvatljivih.append (nezavrsni_znak) for nezavrsni_znak in produkcije.keys(): if nezavrsni_znak not in nova_lista_dohvatljivih: try: del produkcije[nezavrsni_znak] except: pass try: ulaz = open (argv[1], 'r') except IOError: print 'Ne mogu otvoriti ulaznu datoteku: ' + argv[1] exit (1) except IndexError: print 'Sintaksa: ' + argv[0] + ' ulazna_datoteka izlazna_datoteka' exit(1) while 1: try: nova_produkcija = ulaz.readline () if not nova_produkcija: raise EOFError if nova_produkcija[:1] not in produkcije.keys (): produkcije[nova_produkcija[:1]] = []; produkcije[nova_produkcija[:1]].append (nova_produkcija[2:-1]) except EOFError: break izbaci_mrtve_znakove () izbaci_nedohvatljive_znakove () try: izlaz = open (argv[2], 'w') except IOError: print 'Ne mogu otvoriti izlaznu datoteku' + argv[2] exit (1) except IndexError: print 'Sintaksa: ' + argv[0] + ' ulazna_datoteka izlazna_datoteka' exit(1) for nezavrsni_znak in produkcije.keys(): for desna_strana in produkcije[nezavrsni_znak]: izlaz.write (nezavrsni_znak + '~' + desna_strana + '\n') <file_sep>#ifndef _RSA_H #define _RSA_H #define RSA_ENCRYPT 0 #define RSA_DECRYPT 1 #define BUFFER_SIZE 512 void rsa_crypt (const char *key_file, const char *input_file, const char *output_file, int mode); void rsa_generate_key (const char *pub_key_file, const char *prvt_key_file, int length); void rsa_convert_to_base64 (const char *in_file, const char *out_file); void rsa_convert_from_base64 (const char *in_file, const char *out_file); #endif /* _RSA_H */ <file_sep>/* cancel_thread.c - creation of synchronous canceable thread, example of * protecting critical section inside of thread * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdlib.h> #include <pthread.h> void *thread_function (void *unused) { int old_cancel_state; /* Set thread type to synchronously cancelable */ pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); /* start critical section, disable thread cancelation */ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state); /* Critical code goes here */ /* reenable tread cancelation */ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancel_state); /* create cancelation point */ pthread_testcancel(); /* do some more work that is not critical*/ return NULL; } int main () { pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); return EXIT_SUCCESS; } <file_sep>#!/bin/sh # Convert Unix files to DOS files # (C) 2003 <NAME> <<EMAIL>> if [ $# -ne 2 ]; then echo "Usage: unix2dos inputfile outputfile" exit 1 fi sed 's/$/^M/' $1 > $2 <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) int fullscreen = 0; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; int xmax = WINDOW_WIDTH, ymax = WINDOW_HEIGHT, m; float umin, umax, vmin, vmax, epsilon; float oldumin, oldumax, oldvmin, oldvmax; float c_real, c_imag; int point = 0, xcords[2], ycords[2]; void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } void resize_scene(int width, int height) { window_width = width; window_height = height; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, window_width, 0, window_height); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glColor3f(0, 1, 0); } void crtaj_fraktal() { int x0, y0, k; float u0, v0, r, zreal, zimag, tmpre, tmpim, xratio, yratio; yratio = (vmax - vmin) / ymax; xratio = (umax - umin) / xmax; glBegin(GL_POINTS); for (y0 = 0 ; y0 < ymax ; ++y0) { v0 = yratio * y0 + vmin; for (x0 = 0 ; x0 < xmax ; ++x0) { u0 = xratio * x0 + umin; k = -1; zreal = u0; zimag = v0; do { ++k; tmpre = zreal * zreal - zimag * zimag; tmpim = 2 * zreal * zimag; zreal = tmpre + c_real; zimag = tmpim + c_imag; r = sqrt(zreal * zreal + zimag * zimag); } while ((r < epsilon) && (k < m)); glColor3f(0, 0, 1.0 / m * k); glVertex2i(x0, window_height - y0); } } glEnd(); glFlush(); } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'q': exit(EXIT_SUCCESS); } glFlush(); } void mouse_handler(int button, int state, int x, int y) { float tmpx, tmpy, shiftx, shifty; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { xcords[point] = x; ycords[point] = y; ++point; if (point == 2) { glColor3f(1, 1, 1); glBegin(GL_LINES); glVertex2i(xcords[0], WINDOW_HEIGHT - ycords[0]); glVertex2i(xcords[1], WINDOW_HEIGHT - ycords[0]); glVertex2i(xcords[1], WINDOW_HEIGHT - ycords[0]); glVertex2i(xcords[1], WINDOW_HEIGHT - ycords[1]); glVertex2i(xcords[1], WINDOW_HEIGHT - ycords[1]); glVertex2i(xcords[0], WINDOW_HEIGHT - ycords[1]); glVertex2i(xcords[0], WINDOW_HEIGHT - ycords[1]); glVertex2i(xcords[0], WINDOW_HEIGHT - ycords[0]); glEnd(); glFlush(); point = 0; tmpx = (umax - umin) / WINDOW_WIDTH; tmpy = (vmax - vmin) / WINDOW_HEIGHT; shiftx = umin; shifty = vmin; umin = xcords[0] * tmpx + shiftx; umax = xcords[1] * tmpx + shiftx; vmin = (WINDOW_HEIGHT - ycords[1]) * tmpy + shifty; vmax = (WINDOW_HEIGHT - ycords[0]) * tmpy + shifty; crtaj_fraktal(); } } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { umin = oldumin; umax = oldumax; vmin = oldvmin; vmax = oldvmax; crtaj_fraktal(); } } int main(int argc, char **argv) { glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMouseFunc(mouse_handler); epsilon = 200; m = 200; umin = -1.0; umax = 1.0; vmin = -1.2; vmax = 1.2; c_real = 0.32; c_imag = 0.043; oldumin = umin; oldvmin = vmin; oldumax = umax; oldvmax = vmax; printf("<NAME>up\n=================\n"); printf("Desni klik - pocetni skup\n"); printf("Lijevi klik - odabir tocke (gornja lijeva, donja desna) pravokutnika za zoom\n"); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>#include "stats.h" void analyze (FILE *in) { int ch; int i, j; i = j = 0; while ((ch = fgetc (in)) != EOF) { ++total; ++i, ++j; /* word and sentences lenght counter */ if (ch == '.') { /* add sentence length to total sum and reset counter. increase sentece count */ sent_sum += j; j = 0; ++dots; } if (ch == '\n') ++lines; if (isspace (ch)) { /* add word length to total sum and reset counter. increase word count*/ word_sum += i; i = 0; ++words; } if (isalpha(ch)) { if (ch >= 'A' && ch <= 'Z') { ++characters[ch-'A']; ++chars; } if (ch >= 'a' && ch <= 'z') { ++characters[ch-'a']; ++chars; } } } /* Fix initial size of words, lines and sentences (no SPACE or \n character) */ if (total != 0 && words == 0) ++words; if (total != 0 && lines == 0) ++lines; if (total != 0 && dots == 0) ++dots; if (total != 0 && sent_sum == 0) sent_sum += total; if (total != 0 && word_sum == 0) word_sum += total; } void display_graph (FILE *out) { int i, j; /* FIXME: if input is only one character long, the output will be longer than screen width */ for (i = 0 ; i <= 'Z'-'A' ; ++i) { fprintf (out, "%c %-7d", 'a' + i, characters[i]); for (j = 0 ; j < (int)((float) characters[i] / chars * 100) ; ++j) fprintf (out, "*"); fprintf (out, "\n"); } } void display_stats (FILE *out) { fprintf (out, "\nTotal: %d characters, %d words, %d lines\n", total, words, lines); fprintf (out, "%d letters of total %d characters (%4.1f%)\n", chars, total, (float) chars/total*100); fprintf (out, "Average word length: %d (%3.1f)\n", word_sum/words, (float) word_sum/words); fprintf (out, "%d sentences, average length: %d (%3.1f)\n", dots, sent_sum/dots, (float) sent_sum/dots); } <file_sep>/* Labos iz Otvorenog racunarstva * (C) 2005 <NAME> <<EMAIL>> */ import java.io.*; import java.awt.Graphics; import java.applet.Applet; import fer.apr.rasip.dms.*; import fer.apr.rasip.gui.*; public class DataAnalyser extends Applet { public static MainFrame mf; public static DataSourceSim dss; public static MeasuredData md; public void init() { mf = new MainFrame(); dss = new DataSourceSim(); } public void start() { int i; try { dss.open(); } catch (DataSourceException e) { System.out.println (e.toString()); System.exit (1); } while (true) { try { Thread.sleep (2000); } catch (Exception e) { } for (i = 0; i < 16; ++i) { try { MeasuredData dsData = dss.getData (i); mf.setValue (i, md.getValue()); } catch (Exception e) { System.out.println (e.toString()); } } } } public void stop() { try { dss.close(); } catch (Exception e) { } } public void destroy() { try { dss.close(); } catch (Exception e) { } } public static void main (String[] args) { int i; MainFrame mf = new MainFrame(); DataSourceSim dss = new DataSourceSim(); try { dss.open(); while (true) { try { Thread.sleep (2000); } catch (Exception e) { } for (i = 0; i < 16; ++i) { try { MeasuredData md = dss.getData(i); mf.setValue (i, md.getValue()); } catch (Exception e) { System.out.println (e.toString()); } } } } catch (DataSourceException e) { System.out.println (e.toString()); System.exit (1); } } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <gmp.h> #include "rsa.h" #include "base64.h" void convert_to_mpz (mpz_t mpz, char *buffer, int size) { int i; mpz_set_ui (mpz, 0); for (i = 0 ; i < size ; ++i) { mpz_mul_ui (mpz, mpz, 256); mpz_add_ui (mpz, mpz, ((unsigned int) buffer[i]) & 0x0000ff); } } void convert_from_mpz (char *buffer, mpz_t mpz, int size) { int i; mpz_t r; mpz_init (r); for (i = size - 1 ; i > -1 ; --i) buffer[i] = mpz_fdiv_qr_ui (mpz, r, mpz, 256); } void rsa_generate_key (const char *pub_key_file, const char *prvt_key_file, int length) { int i, print_len, len = length / 2; FILE *pub_out, *prvt_out; char buffer[len/2]; gmp_randstate_t state; mpz_t random_num, p, q, n, z, a, b, d, e; if ((pub_out = fopen (pub_key_file, "w")) == NULL) { perror (pub_key_file); exit (EXIT_FAILURE); } if ((prvt_out = fopen (prvt_key_file, "w")) == NULL) { perror (prvt_key_file); exit (EXIT_FAILURE); } mpz_init (random_num); mpz_init (p); mpz_init (q); mpz_init (n); mpz_init (z); mpz_init (a); mpz_init (b); mpz_init (d); mpz_init (e); /* p generation */ gmp_randinit (state, GMP_RAND_ALG_LC, 128); gmp_randseed_ui (state, time (NULL)); mpz_urandomb (random_num, state, len); mpz_nextprime (p, random_num); /* q generation */ gmp_randinit (state, GMP_RAND_ALG_LC, 128); gmp_randseed_ui (state, time (NULL)); mpz_urandomb (random_num, state, len); mpz_nextprime (q, random_num); mpz_nextprime (q, q); /* n = pq calculation */ mpz_mul (n, p, q); /* z = (p - 1) * (q - 1) calculation */ mpz_sub_ui (a, p, 1); mpz_sub_ui (b, q, 1); mpz_mul (z, a, b); /* get e (relativy prime and less then z) parameter */ mpz_set (e, z); while (mpz_cmp (e, z) >= 0) { gmp_randinit (state, GMP_RAND_ALG_LC, 128); gmp_randseed_ui (state, time (NULL)); mpz_urandomm (random_num, state, z); mpz_nextprime (e, random_num); mpz_gcd (a, e, z); if (mpz_get_si (a) == 1) break; } /* e*d mod z = 1, get d */ mpz_invert (d, e, z); /* write public key to file */ fprintf (pub_out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (pub_out, "Description:\n Public key\n\n"); fprintf (pub_out, "Method:\n RSA\n\n"); fprintf (pub_out, "Key length:\n %04x\n\n", length); fprintf (pub_out, "Modulus:"); print_len = gmp_snprintf (buffer, len/2 + 1, "%0Zx", n); for (i = 0 ; i < print_len ; ++i) { if (!(i % 60)) fprintf (pub_out, "\n %c", buffer[i]); else fprintf (pub_out, "%c", buffer[i]); } fprintf (pub_out, "\n\nPublic exponent:"); print_len = gmp_snprintf (buffer, len/2 + 1, "%0Zx", e); for (i = 0 ; i < print_len ; ++i) { if (!(i % 60)) fprintf (pub_out, "\n %c", buffer[i]); else fprintf (pub_out, "%c", buffer[i]); } fprintf (pub_out, "\n---END OS2 CRYPTO DATA---\n"); /* write private key to file */ fprintf (prvt_out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (prvt_out, "Description:\n Private key\n\n"); fprintf (prvt_out, "Method:\n RSA\n\n"); fprintf (prvt_out, "Key length:\n %04x\n\n", length); fprintf (prvt_out, "Modulus:"); print_len = gmp_snprintf (buffer, len/2 + 1, "%0Zx", n); for (i = 0 ; i < print_len ; ++i) { if (!(i % 60)) fprintf (prvt_out, "\n %c", buffer[i]); else fprintf (prvt_out, "%c", buffer[i]); } fprintf (prvt_out, "\n\nPrivate exponent:"); print_len = gmp_snprintf (buffer, len/2 + 1, "%0Zx", d); for (i = 0 ; i < print_len ; ++i) { if (!(i % 60)) fprintf (prvt_out, "\n %c", buffer[i]); else fprintf (prvt_out, "%c", buffer[i]); } fprintf (prvt_out, "\n---END OS2 CRYPTO DATA---\n"); fclose (pub_out); fclose (prvt_out); } void rsa_strip_key (const char *in_file, const char *out_file, const char *str) { char buffer[512]; sprintf (buffer, "./strip_key.pl %s %s %s", in_file, out_file, str); system (buffer); } void rsa_crypt (const char *key_file, const char *input_file, const char *output_file, int mode) { mpz_t a, b, n, key; int i, block_size, block_size_out, size; FILE *in, *out, *fkey, *fmod; char buffer[BUFFER_SIZE]; char *tmp_key_file = "/tmp/key_file"; char *tmp_mod_file = "/tmp/mod_file"; rsa_strip_key (key_file, tmp_key_file, "exponent"); rsa_strip_key (key_file, tmp_mod_file, "Modulus"); mpz_init (a); mpz_init (b); mpz_init (n); mpz_init (key); /* open files */ if ((fkey = fopen (tmp_key_file, "r")) == NULL) { perror (tmp_key_file); exit (EXIT_FAILURE); } if ((fmod = fopen (tmp_mod_file, "r")) == NULL) { perror (tmp_mod_file); exit (EXIT_FAILURE); } if ((in = fopen (input_file, "r")) == NULL) { perror (input_file); exit (EXIT_FAILURE); } if ((out = fopen (output_file, "w")) == NULL) { perror (output_file); exit (EXIT_FAILURE); } /* get keys from file */ mpz_inp_str (n, fmod, 16); mpz_inp_str (key, fkey, 16); i = mpz_sizeinbase (n, 2); block_size = i / 8; block_size_out = block_size + 1; if (mode == RSA_DECRYPT) { --block_size_out; ++block_size; } while (1) { /* get block from input file */ size = fread (buffer, 1, block_size, in); if (!size) break; if (size < block_size) for (i = size; i < block_size; ++i) buffer[i] = '\0'; convert_to_mpz (a, buffer, block_size); mpz_powm (b, a, key, n); convert_from_mpz (buffer, b, block_size_out); /* save crypted output */ fwrite (buffer, 1, block_size_out, out); } fclose (fkey); fclose (fmod); fclose (in); fclose (out); //unlink (tmp_mod_file); //unlink (tmp_key_file); } void rsa_convert_to_base64 (const char *in_file, const char *out_file) { int i, buffer_size, n; unsigned char *in_buffer, *out_buffer; FILE *in, *out; if (!(in = fopen (in_file, "rb"))) { perror (in_file); exit (EXIT_FAILURE); } if (!(out = fopen (out_file, "w"))) { perror (out_file); exit (EXIT_FAILURE); } fprintf (out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (out, "Description:\n Crypted file\n\n"); fprintf (out, "Method:\n RSA\n\n"); fprintf (out, "File name:\n %s\n\n", in_file); fprintf (out, "Data:\n "); fseek (in, 0L, SEEK_END); buffer_size = ftell (in); fseek (in, 0L, SEEK_SET); in_buffer = malloc (buffer_size); out_buffer = malloc (buffer_size * 2); n = fread (in_buffer, 1, buffer_size, in); base64_encode (in_buffer, out_buffer, n); for (i = 0 ; i < strlen (out_buffer) ; ++i) { if (!(i % 60) && i != 0) fprintf (out, "\n "); fprintf (out, "%c", out_buffer[i]); } fprintf (out, "\n---END OS2 CRYPTO DATA---\n"); free (in_buffer); free (out_buffer); fclose (in); fclose (out); } void rsa_convert_from_base64 (const char *in_file, const char *out_file) { unsigned char *out_buffer, *in_buffer, *tmp_buffer; char buffer[256]; FILE *in, *out; int i, j, begin, end, len, n; if (!(in = fopen (in_file, "r"))) { perror (in_file); exit (EXIT_FAILURE); } if (!(out = fopen (out_file, "wb"))) { perror (out_file); exit (EXIT_FAILURE); } do { fgets (buffer, 256, in); if (!strcmp (buffer, "Data:\n")) begin = ftell (in); if (!strcmp (buffer, "---END OS2 CRYPTO DATA---\n")) end = ftell (in) - strlen ("---END OS2 CRYPTO DATA---\n"); } while (!feof (in)); len = end - begin - 1; in_buffer = malloc (len); tmp_buffer = malloc (len); out_buffer = malloc (len); fseek (in, begin, SEEK_SET); n = fread (in_buffer, 1, len, in); for (i = 0, j = 0 ; i < n ; ++i) { if (in_buffer[i] == ' ' || in_buffer[i] == '\n') continue; tmp_buffer[j++] = in_buffer[i]; } tmp_buffer[j] = '\0'; j = base64_decode (tmp_buffer, out_buffer); fwrite (out_buffer, 1, j, out); fclose (in); fclose (out); free (in_buffer); free (tmp_buffer); free (out_buffer); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include "mpi.h" /* zajednicke konstante */ #define MAX_PAUZA 2 #define MAX_ZAHTJEV 4 #define BROJ_SJEDALA 100 #define TAG_ZAHTJEV 10 #define TAG_ODGOVOR 11 /* vrsta poruka koje master salje slave procesima */ #define MSG_NASAO_MJESTO 0 #define MSG_NEMA_MJESTA 1 #define MSG_ZAVRSI 2 /* vraca 0 ako su sva potrebna mjesta slobodna, inace 1 */ int zauzeto(int *mjesta, int pocetno, int duljina) { int i; for (i = pocetno ; i < pocetno + duljina ; ++i) if (mjesta[i]) return 1; return 0; } /* rezervira mjesta u dvorani za odredjenu blagajnu */ void zauzmi_mjesta(int *mjesta, int blagajna, int pocetno, int duljina) { int i; for (i = pocetno ; i < pocetno + duljina ; ++i) mjesta[i] = blagajna; } int main(int argc, char **argv) { int broj_procesa, id_procesa; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &broj_procesa); MPI_Comm_rank(MPI_COMM_WORLD, &id_procesa); /* *id_procesa ide zato da svaki proces dobije jedinstveni seed jer * inace ima problema ako se svih n procesa pokrene u istoj sekundi */ srand((unsigned) time(NULL) * id_procesa); if (id_procesa == 0) { /* master proces */ int poruka[2]; int mjesta[BROJ_SJEDALA] = {0}; int broj_zauzetih = 0, ok; int i, pocetno_mjesto, broj_karata; while(1) { MPI_Recv(poruka, 2, MPI_INT, MPI_ANY_SOURCE, TAG_ZAHTJEV, MPI_COMM_WORLD, &status); fflush(stdout); pocetno_mjesto = poruka[0]; broj_karata = poruka[1]; ok = 0; if (!zauzeto(mjesta, pocetno_mjesto, broj_karata)) { /* obrada pocetnog zahtjeva */ poruka[0] = MSG_NASAO_MJESTO; poruka[1] = pocetno_mjesto; ok = 1; MPI_Send(poruka, 2, MPI_INT, status.MPI_SOURCE, TAG_ODGOVOR, MPI_COMM_WORLD); } else { /* gledaj susjedna mjesta od pocetnog zahtjeva s obje strane */ for (i = 0 ; i < broj_karata ; ++i) if (!zauzeto(mjesta, pocetno_mjesto + i, broj_karata)) { poruka[0] = MSG_NASAO_MJESTO; poruka[1] = pocetno_mjesto + i; ok = 1; MPI_Send(poruka, 2, MPI_INT, status.MPI_SOURCE, TAG_ODGOVOR, MPI_COMM_WORLD); break; } else if (!zauzeto(mjesta, pocetno_mjesto - i, broj_karata)) { poruka[0] = MSG_NASAO_MJESTO; poruka[1] = pocetno_mjesto - i; ok = 1; MPI_Send(poruka, 2, MPI_INT, status.MPI_SOURCE, TAG_ODGOVOR, MPI_COMM_WORLD); break; } } if (ok) { /* zauzmi mjesta i provjeri da li smo gotovi */ broj_zauzetih += broj_karata; zauzmi_mjesta(mjesta, status.MPI_SOURCE, poruka[1], broj_karata); if (broj_zauzetih >= 90) { printf("\nProdano 90 posto ulaznica\n"); printf("--------------------------\n"); for (i = 0 ; i < BROJ_SJEDALA ; ++i) if (i % 10) if (mjesta[i] == 0) printf("* "); else printf("%d ", mjesta[i]); else if (i) printf("\n"); printf("\n"); fflush(stdout); /* signaliziraj svima da nema vise karata i izadji */ poruka[0] = MSG_ZAVRSI; //MPI_Bcast(poruka, 2, MPI_INT, id_procesa, MPI_COMM_WORLD); for (i = 1 ; i < broj_procesa ; ++i) MPI_Send(poruka, 2, MPI_INT, i, TAG_ODGOVOR, MPI_COMM_WORLD); MPI_Finalize(); return 0; } } else { /* Nismo nasli slobodna mjesta za trenutni zahtjev */ poruka[0] = MSG_NEMA_MJESTA; MPI_Send(poruka, 2, MPI_INT, status.MPI_SOURCE, TAG_ODGOVOR, MPI_COMM_WORLD); } } } else { /* slave procesi */ int i, pauza, broj_mjesta, pocetno_mjesto, poruka[2]; while(1) { pauza = rand() % (MAX_PAUZA + 1); broj_mjesta = 1 + rand() % MAX_ZAHTJEV; /* pazi da npr ne zahtjeva pocetno mjesto 2 a 4 ulaznice! */ pocetno_mjesto = broj_mjesta + (rand() % (BROJ_SJEDALA - 2 * broj_mjesta)); /* prazni izlazni buffer jer se inace nista nece ispisati */ fflush(stdout); sleep(pauza); poruka[0] = pocetno_mjesto; poruka[1] = broj_mjesta; MPI_Send(poruka, 2, MPI_INT, 0, TAG_ZAHTJEV, MPI_COMM_WORLD); MPI_Recv(poruka, 2, MPI_INT, 0, TAG_ODGOVOR, MPI_COMM_WORLD, &status); if (poruka[0] == MSG_NASAO_MJESTO) { printf("Blagajna %d zauzela mjesta: ", id_procesa); for (i = poruka[1] ; i < poruka[1] + broj_mjesta ; ++i) printf("%d ", i); printf("\n\n"); } if (poruka[0] == MSG_ZAVRSI) { MPI_Finalize(); return 0; } } } MPI_Finalize(); return 0; } <file_sep>/* tsp.c - problema trgovackog putnika: * * (C) 2003 <NAME> <<EMAIL>> * * Zadan je skup gradova G i cijene putovanja c(i,j) za putovanje iz * grada i u grad j. Potrebo je, krenuvsi iz jednog grada. obici sve * gradove tocno jednom tako da je ukupni trosak puta najmanji * * c(i,j) = c(j,i) * TSP (G(i), G) = min (c(i,j) + TSP (G(j), G \ G(j)) * TSP (G(i), {G(j)}) = c(i,j) * * Slozenost rijesenja (algoritma) je faktorijelna, O((n-1)!) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* Slozenost je n! */ #define MAX_GRAD 15 /* c - matrica udaljenosti izmedju gradova (i, j) */ int c[MAX_GRAD][MAX_GRAD]; /* Operacija skup \ element */ int minus (int *skup, int n, int element) { int i, j; for (i=0 ; i<n ; i++) if (skup[i] == element) break; for (j=i ; j<n-1 ; j++) skup[j] = skup[j+1]; } /* Rjesnje problema, rekurzivno */ int tsp (int polaziste, int *gradovi, int n) { int *lgradovi, min_tsp, pom_tsp, i; lgradovi = (int *) malloc (n * sizeof (int)); memcpy (lgradovi, gradovi, n * sizeof (int)); minus (lgradovi, n, polaziste); --n; if (n == 1) { min_tsp = c[polaziste][lgradovi[0]]; } else { min_tsp = c[polaziste][lgradovi[0]] + tsp (lgradovi[0], lgradovi, n); for (i=0 ; i<n ; i++) { pom_tsp = c[polaziste][lgradovi[i]] + tsp (lgradovi[i], lgradovi, n); if (pom_tsp < min_tsp) min_tsp = pom_tsp; } } free (lgradovi); return min_tsp; } int main () { int gradovi[MAX_GRAD]; int i, j, n, min_tsp; srand (time (NULL)); do { printf ("Unesi broj gradova: "); scanf ("%d", &n); } while (n<2 || n>MAX_GRAD); /* generiraj matricu */ for (i=0 ; i<n ; i++) { gradovi[i] = i; c[i][i] = 0; for (j=i+1 ; j<n ; j++) { c[i][j] = 1 + rand() % 100; c[j][i] = c[i][j]; printf ("c[%d][%d] = %d\n", i, j, c[i][j]); } } min_tsp = tsp (0, gradovi, n); printf ("Najmanji trosak: %d\n", min_tsp); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> struct node_t { int id; struct node_t *next; }; typedef struct node_t node; node *reverse_list(node *head) { node *new_head = NULL, *tmp, *p = head; while (p) { tmp = p->next; if (!new_head) { new_head = p; } else { p->next = new_head; new_head = p; } p = tmp; } return new_head; } int main() { int id; node *head, *tail; node *reversed_head, *p, *tmp; head = tail = NULL; while (fscanf(stdin, "%d", &id) != EOF) { node *new_node = malloc(sizeof(node)); new_node->id = id; new_node->next = NULL; if (!head) { head = tail = new_node; } else { tail->next = new_node; tail = new_node; } } head = reverse_list(head); return 0; } <file_sep>/* getopt_long.h - command line options parsing with getopt_long() * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <time.h> const char *program_name; void print_usage(FILE *stream, int exit_code) { fprintf(stream, "Usage: %s [options]\n", program_name); fprintf(stream, " -h --help Display this usage information\n"); fprintf(stream, " -v --version Display version\n"); exit(exit_code); } void print_date() { time_t date; date = time(&date); printf("%s\n", ctime(&date)); } int main(int argc, char **argv) { int next_option; const char *short_options = "hv"; const struct option long_options[] = { {"help", 0, NULL, 'h'}, {"version", 0, NULL, 'v'}, {NULL, 0, NULL, 0} }; program_name = argv[0]; do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { /* -h or --help */ case 'h': print_usage(stdout, 0); break; /* -v or --version */ case 'v': printf("Version 1.0\n"); exit(0); break; /* Nonexistent option */ case '?': print_usage(stderr, 1); break; /* Done with parsing */ case -1: break; /* Something unexpected occured */ default: abort(); } } while (next_option != -1); print_date(); return EXIT_SUCCESS; } <file_sep>#ifndef _DES_H #define _DES_H #define DES_ENCRYPT 0 #define DES_DECRYPT 1 #define DES_REGULAR_PERMUTATION 0 #define DES_INVERSE_PERMUTATION 1 #define DES_PADDING ' ' typedef unsigned char uchar_t; void des_crypt (const char *in_file, const char *out_file, uchar_t *key, int mode); void des_convert_to_base64 (const char *in_file, const char *out_file); void des_convert_from_base64 (const char *in_file, const char *out_file); void des_generate_key (const char *filename); char *des_get_key_from_file (const char *filename); #endif /* _DES_H */ <file_sep>/* shred.c * * Program prepisuje sadrzaj datoteke s nasumicno odabranim znakovima cime * onemogucava njeno naknadno rekonstruiranje s diska. * * Autor: <NAME> <<EMAIL>> * Zadnja izmjena: 25.6.2003. */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <getopt.h> const char *program_name; void print_usage (FILE *stream, int exit_code) { fprintf (stream, "Usage: %s options [inputfile...]\n", program_name); fprintf (stream, " -h --help Display this usage information\n" " -v --verbose Print verbose messages\n" " -n --passes Number of overwrites [default=25]\n"); exit (exit_code); } long get_file_size (FILE *stream) { int current_position; long size; current_position = ftell (stream); fseek (stream, 0L, SEEK_END); size = ftell (stream); /* return original position */ fseek (stream, current_position, SEEK_SET); return size; } int main (int argc, char **argv) { int next_option; int verbose = 0; int i, j, k; FILE *target; /* Default number of overwrites */ int passes = 30; const char *short_options = "hvn:"; const struct option long_options[] = { {"help", 0, NULL, 'h'}, {"verbose", 0, NULL, 'v'}, {"passes", 1, NULL, 'n'}, {NULL, 0, NULL, 0 } }; program_name = argv[0]; do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { /* -h or --help */ case 'h': print_usage (stdout, 0); break; /* -v or --verbose */ case 'v': verbose = 1; break; /* -n or --passes */ case 'n': passes = *optarg; break; /* Invalid option */ case '?': print_usage (stderr, 1); break; /* No more options */ case -1: break; /* Unexpected */ default: abort (); } } while (next_option != -1); srand ((unsigned) time (NULL)); for (i = optind ; i < argc ; i++) { if ((target = fopen (argv[i], "r+")) != NULL) { for (j = 0 ; j < passes ; ++j) { if (verbose) printf ("%s:\n", argv[i]); if (verbose) { printf ("Pass %d of %d\n", j+1, passes); fflush (stdout); }; rewind (target); for (k = 0 ; k < get_file_size (target) ; k++) fputc (rand () % 255, target); } fclose (target); } else fprintf (stderr, "%s: no such file\n", argv[i]); } return 0; } <file_sep>/* detached.c - creation of detached thread * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdlib.h> #include <pthread.h> void *thread_function(void *unused) { return NULL; } int main() { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); /* alternative approach is to create an ordinary joinable thread and make it detached with pthread_detach() */ pthread_create(&thread, &attr, &thread_function, NULL); pthread_attr_destroy(&attr); return EXIT_SUCCESS; } <file_sep>/* socket_inet.c - get web page content * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #define BUFFER_SIZE 1000 void get_homepage(int socket_fd) { char buffer[BUFFER_SIZE]; ssize_t characters_read_num; sprintf(buffer, "GET /\n"); write(socket_fd, buffer, strlen(buffer)); while (1) { characters_read_num = read(socket_fd, buffer, BUFFER_SIZE); if (characters_read_num == 0) return; fwrite(buffer, sizeof (char), characters_read_num, stdout); } } int main (int argc, char **argv) { int socket_fd; struct sockaddr_in name; struct hostent *hostinfo; if ((hostinfo = gethostbyname(argv[1])) == NULL) return 1; name.sin_family = AF_INET; name.sin_addr = *((struct in_addr*) hostinfo->h_addr); name.sin_port = htons(80); socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (connect(socket_fd, &name, sizeof (struct sockaddr_in)) == -1) { perror("connect"); return 1; } get_homepage(socket_fd); return 0; } <file_sep>#!/usr/bin/python import sys from xml.dom.minidom import parse class NotTextNodeError: pass def getTextFromNode(node): """Strips text from an XML node""" text = "" for n in node.childNodes: if n.nodeType == node.TEXT_NODE: text += n.nodeValue else: raise NotTextNodeError return text def nodeToDictionary(node): dictionary = {} siblings = {} for n in node.childNodes: multiple = False if n.nodeType != n.ELEMENT_NODE: continue if len(node.getElementsByTagName(n.nodeName)) > 1: multiple = True if not siblings.has_key(n.nodeName): siblings[n.nodeName] = [] try: text = getTextFromNode(n) except NotTextNodeError: if multiple: siblings[n.nodeName].append(nodeToDictionary(n)) dictionary.update({n.nodeName:siblings[n.nodeName]}) continue else: dictionary.update({n.nodeName:nodeToDictionary(n)}) continue if multiple: siblings[n.nodeName].append(text) dictionary.update({n.nodeName:siblings[n.nodeName]}) else: dictionary.update({n.nodeName:text}) return dictionary def XMLToDictionary(filename): dom = parse(filename) return nodeToDictionary(dom) if __name__ == "__main__": try: print "Parsing XML data..." addresses = XMLToDictionary(sys.argv[1]) except IndexError: addresses = XMLToDictionary('contacts.xml') query = raw_input ('Enter search pattern: ').lower() for contact in addresses['contacts']['contact']: if query in contact['lastname'].lower() or query in contact['firstname'].lower(): print print 'Name: ' + contact['firstname'] + ' ' + contact['lastname'] print 'Email: ' + contact['email'] <file_sep>/* thread_specific.c - storing data to thread specific data area * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <pthread.h> static pthread_key_t thread_log_key; void write_log(const char *msg) { FILE *thread_log; thread_log = (FILE *) pthread_getspecific(thread_log_key); fprintf(thread_log, "%s\n", msg); } void close_log(void *thread_log) { fclose((FILE *) thread_log); } void *thread_function(void *unused) { FILE *thread_log; char filename[20]; sprintf(filename, "thread%d.log", (int) pthread_self()); thread_log = fopen(filename, "w"); pthread_setspecific(thread_log_key, thread_log); write_log("Thread started"); return NULL; } int main() { int i; pthread_t threads[5]; pthread_key_create(&thread_log_key, close_log); for (i = 0 ; i < 5 ; i++) { pthread_create(&(threads[i]), NULL, thread_function, NULL); pthread_join(threads[i], NULL); } return 0; } <file_sep>// vim: ts=4 #ifndef CHROMOSOME_H #define CHROMOSOME_H static const int dimension = 2; static const int min_value = -100; static const int max_value = 100; static const int precision = 4; static const int value_range = max_value - min_value; class Chromosome { public: double value; unsigned int binary_val; static int n; Chromosome(int); void calculate_value(); }; #endif // CHROMOSOME_H <file_sep>import random import time def selection_sort(array): """Insertion sort Best case: O(n^2) Worst case: O(n^2) Average case: O(n^2) Space complexity: O(1) """ for i in range(len(array) - 1): min = i for j in range(i + 1, len(array)): if array[j] < array[min]: min = j array[i], array[min] = array[min], array[i] return array def insertion_sort(array): """Insertion sort Best case: O(n) Worst case: O(n^2) Average case: O(n^2) Space complexity: O(1) """ for i in range(1, len(array)): key = array[i] j = i while j > 0 and array[j - 1] > key: array[j] = array[j - 1] j = j - 1 array[j] = key return array def shell_sort(array): """Shell sort Best case: O(n) Average case: O(n^3/2) Space complexity: O(1) """ step = len(array) / 2 while step > 0: for i in range(step, len(array)): key = array[i] j = i while j > 0 and array[j - step] > key: array[j] = array[j - step] j = j - step array[j] = key step = step / 2 return array def bubble_sort(array): """Bubble sort Best case: O(n) Average case: O(n^2) Space complexity: O(1) """ for i in range(len(array)): for j in range(len(array) - 1, i, -1): if array[i] > array[j]: array[i], array[j] = array[j], array[i] return array def merge_sort(array): """Merge sort Best case: O(n log n) Average case: O(n log n) Worst case: O(n log n) """ def merge(left, right): i, j = 0, 0 result = [] while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i = i + 1 else: result.append(right[j]) j = j + 1 result += left[i:] result += right[j:] return result if len(array) <= 1: return array else: middle = len(array) / 2 left = merge_sort(array[:middle]) right = merge_sort(array[middle:]) return merge(left, right) def heap_sort(array): """Heap sort Best case: O(n log n) Worst case: O(n log n) Average case: O(n log n) """ def heapify(list, root, last): left = 2 * root right = 2 * root + 1 if left <= last and list[left] > list[root]: largest = left else: largest = root if right <= last and list[right] > list[largest]: largest = right if largest != root: list[root], list[largest] = list[largest], list[root] heapify(list, largest, last) def build_heap(list): n = len(list) - 1 for i in range(n / 2, -1, -1): heapify(list, i, n) build_heap(array) size = len(array) - 1 for i in range(size, 0, -1): array[0], array[i] = array[i], array[0] size = size - 1 heapify(array, 0, size) return array def quick_sort(array): """Quick sort Best case: O(n log n) Average case: O(n log n) Worst case: O(n^2) """ if array == []: return [] return quick_sort([e for e in array[1:] if e <= array[0]]) + array[0:1] + quick_sort([e for e in array[1:] if e > array[0]]) if __name__ == '__main__': array = range(4096) random.shuffle(array) for sort in [insertion_sort, selection_sort, bubble_sort, shell_sort, merge_sort, heap_sort, quick_sort]: start = time.time() sorted_array = sort(array[:]) end = time.time() print "%s: %f" % (sort.__name__.ljust(16), end - start) if sorted_array != sorted(array): print "SORT NOT OK!" <file_sep>#include <iostream> #include "genetic.h" using namespace std; int main(int argc, char **argv) { GeneticAlgorithm ga(1); cout << "Pocetne vrijednosti: " << endl; ga.evaluate(); ga.print(); for (int i = 0 ; i < iterations_num * population_size ; ++i) { ga.evaluate(); ga.select(); ga.breed(); ga.mutate(); } cout << "Vrijednosti nakon " << dec << iterations_num << " iteracija genetskog algoritma: " << endl; ga.print(); ga.result(); return 0; } <file_sep>// vim: ts=4 #ifndef GENETIC_H #define GENETIC_H #include "chromosome.h" using namespace std; static const int iterations_num = 10000; static const int population_size = 10; static const int chromosomes_to_breed = 3; static const double mutation_probability = 0.2; class GeneticAlgorithm { int n, max_index; int indexes[3], parms[10]; unsigned int threshold; double *func_values; Chromosome ***chromosoms; short function; public: GeneticAlgorithm(int); ~GeneticAlgorithm(); void evaluate(); void select(); void breed(); void mutate(); void result(); void print(); }; #endif // GENETIC_H <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) #define MAX_POINTS 100 struct point { int x, y; } points[MAX_POINTS]; struct coef { int a, b, c; } coefs[MAX_POINTS], ray; int ymin, ymax; int fullscreen = 0, current_point = 0, num_points; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; int s[100]; void color_poly(); void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } void resize_scene(int width, int height) { window_width = width; window_height = height; current_point = 0; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, window_width, 0, window_height); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glColor3f(0, 1, 0); } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'c': color_poly(); break; case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'q': exit(EXIT_SUCCESS); } glFlush(); } void draw_poly() { int i; glBegin(GL_LINES); for (i = 0 ; i < num_points ; ++i) { /* crtanje linija */ glVertex2i(points[i].x, points[i].y); glVertex2i(points[i + 1].x, points[i + 1].y); /* racunanje koeficijenata smjera bridova */ coefs[i].a = points[i].y - points[i + 1].y; coefs[i].b = -points[i].x + points[i + 1].x; coefs[i].c = points[i].x * points[i + 1].y - points[i + 1].x * points[i].y; } glEnd(); glFlush(); } double set_t(int x1, int y1, int x2, int y2, int x3, int y3) { int d1 = x2 - x1; int d2 = y2 - y1; double t; if (d1) t = (x3 - x1) / (double) d1; if (d2) t = (y3 - y1) / (double) d2; return t; } int crossings(int x0, int y0, struct coef ray) { int i, x3, y3, w3, n0; int d1, d2; double t, t1; n0 = 0; for (i = 0 ; i < num_points ; ++i) { x3 = coefs[i].b * ray.c - coefs[i].c * ray.b; y3 = -coefs[i].a * ray.c + coefs[i].c * ray.a; w3 = coefs[i].a * ray.b - coefs[i].b * ray.a; if (w3 == 0) continue; x3 /= w3; y3 /= w3; t = set_t(x0, y0, x0 + 1, y0, x3, y3); if (t < 0) continue; t1 = t; t = set_t(points[i].x, points[i].y, points[i+1].x, points[i+1].y, x3, y3); if (t <= 0 || t > 1) continue; if (t == 1) { d1 = ray.a * points[i].x + ray.b * points[i].y + ray.c; d2 = ray.a * points[i+2].x + ray.b * points[i+2].y + ray.c; if ((((d1 > 0) && (d2 > 0)) || ((d1 < 0) && (d2 < 0)))) continue; } s[n0++] = t1; } return n0; } int is_in_poly(int x, int y) { struct coef ray = {0, 1, -y}; if (crossings(x, y, ray) % 2) return 1; return 0; } void color_poly() { int i, y, z, n, tmp; struct coef ray = {0, 1, 0}; int ymin, ymax; ymin = ymax = points[0].y; for (i = 0 ; i < num_points ; ++i) { if (points[i].y < ymin) ymin = points[i].y; if (points[i].y > ymax) ymax = points[i].y; } for (y = ymin ; y < ymax ; y++) { ray.c = -y; n = crossings(0, y, ray); if (n < 2) continue; do { z = 0; for (i = 0 ; i < n - 1 ; ++i) if (s[i] > s[i+1]) { tmp = s[i]; s[i] = s[i+1]; s[i+1] = tmp; z = 1; } } while (z); for (i = 0 ; i < n - 1 ; i += 2) { glBegin(GL_LINES); glVertex2i(s[i], y); glVertex2i(s[i+1], y); glEnd(); } } glFlush(); } void mouse_handler(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && current_point < num_points) { points[current_point].x = x; points[current_point].y = window_height - y; if (current_point == 0) points[num_points] = points[0]; glBegin(GL_POINTS); glVertex2i(points[current_point].x, points[current_point].y); glEnd(); glFlush(); ++current_point; printf("Kordinate tocke %d: (%d, %d)\n", current_point, x, y); } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { resize_scene(window_width, window_height); } if (current_point == num_points && state == GLUT_DOWN) { draw_poly(); if (is_in_poly(x, window_height - y)) printf("Točka (%d, %d) je unutar poligona\n", x, y); else printf("Točka (%d, %d) nije unutar poligona\n", x, y); return; } } int main(int argc, char **argv) { printf("Unesi broj točaka: "); scanf("%d", &num_points); glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMouseFunc(mouse_handler); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>/* des.c - DES implementation */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "des.h" #include "base64.h" /* initial permutation */ uchar_t t1[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; /* C block permutation */ uchar_t t2[28] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36 }; /* D block permutation */ uchar_t t3[28] = { 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; /* key rotation */ uchar_t t4[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; /* C and D block merging */ uchar_t t5[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; /* 32 to 48 bits expansion */ uchar_t t6[48] = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; /* function result */ uchar_t t7[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; /* selection tables */ uchar_t s[8][4][16] = { { {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, { 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13} }, { {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, { 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9} }, { {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, { 1,10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12} }, { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14} }, { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, { 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3} }, { {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, { 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13} }, { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, { 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12} }, { {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, { 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11} } }; /* permutates table source to table dest using permutation table t of size n */ void permutate (uchar_t *perm_table, uchar_t *src, uchar_t *dest, int size, int mode) { int i; i = size / 8; if (i % 8 == 0) --i; while (i >= 0) { dest[i] = '\0'; --i; } for (i = 0 ; i < size ; ++i) { if (mode == DES_REGULAR_PERMUTATION) if (src[(perm_table[i] - 1) / 8] & (0x80 >> ((perm_table[i] - 1) % 8))) dest[i / 8] |= 0x80 >> (i % 8); if (mode == DES_INVERSE_PERMUTATION) if (src[i / 8] & (0x80 >> (i % 8))) dest[(perm_table[i] - 1) / 8] |= 0x80 >> ((perm_table[i] - 1) % 8); } } void f (uchar_t *in_block, uchar_t *out_block, uchar_t *key) { int i; unsigned int sest; uchar_t er[7]; uchar_t rez[4] = {0, 0, 0, 0}; uchar_t row, column; permutate (t6, in_block, er, 48, DES_REGULAR_PERMUTATION); for (i = 0 ; i < 6 ; ++i) er[i] = er[i] ^ key[i]; er[6] = '\0'; for (i = 0 ; i < 8; ++i) { sest = er[(i * 6) / 8] << ((i * 6) % 8); sest |= (er[((i + 1) * 6) / 8] & 0xff) >> (8 - (i * 6) % 8); sest = (sest >> 2) & 0x3f; row = ((sest & 0x20) >> 4) | (sest & 1); column = (sest >> 1) & 0x0f; rez[i / 2] |= (s[i][row][column] & 0x0f) << ((1 - i % 2) * 4); } permutate (t7, rez, out_block, 32, DES_REGULAR_PERMUTATION); } void des_block (uchar_t *in_block, uchar_t *key, uchar_t *out_block, int mode) { int i, j; uchar_t permutation[8], func_res[4]; uchar_t l1[4], r1[4], l2[4], r2[4]; permutate (t1, in_block, permutation, 64, DES_REGULAR_PERMUTATION); for (i = 0 ; i < 4 ; ++i) l1[i] = permutation[i]; for (i = 0 ; i < 4 ; ++i) r1[i] = permutation[i + 4]; for (j = 0; j < 16; ++j) { for (i = 0 ; i < 4 ; ++i) l2[i] = r1[i]; if (mode == DES_ENCRYPT) f (r1, func_res, key + j * 6); if (mode == DES_DECRYPT) f (r1, func_res, key + (15 - j) * 6); for(i = 0 ; i < 4 ; ++i) r2[i] = l1[i] ^ func_res[i]; for(i = 0 ; i < 4 ; ++i) l1[i] = l2[i]; for(i = 0 ; i < 4 ; ++i) r1[i] = r2[i]; } for (i = 0 ; i < 4 ; ++i) permutation[i] = r1[i]; for (i = 0 ; i < 4 ; ++i) permutation[i + 4] = l1[i]; permutate (t1, permutation, out_block, 64, DES_INVERSE_PERMUTATION); } void des_generate_keys (uchar_t *key, uchar_t *key_set) { int i, j, k; uchar_t key_c_block[4], key_d_block[4], key_merged[8]; uchar_t bit, tmp; permutate (t2, key, key_c_block, 28, DES_REGULAR_PERMUTATION); permutate (t3, key, key_d_block, 28, DES_REGULAR_PERMUTATION); for (i = 0 ; i < 16 ; ++i) { for (j = 0 ; j < t4[i] ; ++j) { bit = 0x80 & key_c_block[3]; key_c_block[3] <<= 1; k = 2; while (k >= 0) { tmp = 0x80 & key_c_block[k]; key_c_block[k] <<= 1; if (bit) key_c_block[k] |= (bit >> 7); bit = tmp; --k; } if (bit) key_c_block[3] |= (bit >> 3); bit = 0x80 & key_d_block[3]; key_d_block[3] <<= 1; k = 2; while (k >= 0) { tmp = 0x80 & key_d_block[k]; key_d_block[k] <<= 1; if (bit) key_d_block[k] |= (bit >> 7); bit = tmp; --k; } if (bit) key_d_block[3] |= (bit >> 3); } key_merged[0] = key_c_block[0]; key_merged[1] = key_c_block[1]; key_merged[2] = key_c_block[2]; key_merged[3] = key_c_block[3]; key_merged[4] = key_d_block[0]; key_merged[5] = key_d_block[1]; key_merged[6] = key_d_block[2]; key_merged[7] = key_d_block[3]; for(j = 4 ; j <= 7 ; ++j) { bit = 0x80 & key_merged[7]; key_merged[7] <<= 1; k = 6; while (k >= 4) { tmp = 0x80 & key_merged[k]; key_merged[k] <<= 1; if (bit) key_merged[k] |= (bit >> 7); bit = tmp; --k; } if (bit) key_merged[3] |= (bit >> j); } permutate (t5, key_merged, key_set + i * 6, 48, DES_REGULAR_PERMUTATION); } } /* main DES function - encrypts file with given key and writes output to file */ void des_crypt (const char *in_file, const char *out_file, uchar_t *key, int mode) { int i, size, done; FILE *in, *out; uchar_t in_block[8], out_block[8]; uchar_t *key_set; if (!(in = fopen (in_file, "r"))) { perror (in_file); exit (EXIT_FAILURE); } if (!(out = fopen (out_file, "wb"))) { perror (out_file); exit (EXIT_FAILURE); } key_set = malloc (16 * 6); des_generate_keys (key, key_set); done = 0; while (!done && (size = fread (in_block, 1, 8, in)) !=0 ) { if (feof (in)) { for (i = size ; i < 8 ; ++i) in_block[i] = DES_PADDING; done = 1; } des_block (in_block, key_set, out_block, mode); fwrite (out_block, 8, 1, out); } fclose (in); fclose (out); free (key_set); } void des_convert_to_base64 (const char *in_file, const char *out_file) { int i, buffer_size, n; unsigned char *in_buffer, *out_buffer; FILE *in, *out; if (!(in = fopen (in_file, "rb"))) { perror (in_file); exit (EXIT_FAILURE); } if (!(out = fopen (out_file, "w"))) { perror (out_file); exit (EXIT_FAILURE); } fprintf (out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (out, "Description:\n Crypted file\n\n"); fprintf (out, "Method:\n DES\n\n"); fprintf (out, "File name:\n %s\n\n", in_file); fprintf (out, "Data:\n "); fseek (in, 0L, SEEK_END); buffer_size = ftell (in); fseek (in, 0L, SEEK_SET); in_buffer = malloc (buffer_size); out_buffer = malloc (buffer_size * 2); n = fread (in_buffer, 1, buffer_size, in); base64_encode (in_buffer, out_buffer, n); for (i = 0 ; i < strlen (out_buffer) ; ++i) { if (!(i % 60) && i != 0) fprintf (out, "\n "); fprintf (out, "%c", out_buffer[i]); } fprintf (out, "\n---END OS2 CRYPTO DATA---\n"); free (in_buffer); free (out_buffer); fclose (in); fclose (out); } void des_convert_from_base64 (const char *in_file, const char *out_file) { uchar_t *out_buffer, *in_buffer, *tmp_buffer; char buffer[256]; FILE *in, *out; int i, j, begin, end, len, n; if (!(in = fopen (in_file, "r"))) { perror (in_file); exit (EXIT_FAILURE); } if (!(out = fopen (out_file, "wb"))) { perror (out_file); exit (EXIT_FAILURE); } do { fgets (buffer, 256, in); if (!strcmp (buffer, "Data:\n")) begin = ftell (in); if (!strcmp (buffer, "---END OS2 CRYPTO DATA---\n")) end = ftell (in) - strlen ("---END OS2 CRYPTO DATA---\n"); } while (!feof (in)); len = end - begin - 1; in_buffer = malloc (len); tmp_buffer = malloc (len); out_buffer = malloc (len); fseek (in, begin, SEEK_SET); n = fread (in_buffer, 1, len, in); for (i = 0, j = 0 ; i < n ; ++i) { if (in_buffer[i] == ' ' || in_buffer[i] == '\n') continue; tmp_buffer[j++] = in_buffer[i]; } tmp_buffer[j] = '\0'; j = base64_decode (tmp_buffer, out_buffer); fwrite (out_buffer, 1, j, out); fclose (in); fclose (out); free (in_buffer); free (tmp_buffer); free (out_buffer); } /* generates random DES key to file */ void des_generate_key (const char *filename) { FILE *out; srand ((unsigned) time (NULL)); if (!(out = fopen (filename, "w"))) { perror (filename); exit (EXIT_FAILURE); } fprintf (out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (out, "Description:\n Secret key\n\n"); fprintf (out, "Method:\n DES\n\n"); fprintf (out, "Secret key:\n "); fprintf (out, "%0x%0x\n", rand(), rand()); fprintf (out, "---END OS2 CRYPTO DATA---\n"); fclose (out); } /* returns DES key from well formed key file */ char *des_get_key_from_file (const char *filename) { FILE *in; char buffer[256]; uchar_t *key = malloc (9); unsigned int key1, key2; if (!key) { perror ("malloc"); exit (EXIT_FAILURE); } if (!(in = fopen (filename, "r"))) { perror (filename); exit (EXIT_FAILURE); } do { fgets (buffer, 256, in); if (!strcmp (buffer, "Secret key:\n")) { fgets (buffer, 256, in); buffer[20] = '\0'; sscanf (buffer, "%8x%8x", &key1, &key2); break; } } while (!feof (in)); key[3] = * ((uchar_t *) &key1); key[2] = * (((uchar_t *) &key1) + 1); key[1] = * (((uchar_t *) &key1) + 2); key[0] = * (((uchar_t *) &key1) + 3); key[7] = * ((uchar_t *) &key2); key[6] = * (((uchar_t *) &key2) + 1); key[5] = * (((uchar_t *) &key2) + 2); key[4] = * (((uchar_t *) &key2) + 3); key[8] = '\0'; return key; } <file_sep>#ifndef _SHA_H #define _SHA_H char *sha1 (const char *filename, const char *output); #endif /* _SHA_H */ <file_sep>#!/bin/sh # Convert DOS files to Unix files # (C) 2003 <NAME> <<EMAIL>> if [ $# -ne 2 ]; then echo "Usage: dos2unix inputfile outputfile" exit 1 fi tr -d '\015' < $1 > $2 <file_sep>/* eratosten.c - trazenje prim brojeva pomocu eratostenovog sita * * (C) 2003 <NAME> */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main () { int i, j, n; int *sieve; /* Odredi velicinu sita */ printf ("Unesi velicinu sita: "); scanf ("%d", &n); if ((sieve = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje\n"); exit (1); } /* Inicijalno su svi brojevi prim */ for (i=1 ; i<n ; ++i) sieve[i] = 1; /* Za svaki prim broj ukloni sve njegove visekratnike */ for (i=2 ; i<=sqrt(n) ; ++i) { if (sieve[i] == 1) for (j=2 ; j<=n/i ; ++j) sieve[i*j] = 0; } /* Ispisi prim brojeve */ for (i=1 ; i<n ; ++i) if (sieve[i] == 1) printf ("%d ", i); printf ("\n"); free (sieve); return 0; } <file_sep>/* memory_mapping.c - IPC with mapped memmory * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> #define FILE_LENGTH 0x100 /* get a pseudorandom number withing given interval. use uniform distribuion */ int random_range(int low, int high) { int range = high - low; return low + (int) (((double) range) * rand () / (RAND_MAX + 1.0)); } int main(int argc, char **argv) { int fd; void *file_memory; if (argc != 2) { printf("Output file not specified!\n"); exit(EXIT_FAILURE); } srand((unsigned) time(NULL)); /* open file and seek to the end of the file */ fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); /* allocate space in file */ lseek(fd, FILE_LENGTH + 1, SEEK_SET); write(fd, "", 1); lseek(fd, 0, SEEK_SET); file_memory = mmap(0, FILE_LENGTH, PROT_WRITE, MAP_SHARED, fd, 0); close(fd); /* write random numbers to memmory */ sprintf((char *) file_memory, "%d\n", random_range(-100, 100)); munmap(file_memory, FILE_LENGTH); return EXIT_SUCCESS; } <file_sep>/* signals.c - custom signal handlers * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> void sigint_handler() { fprintf(stderr, "Received: SIGINT(2)\n"); } void sigquit_handler() { fprintf(stderr, "Received: SIGQUIT(3)\n"); } void sigterm_handler() { fprintf(stderr, "Received: SIGTERM(15)\n"); } void sigalrm_handler() { fprintf(stderr, "Received: SIGALRM(14)\n"); exit(0); } int main() { struct sigaction sa; memset(&sa, 0, sizeof (struct sigaction)); sa.sa_handler = sigalrm_handler; sigaction(SIGALRM, &sa, NULL); sa.sa_handler = sigint_handler; sigaction(SIGINT, &sa, NULL); sa.sa_handler = sigquit_handler; sigaction(SIGQUIT, &sa, NULL); sa.sa_handler = sigterm_handler; sigaction(SIGTERM, &sa, NULL); /* send SIGALRM in 10 sec */ alarm(10); /* Run in infinite loop, as program will be stopped by SIGALRM handler */ for (;;); return EXIT_SUCCESS; } <file_sep>import xchat, re __module_name__ = 'triviacheater' __module_version__ = '0.1' __module_description__ = 'trivia quiz cheater' bot_name = 'ZecBot' database_file = 'baza.txt' def chan_msg_hook(word, word_eol, userdata): author, message = word[0], word[1] if author != bot_name: return xchat.EAT_NONE ignore_words = ['hint', 'score', 'Odgovor'] for w in ignore_words: if re.compile(w).findall(message): return xchat.EAT_NONE nums = re.compile('\d+').findall(message) if nums and len(nums) > 1: question_num = nums[1] if question_num < 10: return xchat.EAT_NONE answer = '' try: for s in database[question_num]: answer = answer + s + ' ' answer = answer[:-1] xchat.hook_timer(400 * len(answer), timer_cb, answer.lower()) except KeyError: pass def timer_cb(data): xchat.command('say ' + data) print '*' * 31 print 'Trivia Quiz Cheater version ' + __module_version__ print '*' * 31 database = {} for line in file(database_file): data = line.rstrip().split() database[data[0]] = data[1:] xchat.hook_print("Channel Message", chan_msg_hook) <file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- from sys import exit try: f = file('/proc/acpi/ibm/thermal') data = f.readline().split()[1:] except: print 'Module ibm-acpi is not loaded' exit(1) titles = ['CPU:', 'PCI:', 'HDD:', 'GPU:', 'System battery:', 'UltraBay battery:', 'System battery:', 'UltraBay battery:'] # R60e specific del titles[3], data[3], titles[4], data[4], titles[5], data[5] for e in zip(titles, data): if e[1] != '-128': print e[0], e[1], '°C', else: print e[0], 'No data' <file_sep>#!/usr/bin/python # sudoku.py - sudoku solver # (C) 2006 <NAME> <<EMAIL>> import sys def get_square(table, row, column): """Returns 3x3 square containing element at table[row:column]""" row_start = 3 * (row / 3) row_end = row_start + 3 column_start = 3 * (column / 3) column_end = column_start + 3 return [x[column_start:column_end] for x in table[row_start:row_end]] def move_posible(element, table, row, column): """Checks if move is posible""" if table[row][column] <> 'X': return False if element in table[row]: return False if element in [e[column] for e in table]: return False for r in get_square(table, row, column): if element in r: return False return True def solved(table): """Checks if no more moves are posible""" for row in table: if 'X' in row: return False return True def unique_move(element, table, row, column): """Checks if move is unique (there is no other place in row or column in which given element can go""" if not move_posible(element, table, row, column): return False moves_posible = 0 for i in range(9): if move_posible(element, table, row, i): moves_posible = moves_posible + 1 if moves_posible == 1: return True moves_posible = 0 for i in range(9): if move_posible(element, table, i, column): moves_posible = moves_posible + 1 if moves_posible == 1: return True return False def solution(table): """Solves sudoku puzzle given with table""" while not solved(table): for i in range(9): for j in range(9): for num in range(1,10): if unique_move(str(num), table, i, j): table[i][j] = str(num) break return table def output(table): """Nicer output of solution""" table.insert(3, []) table.insert(7, []) for row in table: row.insert(3, " ") row.insert(7, " ") print " ".join(row) if __name__ == "__main__": try: src = file(sys.argv[1]) except: print 'Syntax: sudoku.py <data file>' sys.exit(1) table = [element.rstrip().split(' ') for element in src] s = solution(table) output(s) <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #define SELECT_TIMEOUT 5 int main() { fd_set readfds, writefds; struct timeval tv; /* check stding for input */ FD_ZERO(&readfds); FD_SET(STDIN_FILENO, &readfds); /* check stdout for writting */ FD_ZERO(&writefds); FD_SET(STDOUT_FILENO, &writefds); tv.tv_sec = SELECT_TIMEOUT; tv.tv_usec = 0; if (select(STDOUT_FILENO + 1, &readfds, &writefds, NULL, &tv) == -1) { perror("select"); return EXIT_FAILURE; } if (FD_ISSET(STDIN_FILENO, &readfds)) printf("STDIN is ready for reading\n"); if (FD_ISSET(STDOUT_FILENO, &writefds)) printf("STDOUT is ready for writing\n"); return EXIT_SUCCESS; } <file_sep>#!/bin/sh # calculates time on the Internet # (C) 2002 <NAME> <<EMAIL>> syslog="/var/log/syslog" grep "Connect time" $syslog | cut -d: -f4 | cut -d" " -f4 | awk '{sum += $1} END{print sum}' <file_sep>import xchat, re __module_name__ = 'kicker' __module_version__ = '0.1' __module_description__ = 'kicks on forbidden words' forbidden_words = ['martin', 'strpic', 'ogame', 'pixica'] def chan_msg_hook(word, word_eol, userdata): author, message = word[0], word[1] for w in forbidden_words: if w.lower() in message.lower(): xchat.command('kick ' + author + ' ' + 'forbidden word: ' + w) xchat.hook_print("Channel Message", chan_msg_hook) <file_sep>/* endian.c - determine endianess of system * * (C) 2005 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> int main() { union { short num; char bytes[sizeof (short)]; } un; un.num = 0x0102; if (sizeof (short) == 2) { if (un.bytes[0] == 1 && un.bytes[1] == 2) printf ("Big endian\n"); else if (un.bytes[0] == 2 && un.bytes[1] == 1) printf ("Little endian\n"); else printf ("Confused... Not little nor big endian?!?\n"); } else { printf ("Size of short int is not 2 bytes\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <file_sep>/* pipe.c - IPC by using pipes * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int writer(const char *msg, int count, FILE *stream) { for (; count > 0 ; count--) { fprintf(stream, "%s\n", msg); fflush(stream); sleep(1); } } int reader(FILE *stream) { char buffer[1024]; while (!feof(stream) && !ferror(stream) && fgets(buffer, sizeof (buffer), stream) != NULL) fputs(buffer, stdout); } int main () { int fds[2]; pid_t pid; pipe(fds); pid = fork(); if (pid == 0) { FILE *stream; close(fds[1]); stream = fdopen(fds[0], "r"); reader(stream); close(fds[0]); } else { FILE *stream; close(fds[0]); stream = fdopen(fds[1], "w"); writer("TEST", 6, stream); close(fds[1]); } return EXIT_SUCCESS; } <file_sep>/* sigchld.c - asynchronous zombie cleaning with SIGCHLD handler * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/wait.h> #include <sys/types.h> sig_atomic_t child_exit_status; void handler(int signal_number) { int status; wait(&status); child_exit_status = status; } int main() { pid_t pid; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = &handler; sigaction(SIGCHLD, &sa, NULL); pid = fork(); if (pid) { /* Parent, sleep for 30s to make sure child will become zombie */ sleep(30); } else { /* Exit immediately. No zombie should be reported within ps command output as it should be collected by signal handler */ exit(0); } return 0; } <file_sep>/* shell_sort.c - Shell sort algoritam * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> void shell_sort (int *a, int n) { int i, j, step, tmp; for (step=n/2 ; step>0 ; step /= 2) for (i=step ; i<n ; i++) { tmp = a[i]; for (j=i ; j>=step && a[j-step]>tmp; j-=step) a[j] = a[j-step]; a[j] = tmp; } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); shell_sort (polje, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>class Singleton(object): """Singleton pattern - make sure we have only one instance of the class""" _instance = None def __new__(cls, *args, **kwargs): if Singleton._instance is None: Singleton._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return Singleton._instance class Borg: """Share state between instances of the class""" _shared_state = {} def __init__(self): self.__dict__ = Borg._shared_state <file_sep>#include <stdio.h> #include <stdlib.h> #include "sha.h" #define UINT 0xFFFFFFFFUL #define ROTL(X, N) ((((X) << N) | ((X) >> (32 - N))) & UINT) int file_end; int finished = 0; unsigned int starting_word; unsigned int K (int t) { if (t >= 0 && t < 20) return 0x5A827999; if (t >= 20 && t < 40) return 0x6ED9EBA1; if (t >= 40 && t < 60) return 0x8F1BBCDC; return 0xCA62C1D6; } unsigned int f_sha1 (int t, unsigned int b, unsigned int c, unsigned int d) { if (t <= 19) return ((b & c) | ((~b) & d)); if ((t >= 40) && (t <= 59)) return ((b & c) | (b & d) | (c & d)); return (b ^ c ^ d); } unsigned int get_padding (FILE *fp, int x, int y) { int getbyte; if (!file_end) { getbyte = getc (fp); if (getbyte != EOF) { starting_word += 8; return (((unsigned int) getbyte) << (8 * (3 - y))); } else { file_end = 1; return (128UL << (8 * (3 - y))); } } if (x < 14) return 0; if ((x == 14) && (y == 0)) file_end = 2; if (file_end == 1) return 0; if (x == 14) { switch (y) { case 0: return (unsigned int) ((starting_word & 0xFF00000000000000U) >> 32); case 1: return (unsigned int) ((starting_word & 0x00FF000000000000U) >> 32); case 2: return (unsigned int) ((starting_word & 0x0000FF0000000000U) >> 32); case 3: return (unsigned int) ((starting_word & 0x000000FF00000000U) >> 32); } } else if (x == 15) { switch (y) { case 0: return (unsigned long int) (starting_word & 0xFF000000Ul); case 1: return (unsigned long int) (starting_word & 0x00FF0000Ul); case 2: return (unsigned long int) (starting_word & 0x0000FF00Ul); case 3: finished = 1; return (unsigned long int) (starting_word & 0x000000FFUl); } } return 0; } char *sha1 (const char *filename, const char *output) { FILE *in, *out; int i, j, t = 0; unsigned int a, b, c, d, e, w[80], temp; unsigned int h[] = {0x67452301UL, 0xEFCDAB89UL, 0x98BADCFEUL, 0x10325476UL, 0xC3D2E1F0UL}; char *hash = malloc (100); finished = 0; starting_word = 0; file_end = 0; if ((in = fopen (filename, "rb")) == NULL) { perror (filename); exit (EXIT_FAILURE); } if ((out = fopen (output, "w")) == NULL) { perror (output); exit (EXIT_FAILURE); } while (!finished) { for (i = 0 ; i < 16 ; ++i) for (j = 0, w[i] = 0 ; j < 4 ; ++j) w[i] |= get_padding (in, i, j); for (t = 16 ; t < 80; ++t) w[t] = ROTL (w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16], 1); a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; for(t = 0 ; t < 80; ++t) { temp = (ROTL (a, 5) + f_sha1 (t, b, c, d) + e + w[t] + K (t)) & UINT; e = d; d = c; c = ROTL(b, 30); b = a; a = temp; } h[0] = (h[0] + a) & UINT; h[1] = (h[1] + b) & UINT; h[2] = (h[2] + c) & UINT; h[3] = (h[3] + d) & UINT; h[4] = (h[4] + e) & UINT; } fprintf (out, "---BEGIN OS2 CRYPTO DATA---\n"); fprintf (out, "Description:\n Signature\n\n"); fprintf (out, "File name:\n %s\n\n", filename); fprintf (out, "Method:\n SHA1\n\n"); fprintf (out, "Key length:\n AO\n\n"); fprintf (out, "Signature:\n %08x%08x%08x%08x%08x\n", h[0], h[1], h[2], h[3], h[4]); fprintf (out, "---END OS2 CRYPTO DATA---\n"); sprintf (hash, "%08x:%08x:%08x:%08x:%08x", h[0], h[1], h[2], h[3], h[4]); fclose (in); fclose (out); return hash; } <file_sep>/* pthread.c - thread creation * * compile with i -lpthread -D_REENTRANT * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define MAX_THREADS 5 void *thread_function(void *arg) { while(1) { printf("Thread: %d (ID = %d)\n", *(int *) arg, pthread_self()); sleep(1); } } int main() { int i, id[MAX_THREADS]; pthread_t threads[MAX_THREADS]; for (i = 0 ; i < MAX_THREADS ; ++i) { id[i] = i; pthread_create(&threads[i], NULL, &thread_function, &id[i]); } /* wait for threads to finish */ for (i = 0 ; i < MAX_THREADS ; ++i) { pthread_join(threads[i], NULL); } return EXIT_SUCCESS; } <file_sep>#!/bin/sh # Displays dropped input packets destination port statistics # Identifier in logs STR="IPT INPUT" # default log file LOG='/var/log/syslog' grep "$STR" $LOG | tr ' ' '\n' | grep DPT | sort | uniq -c | sort -n -r | head -10 <file_sep>/* environtment.c - show environment vriables * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> extern char **environ; int main() { char **var; for (var = environ ; *var ; var++) printf("%s\n", *var); return 0; } <file_sep>/* clrscr.c - clear screen program (conforming to ANSI X3.64 standard) * * (C) 2004 <NAME> <<EMAIL>> * * \033[2J - erase the screen * \033[1;1H - position the cursor to row 1 column 1 */ #include <stdio.h> int main() { printf("\033[2J\033[1;1H"); return 0; } <file_sep>#!/usr/bin/python # Simple Web service for monitoring *nix server # Original XMLRPCServer code provided by <NAME>, 2005. # # ChangeLog: # Dec 31 2005 (ipozgaj) - added configurability via config file # # TODO list: # make command output sequence in same order as in configuration file # make command title letters to be in same case as in configuration file from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler import os, sys, time, ConfigParser config = ConfigParser.ConfigParser() # write preamble to output def open_log (buffer, bgcolor, fgcolor): fgcolor = fgcolor.replace("\"", "") bgcolor = bgcolor.replace("\"", "") buffer = "<body text=\"" + fgcolor + "\" bgcolor=\"" + bgcolor + "\">" buffer = buffer + "<font face=\"Verdana\">" buffer = buffer + "<hr>Time: " + time.strftime ("%c") + "<hr>" return buffer # close HTML tags specified in preamble def close_log (buffer): buffer = buffer + "</font>" buffer = buffer + "</body>" return buffer # add output from system command to user output def add_command_output (buffer, title, command): try: data = os.popen(command).read() data = data.replace ("<", "&lt;") data = data.replace (">", "&gt;") data = "<pre>" + data + "</pre>" except: print "Error" buffer = buffer + "<br><b>" + title + "</b>: " + data return buffer # HTTP server class class RequestHandler (SimpleXMLRPCRequestHandler): def do_GET (self): if config.get ("General", "access_control") == "yes": if self.client_address[0] not in config.options ("Allowed hosts"): print "Rejected request from: " + self.client_address[0] return buffer = "" buffer = open_log (buffer, config.get ("Colors", "background"), config.get ("Colors", "text")) for command in config.options ("Commands"): buffer = add_command_output (buffer, command, config.get ("Commands", command)) buffer = close_log (buffer) # return data to client self.send_response (200) self.send_header ("Content-type", "text/html") self.send_header ("Content-length", str (len (buffer))) self.end_headers() self.wfile.write (buffer) self.wfile.flush() self.connection.shutdown (1) # main function if __name__ == '__main__': print "Parsing configuration file..." config.read ("hostinfo.cfg") service_port = config.get("General", "port") print "Starting service on local port " + service_port + "..." local_server = SimpleXMLRPCServer (("0.0.0.0", int (service_port)), RequestHandler) local_server.register_function (open_log) local_server.register_function (close_log) local_server.register_function (add_command_output) try: local_server.serve_forever() except: print "Shutting down service..." <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) #define ROTATION 1 struct point { float x, y, z; } points[5000]; struct poligon { int v1, v2, v3; } poligons[10000]; struct coef { float a, b, c, d; } coefs[10000]; int zoom = -5; int num_points, num_poligons; int fullscreen = 0, num_points; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; float theta = 0; void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5f); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene() { int i; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef (0.0, 0.0, zoom); glRotatef (theta, 1.0, 0.5, 0.25); glColor3f(0, 1, 0); glBegin(GL_LINES); for (i = 1 ; i < num_poligons ; ++i) { glVertex3f(points[poligons[i].v1].x, points[poligons[i].v1].y, points[poligons[i].v1].z); glVertex3f(points[poligons[i].v2].x, points[poligons[i].v2].y, points[poligons[i].v2].z); glVertex3f(points[poligons[i].v3].x, points[poligons[i].v3].y, points[poligons[i].v3].z); glVertex3f(points[poligons[i].v1].x, points[poligons[i].v1].y, points[poligons[i].v1].z); glVertex3f(points[poligons[i].v2].x, points[poligons[i].v2].y, points[poligons[i].v2].z); glVertex3f(points[poligons[i].v3].x, points[poligons[i].v3].y, points[poligons[i].v3].z); } glEnd(); theta += ROTATION; glutSwapBuffers(); } void resize_scene(int width, int height) { window_width = width; window_height = height; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective (80, (float) window_width / window_height, 1.0, 6000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'y': zoom++; break; case 'x': zoom--; break; case 'q': exit(EXIT_SUCCESS); } glFlush(); } int is_in_model(float x0, float y0, float z0) { int i; for (i = 1 ; i < num_poligons ; ++i) if ((x0 * coefs[i].a + y0 * coefs[i].b + z0 * coefs[i].c + coefs[i].d) > 0) return 0; return 1; } int main(int argc, char **argv) { char mod, *t; float x, y, z; char buffer[256]; FILE *in; int p1, p2, p3; float x0, y0, z0; if (argc != 2) { fprintf(stderr, "Sintaksa: object [obj fajl]\n"); exit(EXIT_FAILURE); } if ((in = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Ne moze se otvoriti: %s\n", argv[1]); exit(EXIT_FAILURE); } printf("Unesi tocku: "); scanf("%f %f %f", &x0, &y0, &z0); num_points = num_poligons = 0; while(fgets(buffer, 256, in)) { t = strchr(buffer, '\n'); *t = '\0'; if (strchr(buffer, '#')) continue; if (sscanf(buffer, "%c %f %f %f", &mod, &x, &y, &z) == 4) { switch (mod) { case 'v': case 'V': ++num_points; points[num_points].x = x; points[num_points].y = y; points[num_points].z = z; break; case 'f': case 'F': ++num_poligons; p1 = poligons[num_poligons].v1 = (int) x; p2 = poligons[num_poligons].v2 = (int) y; p3 = poligons[num_poligons].v3 = (int) z; coefs[num_poligons].a = (points[p2].y - points[p1].y) * (points[p3].z - points[p1].z) - (points[p2].z - points[p1].z) * (points[p3].y - points[p1].y); coefs[num_poligons].b = -(points[p2].x - points[p1].x) * (points[p3].z - points[p1].z) + (points[p2].z - points[p1].z) * (points[p3].x - points[p1].x); coefs[num_poligons].c = (points[p2].x - points[p1].x) * (points[p3].y - points[p1].y) - (points[p2].y - points[p1].y) * (points[p3].x - points[p1].x); coefs[num_poligons].d = -points[p1].x * coefs[num_poligons].a - points[p1].y * coefs[num_poligons].b - points[p1].z * coefs[num_poligons].c; break; } } } if (is_in_model(x0, y0, z0)) printf ("Tocka je unutar tijela\n"); else printf ("Tocka je izvan tijela\n"); glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutIdleFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>/* get_info.c - get host IP from host name * * (C) 2004 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> int main(int argc, char **argv) { int i; char **tmp; struct hostent *host_info; extern int h_errno; if (argc != 2) { fprintf (stderr, "Usage: get_ip hostname\n"); exit (EXIT_FAILURE); } host_info = gethostbyname (argv[1]); if (host_info == NULL) { switch (h_errno) { case HOST_NOT_FOUND: fprintf (stderr, "The specified host is unknown\n"); break; case NO_ADDRESS: fprintf (stderr, "The requested name is valid but does not have an IP address\n"); break; case NO_RECOVERY: fprintf (stderr, "A non recoverable name server error occured\n"); break; case TRY_AGAIN: fprintf (stderr, "A temporary error occured on an authorative name server\n"); break; default: abort (); } exit (EXIT_FAILURE); } printf ("Host official name: %s\n", host_info->h_name); for (i=1, tmp = host_info->h_aliases ; *tmp != NULL ; ++tmp, ++i) printf ("Alias #%i: %s\n", i, *tmp); if (host_info->h_addrtype = AF_INET) printf ("Address type: IPv4\n"); else printf ("Address type: IPv6\n"); printf ("Address length: %d bytes\n", host_info->h_length); for (i=1, tmp = host_info->h_addr_list ; *tmp != NULL ; ++tmp, ++i) printf ("Address #%i: %s\n", i, *tmp); return EXIT_SUCCESS; } <file_sep>/* fork.c - creation of new process with fork() system call * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t pid; pid = fork(); if (pid) { printf("Parent process, PID = %d, created child with PID = %d\n", getpid(), pid); } else { printf("Child process, PID = %d\n", getpid()); } return 0; } <file_sep>#include <iostream> #include <fstream> #include <cstdlib> #include <ctime> #include <cmath> #include "genetic.h" using namespace std; GeneticAlgorithm::GeneticAlgorithm(int func_num) { srand(static_cast<unsigned>(time(NULL))); function = func_num; n = static_cast<int> (ceil(log(value_range * pow(10.0, precision) + 1) / log(2.0))); threshold = static_cast<unsigned int> (pow(2.0, n) - 1); chromosoms = new Chromosome**[population_size]; for (int i = 0 ; i < population_size ; ++i) { chromosoms[i] = new Chromosome*[dimension]; for (int j = 0 ; j < dimension ; ++j) chromosoms[i][j] = new Chromosome((rand() % value_range) + min_value); } func_values = new double[population_size]; cout << "Bounds: [" << min_value << ", " << max_value << "]" << endl; cout << "Population size: " << population_size << endl; cout << "Iterations number: " << iterations_num << endl; cout << "------------------------------------------" << endl; if (function == 1) { ifstream in("parametri.dat"); if(!in) { cerr << "No such file: parametri.dat" << endl; exit(EXIT_FAILURE); } for (int i = 0 ; i < dimension ; ++i) in >> parms[i]; } } GeneticAlgorithm::~GeneticAlgorithm() { } void GeneticAlgorithm::evaluate() { for (int i = 0 ; i < population_size ; ++i) { double sum = 0; func_values[i] = 0; switch (function) { case 1: for (int j = 0 ; j < dimension ; ++j) func_values[i] += pow(chromosoms[i][j]->value - parms[j], 2.0); break; case 2: func_values[i] = fabs(static_cast<double> ((chromosoms[i][0]->value - chromosoms[i][1]->value) * (chromosoms[i][0]->value + chromosoms[i][1]->value))) + pow(pow(chromosoms[i][0]->value, 2.0) + pow(chromosoms[i][1]->value, 2.0), 0.5); break; case 3: for (int j = 0 ; j < dimension ; ++j) sum += pow(chromosoms[i][j]->value, 2.0); func_values[i] = -0.5 + (pow(sin(pow(sum, 0.5)), 2.0) - 0.5) / pow((1.0 + 0.001 * sum), 2.0); break; case 4: for (int j = 0 ; j < dimension ; ++j) sum += pow(chromosoms[i][j]->value, 2.0); func_values[i] = pow(sum, 0.25) * (pow(sin(50 * pow(sum, 0.1)), 2.0) + 1.0); break; } } } void GeneticAlgorithm::select() { for (int iteration = 0 ; iteration < chromosomes_to_breed ; ++iteration) { indexes[iteration] = rand() % population_size; for (int i = iteration - 1 ; i >= 0 ; --i) if (indexes[iteration] == indexes[i]) --iteration; } } void GeneticAlgorithm::breed() { int x, y; unsigned int ch1, ch2, ch3; max_index = indexes[0]; for (int i = 1 ; i < chromosomes_to_breed ; ++i) if (func_values[indexes[i]] > func_values[max_index]) max_index = indexes[i]; for (int i = 0 ; i < chromosomes_to_breed ; ++i) if (indexes[i] != max_index) { x = indexes[i]; if (indexes[i++] != max_index) y = indexes[i]; else y = indexes[i + 1]; break; } for (int k = 0 ; k < dimension ; ++k) { do { ch1 = chromosoms[x][k]->binary_val & chromosoms[y][k]->binary_val; ch3 = rand() % threshold; ch2 = ch3 & (chromosoms[x][k]->binary_val ^ chromosoms[y][k]->binary_val); chromosoms[max_index][k]->binary_val = ch1 | ch2; } while (chromosoms[max_index][k]->binary_val > threshold || chromosoms[max_index][k]->binary_val < 0); chromosoms[max_index][k]->calculate_value(); } } void GeneticAlgorithm::mutate() { unsigned int ch1; for (int j = 0 ; j < dimension ; ++j) { for (int k = 0 ; k < n ; ++k) if ((rand() % static_cast<int>(1 / mutation_probability)) == 0) { ch1 = static_cast<unsigned> (pow(2.0, k)); chromosoms[max_index][j]->binary_val = chromosoms[max_index][j]->binary_val ^ ch1; } chromosoms[max_index][j]->calculate_value(); } } void GeneticAlgorithm::result() { int min_index = 0; double min_val; evaluate(); min_val = func_values[0]; for (int i = 1 ; i < population_size ; ++i) if (func_values[i] < min_val) { min_val = func_values[i]; min_index = i; } cout << "Function minimum: " << min_val << endl; cout << "Minimum point: "; for (int i = 0 ; i < dimension ; ++i) cout << chromosoms[min_index][i]->value << " "; cout << endl; } void GeneticAlgorithm::print() { cout.width(5); cout.precision(2); cout << "Dec\tHex\t\tDec\tHex\t\tF(X)" << endl; for(int i = 0 ; i < population_size ; ++i) { for(int j = 0 ; j < dimension ; ++j) { cout << chromosoms[i][j]->value << "\t"; cout << hex << chromosoms[i][j]->binary_val << "\t\t"; } cout << func_values[i] << endl; } cout << endl; } <file_sep>/* Quicksort implementation in Java * * (C) 2005 <NAME> <<EMAIL>> */ import java.util.Random; class SortExample { public static void main (String[] args) { try { QuickSort qs = new QuickSort (Integer.parseInt (args[0])); qs.fillArray(); qs.printArray(); qs.sortArray(); qs.printArray(); } catch (Exception e) { System.out.println ("You must specify a number of elements"); System.exit (1); } } } class QuickSort { private int array[]; private int size; public QuickSort (int n) { size = n; array = new int[size]; } public void fillArray () { int i; Random rnd = new Random(); for (i = 0 ; i < size ; ++i) array[i] = rnd.nextInt (size + 1); } public void qsort (int left, int right) { int i, j, v, tmp; if (right > left) { v = array[right]; i = left - 1; j = right; while (true) { while (array[++i] < v); while (array[--j] > v); if (i >= j) break; tmp = array[i]; array[i] = array[j]; array[j] = tmp; } tmp = array[i]; array[i] = array[right]; array[right] = tmp; qsort (left, i - 1); qsort (i + 1, right); } } public void sortArray () { qsort (0, size - 1); } public void printArray () { int i; for (i = 0 ; i < size ; ++i) System.out.print (array[i] + " "); System.out.println ("\n"); } } <file_sep>#!/usr/bin/env python # -*- coding: ascii -*- """ Time measuring functions, decorators and context managers """ __author__ = '<NAME> <<EMAIL>' __copyright__ = 'Copyright (c) 2012 <NAME>' __license__ = 'BSD' __version__ = '1.0' import sys import time if sys.platform == 'win32': default_timer = time.clock else: default_timer = time.time # use as decorator def measure_time(func): def _measure_time(*args, **kwargs): start_time = default_timer() res = func(*args, **kwargs) print 'Time elapsed for function {0}: {1}'.format(func.__name__, default_timer() - start_time) return res return _measure_time # use as context manager class MeasureTime: def __enter__(self): self.start_time = default_timer() def __exit__(self, exception_type, exception_val, exception_traceback): print 'Time elapsed: {0}'.format(default_timer() - self.start_time) <file_sep>#!/usr/bin/python # Python decompressor (see compress.py) # (C) 2005 <NAME> <<EMAIL>> from sys import argv, exit from os import path from zlib import decompress if (len (argv) <> 2): print "Syntax compress.py [filename]" exit (1) if (path.isfile (argv[1])): new_filename = argv[1][:-5] else: print "No such file: " + argv[1] exit (1) try: input = open (argv[1], "rb") except: print "Input file error" exit (1) data = input.read() decompressed_data = decompress (data) input.close() try: output = open (new_filename, "wb") except: print "Output file error" exit (1) output.write (decompressed_data) output.close() <file_sep>/* stog_poljem.c - implementacija stoga pomocu polja * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* Stavi novu vrijednost na stog. Vraca 1 ako je operacija uspjela, inace vraca 0 */ int push (int val, int *stack, int stack_size, int *top) { /* Provjeri da li je stog pun */ if (*top > stack_size - 1) return 0; /* Stavi vrijednost na stog i inkrementiraj vrh stoga */ stack[*top] = val; (*top)++; return 1; } /* Uzmi vrijednost sa stoga. Vraca 1 ako je operacija uspjela, inace vraca 0 */ int pop (int *val, int *stack, int *top) { /* Provjeri da li je stog prazan */ if (*top == 0) return 0; /* Procitaj vrijednost sa stoga i dekrementiraj vrh stoga */ (*top)--; *val = stack[*top]; return 1; } int main () { int *stack, top; int x, tmp, stack_size; do { printf ("Unesi velicinu stoga: "); scanf ("%d", &stack_size); } while (stack_size <= 0); /* Inicijaliziraj stog */ if ((stack = (int *) malloc (stack_size * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu inicijalizirati stog\n"); exit (1); }; top = 0; /* Generiraj pseudoslucajne brojeve izmedju 1-100. Ako je generiran parni * broj, stavi ga na stog, ako je neparni, citaj sa stoga. Prekini * izvodjenje kada se pokusa citati sa praznog stoga */ srand ((unsigned) time (NULL)); while (1) { /* Ne racunati pomocu rand() % 100 + 1 !!! */ x = (int) (100.0 * rand() / (RAND_MAX + 1.0)) + 1; /* Da li je broj neparan? */ if (x%2) { if (!pop (&tmp, stack, &top)) { printf ("Stog prazan\n"); exit (0); } else { printf ("pop => %d\n", tmp); } } else { if (!push (x, stack, stack_size, &top)) printf ("Stog pun\n"); else printf ("push (%d)\n", x); } } return 0; } <file_sep>/* merge_sort.c - sortiranje uparivanjem * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> void merge (int *a, int *tmp, int lpos, int rpos, int rend) { int i, lend, n, tmppos; lend = rpos - 1; tmppos = lpos; n = rend - lpos + 1; while (lpos <= lend && rpos <= rend) { if (a[lpos] < a[rpos]) tmp[tmppos++] = a[lpos++]; else tmp[tmppos++] = a[rpos++]; } while (lpos <= lend) tmp[tmppos++] = a[lpos++]; while (rpos <= rend) tmp[tmppos++] = a[rpos++]; for (i=0 ; i<n ; i++, rend--) a[rend] = tmp[rend]; } /* Rekurzivno sortiranje podpolja */ void msort (int *a, int *tmp, int lijevo, int desno) { int sredina; if (lijevo < desno) { sredina = (lijevo + desno) / 2; msort (a, tmp, lijevo, sredina); msort (a, tmp, sredina+1, desno); merge (a, tmp, lijevo, sredina +1, desno); } } void merge_sort (int *a, int n) { int *tmp; tmp = (int *) malloc (n * sizeof (int)); if (tmp) { msort (a, tmp, 0, n-1); free (tmp); } else { printf ("Ne mogu stvoriti pomocno polje za Merge sort\n"); exit (EXIT_FAILURE); } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); merge_sort (polje, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>/* snow.c - snow animation using svgalib * (C) 2004 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <vga.h> #define MODE G640x480x256 #define MAXX 640 #define MAXY 480 #define COLOR 100 #define DENSITY 200 /* lower value is higher density */ char buffer[MAXX][MAXY]; void delete_pixel (int x, int y) { vga_setcolor (0); vga_drawpixel (x, y); buffer[x][y] = 0; vga_setcolor (COLOR); } void init () { int i, j; if (vga_init ()) { fprintf (stderr, "Could not initialize SVGA system\n"); exit (EXIT_FAILURE); }; vga_setmode (MODE); vga_setcolor (COLOR); srand (time ((unsigned) NULL)); for (i=0 ; i<MAXX ; i++) for (j=0 ; j<MAXY ; j++) buffer[i][j] = 0; } int main () { int x, y, i; int direction; init (); while (1) { for (y=MAXY-2 ; y>=0 ; y--) for (x=0 ; x<MAXX ; x++) if (buffer[x][y]) { /* Chose the move direction */ direction = rand () % 2; if (direction) { /* Try to move pixel to left */ if (!buffer[x-1][y+1] && x>0) { delete_pixel (x, y); vga_drawpixel (x-1, y+1); buffer[x-1][y+1] = 1; } else if (!buffer[x+1][y+1] && x<MAXX-1) { delete_pixel (x, y); vga_drawpixel (x+1, y+1); buffer[x+1][y+1] = 1; } else if (!buffer[x][y+1]) { delete_pixel (x, y); vga_drawpixel (x, y+1); buffer[x][y+1] = 1; } } else { /* Move right */ if (!buffer[x+1][y+1] && x<MAXX-1) { delete_pixel (x, y); vga_drawpixel (x+1, y+1); buffer[x+1][y+1] = 1; } else if (!buffer[x-1][y+1] && x>0) { delete_pixel (x, y); vga_drawpixel (x-1, y+1); buffer[x-1][y+1] = 1; } else if (!buffer[x][y+1]) { delete_pixel (x, y); vga_drawpixel (x, y+1); buffer[x][y+1] = 1; } } } vga_waitretrace(); for (i=0 ; i<MAXX ; i++) if ((rand() % DENSITY) == 0) { vga_drawpixel (i, 0); buffer[i][0] = 1; } } return 0; } <file_sep>/* pow.c - racunanjem potencija primjenom rekurzije * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> /* Rekurzivno racunanje */ int power (int x, int y) { if (y==0) return 1; return x * power (x, y-1); } /* Iterativno racunanje */ int power_i (int x, int y) { int i, p; if (y==0) return 1; for (p=1, i=1 ; i<=y ; i++) p *= x; return p; } int main () { int x, y; do { printf ("Unesi dva cijela broja: "); scanf ("%d %d", &x, &y); } while (x<0 || y<0); printf ("Iterativno: %d^%d = %d\n", x, y, power_i (x, y)); printf ("Rekurzivno: %d^%d = %d\n", x, y, power (x, y)); return 0; } <file_sep>/* turing.c - gramatika neogranicenih produkcija iz Turingovog stroja * (C) 2005 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> typedef struct { int stanje; char ulazni_znak; char pomak; } konfiguracija_t; int main (int argc, char **argv) { int broj_stanja, *prihvatljiva_stanja = NULL, tmp, i = 0, j, k, l, n = 0; int broj_prihvatljivih_stanja; char *ulazni_znakovi = NULL, *znakovi_trake = NULL, ch; FILE *in, *out; konfiguracija_t konf, *shema = NULL; if (argc != 3) { fprintf (stderr, "Koristenje: turing [ulazna_datoteka] [izlazna_datoteka]\n"); exit (EXIT_FAILURE); } if ((in = fopen (argv[1], "r")) == NULL) { perror (argv[1]); exit (EXIT_FAILURE); } if ((out = fopen (argv[2], "w")) == NULL) { perror (argv[2]); exit (EXIT_FAILURE); } fscanf (in, "%d,{", &broj_stanja); while (1) { fscanf (in, "%c", &ch); if (ch == ',') continue; assert (ulazni_znakovi = realloc (ulazni_znakovi, ++n)); if (ch == '}') { ulazni_znakovi[n-1] = '\0'; break; } ulazni_znakovi[n-1] = ch; } n = 0; while (1) { fscanf (in, "%c", &ch); if (ch == ',' || ch == '{') continue; assert (znakovi_trake = realloc (znakovi_trake, ++n)); if (ch == '}') { znakovi_trake[n-1] = '\0'; break; } znakovi_trake[n-1] = ch; } fscanf (in, ",{"); n = 0; while (1) { fscanf (in, "%d", &tmp); assert (prihvatljiva_stanja = realloc (prihvatljiva_stanja, ++n * sizeof (int))); prihvatljiva_stanja[n-1] = tmp; fscanf (in, "%c", &ch); if (ch == ',') continue; if (ch == '}') break; } broj_prihvatljivih_stanja = n; fscanf (in, "%c", &ch); assert (shema = malloc (broj_stanja * strlen (znakovi_trake) * sizeof (konfiguracija_t))); while(1) { if ((fscanf (in, "%c", &ch)) == EOF) break; if (ch == '-') { konf.stanje = -1; konf.ulazni_znak = konf.pomak = ' '; fscanf (in, "%c", &ch); *(shema+i) = konf; ++i; continue; } else { if (ch == '\n') continue; else fseek (in, -1, SEEK_CUR); } fscanf (in, "%d,", &konf.stanje); fscanf (in, "%c,", &konf.ulazni_znak); fscanf (in, "%c/\n", &konf.pomak); *(shema+i) = konf; ++i; }; fprintf (out, "[A1] --> [q0][A2]\n"); for (i=0 ; i < strlen (ulazni_znakovi) ; ++i) fprintf (out, "[A2] --> [%c,%c][A2]\n", ulazni_znakovi[i], ulazni_znakovi[i]); fprintf (out, "\n"); fprintf (out, "[A2] --> [A3]\n"); fprintf (out, "[A3] --> [$,B][A3]\n"); fprintf (out, "[A3] --> $\n"); fprintf (out, "\n"); ulazni_znakovi = strdup (strcat (ulazni_znakovi, "$")); for (i=0 ; i<broj_stanja * strlen (znakovi_trake) ; ++i) { konf = shema[i]; if (konf.stanje == -1) continue; if (konf.pomak == 'R') { for (j=0 ; j<strlen (ulazni_znakovi) ; ++j) { fprintf (out, "[q%d]", i/strlen(znakovi_trake)); fprintf (out, "[%c,%c] --> ", ulazni_znakovi[j], znakovi_trake[i % strlen(znakovi_trake)]); fprintf (out, "[%c,%c]", ulazni_znakovi[j], konf.ulazni_znak); fprintf (out, "[q%d]\n", konf.stanje); } } else { for (j=0 ; j<strlen (ulazni_znakovi) ; ++j) for (k=0 ; k<strlen (ulazni_znakovi) ; ++k) for (l=0 ; l<strlen (znakovi_trake); ++l) { fprintf (out, "[%c,%c]", ulazni_znakovi[k], znakovi_trake[l]); fprintf (out, "[q%d]", i/strlen(znakovi_trake)); fprintf (out, "[%c,%c]", ulazni_znakovi[j], znakovi_trake[i % strlen (znakovi_trake)]); fprintf (out, " --> [q%d]", konf.stanje); fprintf (out, "[%c,%c]", ulazni_znakovi[k], znakovi_trake[l]); fprintf (out, "[%c,%c]\n", ulazni_znakovi[j], konf.ulazni_znak); } } } fprintf (out, "\n"); for (i=0 ; i<broj_prihvatljivih_stanja ; ++i) { for (j=0 ; j<strlen (ulazni_znakovi) ; ++j) for (k=0 ; k<strlen (znakovi_trake) ; ++k) { fprintf (out, "[%c,%c]", ulazni_znakovi[j], znakovi_trake[k]); fprintf (out, "[q%d] --> ", prihvatljiva_stanja[i]); fprintf (out, "[q%d]%c[q%d]\n", prihvatljiva_stanja[i], ulazni_znakovi[j], prihvatljiva_stanja[i]); } } for (i=0 ; i<broj_prihvatljivih_stanja ; ++i) { for (j=0 ; j<strlen (ulazni_znakovi) ; ++j) for (k=0 ; k<strlen (znakovi_trake) ; ++k) { fprintf (out, "[q%d]", prihvatljiva_stanja[i]); fprintf (out, "[%c,%c] --> ", ulazni_znakovi[j], znakovi_trake[k]); fprintf (out, "[q%d]%c[q%d]\n", prihvatljiva_stanja[i], ulazni_znakovi[j], prihvatljiva_stanja[i]); } fprintf (out, "[q%d] --> $\n", prihvatljiva_stanja[i]); } fclose (in); fclose (out); free (ulazni_znakovi); free (znakovi_trake); free (prihvatljiva_stanja); free (shema); return EXIT_SUCCESS; } <file_sep>/* lista.c - formira i ispisuje jednostruko povezanu listu od podataka * koji se nalaze u datoteci "ulaz.dat". Podaci su cjelobrojni * brojevi odvojeni razmakom. * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> struct node { int key; struct node *next; }; /* Inicijaliziraj praznu listu */ void init_list (struct node **head) { *head = (struct node *) malloc (sizeof (struct node)); } /* Umetni cvor iza zadanog cvora */ void insert_after (struct node **t, int key) { struct node *new_node; new_node = (struct node *) malloc (sizeof (struct node)); new_node->key = key; new_node->next = (*t)->next; (*t)->next = new_node; } /* Izbrisi sljedeci cvor */ void delete_next (struct node **t) { struct node *p; p = (*t)->next; (*t)->next = (*t)->next->next; free (p); } /* Ispisi sve elemente liste pocevsi od cvora head */ void print_list (struct node *head) { struct node *t = head; while (t->next != NULL) { t = t->next; printf ("%d ", t->key); } } int main () { int n; FILE *in; struct node *head; /* Unosi podatke za listu iz datoteke */ if ((in = fopen ("ulaz.dat", "r")) == NULL) { fprintf (stderr, "No input file\n"); exit (0); } init_list (&head); while ((fscanf (in, "%d", &n)) != EOF) insert_after (&head, n); print_list (head); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> int main() { int i, hits, n = 100000; srand((unsigned) time(NULL)); for (hits = 0, i = 0 ; i < n ; ++i) if ((pow((float)rand() / RAND_MAX, 2) + pow((float)rand() / RAND_MAX, 2)) < 1) ++hits; printf ("%lf\n", 4. * hits / n); return 0; } <file_sep># various dynamic programming problems def get_maxsum_subsequence(array): maximized_sums = [0] * len(array) maximized_sequence = [] for index, element in enumerate(array): if index == 0: maximized_sums[0] = element maximized_sequence = [element] else: maximized_sums[index] = max(maximized_sums[index-1] + element, array[index]) if maximized_sums[index-1] + element > array[index]: maximized_sequence.append(element) else: maximized_sequence = [element] return max(maximized_sums), maximized_sequence print get_maxsum_subsequence([1, 0, 2, 5, -10, 1, -1, 2, -1, 8]) <file_sep>// Sum up two unsigned binary numbers // (C) 2013 <NAME> <<EMAIL>> #include <iostream> #include <string> using namespace std; const string digits = "0123456789ABCDEF"; string add(const string& num1, const string& num2, const int base) { string result(max(num1.length(), num2.length()) + 1, '0'); auto carry = 0; for (unsigned int offset = 1 ; offset <= result.length() ; offset++) { auto d1 = (offset > num1.length()) ? '0' : num1[num1.length() - offset]; auto d2 = (offset > num2.length()) ? '0' : num2[num2.length() - offset]; auto val1 = digits.find(d1); auto val2 = digits.find(d2); result[result.length() - offset] = digits[(val1 + val2 + carry) % base]; carry = (carry + val1 + val2) / base; } return result.substr(result.find_first_not_of("0")); } int main(int argc, char* argv[]) { if (argc < 3) { cerr << argv[0] << " syntax: " << argv[0] << " num1 num2 [base]" << endl; return -1; } const string num1 = string(argv[1]); const string num2 = string(argv[2]); int base = 2; if (argc == 4) { base = stoi(argv[3]); if (base < 2 || base > 16) { cerr << "Base must be in range [2, 16]" << endl; return 1; } } if (num1.find_first_not_of(digits.substr(0, base)) != string::npos || num2.find_first_not_of(digits.substr(0, base)) != string::npos) { cerr << "Arguments must consist only of digits in [" << digits.substr(0, base) << "]" << endl; return 1; } const string sum = add(num1, num2, base); cout << sum << endl; return 0; } <file_sep>/* base64.c - Base64 encoding/decoding as described in RFC1521 * * (C) 2005 <NAME> <<EMAIL>> */ #include <string.h> #include "base64.h" static const char *base64digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; void base64_encode (const unsigned char *src, unsigned char *dest, int len) { for ( ; len >= 3 ; len -= 3) { *dest++ = base64digits[src[0] >> 2]; *dest++ = base64digits[((src[0] << 4) & 0x30) | (src[1] >> 4)]; *dest++ = base64digits[((src[1] << 2) & 0x3c) | (src[2] >> 6)]; *dest++ = base64digits[src[2] & 0x3f]; src += 3; } if (len > 0) { unsigned char fragment; *dest++ = base64digits[src[0] >> 2]; fragment = (src[0] << 4) & 0x30; if (len > 1) fragment |= src[1] >> 4; *dest++ = base64digits[fragment]; *dest++ = (len < 2) ? '=' : base64digits[(src[1] << 2) & 0x3c]; *dest++ = '='; } *dest = '\0'; } int base64_decode (const unsigned char *src, unsigned char *dest) { int len = 0; unsigned char digit[4]; if (src[0] == '+' && src[1] == ' ') src += 2; if (*src == '\n') return 0; do { digit[0] = src[0]; if (DECODE64 (digit[0]) == ERR) return -1; digit[1] = src[1]; if (DECODE64 (digit[1]) == ERR) return -1; digit[2] = src[2]; if (digit[2] != '=' && DECODE64 (digit[2]) == ERR) return -1; digit[3] = src[3]; if (digit[3] != '=' && DECODE64 (digit[3]) == ERR) return -1; src += 4; *dest++ = (DECODE64 (digit[0]) << 2) | (DECODE64 (digit[1]) >> 4); ++len; if (digit[2] != '=') { *dest++ = ((DECODE64 (digit[1]) << 4) & 0xf0) | (DECODE64 (digit[2]) >> 2); ++len; if (digit[3] != '=') { *dest++ = ((DECODE64 (digit[2]) << 6) & 0xc0) | DECODE64 (digit[3]); ++len; } } } while (*src && *src != '\n' && digit[3] != '='); *dest = '\0'; return (len); } <file_sep>/* stablo_poljem.c - implementacija binarnog stabla pomocu polja. * * (C) 2003 <NAME> <<EMAIL>> * * Podaci za cvorove se unose iz datoteke "ulaz.dat", zatim se formira * stablo, te ispisu sortirani podaci koristeci inorder prolazak kroz stablo. * Podaci su cjelobrojni brojevi odvojeni razmakom. Prvi podatak u datoteci * je broj cvorova stabla (broj ostalih podataka u datoteci). */ #include <stdio.h> #include <math.h> #include <stdlib.h> void dodaj_cvor (int key, int root, int *stablo) { if (stablo[root] == 0) { stablo[root] = key; } else { if (key < stablo[root]) { dodaj_cvor (key, root*2, stablo); } else { dodaj_cvor (key, root*2+1, stablo); } } } void inorder (int root, int *stablo) { if (stablo[root*2]) inorder (root*2, stablo); if (stablo[root]) printf ("%d ", stablo[root]); if (stablo[root*2+1]) inorder (root*2+1, stablo); } int main () { FILE *in; int x, n; int *stablo; if ((in = fopen ("ulaz.dat", "r")) == NULL) { fprintf (stderr, "Ulazna datoteka ne postoji\n"); exit (EXIT_FAILURE); } fscanf (in, "%d", &n); /* korisit calloc umjesto malloc zato da se svi elementi * polja inicijalno postave na vrijednost 0. U najgorem * slucaju polje mora biti velicine 2^n*/ stablo = (int *) malloc ((pow (2, n)) * sizeof (int)); while (fscanf (in, "%d", &x) != EOF) dodaj_cvor (x, 1, stablo); inorder (1, stablo); return 0; } <file_sep>/* presjek.c - nalazenje presjeka dva skupa. Primjer za razne * apriorne slozenosti algoritama * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> /* Vraca 0 ako su arg1=arg2, -1 ako arg1<arg2, 1 ako arg1>arg2 */ int compare (const void *arg1, const void *arg2) { if (*(int*) arg1 == *(int *) arg2) return 0; else if (*(int *) arg1 < *(int *) arg2) return -1; else return 1; } /* Brute-force pristup, apriorna slozenost O(n*n) */ int presjek1 (int *a, int *b, size_t n, int **p) { int i, j, k; /* broj zajednickih elementata */ k = 0; /* Usporedi svaki element iz a sa svakim iz b */ for (i=0 ; i<n ; i++) for (j=0 ; j<n ; j++) if (a[i] == b[j]) { /* Dinamicki promjeni velicinu spremnika ze presjek */ *p = realloc (*p, (k + 1) * sizeof (int)); (*p)[k] = a[i]; ++k; } return k; } /* Usporedba prethodno sortiranih polja, slozenost O(n) */ int presjek2 (int *a, int *b, size_t n, int **p) { int i, j, k; i = j = k = 0; while (i<n && j<n) { if (a[i] == b[j]) { *p = realloc (*p, (k+1) * sizeof (int)); (*p)[k] = a[i]; ++i; ++j; ++k; } else if (a[i] < b[j]) { ++i; } else { ++j; } } return k; } int main () { int polje1[] = {1, 8, 2, 22, 19}; int polje2[] = {2, 19, 3, 34, 35}; int *presjek = NULL; int i; size_t velicina; /* sortiraj polja */ /* qsort ima O(n * lg n) */ qsort (polje1, 5, sizeof (int), compare); qsort (polje2, 5, sizeof (int), compare); velicina = presjek2 (polje1, polje2, 5, &presjek); for (i=0 ; i<velicina ; i++) printf ("%d ", presjek[i]); puts (""); return 0; } <file_sep>/* ntest.c - simple port scaner/flooder and network tester * (C) 2004-2005 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #define BUFFER_SIZE 0x200 #define N_FOREVER 0x7FFFFFFF char *program_name = "ntest"; char *program_version = "0.1.2"; /* Display usage and exit with given exit code */ void display_usage (FILE *stream, int exit_code) { fprintf (stream, "Usage: %s [option(s)] host\n", program_name); fprintf (stream, " -p --port Connect to specified port\n"); fprintf (stream, " -n --tries Number of tries (default is 1)\n"); fprintf (stream, " -f --forever Unlimited number od tries\n"); fprintf (stream, " -m --message Text of message to be sent\n"); fprintf (stream, " -c --count Numbers of message write\n"); fprintf (stream, " -F --flood Write messages forever\n"); fprintf (stream, " -d --delay Seconds to wait betwen connect atemps\n"); fprintf (stream, " -w --wait Seconds to wait upon connect\n"); fprintf (stream, " -s --sleep Seconds to wait betwen write atemps\n"); fprintf (stream, " -v --verbose Display verbose messages\n"); fprintf (stream, " -h --help Display this usage information\n"); fprintf (stream, " -V --version Display program version\n"); exit (exit_code); } /* Display program version and credits, then exit */ void display_version () { printf ("%s version %s\n", program_name, program_version); printf ("(C) 2004-2005 <NAME> <<EMAIL>>\n"); exit (EXIT_SUCCESS); } void get_host_response (int socket_fd) { char buffer[BUFFER_SIZE]; ssize_t chars_read_num; while (1) { chars_read_num = read (socket_fd, buffer, BUFFER_SIZE); if (chars_read_num == 0) return; fwrite (buffer, sizeof (char), chars_read_num, stdout); } } void send_msg_to_host (int socket_fd, char *msg) { write (socket_fd, msg, strlen (msg)); } int main (int argc, char **argv) { char *host_name; int socket_fd, port_num; struct sockaddr_in name; struct hostent *hostinfo; int i, count = 1, tries = 1, verbose = 0; int write_delay = 0, atemps_delay = 0, wait_delay = 0; char *message; int next_option; char *short_options="p:n:fm:c:Fd:w:s:vhV"; struct option long_options[] = { {"port", 1, NULL, 'p'}, {"tries", 1, NULL, 'n'}, {"forever", 0, NULL, 'f'}, {"message", 1, NULL, 'm'}, {"count", 1, NULL, 'c'}, {"flood", 0, NULL, 'F'}, {"delay", 1, NULL, 'd'}, {"wait", 1, NULL, 'w'}, {"sleep", 1, NULL, 's'}, {"verbose", 0, NULL, 'v'}, {"help", 0, NULL, 'h'}, {"version", 0, NULL, 'V'}, {NULL, 0, NULL, 0} }; /* Do command line options parsing */ if (argc == 1) display_usage (stderr, 1); do { next_option = getopt_long (argc, argv, short_options, long_options, NULL); switch (next_option) { /* -p or --port */ case 'p': if ((sscanf (optarg, "%d", &port_num)) == 0) { fprintf (stderr, "Invalid port number\n"); exit (EXIT_FAILURE); } break; /* -n or --tries */ case 'n': if ((sscanf (optarg, "%d", &tries)) == 0) { fprintf (stderr, "Invalid number of tries\n"); exit (EXIT_FAILURE); } break; /* -f or --forever */ case 'f': tries = N_FOREVER; break; /* -c or --count */ case 'c': if ((sscanf (optarg, "%d", &count)) == 0) { fprintf (stderr, "Invalid number of write tries\n"); exit (EXIT_FAILURE); } break; /* -F or --flood */ case 'F': count = N_FOREVER; break; /* -m or --message */ case 'm': message = (char *) malloc (sizeof (char) * (strlen (optarg) + 2)); strncpy (message, optarg, sizeof (char) * (strlen (optarg) + 2)); strcat (message, "\n"); break; /* -w or --wait */ case 'w': if ((sscanf (optarg, "%d", &wait_delay)) == 0) { fprintf (stderr, "Invalid number of seconds\n"); exit (EXIT_FAILURE); } break; /* -s or --sleep */ case 's': if ((sscanf (optarg, "%d", &write_delay)) == 0) { fprintf (stderr, "Invalid number of seconds\n"); exit (EXIT_FAILURE); } break; /* -d or --delay */ case 'd': if ((sscanf (optarg, "%d", &atemps_delay)) == 0) { fprintf (stderr, "Invalid number of seconds\n"); exit (EXIT_FAILURE); } break; /* -h or --help */ case 'h': display_usage (stdout, 0); break; /* -v or --verbose */ case 'v': verbose = 1; break; /* -V or --version */ case 'V': display_version (); break; /* Invalid option */ case '?': display_usage (stderr, 1); break; /* Command line parameters parsing over */ case -1: break; /* Unexpected condition */ default: abort (); } } while (next_option != -1); if (argv[optind]) { host_name = (char *) malloc (sizeof (char) * (strlen (argv[optind]) + 1)); strncpy (host_name, argv[optind], sizeof (char) * (strlen (argv[optind]) + 1)); } else { fprintf (stderr, "No hostname found.\n"); exit (EXIT_FAILURE); } if (!port_num || port_num<=0 || port_num >=65535) { fprintf (stderr, "No port or invalid port specified.\n"); exit (EXIT_FAILURE); } if (verbose) printf ("Connecting to %s port %d...\n", host_name, port_num); socket_fd = socket (PF_INET, SOCK_STREAM, 0); name.sin_family = AF_INET; hostinfo = gethostbyname (host_name); if (hostinfo == NULL) { fprintf (stderr, "Could not connect to remote host.\n"); exit (EXIT_FAILURE); } else name.sin_addr = *((struct in_addr*) hostinfo->h_addr); name.sin_port = htons (port_num); for (i=0 ; i<tries ; i++) { if (verbose && tries!=1) fprintf (stderr, "Try %d of %d: ", i+1, tries); if (connect (socket_fd, (struct sockaddr *) &name, sizeof (struct sockaddr_in)) == -1) { perror (host_name); if (i == tries - 1) exit (EXIT_FAILURE); } else break; if (atemps_delay) sleep (atemps_delay); } printf ("Connected.\n"); if (verbose && wait_delay!=0) printf ("Sleeping %d seconds...\n", wait_delay); if (wait_delay) sleep (wait_delay); for (i=0 ; i<count ; i++) { if (verbose && count>1) fprintf (stderr, "Write %d of %d: ", i+1, count); if (verbose) fprintf (stderr, "Sending message: %s", message); send_msg_to_host (socket_fd, message); if (write_delay) sleep (write_delay); } if (verbose) fprintf (stderr, "Waiting for server respose\n"); get_host_response (socket_fd); free (host_name); return 0; } <file_sep>/* heap_sort.c - sortiranje gomilom * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* zamjeni varijable a i b */ void swap (int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } /* Podesavanje gomile. Prvi element polja mora imati indeks 1! */ void adjust_heap (int *a, int i, int n) { int j, tmp; j = i*2; tmp = a[i]; while (j<=n) { if (j<n && (a[j] < a[j+1])) j++; if (tmp > a[j]) break; a[j/2] = a[j]; j *= 2; } a[j/2] = tmp; } /* Napravi gomilu */ void make_heap (int *a, int n) { int i; for (i=n/2 ; i>0 ; i--) adjust_heap (a, i, n); } void heap_sort (int *a, int n) { int i; make_heap (a, n); for (i=n ; i>1 ; i--) { swap (&a[1], &a[i]); adjust_heap (a, 1, i-1); } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); heap_sort (polje-1, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>/* popen.c - redirection with popen * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <unistd.h> int main () { FILE *stream; stream = popen("sort", "w"); fprintf(stream, "This\n"); fprintf(stream, "should\n"); fprintf(stream, "be\n"); fprintf(stream, "sorted\n"); return pclose(stream); } <file_sep>#!/usr/bin/python # retrievec RSS data # (C) 2004 <NAME> <<EMAIL>> import sys, getopt, urllib def display_usage (exit_code): print """Usage: rssview [option(s)] url(s) -h --help Display this usage information -o --output Save downloaded data to file (default is 'rssdata.xml' -v --verbose Turn on verbose messages -V --version Display program version""" sys.exit (exit_code) program_version = "0.1" output = "rssdata.xml" verbose = 0 short_options = "ho:vV" long_options = ["help", "output=", "verbose", "version"] try: options, servers_list = getopt.getopt (sys.argv[1:], short_options, long_options) except getopt.GetoptError: display_usage (1) for option, argument in options: if option in ("-h", "--help"): display_usage (0) if option in ("-o", "--output"): output = argument if option in ("-v", "--verbose"): verbose = 1 if option in ("-V", "--version"): print "rssview version " + program_version if servers_list == []: display_usage (1) for server in servers_list: try: if verbose: print "Retrieving data from: " + server urllib.urlretrieve (server, output) except IOError: print "Temporary failure in name resolution" sys.exit (1) <file_sep>/* redirect.c - stdout redirection * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> int main() { int fds[2]; pid_t pid; pipe(fds); pid = fork(); if (pid == 0) { close(fds[1]); dup2(fds[0], STDIN_FILENO); execlp("sort", "sort", 0); } else { FILE *stream; close (fds[0]); stream = fdopen(fds[1], "w"); fprintf(stream, "This\n"); fprintf(stream, "should\n"); fprintf(stream, "be\n"); fprintf(stream, "sorted\n"); close(fds[1]); waitpid(pid, NULL, 0); } return EXIT_SUCCESS; } <file_sep>/* fibbonaci.c - racunanje Fibbonacijevih brojeva * * (C) 2003 <NAME> <<EMAIL>> * * n-ti Fibbonacijev broj definiran je rekurzivnom formulom: * * F(n) = F(n-1) + F(n-2) za n>=3 * * F(1) = F(2) = 1 * * Fibbonacijev niz: * * 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... */ #include <stdio.h> /* Rekurzivna implementacija */ int fibbonaci (int n) { if (n<=2) return 1; return fibbonaci (n-1) + fibbonaci (n-2); } /* Iterativna implementacija */ int fibbonaci_i (int n) { int i, f1, f2, fibb; f1 = f2 = fibb = 1; i=2; while (++i<=n) { fibb = f1 + f2; f2 = f1; f1 = fibb; } return fibb; } int main () { int x; do { printf ("Unesi prirodni broj: "); scanf ("%d", &x); } while (x<=0); printf ("Iterativno: F(%d) = %d\n", x, fibbonaci_i (x)); printf ("Rekurzivno: F(%d) = %d\n", x, fibbonaci (x)); return 0; } <file_sep>#!/bin/bash rename "s/\ /_/g" *.[Mm][Pp]3 for i in `ls *.[Mm][Pp]3` do mplayer -quiet -ao pcm $i lame -b 64 audiodump.wav $i.mp3 rm audiodump.wav rm $i done rename "s/\.wav//g" *.[Mm][Pp]3 rename "s/_/\ /g" * <file_sep>#!/usr/bin/python from math import hypot from random import random nodes = 100000 hits = 0 for i in range(nodes): if hypot(random(), random()) <= 1: hits = hits + 1 print 4. * hits / nodes <file_sep>/* check_jmbg - provjera ispravnosti JMBG-a * * (C) 2004 <NAME> <<EMAIL>> */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #define JMBG_SIZE 13 int main () { int i, sum; char buffer[JMBG_SIZE+1]; int jmbg[JMBG_SIZE]; printf ("Unesi JMBG: "); fgets (buffer, JMBG_SIZE+1, stdin); for (i=0 ; i<JMBG_SIZE ; ++i) { if (!isdigit(buffer[i])) { fprintf (stderr, "Neispravno unesen JMBG\n"); exit (EXIT_FAILURE); } jmbg[i] = buffer[i] - '0'; } for (sum=0, i=2 ; i<8 ; ++i) sum += i * (jmbg[7-i] + jmbg[13-i]); sum = 11 - (sum % 11); if (sum == jmbg[JMBG_SIZE-1]) printf ("JMBG je ispravan\n"); else printf ("JMBG nije ispravan\n"); return EXIT_SUCCESS; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) typedef struct { float x, y, z; } tocka_t; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; int fullscreen; int i, broj_vrhova; tocka_t ociste, glediste, g1, g2, *vrhovi = NULL, *novi_vrhovi, vrh_t, vrh_p; float t1[4][4] = {0}, t2[4][4] = {0}, t3[4][4] = {0}, t4[4][4] = {0}, t5[4][4] = {0}, tmp[4][4], t[4][4]; float p[4][4] = {0}; float sinus, kosinus; void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } void resize_scene(int width, int height) { window_width = width; window_height = height; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // gluOrtho2D(0, window_width, 0, window_height); gluOrtho2D(-5, 5, -5, 5); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glColor3f(0, 1, 0); } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'q': exit(EXIT_SUCCESS); } } void mouse_handler(int button, int state, int x, int y) { int i; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { glBegin(GL_LINES); for (i = 0 ; i < broj_vrhova ; ++i) { glVertex2f(novi_vrhovi[i].x, novi_vrhovi[i].y); glVertex2f(novi_vrhovi[i+1].x, novi_vrhovi[i+1].y); } glVertex2f(novi_vrhovi[0].x, novi_vrhovi[0].y); glVertex2f(novi_vrhovi[broj_vrhova-1].x, novi_vrhovi[broj_vrhova-1].y); glEnd(); glFlush(); } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { resize_scene(window_width, window_height); } } /* radi samo na 4x4 matricama */ void mnozi_matrice(float *a, float *b, float *rez) { int i, j, k; double zbroj; for (i = 0 ; i < 4 ; ++i) for (j = 0 ; j < 4 ; ++j) { for (zbroj = 0, k = 0 ; k < 4 ; ++k) zbroj += a[i * 4 + k] * b[k * 4 + j]; rez[i * 4 + j] = zbroj; } } /* transformacija tocke */ void transformiraj(tocka_t *orig, float *b, tocka_t *r) { int i, j, k; float a[4], rez[4]; double zbroj; a[0] = orig->x; a[1] = orig->y; a[2] = orig->z; a[3] = 1; for (i = 0 ; i < 1 ; ++i) for (j = 0 ; j < 4 ; ++j) { for (zbroj = 0, k = 0 ; k < 4 ; ++k) zbroj += a[i * 4 + k] * b[k * 4 + j]; rez[i * 4 + j] = zbroj; } r->x = rez[0] / rez[3]; r->y = rez[1] / rez[3]; r->z = rez[2] / rez[3]; } int main(int argc, char **argv) { FILE *in; if (argc != 2) { fprintf(stderr, "Sintaksa: %s [ulaz]\n", argv[0]); exit(EXIT_FAILURE); } if ((in = fopen(argv[1], "r")) == NULL) { perror(argv[1]); exit(EXIT_FAILURE); } fscanf(in, "O = %f %f %f\n", &ociste.x, &ociste.y, &ociste.z); fscanf(in, "G = %f %f %f\n", &glediste.x, &glediste.y, &glediste.z); broj_vrhova = 0; while(!feof(in)) { ++broj_vrhova; vrhovi = realloc(vrhovi, sizeof(tocka_t) * broj_vrhova); fscanf(in, "%f %f %f\n", &vrhovi[broj_vrhova - 1].x, &vrhovi[broj_vrhova - 1].y, &vrhovi[broj_vrhova - 1].z); } t1[0][0] = t1[1][1] = t1[2][2] = t1[3][3] = 1; t1[3][0] = -ociste.x; t1[3][1] = -ociste.y; t1[3][2] = -ociste.z; g1.x = glediste.x - ociste.x; g1.y = glediste.y - ociste.y; g1.z = glediste.z - ociste.z; sinus = g1.y / sqrt(pow(g1.x, 2) + pow(g1.y, 2)); kosinus = g1.x / sqrt(pow(g1.x, 2) + pow(g1.y, 2)); t2[2][2] = t2[3][3] = 1; t2[0][0] = t[1][1] = kosinus; t2[0][1] = -sinus; t2[1][0] = sinus; g2.x = sqrt(pow(g1.x, 2) + pow(g1.y, 2)); g2.y = 0; g2.z = g1.z; sinus = g2.x / sqrt(pow(g2.x, 2) + pow(g2.z, 2)); kosinus = g2.z / sqrt(pow(g2.x, 2) + pow(g2.z, 2)); t3[1][1] = t3[3][3] = 1; t3[0][0] = t3[2][2] = kosinus; t3[0][2] = sinus; t3[2][0] = -sinus; t4[1][0] = t4[2][2] = t4[3][3] = 1; t4[0][1] = -1; t5[1][1] = t5[2][2] = t5[3][3] = 1; t5[0][0] = -1; mnozi_matrice(&t1[0][0], &t2[0][0], &tmp[0][0]); mnozi_matrice(&tmp[0][0], &t3[0][0], &t[0][0]); mnozi_matrice(&t[0][0], &t4[0][0], &tmp[0][0]); mnozi_matrice(&tmp[0][0], &t5[0][0], &t[0][0]); p[2][3] = 1 / sqrt(pow(g2.x, 2) + pow(g2.z, 2)); p[0][0] = p[1][1] = 1; novi_vrhovi = malloc(sizeof(tocka_t) * broj_vrhova); for (i = 0 ; i < broj_vrhova ; ++i) { printf("Tocka %d prije transformacije: [%3.2f %3.2f %3.2f 1]\n", i, vrhovi[i].x, vrhovi[i].y, vrhovi[i].z); transformiraj(&vrhovi[i], &t[0][0], &vrh_t); printf("Tocka %d nakon transformacije: [%3.2f %3.2f %3.2f 1]\n", i, vrh_t.x, vrh_t.y, vrh_t.z); transformiraj(&vrh_t, &p[0][0], &vrh_p); printf("Tocka %d nakon projekcije: [%3.2f %3.2f %3.2f 1]\n\n", i, vrh_p.x, vrh_p.y, vrh_p.z); novi_vrhovi[i] = vrh_t; } glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMouseFunc(mouse_handler); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>/* quick_sort.c - brzo sortiranje * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* Zamijeni sadrzaj varijabli a i b */ void swap (int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } /* Sort umetanjem */ void insertion_sort (int *a, int n) { int i, j, tmp; for (i=1 ; i<n ; i++) { tmp = a[i]; for (j=i; j>=1 && a[j-1]>tmp ; j--) a[j] = a[j-1]; a[j] = tmp; } } /* Median funkcija za Quicksort */ int median (int *a, int left, int right) { int middle; middle = (left + right) / 2; if (a[left] > a[middle]) swap (&a[left], &a[middle]); if (a[left] > a[right]) swap (&a[left], &a[right]); if (a[middle] > a[right]) swap (&a[middle], &a[right]); swap (&a[middle], &a[right-1]); return a[right-1]; } /* Quick sort */ #define CUTOFF (3) void quick_sort (int *a, int left, int right) { int i, j, m; if (left + CUTOFF <= right) { m = median (a, left, right); i = left; j = right - 1; while (1) { while (a[++i] < m); while (a[--j] > m); if (i<j) swap (&a[i], &a[j]); else break; } swap (&a[i], &a[right-1]); quick_sort (a, left, i-1); quick_sort (a, i+1, right); } else { insertion_sort (a + left, right - left + 1); } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); quick_sort (polje, 0, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>/* insertion_sort.c - sortiranje umetanjem * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <time.h> void insertion_sort (int *a, int n) { int i, j, tmp; for (i=1 ; i<n ; i++) { tmp = a[i]; for (j=i; j>=1 && a[j-1]>tmp ; j--) a[j] = a[j-1]; a[j] = tmp; } } int main () { int i, n; int *polje; do { printf ("Unesi velicinu polja: "); scanf ("%d", &n); } while (n<=0); if ((polje = malloc (n * sizeof (int))) == NULL) { fprintf (stderr, "Ne mogu alocirati polje"); exit (1); } srand ((unsigned) time (NULL)); printf ("Generiram polje...\n"); for (i=0 ; i<n ; ++i) polje[i] = rand () % 1000; printf ("Sortitam polje...\n"); insertion_sort (polje, n); /* ispisi sortirano polje */ for (i=0 ; i<n ; i++) printf ("%d ", polje[i]); printf ("\n"); return 0; } <file_sep>/* shm.c - IPC using shared memory * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/shm.h> #include <sys/stat.h> int main() { char *shared_memory; int segment_id, segment_size; struct shmid_ds shmbuffer; /* we will request 1kb of shared memory */ const int shared_segment_size = 0x400; /* alocate shared memory segment */ segment_id = shmget(IPC_PRIVATE, shared_segment_size, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); /* atach segment to process */ shared_memory = (char *) shmat(segment_id, NULL, 0); printf("Shared memory attached at address %p\n", shared_memory); /* get shared memory size (it won't be neccessary 1k as we requested) */ shmctl(segment_id, IPC_STAT, &shmbuffer); segment_size = shmbuffer.shm_segsz; printf("Requested shared memory size: %d\n", shared_segment_size); printf("Alocated shared memory size: %d\n", segment_size); printf("Page size: %d\n", getpagesize()); /* verify that shared memory segment is correctly attached and writeable */ sprintf(shared_memory, "Hello world.\n"); /* detach shared memory segment */ shmdt(shared_memory); /* destory shared memory segment */ shmctl(segment_id, IPC_RMID, 0); return EXIT_SUCCESS; } <file_sep>/* SV5sem.c - process synchronization with process (SYSV) semaphores * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdlib.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/types.h> /* semaphore union */ union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; /* get semaphore ID, allocate a new semaphore if needed */ int allocate_semaphore(key_t key, int sem_flags) { return semget(key, 1, sem_flags); } /* deallocate semaphore */ int deallocate_semaphore(int semid) { union semun ignored_argument; return semctl(semid, 1, IPC_RMID, ignored_argument); } /* semaphore initializaion */ int semaphore_initialize(int semid) { union semun arguments; unsigned short values[1]; values[0] = 1; arguments.array = values; return semctl(semid, 0, SETALL, arguments); } /* wait operation - block until semaphore value gets positive, than decrement by one */ int semaphore_wait(int semid) { struct sembuf operations[1]; /* use first (and only) semaphore */ operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = SEM_UNDO; return semop(semid, operations, 1); } /* post operation - increment by one */ int semaphore_post(int semid) { struct sembuf operations[1]; /* use first (and only) semaphore */ operations[0].sem_num = 0; operations[0].sem_op = 1; operations[0].sem_flg = SEM_UNDO; return semop(semid, operations, 1); } int main () { return EXIT_SUCCESS; } <file_sep>def getperm(l): if not l: yield l else: for element in l: for perm in getperm([x for x in l if x != element]): yield [element] + perm for perm in getperm([1, 2, 3, 4, 5]): print perm <file_sep>/* exec.c - fork a new process and replace it with a new program * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> int main() { pid_t pid; char *program = "ps"; char *arg_list[] = {"ps", "-f", NULL}; /* fork a new process */ pid = fork(); if (pid) { /* Parent process, wait for child to finish */ wait(NULL); } else { /* replace running process with a new program instance */ execvp(program, arg_list); /* This should never print if exec was successfull */ fprintf(stderr, "Error while calling execvp\n"); } return 0; } <file_sep>/* euklid.c - trazenje najvece zajednicke mjere sa Euklidovim algoritmom * * (C) 2003 <NAME> <<EMAIL>> * * Euklidovo svojstvo: * Nzm (u, v) = Nzm (max {u,v} mod min {u,v}, min {u,v}) */ #include <stdio.h> /* Rekurzivna implementacija */ int nzm (int u, int v) { int tmp; if (u == 0) return v; if (u < v) { tmp = u; u = v; v = tmp; } return nzm (u % v, v); } int main () { int x, y; do { printf ("Unesi dva prirodna broja: "); scanf ("%d %d", &x, &y); } while (x<=0 || y<=0); printf ("Nzm (%d, %d) = %d\n", x, y, nzm (x,y)); return 0; } <file_sep>/* fuzzer.c * (C) 2009 <NAME> <<EMAIL>> * * gcc -c -fPIC fuzzer.c * ld -shared -o fuzzer.so fuzzer.o */ #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 0x100 char *p; char *getenv(const char *name) { if (!strncmp(name, "DISPLAY", 7)) return ":0"; return p; } void _init() { p = malloc(BUFFER_SIZE); memset(p, 'A', BUFFER_SIZE); } <file_sep>#ifndef _STATS_H #define _STATS_H #ifndef _STDIO_H #include <stdio.h> #endif /* _STDIO_H */ #ifndef _STDLIB_H #include <stdlib.h> #endif /* _STDLIB_H */ #ifndef _STDLIB_H #include <ctype.h> #endif /* _CTYPE_H */ #define ALPHABET_LENGTH ('Z' - 'A' + 1) int characters[ALPHABET_LENGTH] = {0}; int total=0, chars=0, words=0, lines=0, word_sum=0, dots=0, sent_sum=0; void analyze (FILE *in); void display_graph (FILE *out); void display_stats (FILE *out); #endif /* _STATS_H */ <file_sep>__author__ = '<NAME>' __date__ = '5 Feb 2006' __version__ = '0.1' from sys import maxint infinity = maxint class GraphError(Exception): """Generic graph library exception""" pass class Graph: """Graph theory base class""" def __init__(self, digraph = False): """Initializes empty graph""" self.vertices = [] self.edges = [] self.digraph = digraph def __str__(self): """Nice output of graph""" s = 'Vertices: ' for vertex in self.get_vertices(): s = s + vertex + ' ' s = s + '\nEdges:\n' edges = self.get_edges() edges.sort() for edge in edges: if self.is_digraph(): s = s + '\t' + edge[0] + ' - ' + edge[1] + ' --> ' + str(edge[2]) + '\n' else: if edge[0] < edge[1]: s = s + '\t' + edge[0] + ' - ' + edge[1] + ' --> ' + str(edge[2]) + '\n' return s[:-1] def copy(self): """Returns copy of graph""" c = Graph(self.digraph) c.vertices = self.get_vertices() c.edges = self.get_edges() return c def is_digraph(self): """Returns True if graph is digraph""" return self.digraph def get_size(self): """Returns size of graph""" return len(self.vertices) def add_vertex(self): """Add vertex to graph""" if not self.vertices: self.vertices.append('A') return 'A' new_vertex = chr(max(map(ord, self.vertices)) + 1) self.vertices.append(new_vertex) return new_vertex def remove_vertex(self, vertex): """Removes vertex and all edges containing that vertex""" try: self.vertices.remove(vertex) self.edges = [(start, end, weight) for start, end, weight in self.edges if vertex not in (start, end)] except ValueError: raise GraphError, 'No such vertex in graph' def get_vertices(self): """Returns list of vertices""" return self.vertices[:] def is_vertex(self, vertex): """Returns True if vertex is in graph""" return vertex in self.vertices def get_degree(self, vertex): """Returns degree of vertex""" def sum(l): ret = 0 for i in l: ret = ret +i return ret if not self.is_vertex(vertex): raise GraphError, 'No such vertex' return sum([weight for start, end, weight in self.get_edges() if end == vertex]) def get_out_degree(self, vertex): """Returns outer degree of vertex""" def sum(l): ret = 0 for i in l: ret = ret +i return ret if not self.is_vertex(vertex): raise GraphError, 'No such vertex' return sum([weight for start, end, weight in self.get_edges() if start == vertex]) def adjacent_to(self, vertex): """Returns list of vertices adjacent to given vertex""" adj_list = [] for next_vertex in self.get_vertices(): if self.is_edge(vertex, next_vertex): adj_list.append(next_vertex) return adj_list def add_edge(self, start, end, weight = 1): """Add edge to graph. Edge weight is summed if edge already exists""" if (not self.is_vertex(start)) or (not self.is_vertex(end)): raise GraphError, 'No such vertex in graph' if self.is_edge(start, end): weight = weight + self.get_weight(start, end) self.remove_edge(start, end) self.edges.append((start, end, weight)) if not self.is_digraph(): self.edges = [(a,b,w) for a, b, w in self.edges if (a != end) or (b != start) ] self.edges.append((end, start, weight)) def remove_edge(self, start, end): """Removes edge from graph""" if (not self.is_vertex(start)) or (not self.is_vertex(end)): raise GraphError, 'No such vertex in graph' self.edges = [(s, e, w) for s, e, w in self.get_edges() if start != s or end != e] if not self.is_digraph(): self.edges = [(s, e, w) for s, e, w in self.get_edges() if start != e or end != s] def get_edges(self): """Returns lists of edges""" return self.edges[:] def get_edges_num(self): """Returns number of edges""" return len(self.edges) def is_edge(self, i, j): """Returns true if (i, j) is edge in graph""" for start, end, weight in self.get_edges(): if start == i and end == j and weight != infinity: return True return False def get_weight(self, start, end): """Returns weight of edge""" if not self.is_edge(start, end): raise GraphError, 'No such edge in graph' for s, e, weight in self.get_edges(): if s == start and e == end: return weight def complement(self): """Returns new graph which is complement of given graph (weight of edges is set to 1)""" comp = Graph() comp.vertices = self.get_vertices() for start in self.get_vertices(): for end in self.get_vertices(): if not self.is_edge(start, end) and not comp.is_edge(start, end) and start != end: comp.add_edge(start, end, 1) return comp def get_adj_list(self): """Returns dictionary containing adjacency list of graph""" adj_list = {} for vertex in self.get_vertices(): adj_list[vertex] = self.adjacent_to(vertex) return adj_list def get_adj_matrix(self): """Returns adjacency matrix of graph""" adj_matrix = [[0] * self.get_size() for i in range(self.get_size())] for vertex in self.get_vertices(): for next_vertex in self.get_vertices(): if self.is_edge(vertex, next_vertex): adj_matrix[ord(vertex) - ord('A')][ord(next_vertex) - ord('A')] = self.get_weight(vertex, next_vertex) return adj_matrix def get_inc_matrix(self): """Returns incidency matrix of graph""" inc_matrix = [[0] * self.get_edges_num() for i in range(self.get_size())] for vertex in self.get_vertices(): for edge in self.get_edges(): if vertex in edge: inc_matrix[ord(vertex) - ord('A')][self.edges.index(edge)] = 1 return inc_matrix def nullgraph(): """Returns null graph""" return Graph() def chain(size, weight = 1): """Returns chain of given size with edges set to given weight""" if size == 0: return nullgraph() if size < 0: raise GraphError, 'Invalid graph size' graph = Graph() prev_vertex = graph.add_vertex() for i in range(size - 1): new_vertex = graph.add_vertex() graph.add_edge(prev_vertex, new_vertex, weight) prev_vertex = new_vertex return graph def cycle(size, weight = 1): """Returns cycle of given size with edges set to given weight""" if size in (0, 1): return nullgraph() if size < 0: raise GraphError, 'Invalid graph size' graph = Graph() first = graph.add_vertex() prev_vertex = first for i in range(size - 1): new_vertex = graph.add_vertex() graph.add_edge(prev_vertex, new_vertex, weight) prev_vertex = new_vertex graph.add_edge(first, prev_vertex, weight) return graph def wheel(size, weight = 1): """Returns wheel of given size with edges set to given weight""" if size in (0, 1, 2): return nullgraph() if size < 0: raise GraphError, 'Invalid graph size' graph = cycle(size - 1, weight) base = graph.add_vertex() for vertex in graph.get_vertices(): if base != vertex: graph.add_edge(base, vertex, weight) return graph def complete(size, weight = 1): """Returns complete graph of given size with edges set to given weight""" if size == 0: return nullgraph() if size < 0: raise GraphError, 'Invalid graph size' graph = Graph() for i in range(size): graph.add_vertex() vertices = graph.get_vertices() for i in range(graph.get_size()): for j in range(i): graph.add_edge(vertices[i], vertices[j], weight) return graph def complete_bipartite(r, s, weight = 1): """Returns r,s complete bipartite graph with edges set to given weight""" if r == 0 or s == 0: return nullgraph() if r < 0 or s < 0: raise GraphError, 'Invalid graph size' graph = Graph() r_vertices = [] for i in range(r): r_vertices.append(graph.add_vertex()) s_vertices = [] for i in range(s): s_vertices.append(graph.add_vertex()) for i in r_vertices: for j in s_vertices: graph.add_edge(i, j, weight) return graph def cube(size, w = 1): """Returns cube graph of given size with vertices set to given weight """ def generate_subgraph(subgraph_size, g): if subgraph_size > 1: generate_subgraph(subgraph_size - 1, g) vertices = g.get_vertices() edges = g.get_edges() new_vertices = map(lambda x: g.add_vertex(), vertices) for i in range(len(vertices)): g.add_edge(vertices[i], new_vertices[i], 1) for a, b, w in edges: g.add_edge(new_vertices[vertices.index(a)], new_vertices[vertices.index(b)], w) g = Graph() g.add_vertex() generate_subgraph(size, g) return g def petersen(weight = 1): """Returns Peterson's graph with edges set to given weight""" graph = Graph() a = graph.add_vertex() b = graph.add_vertex() c = graph.add_vertex() d = graph.add_vertex() e = graph.add_vertex() f = graph.add_vertex() g = graph.add_vertex() h = graph.add_vertex() i = graph.add_vertex() j = graph.add_vertex() graph.add_edge(a, b, weight) graph.add_edge(b, c, weight) graph.add_edge(c, d, weight) graph.add_edge(d, e, weight) graph.add_edge(e, a, weight) graph.add_edge(a, f, weight) graph.add_edge(b, g, weight) graph.add_edge(c, h, weight) graph.add_edge(d, i, weight) graph.add_edge(e, j, weight) graph.add_edge(f, h, weight) graph.add_edge(h, j, weight) graph.add_edge(j, g, weight) graph.add_edge(g, i, weight) graph.add_edge(i, f, weight) return graph def depth_first_search(graph, visit_functor, start_vertex = 'A'): """Depth first search of graph. Visit functor is called for every vertex""" def visit(vertex): visit_functor(vertex) visited[vertex] = True for next_vertex in graph.adjacent_to(vertex): if not visited[next_vertex]: visit(next_vertex) visited = {} for vertex in graph.get_vertices(): visited[vertex] = False n = 1 visit(start_vertex) for vertex in graph.get_vertices(): if not visited[vertex]: n = n + 1 visit(vertex) return n def breath_first_search(graph, visit_functor, start_vertex = 'A'): """Breath first search of graph. Visit functor is called for every vertex""" visited = {} for vertex in graph.get_vertices(): visited[vertex] = False next = [start_vertex] while next: current_node = next[0] next = next[0:] visit_functor(current_node) visited[current_node] = True next.extend(graph.adjacent_to(current_node)) next = filter(lambda x: not visited[x], next) if not next and False in visited: next = [visited.index(False)] def number_of_components(graph): """Returns number of unconnected componnents in graph""" def visit_functor(x): pass return depth_first_search(graph, visit_functor) def is_connected(graph): """Returns True if graph is connected""" return number_of_components(graph) == 1 def get_hamilton_path(graph): """Returns True (and path) if graph contains Hamilton path""" marked = 0 path = [] def mark_vertex(start_vertex, vertex, marked): marked = marked + 1 visited[vertex] = marked if visited[vertex] == graph.get_size() and graph.is_edge(vertex, start_vertex): for i in range(1, graph.get_size() + 1): for v in graph.get_vertices(): if i == visited[v]: path.append(v) return for v in graph.get_vertices(): if not visited[v] and graph.is_edge(v, vertex): mark_vertex(start_vertex, v, marked) marked = marked - 1 visited[vertex] = 0 visited = {} for vertex in graph.get_vertices(): visited[vertex] = 0 for vertex in graph.get_vertices(): if not visited[vertex]: mark_vertex(vertex, vertex, marked) return path def is_hamilton(graph): """Returns True if graph is Hamilton's""" return get_hamilton_path(graph) != [] def shortest_path(g, start = 'A', end = None): """Dijkstra's algorithm for shortest path""" graph = g.copy() distances = {} previous = {} for v1 in graph.get_vertices(): for v2 in graph.get_vertices(): if not graph.is_edge(v1, v2): graph.add_edge(v1, v2, infinity) distances[v1] = infinity previous[v1] = None distances[start] = 0 vertices = graph.get_vertices() while vertices: minimal = vertices[0] for vertex in vertices: if distances[vertex] < distances[minimal]: minimal = vertex del vertices[vertices.index(minimal)] for v in graph.get_vertices(): if graph.is_edge(minimal, v): if distances[v] > distances[minimal] + graph.get_weight(minimal, v): distances[v] = distances[minimal] + graph.get_weight(minimal, v) previous[v] = minimal if not end: end = max(graph.get_vertices()) path = [end] t = previous[end] while t: path.insert(0, t) t = previous[t] return distances[end], path def get_any_spanning_tree(graph): """Returns any of graph's spanning trees""" tree_edges = [] def mark_vertex(k): visited[k] = True for i in graph.get_vertices(): if graph.is_edge(i, k) and not visited[i]: tree_edges.append((k, i)) mark_vertex(i) visited = {} for vertex in graph.get_vertices(): visited[vertex] = False for vertex in graph.get_vertices(): if not visited[vertex]: mark_vertex(vertex) return tree_edges def get_minimal_spanning_tree(graph): """Returns minimal spanning weight an tree using kruskal's algorithm""" mst_weigth, mst_edges = 0, [] edges = graph.get_edges() tree_list = [[e] for e in graph.get_vertices()] while edges: minimal_weight = infinity for start, end, weight in edges: if weight < minimal_weight: minimal_weight = weight minimal_edge = (start, end, weight) i = 0 for tree in tree_list: if minimal_edge[0] in tree: first_tree = tree if minimal_edge[1] in tree: second_tree = tree i = i + 1 if first_tree != second_tree: new_tree = first_tree + second_tree tree_list.remove(first_tree) tree_list.remove(second_tree) tree_list.append(new_tree) mst_edges.append(minimal_edge[:-1]) mst_weigth = mst_weigth + minimal_weight edges.remove(minimal_edge) return mst_weigth, mst_edges def vertex_coloring(graph): """Colors the graph and returns mapping list of vertices and colors""" if not graph.get_edges(): return [(v, 1) for x in graph.get_vertices()] def colors_ok(colors): vertices = graph.get_vertices() for i in range(len(vertices)): for j in graph.adjacent_to(vertices[i]): color = colors[vertices.index(j)] if color == colors[i]: return False return True def upper_bound(): vertices = graph.get_vertices() vx = vertices[:] allcol = range(len(vx)) col = [None for x in vx] while vx: v = vx[0] adjacent = [ col[vertices.index(x)] for x in graph.adjacent_to(v) ] available = [ x for x in allcol if adjacent.count(x) == 0 ] col[vertices.index(v)] = min(available) vx.pop(0) return col def enumerate_coloring(vx, col, n): if vx == []: if colors_ok(col): return col else: return None v = vx[0] for i in range(n): c = col[:] c.insert(0, i) ret = enumerate_coloring(vx[1:], c, n) if ret != None: return ret col = upper_bound() n = 1 + max(col) for i in range(2, n): x = enumerate_coloring(graph.get_vertices(), [], i) if x != None: col = x break vertices = graph.get_vertices() return [(v, col[vertices.index(v)]) for v in vertices] def get_chromatic_number(graph): """Returns chromatic number of graph""" return 1 + max(map(lambda x: list(x)[1], vertex_coloring(graph))) def is_planar(g): """Returns True if graph is planar graph""" def _is_k5(g): return (len(g.get_vertices()) == 5) and (len(g.get_edges()) == 20) def _is_k33(g): vx = g.get_vertices() ex = g.get_edges() if (len(vx) != 6) or (len(ex) != 18): return False white = g.adjacent_to(vx[0]) if len(white) != 3: return False black = [ x for x in vx if white.count(x) == 0 ] for v in white: x = g.adjacent_to(v) x.sort() if x != black: return False return True def _remove_0degs(g): map(g.remove_vertex, [x for x in g.get_vertices() if g.get_degree(x) == 0]) def _remove_1degs(g): while True: vx = [x for x in g.get_vertices() if g.get_degree(x) == 1] if vx == []: return map(g.remove_vertex, vx) def _remove_2degs(g): while True: vx = [ x for x in g.get_vertices() if g.get_degree(x) == 2 ] if vx == []: return x = vx[0] conn = g.adjacent_to(x) if not g.is_edge(conn[0], conn[1]): g.add_edge(conn[0], conn[1], 1) g.remove_vertex(x) def _remove_edges(g): _remove_1degs(g) _remove_2degs(g) _remove_0degs(g) def _non_planar_by_limit(g): n = len(g.get_vertices()) m = len(g.get_edges()) / 2 if n < 3: return False if m > (3 * n - 6): return True return False def _non_planar(g, l): if l == []: return _is_k5(g) or _is_k33(g) if _non_planar_by_limit(g): return True if _non_planar(g.copy(), l[1:]): return True a, b, w = l[0] g.remove_edge(a, b) _remove_edges(g) l = [(a,b,w) for a, b, w in l[1:] if g.is_edge(a, b)] return _non_planar(g, l) def _less_than_6deg(g): return [1 for x in g.get_vertices() if g.get_degree(x) < 6] != [] g = g.copy() _remove_edges(g) if not _less_than_6deg(g): return False ex = [(a,b,w) for a, b, w in g.get_edges() if (a < b)] return not _non_planar(g, ex) def get_pairs_number(graph): """Counts the number of solutions to the pairing""" if get_chromatic_number(graph) != 2: raise GraphError, "Not a bipartite graph" colors = vertex_coloring(graph) girls = [v for v,c in colors if c == 0] boys = [v for v,c in colors if c == 1] def _slave(g, b): if g == []: return 1 available = [ x for x in graph.adjacent_to(g[0]) if b.count(x) != 0 ] if available == []: return 0 cnt = 0 for x in available: cnt = cnt + _slave(g[1:], [ y for y in b if y != x ]) return cnt return _slave(girls, boys) def get_max_flow(graph): """Finds the maximum flow in the network""" if not graph.is_digraph(): raise GraphError, "Graph is not directed" flow = Graph(True) map(lambda x: flow.add_vertex(), graph.get_vertices()) map(lambda x: flow.add_edge(list(x)[0],list(x)[1],0), graph.get_edges()) def _connected_to(v): return flow.adjacent_to(v) def _connected_from(v): return [a for a, b, w in flow.get_edges() if b == v] def _is_sink(v): return flow.adjacent_to(v) == [] def _path_append(path, start, end, weight, direction): p = path[:] p.append((start, end, weight, direction)) return p def _augument_flow(path): if path == []: return f = list(path[0])[2] for a, b, w, d in path: if f > w: f = w for a, b, w, d in path: if d: flow.add_edge(a, b, f) else: flow.add_edge(a, b, -1 * f) def _visited(v, path): for a, b, w, d in path: if (a == v) or (b == v): return True return False def _slave(v, path): vx = [x for x in _connected_to(v) if not _visited(x, path) ] if vx == []: if not _is_sink(v): return _augument_flow(path) return for x in vx: free = graph.get_weight(v, x) - flow.get_weight(v, x) if free > 0: _slave(x, _path_append(path, v, x, free, True)) vx = [x for x in _connected_from(v) if not _visited(x, path) ] for x in vx: free = flow.get_weight(x, v) if free > 0: _slave(x, _path_append(path, v, x, free, False)) vx = flow.get_vertices() if vx == []: return flow _slave(vx[0], []) return flow def get_max_flow_val(graph): """Returns the value of a maximum flow of""" flow = get_max_flow(graph) vx = flow.get_vertices() if vx == []: return 0 return flow.get_out_degree(vx[0]) <file_sep>/* simulacija stranicenja algoritmom LFU (Least frequently used) * * Labos iz Operacijskih Sustava * * (C) 2005 <NAME> <<EMAIL>> */ #include <time.h> #include <stdio.h> #include <stdlib.h> #define PAGES_NUM 8 #define PAGE_NEW 1 #define PAGE_HIT 2 int display_usage (FILE *stream, int exit_code) { fprintf (stream, "Usage: lfu frames_count requests_num\n"); exit (exit_code); } int main (int argc, char **argv) { int i, j, min, done, action, frames_count, requests_num; int *requests, *page_frames; int pages[PAGES_NUM+1] = {0}; if (argc != 3) display_usage (stdout, EXIT_SUCCESS); if ((sscanf (argv[1], "%d", &frames_count)) != 1) display_usage (stderr, EXIT_FAILURE); if ((sscanf (argv[2], "%d", &requests_num)) != 1) display_usage (stderr, EXIT_FAILURE); srand ((unsigned) time (NULL)); requests = malloc (requests_num * sizeof (int)); page_frames = calloc (frames_count, sizeof (int)); printf ("Zahtjevi: "); for (i=0 ; i<requests_num ; ++i) { requests[i] = 1 + rand() % 8; printf ("%d", requests[i]); if (i != requests_num - 1) printf (", "); } printf ("\n\n#N\t"); for (i=0 ; i<frames_count ; ++i) printf ("%d\t", i + 1); printf ("\n"); for (i=0 ; i<frames_count ; ++i) printf ("---------"); printf ("\n"); for (i=0 ; i<requests_num ; ++i) { printf ("%d", requests[i]); done = action = 0; for (j=0 ; j<frames_count ; ++j) if (requests[i] == page_frames[j]) { action = PAGE_HIT; ++pages[requests[i]]; done = 1; break; } if (!done) for (j=0 ; j<frames_count ; ++j) if (!page_frames[j]) { action = PAGE_NEW; ++pages[requests[i]]; page_frames[j] = requests[i]; done = 1; break; } if (!done) { action = PAGE_NEW; for (min = 0, j=1 ; j<frames_count ; ++j) if (pages[page_frames[j]] < pages[page_frames[min]]) min = j; pages[page_frames[min]] = 0; page_frames[min] = requests[i]; ++pages[requests[i]]; } for (j=0 ; j<frames_count ; ++j) if (!page_frames[j]) printf ("\t-"); else if (page_frames[j] == requests[i]) if (action == PAGE_NEW) printf ("\t\b[%d]", page_frames[j]); else printf ("\t\b(%d)", page_frames[j]); else printf ("\t%d", page_frames[j]); printf ("\n"); } return EXIT_SUCCESS; } <file_sep>/* filozofi.c - sprjecavanje deadlocka pomocu monitora (problem pet filozofa) * Labos iz Operacijskih Sustava * * (C) 2005 <NAME> <<EMAIL>> */ #include <time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #define NUM 5 pthread_cond_t table_free_cv, sticks_cv[NUM]; pthread_mutex_t monitor = PTHREAD_MUTEX_INITIALIZER; int is_eating[NUM] = {0}; int table_free = 2, sticks[NUM] = {1, 1, 1, 1, 1}; void print_status () { int i; for (i=0 ; i<NUM ; ++i) if (is_eating[i]) printf ("jede\t"); else printf ("misli\t"); printf ("\n"); } void enter_monitor (int i) { pthread_mutex_lock (&monitor); /* cekaj dok za stolom ne bude samo jedan filozof */ while (table_free == 0) pthread_cond_wait (&table_free_cv, &monitor); --table_free; /* cekaj na lijevi i desni stapic */ while (sticks[i] == 0) pthread_cond_wait (&sticks_cv[i], &monitor); --sticks[i]; while (sticks[(i + 1) % NUM] == 0) pthread_cond_wait (&sticks_cv[(i + 1) % NUM], &monitor); --sticks[(i + 1) % NUM]; /* jedi jednu sekundu, ispisi status */ is_eating[i] = 1; pthread_mutex_unlock (&monitor); } void leave_monitor (int i) { pthread_mutex_lock (&monitor); is_eating[i] = 0; sticks[i] = sticks [(i + 1) % NUM] = 1; ++table_free; pthread_cond_broadcast (&sticks_cv[i]); pthread_cond_broadcast (&sticks_cv[(i + 1) % NUM]); pthread_cond_broadcast (&table_free_cv); pthread_mutex_unlock (&monitor); } void *philosoph (void *param) { int i = *((int *) param); srand ((unsigned) time (NULL)); while (1) { sleep (1 + rand() % 2); enter_monitor (i); print_status (); sleep (1 + rand() % 1); leave_monitor (i); } } int main () { int i, philosoph_id[NUM]; pthread_t thread_id[NUM]; /* inicijaliziraj cond varijable */ pthread_cond_init (&table_free_cv, NULL); for (i=0 ; i<NUM ; ++i) pthread_cond_init (&sticks_cv[i], NULL); printf ("Fil #1\tFil #2\tFil #3\tFil #4\tFil #5\n"); printf ("----------------------------------------\n"); /* kreiraj niti */ for (i=0 ; i<NUM ; ++i) { philosoph_id[i] = i; pthread_create (&thread_id[i], NULL, philosoph, &philosoph_id[i]); } /* cekaj na sve niti */ for (i=0 ; i<NUM ; ++i) pthread_join (thread_id[i], NULL); return EXIT_SUCCESS; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <gtk/gtk.h> #include "des.h" #include "rsa.h" #include "sha.h" /* file path for File dialog */ char *file_path; /* GUI main widgets */ GtkWidget *window, *hbox, *vbox, *menu_bar, *notebook; /* menu widgets */ GtkWidget *file_menu, *file_item, *quit_item; GtkWidget *edit_menu, *edit_item, *cut_item, *copy_item, *paste_item; GtkWidget *help_menu, *help_item, *about_item; /* Frame widgets */ GtkWidget *frame_symetric, *frame_asymetric, *frame_hash, *label; GtkWidget *frame_envelope, *frame_signature, *frame_stamp; /* "Envelope" frame widgets */ GtkWidget *env_in_path, *env_in_select, *env_in_view; GtkWidget *env_out_path, *env_out_select, *env_out_view; GtkWidget *env_envelope, *env_select, *env_view; GtkWidget *env_pub_key_path, *env_pub_key_select, *env_pub_key_view; GtkWidget *env_prv_key_path, *env_prv_key_select, *env_prv_key_view; GtkWidget *env_open, *env_generate; /* "Signature" frame widgets */ GtkWidget *sgn_in_path, *sgn_in_select, *sgn_in_view; GtkWidget *sgn_out_path, *sgn_out_select, *sgn_out_view; GtkWidget *sgn_pub_key_path, *sgn_pub_key_select, *sgn_pub_key_view; GtkWidget *sgn_prv_key_path, *sgn_prv_key_select, *sgn_prv_key_view; GtkWidget *sgn_signature, *sgn_select, *sgn_view; GtkWidget *sgn_generate, *sgn_check; /* "Stamp" frame widgets */ GtkWidget *stmp_in_path, *stmp_in_select, *stmp_in_view; GtkWidget *stmp_out_path, *stmp_out_select, *stmp_out_view; GtkWidget *stmp_snd_prv_key_path, *stmp_snd_prv_key_select, *stmp_snd_prv_key_view; GtkWidget *stmp_snd_pub_key_path, *stmp_snd_pub_key_select, *stmp_snd_pub_key_view; GtkWidget *stmp_rcv_prv_key_path, *stmp_rcv_prv_key_select, *stmp_rcv_prv_key_view; GtkWidget *stmp_rcv_pub_key_path, *stmp_rcv_pub_key_select, *stmp_rcv_pub_key_view; GtkWidget *stmp_sgn_path, *stmp_sgn_select, *stmp_sgn_view; GtkWidget *stmp_env_path, *stmp_env_select, *stmp_env_view; GtkWidget *stmp_generate, *stmp_open; /* "Symetric" frame widgets */ GtkWidget *sym_key_path, *sym_key_select, *sym_key_view, *sym_key_generate; GtkWidget *sym_in_path, *sym_in_select, *sym_in_view; GtkWidget *sym_out_path, *sym_out_select, *sym_out_view; GtkWidget *sym_encrypt, *sym_decrypt; /* "Asymetric" frame widgets */ GtkWidget *asym_pub_key_path, *asym_pub_key_select, *asym_pub_key_view, *asym_pub_key_generate; GtkWidget *asym_prv_key_path, *asym_prv_key_select, *asym_prv_key_view, *asym_prv_key_generate; GtkWidget *asym_in_path, *asym_in_select, *asym_in_view; GtkWidget *asym_out_path, *asym_out_select, *asym_out_view; GtkWidget *asym_key_length, *asym_encrypt, *asym_decrypt; /* "Hash" frame widgets */ GtkWidget *hsh_in_path, *hsh_in_select, *hsh_in_view; GtkWidget *hsh_out_path, *hsh_out_select, *hsh_out_view; GtkWidget *hsh_calculate, *hsh_hash; /* "View" file */ static void view_file (GtkWidget *widget, gpointer *filename) { pid_t pid = fork(); if (pid == -1) { perror ("fork"); } else if (!pid) { char *editor = getenv ("EDITOR"); char *file = GTK_ENTRY (filename)->text; char *arg_list[] = {editor, file, NULL}; execvp (editor, arg_list); _exit (0); } } /* About dialog */ static void show_credits() { GtkWidget *dialog; dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "(C) 2005 <NAME> <<EMAIL>>"); gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); } /* sets filename when "OK" is clicked in File dialog */ static void file_return_path (GtkWidget *widget, GtkFileSelection *fs) { file_path = (char *) gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)); } /* sets filename to text box */ static void file_set_path (GtkWidget *widget) { gtk_entry_set_text (GTK_ENTRY (widget), file_path); } /* file select dialog */ static void file_select (GtkWidget *widget, gpointer *data) { GtkWidget *dialog; dialog = gtk_file_selection_new ("Select file"); g_signal_connect_swapped (G_OBJECT (GTK_FILE_SELECTION (dialog)->cancel_button), "clicked", G_CALLBACK (gtk_widget_destroy), G_OBJECT (dialog)); g_signal_connect (G_OBJECT (GTK_FILE_SELECTION (dialog)->ok_button), "clicked", G_CALLBACK (file_return_path), dialog); g_signal_connect_swapped (G_OBJECT (GTK_FILE_SELECTION (dialog)->ok_button), "clicked", G_CALLBACK (file_set_path), data); g_signal_connect_swapped (G_OBJECT (GTK_FILE_SELECTION (dialog)->ok_button), "clicked", G_CALLBACK (gtk_widget_destroy), G_OBJECT (dialog)); gtk_widget_show (dialog); } static void hsh_callback() { char *output = GTK_ENTRY (hsh_out_path)->text; char *hash = sha1 (GTK_ENTRY (hsh_in_path)->text, output); gtk_entry_set_text (GTK_ENTRY (hsh_hash), hash); } static void sym_encrypt_callback() { char *in_file = GTK_ENTRY (sym_in_path)->text; char *out_file = GTK_ENTRY (sym_out_path)->text; char *key_file = GTK_ENTRY (sym_key_path)->text; char *tmp_out_file = "des_out_XXXXXX.$$$"; des_crypt (in_file, tmp_out_file, des_get_key_from_file (key_file), DES_ENCRYPT); des_convert_to_base64 (tmp_out_file, out_file); unlink (tmp_out_file); } static void sym_decrypt_callback() { char *in_file = GTK_ENTRY (sym_in_path)->text; char *out_file = GTK_ENTRY (sym_out_path)->text; char *key_file = GTK_ENTRY (sym_key_path)->text; char *tmp_out_file = "des_out_XXXXXX.$$$"; des_convert_from_base64 (in_file, tmp_out_file); des_crypt (tmp_out_file, out_file, des_get_key_from_file (key_file), DES_DECRYPT); unlink (tmp_out_file); } static void sym_key_generate_callback() { des_generate_key (GTK_ENTRY (sym_key_path)->text); } static void asym_encrypt_callback() { char *in_file = GTK_ENTRY (asym_in_path)->text; char *out_file = GTK_ENTRY (asym_out_path)->text; char *key_file = GTK_ENTRY (asym_pub_key_path)->text; const char *tmp_out_file = "/tmp/rsa.out.tmp"; rsa_crypt (key_file, in_file, tmp_out_file, RSA_ENCRYPT); rsa_convert_to_base64 (tmp_out_file, out_file); unlink (tmp_out_file); } static void asym_decrypt_callback() { char *in_file = GTK_ENTRY (asym_in_path)->text; char *out_file = GTK_ENTRY (asym_out_path)->text; char *key_file = GTK_ENTRY (asym_prv_key_path)->text; const char *tmp_out_file = "/tmp/rsa.out.tmp"; rsa_convert_from_base64 (in_file, tmp_out_file); rsa_crypt (key_file, tmp_out_file, out_file, RSA_DECRYPT); unlink (tmp_out_file); } static void open_envelope() { char buffer[100]; snprintf (buffer, 100, "%s.key", GTK_ENTRY(env_envelope)->text); rsa_convert_from_base64 (buffer, "/tmp/des.key.rsa"); rsa_crypt (GTK_ENTRY(env_prv_key_path)->text, "/tmp/des.key.rsa", "/tmp/des.key", RSA_DECRYPT); des_convert_from_base64 (GTK_ENTRY(env_envelope)->text, "/tmp/msg.des"); des_crypt ("/tmp/msg.des", GTK_ENTRY(env_out_path)->text, des_get_key_from_file ("/tmp/des.key"), DES_DECRYPT); } static void generate_envelope() { char buffer[100]; des_generate_key ("/tmp/des.key"); des_crypt (GTK_ENTRY(env_in_path)->text, "/tmp/msg.des", des_get_key_from_file ("/tmp/des.key"), DES_ENCRYPT); des_convert_to_base64 ("/tmp/msg.des", GTK_ENTRY(env_envelope)->text); rsa_crypt (GTK_ENTRY(env_pub_key_path)->text, "/tmp/des.key", "/tmp/des.key.rsa", RSA_ENCRYPT); snprintf (buffer, 100, "%s.key", GTK_ENTRY(env_envelope)->text); rsa_convert_to_base64 ("/tmp/des.key.rsa", buffer); } static void generate_signature() { sha1 (GTK_ENTRY (sgn_in_path)->text, "/tmp/msg.sha"); rsa_crypt (GTK_ENTRY (sgn_prv_key_path)->text, "/tmp/msg.sha", "/tmp/hash.rsa", RSA_ENCRYPT); rsa_convert_to_base64 ("/tmp/hash.rsa", GTK_ENTRY (sgn_signature)->text); } static void open_signature() { rsa_convert_from_base64 (GTK_ENTRY (sgn_signature)->text, "/tmp/hash.rsa"); rsa_crypt (GTK_ENTRY (sgn_pub_key_path)->text, "/tmp/hash.rsa", GTK_ENTRY (sgn_out_path)->text, RSA_DECRYPT); } static void generate_stamp() { char buffer[100]; des_generate_key ("/tmp/des.key"); des_crypt (GTK_ENTRY(stmp_in_path)->text, "/tmp/msg.des", des_get_key_from_file ("/tmp/des.key"), DES_ENCRYPT); des_convert_to_base64 ("/tmp/msg.des", GTK_ENTRY(stmp_env_path)->text); rsa_crypt (GTK_ENTRY(stmp_rcv_pub_key_path)->text, "/tmp/des.key", "/tmp/des.key.rsa", RSA_ENCRYPT); snprintf (buffer, 100, "%s.key", GTK_ENTRY(stmp_env_path)->text); rsa_convert_to_base64 ("/tmp/des.key.rsa", buffer); sha1 (GTK_ENTRY (stmp_env_path)->text, "/tmp/msg.sha"); rsa_crypt (GTK_ENTRY (stmp_snd_prv_key_path)->text, "/tmp/msg.sha", "/tmp/hash.rsa", RSA_ENCRYPT); rsa_convert_to_base64 ("/tmp/hash.rsa", GTK_ENTRY (stmp_sgn_path)->text); } static void open_stamp() { char buffer[100]; rsa_convert_from_base64 (GTK_ENTRY (stmp_sgn_path)->text, "/tmp/hash.rsa"); rsa_crypt (GTK_ENTRY (stmp_snd_pub_key_path)->text, "/tmp/hash.rsa", GTK_ENTRY (stmp_out_path)->text, RSA_DECRYPT); snprintf (buffer, 100, "%s.key", GTK_ENTRY(stmp_env_path)->text); rsa_convert_from_base64 (buffer, "/tmp/des.key.rsa"); rsa_crypt (GTK_ENTRY(stmp_snd_prv_key_path)->text, "/tmp/des.key.rsa", "/tmp/des.key", RSA_DECRYPT); des_convert_from_base64 (GTK_ENTRY(stmp_env_path)->text, "/tmp/msg.des"); des_crypt ("/tmp/msg.des", GTK_ENTRY(stmp_out_path)->text, des_get_key_from_file ("/tmp/des.key"), DES_DECRYPT); } static void asym_key_generate_callback() { rsa_generate_key (GTK_ENTRY (asym_pub_key_path)->text, GTK_ENTRY (asym_prv_key_path)->text, atoi (GTK_ENTRY (asym_key_length)->text)); } int main (int argc, char **argv) { /* initialize gtk engine */ gtk_init (&argc, &argv); /* main window setup */ window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_container_set_border_width (GTK_CONTAINER (window), 1); gtk_widget_set_size_request (window, 640, 450); gtk_window_set_title (GTK_WINDOW (window), "GPrivacy"); g_signal_connect (G_OBJECT (window), "delete_event", G_CALLBACK (gtk_main_quit), NULL); /* use vbox to get nice widget layout */ vbox = gtk_vbox_new (FALSE, 0); gtk_container_add (GTK_CONTAINER (window), vbox); /* menus setup */ file_menu = gtk_menu_new(); quit_item = gtk_menu_item_new_with_label ("Quit"); gtk_menu_shell_append (GTK_MENU_SHELL (file_menu), quit_item); g_signal_connect_swapped (G_OBJECT (quit_item), "activate", G_CALLBACK (gtk_main_quit), NULL); edit_menu = gtk_menu_new(); cut_item = gtk_menu_item_new_with_label ("Cut"); gtk_menu_shell_append (GTK_MENU_SHELL (edit_menu), cut_item); copy_item = gtk_menu_item_new_with_label ("Copy"); gtk_menu_shell_append (GTK_MENU_SHELL (edit_menu), copy_item); paste_item = gtk_menu_item_new_with_label ("Paste"); gtk_menu_shell_append (GTK_MENU_SHELL (edit_menu), paste_item); help_menu = gtk_menu_new(); about_item = gtk_menu_item_new_with_label ("About"); gtk_menu_shell_append (GTK_MENU_SHELL (help_menu), about_item); g_signal_connect_swapped (G_OBJECT (about_item), "activate", G_CALLBACK (show_credits), NULL); /* menu bar setup */ menu_bar = gtk_menu_bar_new(); gtk_box_pack_start (GTK_BOX (vbox), menu_bar, FALSE, FALSE, 2); file_item = gtk_menu_item_new_with_label ("File"); gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item), file_menu); gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), file_item); edit_item = gtk_menu_item_new_with_label ("Edit"); gtk_menu_item_set_submenu (GTK_MENU_ITEM (edit_item), edit_menu); gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), edit_item); help_item = gtk_menu_item_new_with_label ("Help"); gtk_menu_item_set_submenu (GTK_MENU_ITEM (help_item), help_menu); gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), help_item); gtk_menu_item_right_justify (GTK_MENU_ITEM (help_item)); /* notebook (tabs) setup */ notebook = gtk_notebook_new(); gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP); gtk_box_pack_end (GTK_BOX (vbox), notebook, TRUE, TRUE, 2); /* frames setup */ frame_envelope = gtk_frame_new ("Digital envelope"); gtk_container_set_border_width (GTK_CONTAINER (frame_envelope), 5); label = gtk_label_new ("Digital envelope"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_envelope, label); frame_signature = gtk_frame_new ("Digital signature"); gtk_container_set_border_width (GTK_CONTAINER (frame_signature), 5); label = gtk_label_new ("Digital signature"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_signature, label); frame_stamp = gtk_frame_new ("Digital stamp"); gtk_container_set_border_width (GTK_CONTAINER (frame_stamp), 5); label = gtk_label_new ("Digital stamp"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_stamp, label); frame_symetric = gtk_frame_new ("Symetric cypher (DES)"); gtk_container_set_border_width (GTK_CONTAINER (frame_symetric), 5); label = gtk_label_new ("Symetric cypher"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_symetric, label); frame_asymetric = gtk_frame_new ("Asymetric cypher (RSA)"); gtk_container_set_border_width (GTK_CONTAINER (frame_asymetric), 5); label = gtk_label_new ("Asymetric cypher"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_asymetric, label); frame_hash = gtk_frame_new ("Hash (SHA-1)"); gtk_container_set_border_width (GTK_CONTAINER (frame_hash), 5); label = gtk_label_new ("Hash"); gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame_hash, label); /* "Symetric" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_symetric), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Key file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sym_key_path = gtk_entry_new(); gtk_widget_set_size_request (sym_key_path, 300, 25); gtk_entry_set_text (GTK_ENTRY (sym_key_path), "des_kljuc.txt"); gtk_entry_set_max_length (GTK_ENTRY (sym_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sym_key_path, FALSE, FALSE, 0); sym_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sym_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_key_select), "clicked", G_CALLBACK (file_select), sym_key_path); sym_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sym_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_key_view), "clicked", G_CALLBACK (view_file), sym_key_path); sym_key_generate = gtk_button_new_with_label ("Generate"); gtk_box_pack_start (GTK_BOX (hbox), sym_key_generate, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_key_generate), "clicked", G_CALLBACK (sym_key_generate_callback), NULL); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sym_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sym_in_path), "des_ulaz.txt"); gtk_widget_set_size_request (sym_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sym_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sym_in_path, FALSE, FALSE, 0); sym_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sym_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_in_select), "clicked", G_CALLBACK (file_select), sym_in_path); sym_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sym_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_in_view), "clicked", G_CALLBACK (view_file), sym_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sym_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sym_out_path), "des_izlaz.txt"); gtk_entry_set_max_length (GTK_ENTRY (sym_out_path), 100); gtk_widget_set_size_request (sym_out_path, 300, 25); gtk_box_pack_start (GTK_BOX (hbox), sym_out_path, FALSE, FALSE, 0); sym_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sym_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_out_select), "clicked", G_CALLBACK (file_select), sym_out_path); sym_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sym_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sym_out_view), "clicked", G_CALLBACK (view_file), sym_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 10); sym_encrypt = gtk_button_new_with_label ("Encrypt"); gtk_widget_set_size_request (sym_encrypt, 110, 30); gtk_box_pack_start (GTK_BOX (hbox), sym_encrypt, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (sym_encrypt), "clicked", G_CALLBACK (sym_encrypt_callback), NULL); sym_decrypt = gtk_button_new_with_label ("Decrypt"); gtk_widget_set_size_request (sym_decrypt, 110, 30); gtk_box_pack_start (GTK_BOX (hbox), sym_decrypt, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (sym_decrypt), "clicked", G_CALLBACK (sym_decrypt_callback), NULL); /* "Asymetric" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_asymetric), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Private key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); asym_prv_key_path = gtk_entry_new(); gtk_widget_set_size_request (asym_prv_key_path, 300, 25); gtk_entry_set_text (GTK_ENTRY (asym_prv_key_path), "rsa_tajni_kljuc.txt"); gtk_entry_set_max_length (GTK_ENTRY (asym_prv_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), asym_prv_key_path, FALSE, FALSE, 0); asym_prv_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), asym_prv_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_prv_key_select), "clicked", G_CALLBACK (file_select), asym_prv_key_path); asym_prv_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), asym_prv_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_prv_key_view), "clicked", G_CALLBACK (view_file), asym_prv_key_path); asym_prv_key_generate = gtk_button_new_with_label ("Generate"); gtk_box_pack_start (GTK_BOX (hbox), asym_prv_key_generate, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_prv_key_generate), "clicked", G_CALLBACK (asym_key_generate_callback), NULL); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Public key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); asym_pub_key_path = gtk_entry_new(); gtk_widget_set_size_request (asym_pub_key_path, 300, 25); gtk_entry_set_text (GTK_ENTRY (asym_pub_key_path), "rsa_javni_kljuc.txt"); gtk_entry_set_max_length (GTK_ENTRY (asym_pub_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), asym_pub_key_path, FALSE, FALSE, 0); asym_pub_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), asym_pub_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_pub_key_select), "clicked", G_CALLBACK (file_select), asym_pub_key_path); asym_pub_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), asym_pub_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_pub_key_view), "clicked", G_CALLBACK (view_file), asym_pub_key_path); asym_pub_key_generate = gtk_button_new_with_label ("Generate"); gtk_box_pack_start (GTK_BOX (hbox), asym_pub_key_generate, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_pub_key_generate), "clicked", G_CALLBACK (asym_key_generate_callback), NULL); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); asym_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (asym_in_path), "rsa_ulaz.txt"); gtk_widget_set_size_request (asym_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (asym_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), asym_in_path, FALSE, FALSE, 0); asym_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), asym_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_in_select), "clicked", G_CALLBACK (file_select), asym_in_path); asym_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), asym_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_in_view), "clicked", G_CALLBACK (view_file), asym_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); asym_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (asym_out_path), "rsa_izlaz.txt"); gtk_entry_set_max_length (GTK_ENTRY (asym_out_path), 100); gtk_widget_set_size_request (asym_out_path, 300, 25); gtk_box_pack_start (GTK_BOX (hbox), asym_out_path, FALSE, FALSE, 0); asym_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), asym_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_out_select), "clicked", G_CALLBACK (file_select), asym_out_path); asym_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), asym_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (asym_out_view), "clicked", G_CALLBACK (view_file), asym_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Key length"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); asym_key_length = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (asym_key_length), "128"); gtk_entry_set_max_length (GTK_ENTRY (asym_key_length), 4); gtk_widget_set_size_request (asym_key_length, 50, 25); gtk_box_pack_start (GTK_BOX (hbox), asym_key_length, FALSE, FALSE, 0); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 10); asym_encrypt = gtk_button_new_with_label ("Encrypt"); gtk_widget_set_size_request (asym_encrypt, 110, 30); gtk_box_pack_start (GTK_BOX (hbox), asym_encrypt, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (asym_encrypt), "clicked", G_CALLBACK (asym_encrypt_callback), NULL); asym_decrypt = gtk_button_new_with_label ("Decrypt"); gtk_widget_set_size_request (asym_decrypt, 110, 30); gtk_box_pack_start (GTK_BOX (hbox), asym_decrypt, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (asym_decrypt), "clicked", G_CALLBACK (asym_decrypt_callback), NULL); /* "Hash" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_hash), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); hsh_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (hsh_in_path), "sha_ulaz.txt"); gtk_widget_set_size_request (hsh_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (hsh_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), hsh_in_path, FALSE, FALSE, 0); hsh_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), hsh_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (hsh_in_select), "clicked", G_CALLBACK (file_select), hsh_in_path); hsh_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), hsh_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (hsh_in_view), "clicked", G_CALLBACK (view_file), hsh_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); hsh_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (hsh_out_path), "sha_izlaz.txt"); gtk_widget_set_size_request (hsh_out_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (hsh_out_path), 100); gtk_box_pack_start (GTK_BOX (hbox), hsh_out_path, FALSE, FALSE, 0); hsh_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), hsh_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (hsh_out_select), "clicked", G_CALLBACK (file_select), hsh_out_path); hsh_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), hsh_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (hsh_out_view), "clicked", G_CALLBACK (view_file), hsh_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Hash"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); hsh_hash = gtk_entry_new(); gtk_widget_set_size_request (hsh_hash, 300, 25); gtk_box_pack_start (GTK_BOX (hbox), hsh_hash, FALSE, FALSE, 0); hsh_calculate = gtk_button_new_with_label ("Calculate hash"); gtk_box_pack_start (GTK_BOX (hbox), hsh_calculate, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (hsh_calculate), "clicked", G_CALLBACK (hsh_callback), NULL); /* "Envelope" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_envelope), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); env_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (env_in_path), "ulaz.txt"); gtk_widget_set_size_request (env_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (env_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), env_in_path, FALSE, FALSE, 0); env_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), env_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_in_select), "clicked", G_CALLBACK (file_select), env_in_path); env_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), env_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_in_view), "clicked", G_CALLBACK (view_file), env_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); env_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (env_out_path), "izlaz.txt"); gtk_widget_set_size_request (env_out_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (env_out_path), 100); gtk_box_pack_start (GTK_BOX (hbox), env_out_path, FALSE, FALSE, 0); env_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), env_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_out_select), "clicked", G_CALLBACK (file_select), env_out_path); env_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), env_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_out_view), "clicked", G_CALLBACK (view_file), env_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Private key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); env_prv_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (env_prv_key_path), "rsa_b_tajni.txt"); gtk_widget_set_size_request (env_prv_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (env_prv_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), env_prv_key_path, FALSE, FALSE, 0); env_prv_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), env_prv_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_prv_key_select), "clicked", G_CALLBACK (file_select), env_prv_key_path); env_prv_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), env_prv_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_prv_key_view), "clicked", G_CALLBACK (view_file), env_prv_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Public key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); env_pub_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (env_pub_key_path), "rsa_b_javni.txt"); gtk_widget_set_size_request (env_pub_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (env_pub_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), env_pub_key_path, FALSE, FALSE, 0); env_pub_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), env_pub_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_pub_key_select), "clicked", G_CALLBACK (file_select), env_pub_key_path); env_pub_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), env_pub_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_pub_key_view), "clicked", G_CALLBACK (view_file), env_pub_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Envelope"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); env_envelope = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (env_envelope), "omotnica.txt"); gtk_widget_set_size_request (env_envelope, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (env_envelope), 100); gtk_box_pack_start (GTK_BOX (hbox), env_envelope, FALSE, FALSE, 0); env_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), env_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_select), "clicked", G_CALLBACK (file_select), env_envelope); env_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), env_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (env_view), "clicked", G_CALLBACK (view_file), env_envelope); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); env_open = gtk_button_new_with_label ("Open envelope"); gtk_box_pack_start (GTK_BOX (hbox), env_open, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (env_open), "clicked", G_CALLBACK (open_envelope), NULL); env_generate = gtk_button_new_with_label ("Generate envelope"); gtk_box_pack_start (GTK_BOX (hbox), env_generate, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (env_generate), "clicked", G_CALLBACK (generate_envelope), NULL); /* "Signature" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_signature), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sgn_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sgn_in_path), "ulaz.txt"); gtk_widget_set_size_request (sgn_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sgn_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sgn_in_path, FALSE, FALSE, 0); sgn_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sgn_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_in_select), "clicked", G_CALLBACK (file_select), sgn_in_path); sgn_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sgn_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_in_view), "clicked", G_CALLBACK (view_file), sgn_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sgn_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sgn_out_path), "izlaz.txt"); gtk_widget_set_size_request (sgn_out_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sgn_out_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sgn_out_path, FALSE, FALSE, 0); sgn_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sgn_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_out_select), "clicked", G_CALLBACK (file_select), sgn_out_path); sgn_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sgn_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_out_view), "clicked", G_CALLBACK (view_file), sgn_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Private key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sgn_prv_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sgn_prv_key_path), "rsa_a_tajni.txt"); gtk_widget_set_size_request (sgn_prv_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sgn_prv_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sgn_prv_key_path, FALSE, FALSE, 0); sgn_prv_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sgn_prv_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_prv_key_select), "clicked", G_CALLBACK (file_select), sgn_prv_key_path); sgn_prv_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sgn_prv_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_prv_key_view), "clicked", G_CALLBACK (view_file), sgn_prv_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Public key"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sgn_pub_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sgn_pub_key_path), "rsa_a_javni.txt"); gtk_widget_set_size_request (sgn_pub_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sgn_pub_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), sgn_pub_key_path, FALSE, FALSE, 0); sgn_pub_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sgn_pub_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_pub_key_select), "clicked", G_CALLBACK (file_select), sgn_pub_key_path); sgn_pub_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sgn_pub_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_pub_key_view), "clicked", G_CALLBACK (view_file), sgn_pub_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Digital sign"); gtk_widget_set_size_request (label, 100, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); sgn_signature = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (sgn_signature), "potpis.txt"); gtk_widget_set_size_request (sgn_signature, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (sgn_signature), 100); gtk_box_pack_start (GTK_BOX (hbox), sgn_signature, FALSE, FALSE, 0); sgn_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), sgn_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_select), "clicked", G_CALLBACK (file_select), sgn_signature); sgn_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), sgn_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (sgn_view), "clicked", G_CALLBACK (view_file), sgn_signature); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); sgn_generate = gtk_button_new_with_label ("Generate signature"); gtk_box_pack_start (GTK_BOX (hbox), sgn_generate, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (sgn_generate), "clicked", G_CALLBACK (generate_signature), NULL); sgn_check = gtk_button_new_with_label ("Check signature"); gtk_box_pack_start (GTK_BOX (hbox), sgn_check, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (sgn_check), "clicked", G_CALLBACK (open_signature), NULL); /* "Stamp" panel setup */ vbox = gtk_vbox_new (FALSE, 10); gtk_container_add (GTK_CONTAINER (frame_stamp), vbox); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Input file"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_in_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_in_path), "ulaz.txt"); gtk_widget_set_size_request (stmp_in_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_in_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_in_path, FALSE, FALSE, 0); stmp_in_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_in_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_in_select), "clicked", G_CALLBACK (file_select), stmp_in_path); stmp_in_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_in_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_in_view), "clicked", G_CALLBACK (view_file), stmp_in_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Output file"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_out_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_out_path), "izlaz.txt"); gtk_widget_set_size_request (stmp_out_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_out_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_out_path, FALSE, FALSE, 0); stmp_out_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_out_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_out_select), "clicked", G_CALLBACK (file_select), stmp_out_path); stmp_out_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_out_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_out_view), "clicked", G_CALLBACK (view_file), stmp_out_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Sign file"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_sgn_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_sgn_path), "pecat.txt"); gtk_widget_set_size_request (stmp_sgn_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_sgn_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_sgn_path, FALSE, FALSE, 0); stmp_sgn_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_sgn_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_sgn_select), "clicked", G_CALLBACK (file_select), stmp_sgn_path); stmp_sgn_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_sgn_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_sgn_view), "clicked", G_CALLBACK (view_file), stmp_sgn_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Envelope file"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_env_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_env_path), "omotnica.txt"); gtk_widget_set_size_request (stmp_env_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_env_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_env_path, FALSE, FALSE, 0); stmp_env_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_env_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_env_select), "clicked", G_CALLBACK (file_select), stmp_env_path); stmp_env_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_env_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_env_view), "clicked", G_CALLBACK (view_file), stmp_env_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Sender public key"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_snd_pub_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_snd_pub_key_path), "rsa_a_javni.txt"); gtk_widget_set_size_request (stmp_snd_pub_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_snd_pub_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_pub_key_path, FALSE, FALSE, 0); stmp_snd_pub_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_pub_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_snd_pub_key_select), "clicked", G_CALLBACK (file_select), stmp_snd_pub_key_path); stmp_snd_pub_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_pub_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_snd_pub_key_view), "clicked", G_CALLBACK (view_file), stmp_snd_pub_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Sender private key"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_snd_prv_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_snd_prv_key_path), "rsa_a_tajni.txt"); gtk_widget_set_size_request (stmp_snd_prv_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_snd_prv_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_prv_key_path, FALSE, FALSE, 0); stmp_snd_prv_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_prv_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_snd_prv_key_select), "clicked", G_CALLBACK (file_select), stmp_snd_prv_key_path); stmp_snd_prv_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_snd_prv_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_snd_prv_key_view), "clicked", G_CALLBACK (view_file), stmp_snd_prv_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Receiver public key"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_rcv_pub_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_rcv_pub_key_path), "rsa_b_javni.txt"); gtk_widget_set_size_request (stmp_rcv_pub_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_rcv_pub_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_pub_key_path, FALSE, FALSE, 0); stmp_rcv_pub_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_pub_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_rcv_pub_key_select), "clicked", G_CALLBACK (file_select), stmp_rcv_pub_key_path); stmp_rcv_pub_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_pub_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_rcv_pub_key_view), "clicked", G_CALLBACK (view_file), stmp_rcv_pub_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); label = gtk_label_new ("Receiver private key"); gtk_widget_set_size_request (label, 140, 20); gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); stmp_rcv_prv_key_path = gtk_entry_new(); gtk_entry_set_text (GTK_ENTRY (stmp_rcv_prv_key_path), "rsa_b_tajni.txt"); gtk_widget_set_size_request (stmp_rcv_prv_key_path, 300, 25); gtk_entry_set_max_length (GTK_ENTRY (stmp_rcv_prv_key_path), 100); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_prv_key_path, FALSE, FALSE, 0); stmp_rcv_prv_key_select = gtk_button_new_with_label ("Select"); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_prv_key_select, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_rcv_prv_key_select), "clicked", G_CALLBACK (file_select), stmp_rcv_prv_key_path); stmp_rcv_prv_key_view = gtk_button_new_with_label ("View"); gtk_box_pack_start (GTK_BOX (hbox), stmp_rcv_prv_key_view, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (stmp_rcv_prv_key_view), "clicked", G_CALLBACK (view_file), stmp_rcv_prv_key_path); hbox = gtk_hbox_new (FALSE, 10); gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); stmp_generate = gtk_button_new_with_label ("Generate stamp"); gtk_box_pack_start (GTK_BOX (hbox), stmp_generate, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (stmp_generate), "clicked", G_CALLBACK (generate_stamp), NULL); stmp_open = gtk_button_new_with_label ("Open stamp"); gtk_box_pack_start (GTK_BOX (hbox), stmp_open, TRUE, TRUE, 0); g_signal_connect (G_OBJECT (stmp_open), "clicked", G_CALLBACK (open_stamp), NULL); /* Show all widgets and run the engine */ gtk_widget_show_all (window); gtk_main(); return 0; } <file_sep>#!/usr/bin/python import sys log = [] identifier = "IPT INPUT packet died" try: f = file(sys.argv[1]) except IndexError: print "Usage: grep_log logname" sys.exit(1) except IOError: print "Could not open: " + sys.argv[1] sys.exit(1) for line in f: index = line.find(identifier) if index == -1: continue l = line.split() l[0] = " ".join(l[:2]) del l[1:9] print l log.append(l) <file_sep>// turing.cpp // Samostalni projekt iz Automata, formalnih jeuika i jezicnih procesora 1 // Prihvacanje jezika koji sadrzni nizove oblika a^ib^ic^i // (C) 2004 <NAME> <<EMAIL>> #include <iostream> #include <cstdlib> #include <cstring> using namespace std; const unsigned int broj_stanja = 7; const unsigned int broj_znakova_trake = 7; const unsigned int maksimalna_velicina_trake = 1000; struct TStanje { int stanje; char znak; char pomak; }; const TStanje KRAJ = {-1, 0, 0}; TStanje prijelazi[broj_stanja][broj_znakova_trake] = { {{1,'A','R'}, KRAJ, KRAJ, KRAJ, KRAJ, KRAJ, KRAJ}, {{1,'a','R'}, {2,'B','R'}, KRAJ, KRAJ, {1,'B','R'}, KRAJ, KRAJ}, {KRAJ, {2,'b','R'}, {3,'C','L'}, KRAJ, KRAJ, {2,'C','R'}, KRAJ}, {{3,'a','L'},{3,'b','L'}, {2,'c','L'}, {4,'A','R'}, {3,'B','L'}, {3,'C','L'},{3,' ','L'}}, {{1,'A','R'}, KRAJ, KRAJ, KRAJ, {5,'B','R'}, KRAJ, {5,' ','L'}}, {KRAJ, KRAJ, KRAJ, KRAJ, {5,'B','R'}, {5,'C','R'}, {6,' ','L'}}, {KRAJ, KRAJ, KRAJ, KRAJ, KRAJ, KRAJ, KRAJ} }; class Turing { private: char *traka; int stanje; int polozaj_glave; int prihvatljivo_stanje; public: Turing (char *ulazni_niz); ~Turing (); bool korak (); void simuliraj (); void ispisi_stanje (); }; Turing::Turing (char *ulazni_niz) { traka = strdup (strcat (ulazni_niz, " ")); stanje = 0; polozaj_glave = 0; prihvatljivo_stanje = 6; } Turing::~Turing () { delete traka; } void Turing::ispisi_stanje () { cout << "Stanje: " << stanje << '\t'; cout << "Traka: " << traka << endl; cout << " " << '\t' << " "; for (int i=0 ; i<polozaj_glave ; ++i) cout << " "; cout << "^" << endl; } bool Turing::korak () { int i; char ulazni_znak = traka[polozaj_glave]; switch (ulazni_znak) { case 'a': i = 0; break; case 'b': i = 1; break; case 'c': i = 2; break; case 'A': i = 3; break; case 'B': i = 4; break; case 'C': i = 5; break; case ' ': i = 6; break; default: abort(); } if (prijelazi[stanje][i].stanje == -1) return false; traka[polozaj_glave] = prijelazi[stanje][i].znak; if (prijelazi[stanje][i].pomak == 'R') ++polozaj_glave; else --polozaj_glave; stanje = prijelazi[stanje][i].stanje; return true; } void Turing::simuliraj () { ispisi_stanje (); while (korak ()) ispisi_stanje (); if (stanje == prihvatljivo_stanje) cout << "Niz se prihvaca" << endl; else cout << "Niz se ne prihvaca" << endl; } int main () { char s[maksimalna_velicina_trake]; cout << "Unesi ulazni niz: "; cin >> s; for (unsigned int i=0 ; i<strlen(s) ; ++i) if (s[i] != 'a' && s[i] != 'b' && s[i] != 'c') { cerr << "Nije unesen ispravan niz" << endl; exit (EXIT_FAILURE); } Turing *ts = new Turing (s); ts->simuliraj(); delete ts; return EXIT_SUCCESS; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/poll.h> #define POLL_TIMEOUT 5 int main() { struct pollfd fds[2]; /* check stdin for input */ fds[0].fd = STDIN_FILENO; fds[0].events = POLLIN; /* check stdout for writting */ fds[1].fd = STDOUT_FILENO; fds[1].events = POLLOUT; if (poll(fds, 2, POLL_TIMEOUT * 1000) == -1) { perror("poll"); return EXIT_FAILURE; } if (fds[0].revents & POLLIN) printf("STDIN is ready for reading\n"); if (fds[1].revents & POLLOUT) printf("STDOUT is ready for writing\n"); return EXIT_SUCCESS; } <file_sep>/* simulator DKA za 1. labos iz afjjp1 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #define MAXLEN 1000 int main () { int i, j, m, n, *tablica, pocetno, stanje; FILE *in; char *buffer, *s; if ((in = fopen ("tablica.dat", "r")) == NULL) { perror ("tablica.dat"); exit (EXIT_FAILURE); } fscanf (in, "%d\n", &n); fscanf (in, "%d\n", &m); assert (s = (char *) malloc (m + 1)); fgets (s, m + 1, in); pocetno = stanje = n / 2 - 1; assert (tablica = (int *) malloc (sizeof (int) * (m+1) * n)); for (i=0 ; i<n ; ++i) for (j=0 ; j<m+1 ; ++j) fscanf (in, "%d ", &tablica[i * (m+1) + j]); fclose (in); printf ("Unesi niz znakova: "); assert (buffer = (char *) malloc (MAXLEN)); fgets (buffer, MAXLEN, stdin); printf ("\n%d", stanje); for (j=0 ; j<strlen(buffer)-1 ; ++j) { if (strchr (s, buffer[j])) for (i=0 ; i<m+1 ; ++i) if (s[i] == buffer[j]) { stanje = tablica[(m + 1) * stanje + i]; break; } printf ("--(%c)-->%d", buffer[j], stanje); } if (stanje == pocetno) printf ("\nNiz se prihvaca\n"); else printf ("\nNiz se ne prihvaca\n"); free (s); free (tablica); free (buffer); return EXIT_SUCCESS; } <file_sep>#!/usr/bin/python import urllib import htmllib import formatter class HTMLTableParser(htmllib.HTMLParser): def __init__(self): self.data = [] self.td_data = [] self.in_table = True self.in_center = True htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) def start_table(self, attributes): in_table = True def end_table(self): in_table = False def start_tr(self, attributes): self.row = [] def end_tr(self): self.data.append(self.row) def start_td(self, attributes): self.td_data = [] def end_td(self): self.row.append(" ".join(self.td_data)) def start_center(self, attributes): self.in_center = True def end_center(self): self.in_center = False def handle_data(self, data): if self.in_table: self.td_data.append(data.rstrip().lstrip()) if self.in_center and 'sati' in data: print data + '\n' def extract_data(url): html = urllib.urlopen(url).read() parser = HTMLTableParser() parser.feed(html) parser.close() return parser.data def formatted_output(data): print 'Grad Vjetar Temp Vlaga', print ' Tlak/+- u 1h Vrijeme' print '-' * 75 for line in data[1:]: print line[0][2:].ljust(21), print line[1].ljust(3) + line[2].ljust(5), print line[3].ljust(5) + line[4].ljust(5), print line[5].ljust(8) + line[6].ljust(6), print line[7] if __name__ == '__main__': data = extract_data('http://vrijeme.hr/croa_n.html')[:-1] formatted_output(data) <file_sep>#!/usr/bin/python url = raw_input('URL: ') coded = ['%' + hex(ord(ch)).split('x')[1] for ch in url] print "".join(coded) <file_sep>// Matrica // (C) 2006 <NAME> <<EMAIL>> #include <iostream> #include <fstream> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <algorithm> using namespace std; // glavna Matrix klasa class Matrix { protected: int rows, columns; double *elements; void clear_matrix(); public: Matrix() : rows(0), columns(0), elements(NULL) {}; Matrix(unsigned int, unsigned int); Matrix(const Matrix&); Matrix(string) throw(string); ~Matrix(); Matrix transposed(); Matrix lu_decomposition() throw(string); Matrix lup_decomposition(Matrix& b) throw(string); Matrix& forward_substitution(Matrix&) throw(string); Matrix& backward_substitution(Matrix&) throw(string); friend ostream& operator<<(ostream&, const Matrix&); friend Matrix operator*(const Matrix&, const double); friend Matrix operator*(const double, const Matrix&); friend Matrix operator*(const Matrix&, const Matrix&) throw(string); friend Matrix operator+(const Matrix&, const Matrix&) throw(string); friend Matrix operator-(const Matrix&, const Matrix&) throw(string); friend Matrix& operator+=(Matrix&, const Matrix&) throw(string); friend Matrix& operator-=(Matrix&, const Matrix&) throw(string); friend Matrix& operator*=(Matrix&, const double); double& operator()(int i, int j) const throw(string) { if (i >= rows || j >= columns || i < 0 || j < 0) { throw string("Matrix index out of bound"); exit(EXIT_FAILURE); } return elements[i * columns + j]; } Matrix& operator=(const Matrix& m) { if (&m != this) { rows = m.rows; columns = m.columns; elements = new double[rows * columns]; memcpy(elements, m.elements, rows * columns * sizeof(double)); } return *this; } }; // klasa za rjesavanje linearnih sustava class LinearSystem { Matrix A, b; public: LinearSystem(Matrix& A, Matrix& b) : A(A), b(b) {}; Matrix lu_solve(); Matrix lup_solve(); }; // kreira nul matrixu dimenzija MxN Matrix::Matrix(unsigned int m, unsigned int n) { rows = m; columns = n; elements = new double[rows * columns]; clear_matrix(); } // copy konstruktor Matrix::Matrix(const Matrix& m) { rows = m.rows; columns = m.columns; elements = new double[rows * columns]; memcpy(elements, m.elements, rows * columns * sizeof(double)); } // kreira i inicijalizira matricu brojevima iz datoteke Matrix::Matrix(string filename) throw(string) { rows = columns = 0; elements = NULL; ifstream ifs(filename.c_str()); if (!ifs) { throw string("No such file: " + filename); exit(EXIT_FAILURE); } string s; while (getline(ifs, s)) ++rows; ifs.close(); ifs.open(filename.c_str()); double num; vector<double> v; while(ifs) { ifs >> num; v.push_back(num); } columns = (v.size() - 1) / rows; elements = new double[rows * columns]; for (unsigned int i = 0 ; i < v.size() - 1 ; ++i) elements[i] = v[i]; } // destruktor Matrix::~Matrix() { if (elements) delete[] elements; } // postavlja sve elemente matrice na nulu void Matrix::clear_matrix() { for (int i = 0 ; i < rows ; ++i) for (int j = 0 ; j < columns ; ++j) (*this)(i, j) = 0; } // << operator ostream& operator<<(ostream& os, const Matrix& m) { for (int i = 0 ; i < m.rows ; ++i) { for (int j = 0 ; j < m.columns ; ++j) os << m.elements[i * m.columns + j] << " "; os << endl; } return os; } // += operator Matrix& operator+=(Matrix& left, const Matrix& right) throw(string) { if (left.rows != right.rows || left.columns != right.columns) { throw string("Matrices of incompatible type"); exit(EXIT_FAILURE); } Matrix result(left.rows, left.columns); for (int i = 0 ; i < left.rows ; ++i) for (int j = 0 ; j < left.columns ; ++j) left(i, j) += right(i, j); return left; } // -= operator Matrix& operator-=(Matrix& left, const Matrix& right) throw(string) { if (left.rows != right.rows || left.columns != right.columns) { throw string("Matrices of incompatible type"); exit(EXIT_FAILURE); } Matrix result(left.rows, left.columns); for (int i = 0 ; i < left.rows ; ++i) for (int j = 0 ; j < left.columns ; ++j) left(i, j) -= right(i, j); return left; } // *= operator Matrix& operator*=(Matrix& left, const double right) { Matrix result(left.rows, left.columns); for (int i = 0 ; i < left.rows ; ++i) for (int j = 0 ; j < left.columns ; ++j) left(i, j) *= right; return left; } // zbrajanje Matrix operator+(const Matrix& left, const Matrix& right) throw(string) { if (left.rows != right.rows || left.columns != right.columns) { throw string("Matrices of incompatible type"); exit(EXIT_FAILURE); } Matrix result(left.rows, left.columns); for (int i = 0 ; i < left.rows ; ++i) for (int j = 0 ; j < left.columns ; ++j) result(i, j) = left(i, j) + right(i, j); return result; } // oduzimanje Matrix operator-(const Matrix& left, const Matrix& right) throw(string) { if (left.rows != right.rows || left.columns != right.columns) { throw string("Matrices of incompatible type"); exit(EXIT_FAILURE); } Matrix result(left.rows, left.columns); for (int i = 0 ; i < left.rows ; ++i) for (int j = 0 ; j < left.columns ; ++j) result(i, j) = left(i, j) - right(i, j); return result; } // mnozenje matrice skalarom s desna Matrix operator*(const Matrix& matrix, const double scalar) { Matrix result(matrix); for (int i = 0 ; i < result.rows ; ++i) for (int j = 0 ; j < result.columns ; ++j) result(i, j) *= scalar; return result; } // mnozenje matrice skalarom s lijeva Matrix operator*(const double scalar, const Matrix& matrix) { Matrix result(matrix); for (int i = 0 ; i < result.rows ; ++i) for (int j = 0 ; j < result.columns ; ++j) result(i, j) *= scalar; return result; } // transponiranje Matrix Matrix::transposed() { Matrix result(columns, rows); for (int i = 0 ; i < rows ; ++i) for (int j = 0 ; j < columns ; ++j) result(j, i) = (*this)(i, j); return result; } // unaprijedna supstitucija Matrix& Matrix::forward_substitution(Matrix& b) throw(string) { if (rows != columns) { throw string("Operation can be done only on quadratic matrices"); exit(EXIT_FAILURE); } if (b.columns != 1) { throw string("Substitution can be done only with vectors"); exit(EXIT_FAILURE); } if (b.rows != rows) { throw string("Matrix and vector are not compatible type for substitution"); exit(EXIT_FAILURE); } for (int i = 0 ; i < b.rows - 1 ; ++i) for (int j = i + 1 ; j < b.rows ; ++j) b(j, 0) -= (*this)(j, i) * b(i, 0); return b; } // unazadnja supstitucija Matrix& Matrix::backward_substitution(Matrix& b) throw(string) { if (rows != columns) { throw string("Operation can be done only on quadratic matrices"); exit(EXIT_FAILURE); } if (b.columns != 1) { throw string("Substitution can be done only with vectors"); exit(EXIT_FAILURE); } if (b.rows != rows) { throw string("Matrix and vector are not compatible type for substitution"); exit(EXIT_FAILURE); } for (int i = b.rows - 1 ; i >= 0 ; --i) { b(i, 0) /= (*this)(i, i); for (int j = 0 ; j < i ; ++j) b(j, 0) -= (*this)(j, i) * b(i, 0); } return b; } // mnozenje matrice s matricom Matrix operator*(const Matrix& left, const Matrix& right) throw(string) { if (left.columns != right.rows) { throw string("Matrices of incompatible type"); exit(EXIT_FAILURE); } Matrix result(left.rows, right.columns); for (int i = 0 ; i < result.rows ; ++i) for (int j = 0 ; j < result.columns ; ++j) for (int k = 0 ; k < left.columns ; ++k) result(i, j) += left(i, k) * right(k, j); return result; } // lu dekompozicija Matrix Matrix::lu_decomposition() throw(string) { if (rows != columns) { throw string("LU decomposition can be done only on quadratic matrices"); exit(EXIT_FAILURE); } Matrix result(*this); for (int i = 0 ; i < rows - 1 ; ++i) for (int j = i + 1 ; j < rows ; ++j) { result(j, i) /= result(i, i); for (int k = i + 1 ; k < rows ; ++k) result(j, k) -= result(j, i) * result(i, k); } return result; } // lup dekompozicija Matrix Matrix::lup_decomposition(Matrix& b) throw(string) { if (rows != columns) { throw string("LU decomposition can be done only on quadratic matrices"); exit(EXIT_FAILURE); } Matrix result(*this); int p[rows]; for (int i = 0 ; i < rows ; ++i) p[i] = i; for (int i = 0 ; i < rows - 1; ++i) { int pivot = i; for (int j = i + 1 ; j < rows ; ++j) if (fabs(result(p[j], i)) > fabs(result(p[pivot], i))) pivot = j; swap(p[i], p[pivot]); swap(b(i, 0), b(pivot, 0)); for (int j = i + 1 ; j < rows ; ++j) { result(p[j], i) /= result(p[i], i); for (int k = i + 1 ; k < rows ; ++k) result(p[j], k) -= result(p[j], i) * result(p[i], k); } } return result; } // rjesavanje sustava LU dekompozicijom Matrix LinearSystem::lu_solve() { Matrix lu, old_b(b); lu = A.lu_decomposition(); lu.forward_substitution(b); lu = lu.backward_substitution(b); b = old_b; return lu; } // rjesavanje sustava LUP dekompozicijom Matrix LinearSystem::lup_solve() { Matrix lup, old_b(b); lup = A.lu_decomposition(); lup.forward_substitution(b); lup = lup.backward_substitution(b); b = old_b; return lup; } // main int main() { try { Matrix A("m.txt"), b("v.txt"); LinearSystem ls(A, b); cout << "Rjesenje LU dekompozicijom: " << endl; cout << ls.lup_solve(); } catch (string s) { cerr << s << endl; exit(EXIT_FAILURE); } return EXIT_SUCCESS; } <file_sep>/* thread_cleanup_handler.c - example of using cleanup handler for thread * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdlib.h> #include <pthread.h> void *allocate_buffer(size_t size) { return malloc(size); } void deallocate_buffer(void *buffer) { free(buffer); } void *thread_function(void *unused) { void *temp_buffer = allocate_buffer(1024); /* register a cleanup handler and make sure buffer gets deallocated */ pthread_cleanup_push(deallocate_buffer, temp_buffer); /* some work */ /* deregister cleanup hadnler, as we pass non zero argument it will invoke the handler itself before deregistering */ pthread_cleanup_pop(1); } int main() { pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); return EXIT_SUCCESS; } <file_sep>#!/usr/bin/python # Simple python data compression programm # (C) 2005 <NAME> <<EMAIL>> from sys import argv, exit from os import path from zlib import compress if (len (argv) <> 2): print "Syntax compress.py [filename]" exit (1) if (path.isfile (argv[1])): new_filename = argv[1] + '.pycp' else: print "No such file: " + argv[1] exit (1) try: input = open (argv[1], "rb") except: print "Input file error" exit (1) data = input.read() compressed_data = compress (data) input.close() try: output = open (new_filename, "wb") except: print "Output file error" exit (1) output.write (compressed_data) output.close() <file_sep>class Proxy: def __init__(self, target): self.target = target def __getattr__(self, attr): return getattr(self.target, attr) class Foo: def first(self): print 'First method' def second(self): print 'Second method' class FooProxy(Proxy): def second(self): pass print 'Base class:' f = Foo() f.first() f.second() print '\nProxy class:' fp = FooProxy(f) fp.first() fp.second() <file_sep>/* fifo.c - FIFO (named pipe) creation * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> int main() { int fd; fd = mkfifo("fifo", S_IWUSR | S_IRUSR); return 0; } <file_sep>/* mutex.c - thread synchronization with mutex * * (C) 2003 <NAME> <<EMAIL>> */ #include <malloc.h> #include <pthread.h> struct node { int key; struct node *next; } *head; /* alternative is to call pthread_mutex_init() */ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_function(void *unused) { struct node *next_node; while (1) { /* lock the mutex */ pthread_mutex_lock(&mutex); if (head == NULL) { next_node = NULL; } else { next_node = head; head = head->next; } /* Unlock the mutex */ pthread_mutex_unlock(&mutex); if (next_node == NULL) break; free (next_node); } return NULL; } int main() { pthread_t thread; /* insert queue initialization here */ pthread_create(&thread, NULL, thread_function, NULL); return 0; } <file_sep>from html.parser import HTMLParser from http.client import HTTPConnection artist, song = "", "" class AntenaZgHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag == "td": if attrs[0] == ('class', 'song'): song = attrs[1][1] print(song) if attrs[0] == ('class', 'artist'): artist = attrs[1][1] print(artist, end = " - ") def handle_endtag(self, tag): pass for page in range(1, 61): conn = HTTPConnection("300.antenazagreb.hr") conn.request("GET", "/?page={}".format(page)) response = conn.getresponse() parser = AntenaZgHTMLParser() data = response.read() parser.feed(str(data)) conn.close()<file_sep>#!/bin/bash rename "s/\ /_/g" * for i in `ls *.wav` do lame -b 48 $i $i.mp3 rm $i done rename "s/\.wav//g" * rename "s/_/\ /g" * <file_sep>/* red_poljem.c - implementacija reda pomocu ciklickog polja * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #define QUEUE_SIZE 100 /* Stavi podatak u red */ int put (int val, int *queue, int *in, int out) { /* Da li je red pun */ if ((*in + 1) % QUEUE_SIZE == out) return 0; (*in)++; *in %= QUEUE_SIZE; queue[*in] = val; return 1; } /* Uzmi podatak iz reda */ int get (int *val, int *queue, int in, int *out) { /* Da li je red prazan */ if (in == *out) return 0; (*out)++; *out %= QUEUE_SIZE; *val = queue[*out]; return 1; } int main () { int in, out, x; int queue[QUEUE_SIZE]; in = out = 0; /* Primjer koristenja */ put (1, queue, &in, out); put (2, queue, &in, out); get (&x, queue, in, &out); printf ("%d\n", x); put (3, queue, &in, out); get (&x, queue, in, &out); printf ("%d\n", x); get (&x, queue, in, &out); printf ("%d\n", x); return 0; } <file_sep>/* red_listom.c - implementacija reda pomocu jednostruko povezane liste * * (C) 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> struct node_t { int key; struct node_t *next; }; typedef struct node_t node; /* Stavi podatak u red */ void put (int val, node **head, node **tail) { node *new_node; new_node = (node *) malloc (sizeof (node)); new_node->key = val; new_node->next = NULL; if (*head == NULL) { *head = new_node; } else { (*tail)->next = new_node; } *tail = new_node; } /* Uzmi podatak iz reda */ int get (node **head, node **tail) { int ret_val; node *tmp; if (*head == NULL) return -1; tmp = *head; ret_val = tmp->key; *head = (*head)->next; free (tmp); return ret_val; } int main () { node *head, *tail; head = tail = NULL; /* Primjer koristenja */ put (1, &head, &tail); put (2, &head, &tail); printf ("%d\n", get (&head, &tail)); put (3, &head, &tail); printf ("%d\n", get (&head, &tail)); printf ("%d\n", get (&head, &tail)); return 0; } <file_sep>/* port_flooder.c - floods a given port on host * (C) 2005 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> char *hostname = NULL; //nx6800 int port_num = 0; int verbose = 1; void *thread (void *param) { int socket_fd; struct sockaddr_in name; struct hostent *hostinfo; socket_fd = socket (AF_INET, SOCK_STREAM, 0); name.sin_family = AF_INET; if ((hostinfo = gethostbyname (hostname)) == 0) { fprintf (stderr, "Ne mogu resolvati hostname\n"); exit (EXIT_FAILURE); } name.sin_addr = *((struct in_addr *) hostinfo->h_addr); name.sin_port = htons (port_num); if (verbose) printf ("Pokrenuta nit: %d\n", *((int *) param)); if (connect (socket_fd, &name, sizeof (struct sockaddr_in)) == -1) perror ("connect"); } int main (int argc, char **argv) { int i, num_threads, *thread_idn; pthread_t *thread_id; if (argc != 4) { fprintf (stderr, "Sintaksa: flood broj_poruka hostname port\n"); exit (EXIT_FAILURE); } num_threads = atoi (argv[1]); hostname = strdup (argv[2]); port_num = atoi (argv[3]); thread_id = malloc (sizeof (pthread_t) * num_threads); thread_idn = malloc (sizeof (int) * num_threads); for (i=0 ; i<num_threads ; ++i) { thread_idn[i] = i + 1; pthread_create (&thread_id[i], NULL, &thread, (void *) &thread_idn[i]); } sleep (5); return 0; } <file_sep>#ifndef _UTILS_H #define _UTILS_H #include <ctype.h> #define ERR -1 #define DECODE64(c) (isascii (c) ? base64val[c] : ERR) static const char base64val[] = { ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, 62, ERR, ERR, ERR, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ERR, ERR, ERR, ERR, ERR, ERR, ERR, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ERR, ERR, ERR, ERR, ERR, ERR, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, ERR, ERR, ERR, ERR, ERR }; void base64_encode (const unsigned char *src, unsigned char *dest, int len); int base64_decode (const unsigned char *src, unsigned char *dest); #endif /* _UTILS_H */ <file_sep>#!/usr/bin/python # simple hexdump program # # (C) 2004 <NAME> <<EMAIL>> import sys, string def dump (stream): eol = address = 0 str = '' for ch in stream.read(): if eol % 16 == 0: address = address + 8 print ' %(str)s\n%(address)08X ' % vars(), str = '' out = ord (ch) if ch in string.printable and ch not in string.whitespace: str = str + ch else: if ch == ' ': str = str + ' ' else: str = str + '.' print '%(out)02X' % vars(), eol = eol + 1 for arg in sys.argv[1:]: try: fd = open(arg, 'r') except IOError: print 'Cannot open:', arg else: dump (fd) fd.close () print "" <file_sep>/* two_pipes.c - duplex communication using pipes * * (C) 2005 <NAME> <<EMAIL>> */ #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #define BUFFER_LENGTH 10 int main(int argc, char **argv) { pid_t pid; char buffer[BUFFER_LENGTH]; int operand1, operand2, operacija, num, tmp, fds_in[2], fds_out[2]; int tocno, odgovor; if (argc != 2) { fprintf(stderr, "Sintaksa: a.out broj_upita\n"); exit(EXIT_SUCCESS); } if (sscanf (argv[1], "%d", &num) != 1) { fprintf(stderr, "Sintaksa: a.out broj_upita\n"); exit(EXIT_FAILURE); } while (num--) { srand((unsigned) time (NULL)); if (pipe(fds_in) == -1 || pipe (fds_out) == -1) { perror("pipe"); exit(EXIT_FAILURE); } if ((pid = fork ()) == -1 ) { perror("fork"); exit(EXIT_FAILURE); } if (pid == 0) { close(fds_in[1]); close(fds_out[0]); dup2(fds_in[0], STDIN_FILENO); dup2(fds_out[1], STDOUT_FILENO); if (execlp("bc", "bc", NULL) == -1) { perror("bc"); exit(EXIT_FAILURE); } close (fds_out[1]); } else { close(fds_in[0]); close(fds_out[1]); operand1 = rand() % 99 + 1; operand2 = rand() % 99 + 1; operacija = rand() % 4; switch (operacija) { case 0: sprintf(buffer, "%d+%d\n", operand1, operand2); break; case 1: sprintf(buffer, "%d-%d\n", operand1, operand2); break; case 2: sprintf(buffer, "%d*%d\n", operand1, operand2); break; case 3: sprintf(buffer, "%d/%d\n", operand1, operand2); break; } write(STDOUT_FILENO, buffer, strlen (buffer) - 1); printf(" = "); fflush(stdout); scanf("%d", &odgovor); write(fds_in[1], buffer, strlen (buffer)); close(fds_in[1]); wait(NULL); tmp = read(fds_out[0], buffer, BUFFER_LENGTH); buffer[tmp] = '\0'; sscanf(buffer, "%d", &tocno); if (tocno == odgovor) printf ("TOCNO\n\n"); else printf ("NETOCNO [Tocan odgovor = %d]\n\n", tocno); } } return EXIT_SUCCESS; } <file_sep>/* mmap_cat.c - emulate basic cat(1) functionality with mmaped files * * (C) 2010 <NAME> <<EMAIL>> */ #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char **argv) { char **filename; if (argc == 1) { printf("Usage mmap_cat [file]...\n"); return EXIT_SUCCESS; } for (filename = argv, filename++ ; *filename != NULL ; filename++) { int fd, length; char *buffer; struct stat fs; if ((fd = open(*filename, O_RDONLY)) == -1) { perror(*filename); continue; } fstat(fd, &fs); length = fs.st_size; if ((buffer = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) { perror("mmap"); continue; } write(STDIN_FILENO, buffer, length); close(fd); } return EXIT_SUCCESS; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) #define MAX_POINTS 100 struct point { int x, y; } points[MAX_POINTS]; struct coef { int a, b, c; } coefs[MAX_POINTS]; int ymin, ymax; int fullscreen = 0, current_point = 0, num_points; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } void resize_scene(int width, int height) { window_width = width; window_height = height; current_point = 0; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, window_width, 0, window_height); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glColor3f(0, 1, 0); } void color_poly() { int i, x, y, L, D; int xmin, xmax, ymin, ymax; xmin = xmax = points[0].x; ymin = ymax = points[0].y; for (i = 0 ; i < num_points ; ++i) { if (points[i].x < xmin) xmin = points[i].x; if (points[i].x > xmax) xmax = points[i].x; if (points[i].y < ymin) ymin = points[i].y; if (points[i].y > ymax) ymax = points[i].y; } for (y = ymin ; y < ymax ; y++) { L = xmin; D = xmax; for (i = 0 ; i < num_points ; ++i) { if (coefs[i].a != 0) { x = (-coefs[i].b * y - coefs[i].c) / coefs[i].a; } if (points[i].y < points[i + 1].y && x > L) L = x; if (points[i].y > points[i + 1].y && x < D) D = x; } if (L < D) { glBegin(GL_LINES); glVertex2i(L, y); glVertex2i(D, y); glEnd(); } } } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'c': color_poly(); break; case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'q': exit(EXIT_SUCCESS); } glFlush(); } void draw_poly() { int i; glBegin(GL_LINES); for (i = 0 ; i < num_points ; ++i) { /* crtanje linija */ glVertex2i(points[i].x, points[i].y); glVertex2i(points[i + 1].x, points[i + 1].y); /* racunanje koeficijenata smjera bridova */ coefs[i].a = points[i].y - points[i + 1].y; coefs[i].b = -points[i].x + points[i + 1].x; coefs[i].c = points[i].x * points[i + 1].y - points[i + 1].x * points[i].y; } glEnd(); glFlush(); } int is_in_poly(int x, int y) { int i; for (i = 0 ; i < num_points ; ++i) if (x * coefs[i].a + y * coefs[i].b + coefs[i].c > 0) return 0; return 1; } void mouse_handler(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && current_point < num_points) { points[current_point].x = x; points[current_point].y = window_height - y; if (current_point == 0) points[num_points] = points[0]; glBegin(GL_POINTS); glVertex2i(points[current_point].x, points[current_point].y); glEnd(); glFlush(); ++current_point; printf("Kordinate tocke %d: (%d, %d)\n", current_point, x, y); } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { resize_scene(window_width, window_height); } if (current_point == num_points && state == GLUT_DOWN) { draw_poly(); if (is_in_poly(x, window_height - y)) printf("Točka (%d, %d) je unutar poligona\n", x, y); else printf("Točka (%d, %d) nije unutar poligona\n", x, y); return; } } int main(int argc, char **argv) { printf("Unesi broj točaka: "); scanf("%d", &num_points); glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMouseFunc(mouse_handler); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>/* bresenham.c - Crtanja linija u OpenGL-u pomocu ugradjene funkcije i Bresenhamovog postupka * (C) 2006 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <math.h> #ifndef __linux__ #include <windows.h> #endif #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #define SCREEN_WIDTH 1024 #define SCREEN_HEIGHT 768 #define WINDOW_WIDTH 640 #define WINDOW_HEIGHT 480 #define WINDOW_POS_X ((SCREEN_WIDTH - WINDOW_WIDTH) / 2) #define WINDOW_POS_Y ((SCREEN_HEIGHT - WINDOW_HEIGHT) / 2) #define DIRECTION_RIGHT 1 #define DIRECTION_LEFT -1 #define DIRECTION_UP 1 #define DIRECTION_DOWN -1 struct point { double x, y; } points[2]; int fullscreen = 0, p = 0; int window_width = WINDOW_WIDTH, window_height = WINDOW_HEIGHT; void init_gl() { glShadeModel(GL_SMOOTH); glClearColor(0, 0, 0, 0.5); glClearDepth(1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void draw_line(int ax, int ay, int bx, int by) { float d; int i, x, y, dx, dy, direction_x, direction_y; glBegin(GL_LINES); glVertex2i(ax, ay + 5); glVertex2i(bx, by + 5); glEnd(); x = ax; y = ay; dx = bx - ax; dy = by - ay; /* odredi smjer prirasta pravca */ if (dx > 0 && dy < 0) { direction_x = DIRECTION_RIGHT; direction_y = DIRECTION_DOWN; } else if (dx < 0 && dy < 0) { direction_x = DIRECTION_LEFT; direction_y = DIRECTION_DOWN; } else if (dx < 0 && dy > 0) { direction_x = DIRECTION_LEFT; direction_y = DIRECTION_UP; } else { direction_x = DIRECTION_UP; direction_y = DIRECTION_RIGHT; } /* apsolutni iznos prirasta */ dx = abs(dx); dy = abs(dy); glBegin(GL_POINTS); if (abs(dx) > abs(dy)) { /* veci je prirast po x varijabli */ d = (double) dy / dx - 0.5; for (i = 0 ; i <= dx ; ++i) { glVertex2i(x, y); if (d > 0) { y += direction_y; d -= 1; } x += direction_x; d += (double) dy / dx; } } else { /* veci je prirast po y varijabli */ d = (double) dx / dy - 0.5; for (i = 0 ; i <= dy ; ++i) { glVertex2i(x, y); if (d > 0) { x += direction_x; d -= 1; } y += direction_y; d += (double) dx / dy; } } glEnd(); } void draw_scene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); } void resize_scene(int width, int height) { window_width = width; window_height = height; p = 0; glViewport(0, 0, window_width, window_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, window_width, 0, window_height); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glColor3f(0, 1, 0); } void keyboard_handler(unsigned char key, int x, int y) { switch (key) { case 'r': glColor3f(1, 0, 0); break; case 'g': glColor3f(0, 1, 0); break; case 'b': glColor3f(0, 0, 1); break; case 'f': if (!fullscreen) glutFullScreen(); else glutReshapeWindow(window_width, window_height); fullscreen ^= 1; break; case 'q': exit(EXIT_SUCCESS); } glRecti(window_width - 15, window_height - 15, window_width, window_height); glFlush(); } void mouse_handler(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { points[p].x = x; points[p].y = window_height - y; p ^= 1; if(!p) draw_line(points[0].x, points[0].y, points[1].x, points[1].y); else glVertex2i(x, window_height - y); printf("Kordinate tocke %d: (%d, %d)\n", 2 - p, x, y); glFlush(); } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { resize_scene(window_width, window_height); } } int main(int argc, char **argv) { glutInit(&argc, argv); init_gl(); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(window_width, window_height); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow(argv[0]); glutDisplayFunc(draw_scene); glutReshapeFunc(resize_scene); glutKeyboardFunc(keyboard_handler); glutMouseFunc(mouse_handler); printf("Crtanje linija Bresenhamerovim postupkom\n"); printf("Tipke r, g, b mijenjaju boju, q izlazi iz programa\n"); glutMainLoop(); return EXIT_SUCCESS; } <file_sep>/* condvar.c - thread synchronization with conditional variables * * (C 2003 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condvar = PTHREAD_COND_INITIALIZER; int producer_done = 0; void *consumer_thread() { pthread_mutex_lock(&mutex); while(!producer_done) pthread_cond_wait(&condvar, &mutex); printf("Consumer lock\n"); pthread_mutex_unlock(&mutex); } void *producer_thread() { sleep(10); pthread_mutex_lock(&mutex); printf("Producer lock\n"); producer_done = 1; pthread_cond_signal(&condvar); pthread_mutex_unlock(&mutex); } int main() { pthread_t consumer, producer; pthread_create(&consumer, NULL, &consumer_thread, NULL); pthread_create(&producer, NULL, &producer_thread, NULL); pthread_join(consumer, NULL); pthread_join(producer, NULL); return EXIT_SUCCESS; } <file_sep>/* faktorijele.c - rekurzivno racunanje faktorijela * * (C) 2003 <NAME> <<EMAIL>> * * n! = n * (n-1)! */ #include <stdio.h> int fact (int n) { if (n == 0) return 1; else return n * fact (n-1); } int main () { int x; do { printf ("Unesi prirodni broj: "); scanf ("%d", &x); } while (x<0); printf ("%d! = %d\n", x, fact (x)); return 0; } <file_sep>/* lamport.c - iskljucivanje niti Lamportovim algoritmom * * Labos iz Operacijskih Sustava * * (C) 2005 <NAME> <<EMAIL>> * * Prevesti sa: gcc -lpthread -D_REENTRANT lamport.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> int number_of_threads; int *search, *num; int get_max_value (int *array) { int i, maxval; for (i=0, maxval=0 ; i<number_of_threads ; ++i) if (array[i] > array[maxval]) maxval = i; return array[maxval]; } int cmp4 (int a1, int b1, int a2, int b2) { if (a1 == a2) { if (b1 > b2) return 1; else if (b1 < b2) return -1; else return 0; } if (a1 > a2) return 1; else return -1; } void lock_state (int i) { int j; search[i] = 1; num[i] = get_max_value (num) + 1; search[i] = 0; for (j=0 ; j<number_of_threads ; ++j) { while (search[j]); while (num[j] && (cmp4 (num[j], j, num[i], i) == -1)); } } void unlock_state (int i) { num[i] = 0; } void *thread_function (void *i) { int k, m; for (k=1 ; k<=5 ; ++k) { lock_state (*((int *) i)); for (m=1 ; m<=5 ; ++m) { printf ("%d ", 1 + * ((int *) i)); printf ("%d ", k); printf ("%d\n", m); sleep (1); } unlock_state (*((int *) i)); } return NULL; } int main (int argc, char **argv) { int i; int *params; pthread_t *threads; if (argc != 2) { fprintf (stderr, "Koristenje: lamport broj_niti\n"); exit (EXIT_FAILURE); } if ((sscanf (argv[1], "%d", &number_of_threads)) != 1) { fprintf (stderr, "Koristenje: lamport broj_niti\n"); exit (EXIT_FAILURE); } search = calloc (number_of_threads, sizeof (int)); num = calloc (number_of_threads, sizeof (int)); threads = malloc (number_of_threads * sizeof (pthread_t)); params = malloc (number_of_threads * sizeof (int)); if (!search || !num || !threads || !params) { fprintf (stderr, "Alokacija memorije nije uspjela\n"); exit (EXIT_FAILURE); } for (i = 0 ; i < number_of_threads ; ++i) { params[i] = i; if (pthread_create (&threads[i], NULL, &thread_function, &params[i])) { perror ("pthread_create"); exit (EXIT_FAILURE); } } for (i = 0 ; i < number_of_threads ; ++i) if (pthread_join (threads[i], NULL)) { perror ("pthread_join"); exit (EXIT_FAILURE); } free (search); free (num); free (threads); free (params); return EXIT_SUCCESS; } <file_sep>/* rwlock - example on using ReadWrite locks * * (C) 2009 <NAME> <<EMAIL>> */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> int shared_data = 0; pthread_rwlock_t lock; void *locker_thread() { printf("Writer Thread: Entering locker thread\n"); sleep(1); pthread_rwlock_rdlock(&lock); printf("Writer Thread: Placed read lock\n"); sleep(5); pthread_rwlock_unlock(&lock); printf("Writer Thread: Released read lock\n"); pthread_rwlock_wrlock(&lock); printf("Writer Thread: Placed write lock\n"); sleep(5); pthread_rwlock_unlock(&lock); printf("Writer Thread: Released write lock\n"); return NULL; } void *reader_thread() { int i; for (i = 0 ; i < 10 ; ++i) { pthread_rwlock_rdlock(&lock); printf("Reader Thread: Placed read lock\n"); pthread_rwlock_unlock(&lock); sleep(1); } return NULL; } int main() { pthread_t threads[2]; pthread_rwlock_init(&lock, NULL); pthread_create(&threads[0], NULL, locker_thread, NULL); pthread_create(&threads[1], NULL, reader_thread, NULL); pthread_join(threads[0], NULL); pthread_join(threads[1], NULL); pthread_rwlock_destroy(&lock); return EXIT_SUCCESS; }
dc86d5d3cd117665d752574b78d77da91d13e3c8
[ "Java", "Python", "C", "C++", "Shell" ]
138
C
ipozgaj/playground_sources
6709519d6006256d5a491b107e07beaf5fdc0184
1a27e0ba03ca623c2e414de1e6364c866297228b
refs/heads/master
<file_sep>tensorflow>=1.13,<2.0 sphinx==1.8.* sphinx_rtd_theme==0.4.* recommonmark==0.5.* <file_sep># Copyright 2019 The AdaNet Authors. 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 # https://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. """Distributed placement strategy tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools from absl.testing import parameterized from adanet.distributed.placement import ReplicationStrategy from adanet.distributed.placement import RoundRobinStrategy import tensorflow as tf class ReplicationStrategyTest(tf.test.TestCase): def test_strategy(self): strategy = ReplicationStrategy() num_subnetworks = 3 subnetwork_index = 1 self.assertTrue(strategy.should_build_ensemble(num_subnetworks)) self.assertTrue( strategy.should_build_subnetwork(num_subnetworks, subnetwork_index)) self.assertTrue(strategy.should_train_subnetworks(num_subnetworks)) class Config(object): def __init__(self, num_worker_replicas, global_id_in_cluster): self.num_worker_replicas = num_worker_replicas self.global_id_in_cluster = global_id_in_cluster def _testcase_name(name, drop_remainder): return "{}{}".format(name, "_drop_remainder" if drop_remainder else "") class RoundRobinStrategyTest(parameterized.TestCase, tf.test.TestCase): # pylint: disable=g-complex-comprehension @parameterized.named_parameters( itertools.chain(*[[ { "testcase_name": _testcase_name("one_worker_one_subnetwork", drop_remainder), "num_workers": 1, "num_subnetworks": 1, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True], "want_should_build_subnetwork": [[True]], "want_should_train_subnetworks": [True], }, { "testcase_name": _testcase_name("three_workers_one_subnetworks", drop_remainder ), "num_workers": 3, "num_subnetworks": 1, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, True, True], "want_should_build_subnetwork": [[True], [True], [True]], "want_should_train_subnetworks": [True, True, True], }, { "testcase_name": _testcase_name("two_workers_one_subnetworks", drop_remainder), "num_workers": 2, "num_subnetworks": 5, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False], "want_should_build_subnetwork": [[True, True, True, True, True], [ True, not drop_remainder, not drop_remainder, not drop_remainder, not drop_remainder, ]], "want_should_train_subnetworks": [False, True], }, { "testcase_name": _testcase_name("one_worker_three_subnetworks", drop_remainder ), "num_workers": 1, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True], "want_should_build_subnetwork": [[True, True, True]], "want_should_train_subnetworks": [True], }, { "testcase_name": _testcase_name("two_workers_three_subnetworks", drop_remainder ), "num_workers": 2, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False], "want_should_build_subnetwork": [ [True, True, True], [True, not drop_remainder, not drop_remainder], ], "want_should_train_subnetworks": [False, True], }, { "testcase_name": _testcase_name("three_workers_three_subnetworks", drop_remainder), "num_workers": 3, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False], "want_should_build_subnetwork": [ [True, True, True], [True, False, not drop_remainder], [False, True, False], ], "want_should_train_subnetworks": [False, True, True], }, { "testcase_name": _testcase_name("four_workers_three_subnetworks", drop_remainder), "num_workers": 4, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False, False], "want_should_build_subnetwork": [ [True, True, True], [True, False, False], [False, True, False], [False, False, True], ], "want_should_train_subnetworks": [False, True, True, True], }, { "testcase_name": _testcase_name("five_workers_three_subnetworks", drop_remainder), "num_workers": 5, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False, False, True], "want_should_build_subnetwork": [ [True, True, True], [True, False, False], [False, True, False], [False, False, True], [True, True, True], ], "want_should_train_subnetworks": [False, True, True, True, False], }, { "testcase_name": _testcase_name("six_workers_three_subnetworks", drop_remainder ), "num_workers": 6, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False, False, True, False], "want_should_build_subnetwork": [ [True, True, True], [True, False, False], [False, True, False], [False, False, True], [True, True, True], [True, not drop_remainder, not drop_remainder], ], "want_should_train_subnetworks": [False, True, True, True, False, True], }, { "testcase_name": _testcase_name("seven_workers_three_subnetworks", drop_remainder), "num_workers": 7, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False, False, True, False, False], "want_should_build_subnetwork": [ [True, True, True], [True, False, False], [False, True, False], [False, False, True], [True, True, True], [True, False, not drop_remainder], [False, True, False], ], "want_should_train_subnetworks": [False, True, True, True, False, True, True], }, { "testcase_name": _testcase_name("eight_workers_three_subnetworks", drop_remainder), "num_workers": 8, "num_subnetworks": 3, "drop_remainder": drop_remainder, "want_should_build_ensemble": [True, False, False, False, True, False, False, False], "want_should_build_subnetwork": [ [True, True, True], [True, False, False], [False, True, False], [False, False, True], [True, True, True], [True, False, False], [False, True, False], [False, False, True], ], "want_should_train_subnetworks": [False, True, True, True, False, True, True, True], }, ] for drop_remainder in [False, True]])) # pylint: enable=g-complex-comprehension def test_methods(self, num_workers, num_subnetworks, drop_remainder, want_should_build_ensemble, want_should_build_subnetwork, want_should_train_subnetworks): should_build_ensemble = [] should_build_subnetwork = [] should_train_subnetworks = [] for worker_index in range(num_workers): strategy = RoundRobinStrategy(drop_remainder) strategy.config = Config(num_workers, worker_index) should_build_ensemble.append( strategy.should_build_ensemble(num_subnetworks)) should_build_subnetwork.append([]) should_train_subnetworks.append( strategy.should_train_subnetworks(num_subnetworks)) for subnetwork_index in range(num_subnetworks): should_build_subnetwork[-1].append( strategy.should_build_subnetwork(num_subnetworks, subnetwork_index)) self.assertEqual(want_should_build_ensemble, should_build_ensemble) self.assertEqual(want_should_build_subnetwork, should_build_subnetwork) self.assertEqual(want_should_train_subnetworks, should_train_subnetworks) if __name__ == "__main__": tf.test.main()
5f3c4400126a875b1506f04481170473e931e9a6
[ "Python", "Text" ]
2
Text
lsheiba/adanet
7af1f76a86ed610d3998c81b649e44276a529a39
154c7ade861139ee85924d53d3af492bcaa54237
refs/heads/master
<repo_name>robbiev/godup<file_sep>/main.go package main import ( "fmt" "math" ) const prime = 1021 func naiveIndexOf(s string, pattern string) int { Outer: for i := 0; i < len(s)-len(pattern); i++ { for j := range pattern { if s[i+j] != pattern[j] { continue Outer } } return i } return -1 } func rabinFingerprint(str string) uint32 { hash := uint32(0) maxPow := len(str) - 1 for i := 0; i < len(str); i++ { hash += uint32(str[i]) * uint32(math.Pow(prime, float64(maxPow-i))) } return hash } func nextRabinFingerprint(pow uint32, oldHash uint32, in, out uint8) uint32 { return (prime * (oldHash - (uint32(out) * pow))) + uint32(in) } func rabinKarpIndexOf(s string, pattern string) int { if len(s) == 0 || len(pattern) == 0 || len(s) < len(pattern) { return -1 } if len(s) == len(pattern) { if s != pattern { return -1 } return 0 } pow := uint32(math.Pow(prime, float64(len(pattern)-1))) hpattern := rabinFingerprint(pattern) hs := rabinFingerprint(s[0:len(pattern)]) for i := 0; i <= len(s)-len(pattern); i++ { if hs == hpattern { if s[i:i+len(pattern)] == pattern { return i } } inIndex := i + len(pattern) if inIndex < len(s) { hs = nextRabinFingerprint(pow, hs, s[inIndex], s[i]) } } return -1 } func main() { fmt.Println(naiveIndexOf("blah", "a")) fmt.Println(naiveIndexOf("blah", "x")) fmt.Println(rabinKarpIndexOf("blah", "a")) fmt.Println(rabinKarpIndexOf("blah", "x")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "blah")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blahblah", "blah")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "b")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "l")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "a")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "h")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "bl")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "la")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "ah")) fmt.Println("===") fmt.Println(rabinKarpIndexOf("blah", "lah")) }
0602fac850299541acfdd253c7a804de4304ea7c
[ "Go" ]
1
Go
robbiev/godup
49d5f5249a6725a92bae3e39029cc5f81a640413
3cfadf3cb473dd3812db35365c9d838c5cc90ce0
refs/heads/master
<file_sep>###################### ##title: make shots charts ##description: analyze shots data of NBA ##inputs: data of Andre, Draymond, Kevin, Klay, Stephen ##outputs: several charts ###################### court_file <- "../images/nba-court.jpg" court_image <- rasterGrob( readJPEG(court_file), width = unit(1, "npc"), height = unit(1, "npc") ) pdf(file = "../images/andre-iguodala-shot-chart.pdf") ggplot(data = andre)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ ggtitle("Shot Chart: <NAME>")+ theme_minimal() dev.off() pdf(file = "../images/draymond-green-shot-chart.pdf") ggplot(data = draymond)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ ggtitle("Shot Chart: Draymond Green")+ theme_minimal() dev.off() pdf(file = "../images/kevin-durant-shot-chart.pdf") ggplot(data = andre)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ ggtitle("Shot Chart: <NAME>")+ theme_minimal() dev.off() pdf(file = "../images/klay-thompson-shot-chart.pdf") ggplot(data = andre)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ ggtitle("Shot Chart: <NAME>")+ theme_minimal() dev.off() pdf(file = "../images/stephen-curry-shot-chart.pdf") ggplot(data = andre)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ ggtitle("Shot Chart: <NAME>")+ theme_minimal() dev.off() pdf(file = "../images/gsw-shot-chart.pdf", width = 8, height = 7, title = "Shot Charts") ggplot(data = total)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ theme_minimal()+ facet_wrap(.~ name) dev.off() png(filename = "../images/gsw-shot-chart.png", width = 8, height = 7, units = "in", res = 1200) ggplot(data = total)+ annotation_custom(court_image, -250, 250, -50, 420)+ geom_point(aes(x = x, y = y, color = shot_made_flag))+ ylim(-50,420)+ theme_minimal()+ facet_wrap(.~ name) dev.off() <file_sep>library(testthat) context("Test for auxillary functions") test_that("aux_mean works as expected",{ expect_equal(aux_mean(10,0.1),1) expect_length(aux_mean(5,0.5),1) expect_type(aux_mean(20,0.1), "double") }) test_that("aux_variance works as expected",{ expect_equal(aux_variance(10,0.1),0.9) expect_length(aux_variance(5,0.5),1) expect_type(aux_variance(20,0.1),"double") }) test_that("aux_mode works as expected",{ expect_equal(aux_mode(20,0.1), 2) expect_length(aux_mode(20,0.5),1) expect_type(aux_mode(20,0.1),"integer") }) test_that("aux_skewness works as expected",{ expect_equal(aux_skewness(10,0.3),(1-2*0.3)/sqrt(10*0.3*(1-0.3))) expect_length(aux_skewness(5,0.5),1) expect_type(aux_skewness(20,0.1),"double") }) test_that("aux_kurtosis works as expected",{ expect_equal(aux_kurtosis(10,0.1),0.5111111) expect_length(aux_kurtosis(5,0.5),1) expect_type(aux_kurtosis(20,0.1),"double") }) <file_sep># Binomial Related Functions # 1.1 # title Check probability value function # description Check if the probability value is valid # param prob The Probability that we check whether is valid (numeric) # return a logical vector of whether prob is a valid probability #examples #check_prob(0.5) library(ggplot2) check_prob <- function(prob){ if(prob<=1 & prob >= 0){ return(TRUE) }else{ stop("invalid prob value") } } # title Check trials value function # description Check if the trials value is valid # param trials The parameter that we check whether is valid or not # return A logical vector of whether prob is a valid probability #examples #check_trials(0.5) #check_trials(3) check_trials <- function(trials){ if((trials > 0) & (trials%%1 == 0 )){ return(TRUE) }else{ stop("invalid trials value") } } # title Check success value function # description Check if the success value is valid # param success The success value that we check whether is valid # param trials The trials value that we check whether is valid # return A logical vector of whether the success is a valid probability #examples #check_success(5,1) #check_success(1,5) check_success <- function(success,trials){ if((success >=0 )& (success%%1 == 0) &(check_trials(trials))&(success<= trials)){ return(TRUE) }else{ stop("invalid success value") } } # 1.2 # title Auxillary Mean function # description Compute the expected value of the binomial distribution # param trials Number of trials in the binomial distribution # param prob Probability of success in the binomial distribution # return the expected value of binomial distribution #examples #aux_mean(10, 0.3) aux_mean <- function(trials, prob){ check_trials(trials) check_prob(prob) return(trials*prob) } # title Auxillary variance function # description Compute the variance of the binomial distribution # param trials Number of trials in the binomial distribution # param prob Probability of success in the binomial distribution # return the variance of binomial distribution #examples #aux_variance(10, 0.3) aux_variance <- function(trials, prob){ check_trials(trials) check_prob(prob) return(trials*prob*(1-prob)) } # title Auxillary Mode function # description Compute the mode of the binomial distribution # param trials Number of trials in the binomial distribution # param prob Probability of success in the binomial distribution # return the mode of binomial distribution #examples #aux_mode(10, 0.3) aux_mode <- function(trials, prob){ check_trials(trials) check_prob(prob) m <- trials*prob+prob if(prob == 0){ return(0) }else if(prob == 1){ return(trials) }else if(!grepl("\\.", as.character(m))){ return(c(m-1, m)) }else{ return(as.integer(m)) } } # title Auxillary Skewness function # description Compute the skewness of the binomial distribution # param trials Number of trials in the binomial distribution # param prob Probability of success in the binomial distribution # return the skewness of binomial distribution #examples #aux_skewness(10, 0.3) aux_skewness <- function(trials, prob){ check_trials(trials) check_prob(prob) skewness <- (1-2*prob)/sqrt(trials * prob * (1- prob)) return(skewness) } # title Auxillary Kurtosis function # description Compute the kurtosis of the binomial distribution # param trials Number of trials in the binomial distribution # param prob Probability of success in the binomial distribution # return the kurtosis of binomial distribution #examples #aux_kurtosis(10, 0.3) aux_kurtosis <- function(trials, prob){ check_trials(trials) check_prob(prob) kurtosis= (1 - 6 * prob * (1-prob) )/(trials * prob * (1-prob)) return(kurtosis) } # 1.3 #' @title binomial choose function #' @description calculates the number of combinations in which k successes can occur in n trials #' @param n number of trials #' @param k number of success #' @return the number of combinations in which k successes can occur in n trials #' @export #' @examples # bin_choose(n = 5, k = 2) # bin_choose(5,0) # bin_choose(5,1:3) #' @export bin_choose <- function(n,k){ if (check_success(k,n)){ return(factorial(n)/(factorial(k)*factorial(n-k))) }else{ stop("invalid input") } } # 1.4 #' @title Binomial Probability #' @description Calculates probability given certain number of successes, probability and trials #' @param trials Number of trials (numeric) #' @param success Number of successes (numeric) #' @param prob Probability of success in one trial (numeric) #' @return Returns the probability given certain number of successes, probability and trials #' @export #' @examples #' bin_probability(success = 2, trials = 5, prob = 0.5) #' bin_probability(success = 0:2, trials = 5, prob = 0.5) #' bin_probability(success = 55, trials = 100, prob = 0.45) #' @export bin_probability <- function(success, trials, prob){ if(!check_trials(trials)){ stop("invalid trials value") }else if(!check_prob(prob)){ stop("invalid probability value") }else if(!check_success(success, trials) ){ stop("invalid success value") }else{ bin_choose(trials, success)*(prob^(success))*((1-prob)^(trials-success)) } } # 1.5 #' @title binomial distribution function #' @description calculates the probability of different number of success trials #' @param trials number of trials #' @param prob success rate of each trials #' @return A data frame with number of success and its probability #' @export #' @examples #' bin_distribution(trials = 5, prob = 0.5) bin_distribution <- function(trials,prob){ probability <- c() if (check_trials(trials) & check_prob(prob)) { for (i in c(0:trials)) { probability[i+1] = bin_probability(i,trials,prob) } success <- c(0:trials) prob_table <- data.frame(cbind(success,probability)) class(prob_table) <- c("bindist","data.frame") return(prob_table) } } #' @export plot.bindist <- function(x){ library(ggplot2) bin_dis <- ggplot2::ggplot(x, ggplot2::aes(x= x$success, y = x$probability))+ ggplot2::labs(x="successes")+ ggplot2::geom_histogram(stat = "identity", color = "#C0C0C0", fill="#C0C0C0")+ ggplot2::theme_classic() bindist <- bin_dis + ggplot2::scale_y_continuous(breaks = seq(0, max(x$probability), by = 0.05))+ ggplot2::scale_x_continuous(breaks=(seq(0, max(x$success), by = 1))) return(bindist) } # 1.6 #' @title binomial cumulative function #' @description calculates the probability and cumulative probability of different success times #' @param trials number of trials #' @param success success rate of each trials #' @return A data frame with number of success, probability and cumulative probability #' @export #' @examples #' bin_cumulative(5,0.5) bin_cumulative<-function(trials,prob){ cum<-c() bin_dist<-bin_distribution(trials,prob) for (i in c(1:length(bin_dist$probability))){ if (i==1){ cum[i]<-bin_dist$probability[i] } else{ cum[i]<-cum[i-1]+bin_dist$probability[i] } } bin_dist$cumulative<-cum class(bin_dist)<-c("bincum","data.frame") return(bin_dist) } #' @export plot.bincum <- function(x){ library(ggplot2) bincum <- ggplot2::ggplot(data = x, ggplot2::aes(x= x$success, y = x$cumulative)) + ggplot2::geom_line() + ggplot2::geom_point(shape = 1, size = 3) + ggplot2::theme_classic() + ggplot2::labs(x = "success", y = "") bincum <- bincum + ggplot2::scale_y_continuous(breaks = seq(0, 1, by = 0.2)) return(bincum) } #1.7 #' @title Binomial Variable #' @description Calculate and form a Binomial Random Variable #' @param trials Number of trials (numeric) #' @param prob Probability of success (numeric) #' @return A Binomial Random Variable object with attributes of trials and probability #' @export #' @examples #' bin_variable(trials = 5, prob = 0.5) bin_variable <- function(trials, prob) { check_trials(trials) check_prob(prob) binvar <- list(trials = trials, prob = prob) class(binvar) <- c("binvar") binvar } #' @export print.binvar <- function(x) { cat('"Binomial variable"\n\n') cat("Parameters\n") cat("- number of trials:", x$trials, "\n") cat("- prob of success :", x$prob) } #' @export summary.binvar <- function(x) { trials <- x$trials prob <- x$prob summary.binvar <- list(trials = x$trials, prob = x$prob, mean = aux_mean(trials, prob), variance = aux_variance(trials, prob), mode = aux_mode(trials, prob), skewness = aux_skewness(trials, prob), kurtosis = aux_kurtosis(trials, prob)) class(summary.binvar) <- c("summary.binvar", "list") summary.binvar } #' @export print.summary.binvar <- function(x) { cat('"Summary Binomial"\n\n') cat("Parameters\n") cat("- number of trials:", x$trials, "\n\n") cat("- prob of success :", x$prob, "\n\n") cat("Measures\n\n") cat("- mean :", x$mean, "\n\n") cat("- variance:", x$variance, "\n\n") cat("- mode :", x$mode, "\n\n") cat("- skewness:", x$skewness, "\n\n") cat("- kurtosis:", x$kurtosis,"\n\n") } # 1.8 #' @title Binomial Mean #' @description Computes the expected value of the binomial distribution #' @param trials Number of trials in the binomial distribution (numeric) #' @param prob Probability of success in the binomial distribution (numeric) #' @return Expected value of binomial distribution #' @export #' @examples #' bin_mean(10,0.1) bin_mean <- function(trials, prob){ check_trials(trials) check_prob(prob) return(aux_mean(trials, prob)) } #' @title Binomial variance function #' @description Compute the variance of the binomial distribution #' @param trials Number of trials in the binomial distribution #' @param prob Probability of success in the binomial distribution #' @return the variance of binomial distribution #' @export #' @examples #' bin_variance(10,0.1) bin_variance <- function(trials, prob){ check_trials(trials) check_prob(prob) return(aux_variance(trials, prob)) } #' @title Binomial Mode function #' @description: Compute the mode of the binomial distribution #' @param trials Number of trials in the binomial distribution #' @param prob Probability of success in the binomial distribution #' @return the mode of binomial distribution #' @export #' @examples #' bin_mode(10,0.1) bin_mode <- function(trials, prob){ check_trials(trials) check_prob(prob) return(aux_mode(trials, prob)) } #' @title Binomial Skewness function #' @description: Compute the skewness of the binomial distribution #' @param: trials Number of trials in the binomial distribution #' @param: prob Probability of success in the binomial distribution #' @return the skewness of binomial distribution #' @export #' @examples #' bin_skewness(10,0.1) bin_skewness <- function(trials, prob){ check_trials(trials) check_prob(prob) return(aux_skewness(trials, prob)) } #' @title Binomial Kurtosis function #' @description Compute the kurtosis of the binomial distribution #' @param trials Number of trials in the binomial distribution #' @param prob Probability of success in the binomial distribution #' @return the kurtosis of binomial distribution #' @export #' @examples #' bin_kurtosis(10,0.1) bin_kurtosis <- function(trials, prob){ check_trials(trials) check_prob(prob) return(aux_kurtosis(trials, prob)) } <file_sep>###################### ##title: make shots data ##description: analyze shots data of NBA ##inputs: data of Andre, Draymond, Kevin, Klay, Stephen ##outputs: organized data ###################### setwd("/Users/zhangxihuan/Desktop/workout01/code") andre <- read.csv(file= "/Users/zhangxihuan/Desktop/workout01/data/andre-iguodala.csv", stringsAsFactors = FALSE) draymond <- read.csv(file= "/Users/zhangxihuan/Desktop/workout01/data/draymond-green.csv", stringsAsFactors = FALSE) kevin <- read.csv(file= "/Users/zhangxihuan/Desktop/workout01/data/kevin-durant.csv", stringsAsFactors = FALSE) klay <- read.csv(file= "/Users/zhangxihuan/Desktop/workout01/data/klay-thompson.csv", stringsAsFactors = FALSE) stephen <- read.csv(file= "/Users/zhangxihuan/Desktop/workout01/data/stephen-curry.csv", stringsAsFactors = FALSE) andre$name <- c("<NAME>") draymond$name <- c("<NAME>") kevin$name <- c("<NAME>") klay$name <- c("<NAME>") stephen$name <- c("<NAME>") andre$shot_made_flag[andre$shot_made_flag == "n"]<- c("shot_no") andre$shot_made_flag[andre$shot_made_flag == "y"]<- c("shot_yes") draymond$shot_made_flag[draymond$shot_made_flag == "n"]<- c("shot_no") draymond$shot_made_flag[draymond$shot_made_flag == "y"]<- c("shot_yes") kevin$shot_made_flag[kevin$shot_made_flag == "n"]<- c("shot_no") kevin$shot_made_flag[kevin$shot_made_flag == "y"]<- c("shot_yes") klay$shot_made_flag[klay$shot_made_flag == "n"]<- c("shot_no") klay$shot_made_flag[klay$shot_made_flag == "y"]<- c("shot_yes") stephen$shot_made_flag[stephen$shot_made_flag == "n"]<- c("shot_no") stephen$shot_made_flag[stephen$shot_made_flag == "y"]<- c("shot_yes") andre$minute <- 12*andre$period - andre$minutes_remaining draymond$minute <- 12*draymond$period - draymond$minutes_remaining kevin$minute <- 12*kevin$period - kevin$minutes_remaining klay$minute <- 12*klay$period - klay$minutes_remaining stephen$minute <- 12*stephen$period - stephen$minutes_remaining sink(file = "../output/andre-iguodala-summary.txt") summary(andre) sink() sink(file = "../output/draymond-green-summary.txt") summary(draymond) sink() sink(file = "../output/kevin-durant-summary.txt") summary(kevin) sink() sink(file = "../output/klay-thompson-summary.txt") summary(klay) sink() sink(file = "../output/stephen-curry-summary.txt") summary(stephen) sink() total <- rbind(andre, draymond, kevin, klay, stephen) write.csv(total, "../data/shots-data.csv") sink(file = "../output/shots-data-summary.txt") summary(total) sink() <file_sep># Overview `"binomial"` is a self-created R package that implements functions for calculating probabilities of a Binomial random variable, and related calculations such as the probability distribution, and expected value, variance, etc. ## Steps ##### 1) Calculate the number of different combinations given certain number of trials and successes. ##### 2) Find the probability given certain number of trials and successes ##### 3) obtain a dataframe given certain number of trials and successes ##### 4) Plot the histogram of above dataframe ##### 5) Calculate the cumulative probability ##### 7) Create binomial variable using given number of trials and successes ##### 8) Obtain a summary of binomial variable above ##### 9) Calculate several statistics of binomial variable above `bin_mean` gives the mean of given binomial distribution. `bin_variance` gives the variance of given binomial distribution. `bin_mode` gives the mode of given binomial distribution. `bin_skewness` gives the skewness of given binomial distribution. `bin_kurtosis` gives the kurtosis of given binomial distribution. ## Motivation This package is used to illustrate the usage and concepts of binomial package. ## Installation Install the development version from GitHub via the package `"devtools"`: ```r # development version from GitHub: #install.packages("devtools") # install "binomial" (without vignettes) devtools::install_github("stat133-sp19/hw-stat133-xihuanzhang/workout03/binomial") # install "binomial" (with vignettes) devtools::install_github("stat133-sp19/hw-stat133-xihuanzhang/workout03/binomial", build_vignettes = TRUE) # If it doesn't work, add 'force = TRUE' devtools::install_github("stat133-sp19/hw-stat133-xihuanzhang/workout03/binomial", force = TRUE) ``` ## Usage step 1) loading the package using library(binomial) step 2) test the functions step 3) provide desired number of trials, number of sucesses and probability for one single trial. step 4) the binomial package will return the results corresponding to given inputs The content below provides some specific examples using binomial package ```{r} #for example, we play 5 times and expect 2 successes bin_choose(n=5,k=2) #We generate the bin_probability function using bin_choose function above. Using the functions below, we can calculate the probability of winning 2 times in 5 trials with success probability of 0.5 for each single trial. bin_probability(success = 2, trials = 5, prob = 0.5) #Using given number of trials and successes, we can obtain a data frame containing all the results(probability) corresponding to consequtive number of trials from 0 to the given number of trials dis1 <- bin_distribution(trials = 5, prob = 0.5) dis1 #plot the data frame above plot(dis1) #Using given number of trials and successes, we can obtain a data frame containing all the results(probability and cumulative probability) corresponding to consequtive number of trials from 0 to the given number of trials bin_cum<- bin_cumulative(trials = 5, prob = 0.5) bin_cum #plot the bin_cum we obtained above. plot(bin_cum) #obtian some statistics of our generated binomial variables bin_mean(10,0.5) bin_variance(10,0.5) bin_mode(10,0.5) bin_skewness(10,0.5) bin_kurtosis(10,0.5) ``` <file_sep>library(testthat) context("tests for binomial functions") #bin_choose test_that("bin_choose is as expected", { expect_equal(bin_choose(n = 5, k = 2),10) expect_type(bin_choose(n = 10, k = 3),"double") expect_length(bin_choose(n = 10, k = 3),1) }) #bin_probability test_that("bin_probability is as expected", { expect_equal(bin_probability(success = 4, trials = 5, prob = 0.5), 0.15625) expect_type(bin_probability(success = 2, trials = 10, prob = 0.5), "double") expect_length(bin_probability(success = 4, trials = 10, prob = 0.5), 1) }) #bin_distribution test_that("bin_distribution is as expected", { expect_is(bin_distribution(trials = 10, prob = 0.5), c("bindis","data.frame")) expect_type(bin_distribution(trials = 10, prob = 0.5),"list") expect_length(bin_distribution(trials = 10, prob = 0.5), 2) }) #bin_cumulative test_that("bin_cumulative is as expected", { expect_is(bin_cumulative(trials = 10, prob = 0.5), c("bincum", "data.frame")) expect_type(bin_cumulative(trials = 10, prob = 0.5),"list") expect_length(bin_cumulative(trials = 10, prob = 0.5),3) }) <file_sep>warmup01-xihuan-zhang ================ star wars ========= Include one of the character's quote using a markdown blockquote. ================================================================= > <NAME>: "You can work as a mechanic on my team. But when it comes to your mission as a spy, I don't want anything to do wity it." Include an image of the character. ================================== ![image of <NAME>](https://vignette.wikia.nocookie.net/starwars/images/d/dd/Jarek.jpg/revision/latest?cb=20180905013807) Use a markdown table with two columns to include things like species, gender, color,etc. ======================================================================================== | <NAME> | Description | |--------------|---------------| | Species | Human | | Gender | Male | | Hair color | Black,graying | | Eye color | Brown | | Skin color | Dark | Cooking Recipe ============== Use an unordered list(of bullets) to list the ingredients. ========================================================== - 2 cups plus 3 tablespoons (285 grams) all-purpose flour - 1 1/2 teaspoons baking soda - 1/2 teaspoon fine sea salt - 1 cup (200 grams) granulated sugar - 1/2 cup (110 grams) coconut oil, warmed just enough to liquefy - 1 1/2 cups full- or low-fat coconut milk (see Note) - 1 tablespoon (15 ml) plain vinegar Use another unordered list to list any "special"kitchen tools that are needed. ============================================================================== - Oven - Pan Describe the steps of the recipe ================================ > Heat oven to 350 degrees F. Line the bottom of 9-inch round cake pan with a fitted round of parchment paper and coat the bottoms and sides with nonstick cooking spray. > Whisk together flour, baking soda, salt and granulated sugar in the bottom of a large mixing bowl. Add coconut oil, coconut milk, and vinegar and whisk until batter is smooth. > Pour into prepared pan. Bake for 25 to 30 minutes \[updated to note: it’s sounding in the comments like it’s taking some people a bit longer — it’s not done until the center is set, even if it’s longer than it took me\], or until the top is springy and a tester inserted in the center comes out batter-free. Cool the cake in the pan on a wire rack for 10 minutes, then cut around it with a knife to ensure it is loosened and flip it out onto a cooling rack to cool the rest of the way. > If you wish to make a glaze: Whisk together 3/4 cup powdered sugar with 1 to 2 tablespoons of the leftover coconut milk, adding a little at a time, until it is smooth but not too runny. Add a pinch of salt, if you wish. Once cake is fully cool, spread over the top of the cake and smooth to the edges with a knife or small offset spatula, where it will find its way down the sides decoratively on its own. I added some white confetti sprinkles, but toasted coconut chips would be nice here too. Include an image to show the appearance of the meal. ==================================================== ![image of the meal](https://smittenkitchendotcom.files.wordpress.com/2019/01/plush-coconut-cake-vegan.jpg?w=1500) Is there an special season of the year for it? ============================================== > No. Are there variations of the recipe? Using other ingredients? ============================================================ > Yes. Euclidean Distance ================== > Definition > The Euclidean distance between points p and q is the length of the line segment connecting them ($\\overline{\\textbf{p,q}}$). In Cartesian coordinates, if **p** = (*p*<sub>1</sub>,*p*<sub>2</sub>,…,*p*<sub>*n*</sub>) and **q** = (*q*<sub>1</sub>,*q*<sub>2</sub>,…,*q*<sub>*n*</sub>) are two points in Euclidean n-space, then the distance (d) from to , or from to is given by the Pythagorean formula: > The position of a point in a Euclidean *n* -space is a Euclidean vector. So, p and *q* may be represented as Euclidean vectors, starting from the origin of the space (initial point) with their tips (terminal points) ending at the two points. The Euclidean norm, or Euclidean length, or magnitude of a vector measures the length of the vector: $\\| \\mathbf {p} \\| = \\sqrt { p \_ {1} ^ {2} + p \_ {2} ^ {2} + \\cdots + p \_{n} ^ {2}} = \\sqrt { \\mathbf {p} \\cdot \\mathbf {p}}$ > where the last expression involves the dot product. <file_sep>library(testthat) context("tests for Checker functions") # Test check_prob test_that("Test if the check_prob works",{ expect_true(check_prob(0)) expect_length(check_prob(0.2),1) expect_type(check_prob(0.3), "logical") } ) # Test check_trials test_that("Test if the check_trials works",{ expect_true(check_trials(5)) expect_length(check_trials(1),1) expect_type(check_trials(13),"logical") }) # Test check_success test_that("Test if the check_success works",{ expect_true(check_success(3,9)) expect_length( check_success(2,10),1) expect_type(check_trials(15),"logical") } ) <file_sep>--- title: "Vignette" author: "<NAME>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Vignette Title} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo = FALSE, message= FALSE} knitr::opts_chunk$set(collapse = T, comment="#>") library(binomial) library(ggplot2) ``` Vignettes are long form documentation commonly included in packages. Because they are part of the distribution of the package, they need to be as compact as possible. The `html_vignette` output type provides a custom style sheet (and tweaks some options) to ensure that the resulting html is as small as possible. The `html_vignette` format: - Never uses retina figures - Has a smaller default figure size - Uses a custom CSS stylesheet instead of the default Twitter Bootstrap style # Binomial `"binomial"` is a self-created R package that implements functions for calculating probabilities of a Binomial random variable, and related calculations such as the probability distribution, and expected value, variance, etc. ### 1) Calculate the number of different combinations given certain number of trials and successes. for example, we play 5 times and expect 2 successes ```{r} bin_choose(n=5,k=2) ``` ### 2) Find the probability given certain number of trials and successes We generate the bin_probability function using bin_choose function above. Using the functions below, we can calculate the probability of winning 2 times in 5 trials with success probability of 0.5 for each single trial. ```{r} bin_probability(success = 2, trials = 5, prob = 0.5) ``` ### 3) obtain a dataframe given certain number of trials and successes Using given number of trials and successes, we can obtain a data frame containing all the results(probability) corresponding to consequtive number of trials from 0 to the given number of trials ```{r} dis1 <- bin_distribution(trials = 5, prob = 0.5) dis1 ``` ### 4) Plot the histogram of above dataframe ```{r} plot(dis1) ``` ### 5) Calculate the cumulative probability Using given number of trials and successes, we can obtain a data frame containing all the results(probability and cumulative probability) corresponding to consequtive number of trials from 0 to the given number of trials ```{r} bin_cum<- bin_cumulative(trials = 5, prob = 0.5) bin_cum ``` ### 6) Plot the cumulative probability plot the bin_cum we obtained above. ```{r} plot(bin_cum) ``` ### 7) Create binomial variable using given number of trials and successes ```{r} bin_var <- bin_variable(trials=5,prob=0.5) bin_var ``` ### 8) Obtain a summary of binomial variable above ```{r} bin_sum <- summary(bin_var) bin_sum ``` ### 9) Calculate several statistics of binomial variable above `bin_mean` gives the mean of given binomial distribution. `bin_variance` gives the variance of given binomial distribution. `bin_mode` gives the mode of given binomial distribution. `bin_skewness` gives the skewness of given binomial distribution. `bin_kurtosis` gives the kurtosis of given binomial distribution. ```{r} bin_mean(10,0.5) bin_variance(10,0.5) bin_mode(10,0.5) bin_skewness(10,0.5) bin_kurtosis(10,0.5) ``` <file_sep>library(shiny) library(ggplot2) library(reshape2) ui <- fluidPage( titlePanel(title = "Three Models of Investment"), fluidRow( column(4, sliderInput("amount", "Initial Amount", min = 1, max = 100000, step = 500, value = 1000, pre = "$")), column(4, sliderInput("rate", "Return Rate (in %)", min = 0, max = 20, step = 0.1, value = 5)), column(4, sliderInput("years", "Years", min = 0, max = 50, step = 1, value = 10)), column(4, sliderInput("contrib", "Annual Contribution", min = 0, max = 50000, step = 500, value = 2000, pre = "$")), column(4, sliderInput("growth", "Growth Rate(in %)", min = 0, max = 20, step = 0.1, value = 2)), column(4, selectInput("facet", "Facet?", c("Yes","No")) ), # Show a plot and a table of the generated distribution mainPanel( h3("Timeline"), plotOutput("distPlot",width = "150%"), h3("balances"), verbatimTextOutput("modalities") ))) server <- function(input, output) { output$distPlot <- renderPlot({ FV <- c() for (i in 1:input$years){ FV[i]= input$amount*((1+(input$rate/100))^i) } FVA <- c() for (i in 1:input$years){ FVA[i]=input$amount*((1+(input$rate/100))^i)+input$contrib*((((1+(input$rate/100))^i)-1)/(input$rate/100)) } FVGA <- c() for (i in 1:input$years){ FVGA[i]= input$amount*((1+(input$rate/100))^i)+(input$contrib*((((1+(input$rate/100))^i)-((1+(input$growth/100))^i))/((input$rate/100)-(input$growth/100)))) } modalities <- data.frame(year=0:input$years,no_contrib=c(input$amount,FV), fixed_contrib=c(input$amount,FVA), growing_contrib=c(input$amount,FVGA)) if (input$facet == "Yes") { df.m = melt(modalities, id.vars ="year", measure.vars = c("no_contrib","fixed_contrib","growing_contrib")) ggplot(df.m, aes(year, value)) + geom_area(aes(fill = variable), alpha = 0.3) + geom_point(aes(colour = variable)) + geom_line(aes(colour = variable))+ scale_x_discrete(name ="Years", limits = c(0:input$years)) + ylab("Value") + ggtitle("Three modes of investing")+ theme_bw()+ facet_wrap(~variable) } else if (input$facet == "No"){ df.m = melt(modalities, id.vars ="year", measure.vars = c("no_contrib","fixed_contrib","growing_contrib")) ggplot(df.m, aes(year, value)) + geom_point(aes(color = variable)) + geom_line(aes(color = variable)) + scale_x_discrete(name ="Years", limits = c(0:input$years)) + ylab("Balance") + ggtitle("Growth of Investment Models") } }) modalities <- reactive({ FV <- c() for (i in 1:input$years){ FV[i]= input$amount*((1+(input$rate/100))^i) } FVA <- c() for (i in 1:input$years){ FVA[i]=input$amount*((1+(input$rate/100))^i)+input$contrib*((((1+(input$rate/100))^i)-1)/(input$rate/100)) } FVGA <- c() for (i in 1:input$years){ FVGA[i]= input$amount*((1+(input$rate/100))^i)+(input$contrib*((((1+(input$rate/100))^i)-((1+(input$growth/100))^i))/((input$rate/100)-(input$growth/100)))) } modalities <- data.frame(year=0:input$years,no_contrib=c(input$amount,FV), fixed_contrib=c(input$amount,FVA), growing_contrib=c(input$amount,FVGA)) }) output$modalities <- renderPrint({(modalities())}) } shinyApp(ui = ui, server = server)<file_sep>--- title: "warmup01-xihuan-zhang" output: github_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` #star wars #Include one of the character's quote using a markdown blockquote. ><NAME>: "You can work as a mechanic on my team. But when it comes to your mission as a spy, I don't want anything to do wity it." #Include an image of the character. ![image of <NAME>](https://vignette.wikia.nocookie.net/starwars/images/d/dd/Jarek.jpg/revision/latest?cb=20180905013807) #Use a markdown table with two columns to include things like species, gender, color,etc. <NAME>|Description ---|--- Species|Human Gender|Male Hair color|Black,graying Eye color|Brown Skin color|Dark #Cooking Recipe #Use an unordered list(of bullets) to list the ingredients. * 2 cups plus 3 tablespoons (285 grams) all-purpose flour * 1 1/2 teaspoons baking soda * 1/2 teaspoon fine sea salt * 1 cup (200 grams) granulated sugar * 1/2 cup (110 grams) coconut oil, warmed just enough to liquefy * 1 1/2 cups full- or low-fat coconut milk (see Note) * 1 tablespoon (15 ml) plain vinegar #Use another unordered list to list any "special"kitchen tools that are needed. * Oven * Pan #Describe the steps of the recipe > Heat oven to 350 degrees F. Line the bottom of 9-inch round cake pan with a fitted round of parchment paper and coat the bottoms and sides with nonstick cooking spray. > Whisk together flour, baking soda, salt and granulated sugar in the bottom of a large mixing bowl. Add coconut oil, coconut milk, and vinegar and whisk until batter is smooth. > Pour into prepared pan. Bake for 25 to 30 minutes [updated to note: it’s sounding in the comments like it’s taking some people a bit longer — it’s not done until the center is set, even if it’s longer than it took me], or until the top is springy and a tester inserted in the center comes out batter-free. Cool the cake in the pan on a wire rack for 10 minutes, then cut around it with a knife to ensure it is loosened and flip it out onto a cooling rack to cool the rest of the way. > If you wish to make a glaze: Whisk together 3/4 cup powdered sugar with 1 to 2 tablespoons of the leftover coconut milk, adding a little at a time, until it is smooth but not too runny. Add a pinch of salt, if you wish. Once cake is fully cool, spread over the top of the cake and smooth to the edges with a knife or small offset spatula, where it will find its way down the sides decoratively on its own. I added some white confetti sprinkles, but toasted coconut chips would be nice here too. #Include an image to show the appearance of the meal. ![image of the meal](https://smittenkitchendotcom.files.wordpress.com/2019/01/plush-coconut-cake-vegan.jpg?w=1500) #Is there an special season of the year for it? > No. #Are there variations of the recipe? Using other ingredients? > Yes. #Euclidean Distance > Definition > The Euclidean distance between points p and q is the length of the line segment connecting them ($\overline{\textbf{p,q}}$). >In Cartesian coordinates, if $\mathbf{p} = \left(p_{1}, p_{2}, \ldots , p_{n} \right)$ and $\mathbf{q} = \left(q_{1}, q_{2} , \dots , q_{n} \right)$ are two points in Euclidean n-space, then the distance (d) from \mathbf{p } to \mathbf{q}, or from \mathbf{q} to \mathbf{ p } is given by the Pythagorean formula: \begin{aligned}d (\mathbf{p} , \mathbf {q} ) = d ( \mathbf{q} , \mathbf{p} ) & = \sqrt { \left( q_{1} - p_{1} \right) ^ {2} + \left( q_{2} - p_{2} \right) ^ {2} + \cdots + \left( q_{n} - p_{n} \right) ^ {2} } \\ & = \sqrt { \sum_{i = 1 } ^ {n} \left( q_{i} - p_{i} \right) ^ {2} } \end{aligned} >The position of a point in a Euclidean $n$ -space is a Euclidean vector. So, p and $q$ may be represented as Euclidean vectors, starting from the origin of the space (initial point) with their tips (terminal points) ending at the two points. The Euclidean norm, or Euclidean length, or magnitude of a vector measures the length of the vector: $\| \mathbf {p} \| = \sqrt { p _ {1} ^ {2} + p _ {2} ^ {2} + \cdots + p _{n} ^ {2}} = \sqrt { \mathbf {p} \cdot \mathbf {p}}$ >where the last expression involves the dot product.<file_sep>Workout 1 ================ <NAME> ``` r library(dplyr) ``` ## ## Attaching package: 'dplyr' ## The following objects are masked from 'package:stats': ## ## filter, lag ## The following objects are masked from 'package:base': ## ## intersect, setdiff, setequal, union <img src="../images/gsw-shot-chart.png" width="100%" style="display: block; margin: auto;" /> 5.1)Effective Shooting Percentage ``` r newdata <- read.csv(file = "../data/shots-data.csv", header = TRUE,sep = ",") name_shottype <- select(newdata, name, shot_type, shot_made_flag) ``` ``` r #2PT Effective Shooting % by Player two_points <- filter(name_shottype, shot_type == "2PT Field Goal") arrange( summarise(group_by(two_points, name), total = length(shot_type), made = sum(shot_made_flag == "shot_yes"), perc_made = made/total ), desc(perc_made)) ``` ## # A tibble: 5 x 4 ## name total made perc_made ## <fct> <int> <int> <dbl> ## 1 <NAME> 210 134 0.638 ## 2 <NAME> 643 390 0.607 ## 3 <NAME> 563 304 0.540 ## 4 <NAME> 640 329 0.514 ## 5 <NAME> 346 171 0.494 ``` r #3PT Effective Shooting % by Player three_points <- filter(name_shottype, shot_type == "3PT Field Goal") arrange( summarise(group_by(three_points, name), total = length(shot_type), made = sum(shot_made_flag == "shot_yes"), perc_made = made/total ), desc(perc_made)) ``` ## # A tibble: 5 x 4 ## name total made perc_made ## <fct> <int> <int> <dbl> ## 1 <NAME> 580 246 0.424 ## 2 <NAME> 687 280 0.408 ## 3 <NAME> 272 105 0.386 ## 4 <NAME> 161 58 0.360 ## 5 Graymond Green 232 74 0.319 ``` r #Effective Shooting % by Player arrange( summarise(group_by(name_shottype, name), total = length(shot_type), made = sum(shot_made_flag == "shot_yes"), perc_made = made/total ), desc(perc_made)) ``` ## # A tibble: 5 x 4 ## name total made perc_made ## <fct> <int> <int> <dbl> ## 1 <NAME> 915 495 0.541 ## 2 <NAME> 371 192 0.518 ## 3 <NAME> 1220 575 0.471 ## 4 <NAME> 1250 584 0.467 ## 5 Graymond Green 578 245 0.424 5.2)Narrative Report ====== ![Image of the Warriors](https://qph.fs.quoracdn.net/main-qimg-ec232d1c77da1599213e14b078d5b476) - Introduction: Golden State Warriors began in Philadelphia in 1946 and got their inaugural championship in the 1946-1947 season. It holds the name Golden State Warriors since 1971. In history, GSW has won four seasons, including the most recent 2014-2015, 2016-2017 and 2017-2018 seasons. The GSW has raised many famous players, such as <NAME> who got the NBA most valuable player award in the 2015-2016 season. As a competitive team, the GSW attracts much attention from the world, and many people want to know if it can remain champions in the 2018-2019 season. I analyzed their data in the 2016-2017 season to predict if they are going to be the champion in this season. - Motivation: Since the 2016-2017 season is a recent one, their current strength doesn’t change a lot compared to that season. We can predict the result by analyzing different members’ performance in the 2016-2017 season. - Background: The 2014-2015 season is a significant turning point for the GSW. They got their first champion after 40 years of obscurity. The GSW started the Steve Kerr era which is the Championship Era since that season. Under the leading of Steve Kerr, the GSW becomes a rising star in the world of basketball. The “famous four” of GSW are <NAME>, <NAME>, <NAME>, and <NAME>, and they all had incredible performance in recent seasons. Plus, <NAME> is also a key player of GSW. - Data and Analysis: I got those five players’ statistic in the 2016-2017 season from the GitHub website, which includes their game date, shot type, shot distance and many other data. I picked the two points shot statistic and three points shot statistic and made a table. ##### 2PT Effective Shooting % by Player: ``` r two_points <- filter(name_shottype, shot_type == "2PT Field Goal") arrange( summarise(group_by(two_points, name), total = length(shot_type), made = sum(shot_made_flag == "shot_yes"), perc_made = made/total ), desc(perc_made)) ``` ## # A tibble: 5 x 4 ## name total made perc_made ## <fct> <int> <int> <dbl> ## 1 <NAME> 210 134 0.638 ## 2 <NAME> 643 390 0.607 ## 3 <NAME> 563 304 0.540 ## 4 <NAME> 640 329 0.514 ## 5 Graymond Green 346 171 0.494 ##### 3PT Effective Shooting % by Player: ``` r three_points <- filter(name_shottype, shot_type == "3PT Field Goal") arrange( summarise(group_by(three_points, name), total = length(shot_type), made = sum(shot_made_flag == "shot_yes"), perc_made = made/total ), desc(perc_made)) ``` ## # A tibble: 5 x 4 ## name total made perc_made ## <fct> <int> <int> <dbl> ## 1 <NAME> 580 246 0.424 ## 2 <NAME> 687 280 0.408 ## 3 <NAME> 272 105 0.386 ## 4 <NAME> 161 58 0.360 ## 5 Graymond Green 232 74 0.319 ![Klay Thompson](https://media.gettyimages.com/photos/klay-thompson-of-the-golden-state-warriors-poses-for-a-portrait-with-picture-id970201180) From the tables above, we can see that <NAME> did 640 two points shots which is the most among five players, and succeed in the percentage of 51.4%. For three points shots, Klay made the second most shots and had got the highest success rate. It’s obvious that Klay’s strategy is to make more shots. Comparing to his two points shot, he did better in three points shots. ![<NAME>](https://www.gannett-cdn.com/-mm-/7349fb2ec8fa6eae87731d37a08df41a4a952655/c=320-223-4187-2408/local/-/media/2018/05/31/USATODAY/USATODAY/636633217332508663-2018-05-30-Andre-Iguodala.jpg?width=3200&height=1680&fit=crop) Although <NAME> made 210 two points shots which is the least among five players, he got the highest success rate, 63.8%. Andre also did the least three points shots with a success rate of 36%. Andre did much better in two points shots than three points shots. He focused on the quality more than quantity. ![<NAME>](https://static01.nyt.com/images/2017/04/07/sports/07durant-web1/07durant-web1-articleLarge.jpg?quality=75&auto=webp&disable=upscale) <NAME> got the second place in two points shots success rate and the third place in three points rate. Meanwhile, he attempted more two points shots than three points shots. It turns out that he tended to be a two points shots player. However, both the three points and two points success rate of current season are less than the 2016-2017 season. ![<NAME>](https://cdn.vox-cdn.com/thumbor/QnyGzZIeq92Mba_HwcQ87qUmBzU=/0x0:3915x2613/1200x800/filters:focal(1706x113:2332x739)/cdn.vox-cdn.com/uploads/chorus_image/image/59594853/usa_today_10816472.1525210208.jpg) <NAME> is a superstar even in such a famous team which has many talented players. As it shows in the table, Stephen did a good job in both two points shots and three points shots. For many players, they got a decreasing success rate when they have more attempts. However, Stephen kept a high success rate at the same time as having many attempts. ![Draymond Green](https://mk0slamonlinensgt39k.kinstacdn.com/wp-content/uploads/2017/11/Featured-Draymond.jpg) <NAME> is also an excellent player. It seems that he got the lowest success rate in both kinds of shots among five players, but his performance is still much better than many players from other teams. The reason he ranked at such a place is that the other four players are the best among top players. He makes huge progress in the current season where he got a 54.9% success rate on two points shots. It is highly likely that he will achieve a higher overall success rate than the 2016-2017 season. - Discussion: At the beginning of 2018, a talented player De<NAME> joined the GSW, and made the whole team even more competitive. However, it turns out that the GSW is facing some difficulties in the current season. On November 22nd, 2018, the GSW missed Stephen Curry and took their fourth consecutive loss to Oklahoma City Thunder, and they were finally defeated by 95 to 123. It was the first time that <NAME> had a taste of four-game losing streak since he was the coach. The last time when the GSW suffered a four-game losing streak was in the 2012-2013 season. However, they still have the chance to win this season since players still keep a high success rate now. For example, according to the statistic from basketball-reference website, Andre has a three points shots success rate of 64.2% which is higher than his success rate in the 2016-2017 season. Overall, five players all keep a stable performance in this season. - Conclusion: The GSW has a similar statistic as the 2016-2017 season where they won the championship, so they are a strong candidate for the champion in the 2018-2019 season. Although they are facing a very tough fight, they are still able to improve the situation as long as the coach Kerr set a powerful strategy and all players do as well as usual. Plus, with <NAME>’s return, the Warriors have an even higher possibility to win the championship. In the recent Warriors and Nuggets game, the Warriors created the record of 51-point first quarter and a 142-111 victory at the end. In general, the chances of the Warriors winning this season are great, but it also depends on the Warriors performance in the playoffs. The result gained from past data can only be an estimation or a prediction but can’t be a conclusion since the situation changes in every game. We can never jump to the conclusion before collecting all the data. Do you think the GSW could win the champion again? Who is the MVP in your mind? Let’s stay focus on the Warriors’ performance together! Good luck, Warriors! - references: <https://github.com/ucb-stat133/stat133-hws> <https://www.basketball-reference.com/teams/GSW/2019.html> <https://www.basketball-reference.com/players/c/curryst01.html> <https://www.basketball-reference.com/players/t/thompkl01.html> <https://www.basketball-reference.com/players/i/iguodan01.html> <https://www.basketball-reference.com/players/d/duranke01.html> <https://www.basketball-reference.com/players/g/greendr01.html> <file_sep>* `period:` an NBA game is divided in 4 periods of 12 mins each. For example, a value for `period = 1` refers to the first period(the first 12 mins of the game). * `minutes_remaining` and `seconds_remaining` have to do with the amount of time in minutes and seconds, respectively, that remained to be played in a givin period. * `shot_made_flag` indicates whether a shot was made (y) or missed (n). * `action_type` has to do with the basketball moves used by players, either to pass by defenders to gain access to the basket, or to get a clean pass to a teammate to score a two pointer or three pointer. * `shot_type` indicates whether a shot is a 2-point field goal, or a 3-point field goal. * `shot_distance:` distance to the basket(measured in feet). * `x` and `y` refer to the court coordinates (measured in inches) where a shot occurred.
e26f5924c22e7536d83d51ac3219a9ce4af16483
[ "Markdown", "R", "RMarkdown" ]
13
R
stat133-sp19/hw-stat133-xihuanzhang
a2bf17ccc8b8136ddde7858927dcef6d5d639269
1cd3e35a8a7be73f2174296c3c04dc07dbfb84d4
refs/heads/main
<repo_name>ariespirgel/vized<file_sep>/R/download-ipeds-files.R ipeds_download <- function(filename) { if (!file.exists(paste0("data-raw/", tolower(filename), ".csv"))) { download.file( paste0("https://nces.ed.gov/ipeds/datacenter/data/", filename, ".zip"), paste0("data-raw/", filename, ".zip") ) unzip(paste0("data-raw/", filename, ".zip"), exdir = "data-raw") # unzips unlink(paste0("data-raw/", filename, ".zip")) # removes zip file # if there is a revised and unrevised file, this keeps only the revised if (file.exists(paste0("data-raw/", tolower(filename), ".csv")) & file.exists(paste0("data-raw/", tolower(filename), "_rv.csv"))) { unlink(paste0("data-raw/", tolower(filename), ".csv")) } } else { print("File already exists!") } } <file_sep>/README.md # vized vized R package This package contains cleaned and formatted datasets from the IPEDS Data Center. This collection of datasets is used to teach the Data Visualization and Transformation in R workshop. <file_sep>/data-raw/ipeds-admissions.R library(tidyverse) download_years <- as.character(2018) for (i in download_years) { ipeds_download(paste0("ADM", i)) } admit_files <- fs::dir_ls("data-raw", regex = "adm2.*\\.csv$") ipeds_admissions <- admit_files %>% map_dfr(read_csv, .id = "year") %>% mutate(year = str_extract(year, "[[:digit:]]+")) ipeds_admissions <- ipeds_admissions %>% select(unit_id = UNITID, year, applicants_total = APPLCN, admissions_total = ADMSSN, enrolled_total = ENRLT, sat_submitted_n = SATNUM, # act_submitted_n = ACTNUM, sat_ebrw_25th = SATVR25, sat_ebrw_75th = SATVR75, sat_math_25th = SATMT25, sat_math_75th = SATMT75 # act_composite_25th = ACTCM25, # act_composite_75th = ACTCM75, # act_english_25th = ACTEN25, # act_english_75th = ACTEN75, # act_math_25th = ACTMT25, # act_math_75th = ACTMT75 ) load("~/Desktop/vized/R/sysdata.rda") ipeds_admissions <- inner_join(ipeds_admissions, ipeds_directory) %>% select(unit_id, institution_name, year, sector_description, state_description, latitude, longitude, everything()) ipeds_sat <- ipeds_admissions %>% filter(year == "2018") %>% select(unit_id, institution_name, sat_ebrw_25th:sat_math_75th) %>% pivot_longer(cols = contains("sat"), names_to = "test", values_to = "score") %>% mutate(percentile = paste0(parse_number(test), "th"), test = str_sub(test, start = 1, end = 8)) %>% select(unit_id:test, percentile, score) %>% spread(test, score) usethis::use_data(ipeds_sat, overwrite = TRUE) ivy_plus_unit_ids <- c(110635, 217156, 144050, 190150, 190415, 166027, 166683, 215062, 186131, 243744, 130794) ipeds_funnel <- ipeds_admissions %>% filter(year == "2018") %>% mutate(ivy_plus_exchange = if_else(unit_id %in% ivy_plus_unit_ids, "IvyPlus Exchange", "Other")) %>% select(unit_id, institution_name, sector_description, state_description, ivy_plus_exchange, applicants_total, admitted_total = admissions_total, enrolled_total) %>% mutate(admit_rate = round(admitted_total / applicants_total, digits = 4), yield_rate = round(enrolled_total / admitted_total, digits = 4)) %>% filter(sector_description %in% c("Public, 4-year or above", "Private not-for-profit, 4-year or above")) usethis::use_data(ipeds_funnel, overwrite = TRUE) <file_sep>/data-raw/ipeds-distance.R library(tidyverse) download_years <- as.character(c(2016:2018)) for (i in download_years) { ipeds_download(paste0("EF", i, "A_DIST")) } distance_files <- fs::dir_ls("data-raw", regex = "ef2.*\\.csv$") ipeds_distance <- distance_files %>% map_dfr(read_csv, .id = "year") %>% mutate(year = str_extract(year, "[[:digit:]]+")) ipeds_distance <- ipeds_distance %>% mutate(level = case_when( EFDELEV == 2 ~ "undergraduate", EFDELEV == 12 ~ "graduate" ), year = as.integer(year)) %>% select(unit_id = UNITID, year, level, all_distance = EFDEEXC, some_distance = EFDESOM, no_distance = EFDENON) %>% drop_na(level) %>% pivot_longer(all_distance:no_distance, names_to = "distance_type", values_to = "headcount") %>% drop_na(headcount) load("~/Desktop/vized/R/sysdata.rda") ipeds_distance <- inner_join( ipeds_directory %>% select(unit_id:sector_description, -year), ipeds_distance ) %>% select(unit_id, institution_name, year, everything()) usethis::use_data(ipeds_distance, overwrite = TRUE) <file_sep>/data-raw/ipeds-dictionary.R library(tidyverse) library(readxl) download_years <- as.character(2018) for (i in download_years) { ipeds_download(paste0("HD", i, "_Dict")) } dictionary_files_list <- fs::dir_ls("data-raw", regexp = "hd20.*\\.xlsx$") ipeds_dictionary <- dictionary_files_list %>% map_dfr(read_excel, sheet = "Frequencies", .id = "year") %>% mutate(year = str_extract(year, "[[:digit:]]+")) # sector ------------------------------------------------------------------ ipeds_sector <- ipeds_dictionary %>% filter(varname == "SECTOR") %>% mutate(codevalue = as.integer(codevalue)) %>% select(sector_code = codevalue, sector_description = valuelabel) usethis::use_data(ipeds_sector, overwrite = TRUE) # state ------------------------------------------------------------------- ipeds_state <- ipeds_dictionary %>% filter(varname == "STABBR") %>% select(state_abbreviation = codevalue, state_description = valuelabel) %>% distinct() usethis::use_data(ipeds_state, overwrite = TRUE) <file_sep>/data-raw/ipeds-salaries.R library(tidyverse) download_years <- as.character(2018) for (i in download_years) { ipeds_download(paste0("SAL", i, "_NIS")) } salary_files <- fs::dir_ls("data-raw", regex = "sal2.*\\.csv$") ipeds_salary <- salary_files %>% map_dfr(read_csv, .id = "year") %>% mutate(year = str_extract(year, "[[:digit:]]+")) %>% select(-starts_with("X")) ipeds_salary <- ipeds_salary %>% pivot_longer(SANIN01:SANIT14, names_to = "type", values_to = "value") %>% mutate(type2 = if_else(str_sub(type, -3, -3) == "N", "headcount", "salary"), occupation = case_when( str_sub(type, -2) == "01" ~ "Total", str_sub(type, -2) == "02" ~ "Research", str_sub(type, -2) == "03" ~ "Public service", str_sub(type, -2) == "04" ~ "Librarians, Curators, Archivists, and Academic Affairs and Other Education Services", str_sub(type, -2) == "05" ~ "Management", str_sub(type, -2) == "06" ~ "Business and Financial Operations", str_sub(type, -2) == "07" ~ "Computer, Engineering, and Science", str_sub(type, -2) == "08" ~ "Community, Social Service, Legal, Arts, Design, Entertainment, Sports and Media", str_sub(type, -2) == "09" ~ "Healthcare Practioners and Technical", str_sub(type, -2) == "10" ~ "Service", str_sub(type, -2) == "11" ~ "Sales and related", str_sub(type, -2) == "12" ~ "Office and Administrative Support", str_sub(type, -2) == "13" ~ "Natural Resources, Construction, and Maintenance", str_sub(type, -2) == "14" ~ "Production, Transportation, and Material Moving" )) %>% filter(occupation != "Total") %>% select(-type, -year) %>% spread(type2, value) %>% rename(unit_id = UNITID) load("~/Desktop/vized/R/sysdata.rda") ipeds_salary <- inner_join( ipeds_directory %>% filter(year == "2018") %>% select(unit_id:state_description, -year), ipeds_salary ) %>% filter(headcount != 0) usethis::use_data(ipeds_salary, overwrite = TRUE) <file_sep>/R/data.R #' @importFrom tibble tibble NULL #' IPEDS Coordinates #' #' Latitude and longitude for IPEDS institutions in the Lower 48 states. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{sector_description}{Sector of institution.} #' \item{state_description}{State of institution.} #' \item{latitude, longitude}{Latitude and longitude of institution.} #' } "ipeds_coordinates" #' IPEDS Directory #' #' IPEDS directory information. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{year}{Year of data.} #' \item{sector_description}{Sector of institution} #' \item{state_description}{State of institution.} #' \item{latitude, longitude}{Latitude and longitude of institution.} #' } "ipeds_directory" #' IPEDS Distance #' #' IPEDS distance education headcounts. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{year}{Year of data.} #' \item{sector_description}{Sector of institution.} #' \item{level}{Student level.} #' \item{distance_type}{No distance, some distance, or all distance.} #' \item{headcount}{Number of students.} #' } "ipeds_distance" #' IPEDS Funnel #' #' IPEDS first-time in college applied, admitted, enrolled data for 4-year #' public and 4-year private not-for-profit schools. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{sector_description}{Sector of institution.} #' \item{state_description}{State of institution.} #' \item{ivy_plus_exchange}{Indicates Ivy League and IvyPlus Exchange schools.} #' \item{applicants_total}{Number of first-time in college applicants.} #' \item{admissions_total}{Number of first-time in college applicants who were admitted.} #' \item{enrolled_total}{Number of first-time in college applicants who enrolled.} #' \item{admit_rate}{The proportion of applicants who were admitted.} #' \item{yield_rate}{The proportion of admits who enrolled.} #' } "ipeds_funnel" #' IPEDS Salary #' #' IPEDS number and salary outlays for full-time nonmedical noninstructional staff by occupation. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{year}{Year of data.} #' \item{sector_description}{Sector of institution.} #' \item{state_description}{State of institution.} #' \item{headcount}{Number of employees.} #' \item{salary}{Total salary.} #' } "ipeds_salary" #' IPEDS Sector #' #' IPEDS sector code and sector description lookup table. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{sector_code, sector_description}{Sector code and sector description.} #' } "ipeds_sector" #' IPEDS State #' #' US state abbreviation and state description lookup table. #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{state_abbreviation, state_description}{State code and state description.} #' } "ipeds_state" #' IPEDS Test Scores #' #' IPEDS SAT scores for first-time in college students #' #' @source IPEDS Data Center, #' <https://nces.ed.gov/ipeds/datacenter/DataFiles.aspx?goToReportId=7> #' @format Data frame with columns #' \describe{ #' \item{unit_id}{IPEDS unit ID number.} #' \item{institution_name}{Name of school.} #' \item{percentile}{SAT score percentile.} #' \item{sat_ebrw}{SAT Evidenced Based Reading score.} #' \item{sat_math}{SAT Math score.} #' } "ipeds_sat" <file_sep>/data-raw/ipeds-directory.R library(tidyverse) library(readxl) download_years <- as.character(2018) for (i in download_years) { ipeds_download(paste0("HD", i)) } directory_files_list <- fs::dir_ls("data-raw", regexp = "hd20.*\\.csv$") ipeds_directory <- directory_files_list %>% map_dfr(read_csv, .id = "year") %>% mutate(year = str_extract(year, "[[:digit:]]+")) ipeds_directory <- ipeds_directory %>% select(unit_id = UNITID, institution_name = INSTNM, year, sector_code = SECTOR, state_code = FIPS, state_abbrev = STABBR, longitude = LONGITUD, latitude = LATITUDE) # add descriptions -------------------------------------------------------- load("data/ipeds_sector.rda") load("data/ipeds_state.rda") ipeds_directory <- ipeds_directory %>% inner_join(ipeds_sector) %>% inner_join(ipeds_state %>% rename(state_abbrev = state_abbreviation)) ipeds_directory <- ipeds_directory %>% select(unit_id, institution_name, year, sector_description, state_description, longitude, latitude) usethis::use_data(ipeds_directory, overwrite = TRUE, internal = TRUE) # ipeds coordinates ------------------------------------------------------- non_lower_48 <- c("American Samoa", "Alaska", "Hawaii", "Puerto Rico", "Virgin Islands", "Federated States of Micronesia", "Guam", "Marshall Islands", "Northern Marianas", "Palau") ipeds_coordinates <- ipeds_directory %>% filter(year == "2018") %>% select(unit_id, institution_name, sector_description, state_description, latitude, longitude) %>% filter(!state_description %in% non_lower_48) usethis::use_data(ipeds_coordinates, overwrite = TRUE)
f0ec3ae068ddfe95125e8bffa7c2c578dd365ef8
[ "Markdown", "R" ]
8
R
ariespirgel/vized
1ede72c4581d10aeaa3cd6ef0f17f3999a55d9bd
f52664ba61c05082b550f8eb2f312c9473e60d15
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Global : MonoBehaviour { public static int sc; // Use this for initialization void Start () { sc = 0; } // Update is called once per frame void Update () { } }
8ad368747ef073006d7a2dab7ad503f34e382196
[ "C#" ]
1
C#
DevOpHBLICT/Hungry_Hanson
3bf58b652a3fbcff54d20054eb941152e6e8ea18
f1b11445b62b2301bf9478015cea2d38d7256676
refs/heads/main
<repo_name>renanetec/MilhasParaKm<file_sep>/Program.cs using System; namespace milhasparakm { class Program { static void Main(string[] args) { Console.Clear(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("conversor de milhas em km"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Red; double milhas = 2; //escolha 1 numero para milhas //salve usando o comando CTRL + S no teclado double km = 1.609; //lembrando que 1 milha é igual a 1.609 km double doublemutiplicacao = milhas * km; Console.WriteLine($"{milhas} * {km} = {doublemutiplicacao} km\n"); Console.ResetColor(); //no terminal use o comando dotnet run } } }
7766c4c6037f2ec48f63a29ee06ef6e047308cac
[ "C#" ]
1
C#
renanetec/MilhasParaKm
69cd245693660ed8d0ec61f9bb747b6e6164803f
19aea1ad5746f6ad2f99c51a4ba5a04f593ceedf
refs/heads/master
<repo_name>rajatmore13/Roger---The-Angularbot<file_sep>/src/app/chat/chat-dialog/chat-dialog.component.ts import { Component, OnInit } from '@angular/core'; import { ChatService,Message } from '../chat.service'; import { Observable } from 'rxjs'; import { scan } from 'rxjs/operators'; import { AuthService } from '../../core/auth.service'; import { Location } from '@angular/common'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'chat-dialog', templateUrl: './chat-dialog.component.html', styleUrls: ['./chat-dialog.component.css'] }) export class ChatDialogComponent implements OnInit { messages: Observable<Message[]>; formValue: string; constructor(private chat:ChatService, public authService: AuthService,private location : Location) { } ngOnInit() { this.messages = this.chat.conversation.asObservable() .pipe(scan((acc, val) => acc.concat(val) )); } sendMessage(){ this.chat.converse(this.formValue); this.formValue=''; } logout(){ this.authService.doLogout() .then((res) => { this.location.back(); }, (error) => { console.log("Logout error", error); }); } }
2b07abdaca26084c00b5a10b7820f3ce92820fca
[ "TypeScript" ]
1
TypeScript
rajatmore13/Roger---The-Angularbot
e65cb751ccc05b0d5489cd803141a7064d1fe040
665c8cca2be36fd91e22d8838d5d5afa117a8a8b
refs/heads/main
<repo_name>Kaihua-Chen/URP-Application-of-IoT-in-Agriculture<file_sep>/Hardware Part (using Arduino)/DHT11_BH1750_spg_data.ino #include <Wire.h> #include "Adafruit_SGP30.h" #include "DHT.h" Adafruit_SGP30 sgp; //#define ADDRESS_BH1750FVI 0x23 //ADDR="L" for this module //#define ONE_TIME_H_RESOLUTION_MODE 0x20 #define DHTPIN 8 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); #define ADDRESS_BH1750FVI 0x23 //ADDR="L" for this module #define ONE_TIME_H_RESOLUTION_MODE 0x20 byte highByte = 0; byte lowByte = 0; unsigned int sensorOut = 0; unsigned int illuminance = 0; void setup() { Wire.begin(); Serial.begin(9600); while (!Serial) { delay(10); } // Wait for serial console to open! // Serial.println("Test Begin~"); dht.begin(); if (! sgp.begin()){ // Serial.println("Sensor not found :("); // while (1); } // Serial.print("Found SGP30 serial #"); // Serial.print(sgp.serialnumber[0], HEX); // Serial.print(sgp.serialnumber[1], HEX); // Serial.println(sgp.serialnumber[2], HEX); // If you have a baseline measurement from before you can assign it to start, to 'self-calibrate' //sgp.setIAQBaseline(0x8E68, 0x8F41); // Will vary for each sensor! } int counter = 0; void loop() { Wire.beginTransmission(ADDRESS_BH1750FVI); //"notify" the matching device Wire.write(ONE_TIME_H_RESOLUTION_MODE); //set operation mode Wire.endTransmission(); delay(180); Wire.requestFrom(ADDRESS_BH1750FVI, 2); //ask Arduino to read back 2 bytes from the sensor highByte = Wire.read(); // get the high byte lowByte = Wire.read(); // get the low byte sensorOut = (highByte<<8)|lowByte; illuminance = sensorOut/1.2; //BH1750数据输出 // Serial.print("Illum: "); Serial.print(illuminance); Serial.print(" "); // Serial.println(" lux"); //DHT11数据输出 float hum = dht.readHumidity(); //将湿度值赋给hum // Serial.print("Hum:"); Serial.print(hum); Serial.print(" "); // Serial.print("%/t"); float tem = dht.readTemperature(); //将湿度值赋给tem // Serial.print(" Temp:"); Serial.print(tem); Serial.print(" "); // Serial.println("*C"); if (! sgp.IAQmeasure()) { // Serial.println("Measurement failed"); return; } // Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.print(" "); // Serial.print(" ppb\t"); // Serial.print("eCO2 "); Serial.print(sgp.eCO2); Serial.print(" "); // Serial.println(" ppm"); if (! sgp.IAQmeasureRaw()) { // Serial.println("Raw Measurement failed"); return; } // Serial.print("Raw H2 "); Serial.print(sgp.rawH2); Serial.print(" "); // Serial.print(" \t"); // Serial.print("Raw Ethanol "); Serial.println(sgp.rawEthanol); // Serial.println(""); // Serial.println("---------------------------------"); delay(1000); // counter++; // if (counter == 30) { // counter = 0; // uint16_t TVOC_base, eCO2_base; // if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) { // Serial.println("Failed to get baseline readings"); // return; // } // Serial.print("****Baseline values: eCO2: 0x"); Serial.print(eCO2_base, HEX); // Serial.print(" & TVOC: 0x"); Serial.println(TVOC_base, HEX); // } } <file_sep>/GUI Part (Using PyQt)/demo1.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'demo1.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_URPMainWindow(object): def setupUi(self, URPMainWindow): URPMainWindow.setObjectName("URPMainWindow") URPMainWindow.resize(1289, 725) self.centralwidget = QtWidgets.QWidget(URPMainWindow) self.centralwidget.setObjectName("centralwidget") self.splitter = QtWidgets.QSplitter(self.centralwidget) self.splitter.setGeometry(QtCore.QRect(390, 20, 881, 681)) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.tabWidget = QtWidgets.QTabWidget(self.splitter) self.tabWidget.setEnabled(True) self.tabWidget.setStyleSheet("QTabBar::tab{width:100;height:30}\n" "QTabBar::tab{font: 75 10pt \"等线\"}\n" "") self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded) self.tabWidget.setUsesScrollButtons(True) self.tabWidget.setDocumentMode(False) self.tabWidget.setTabsClosable(False) self.tabWidget.setTabBarAutoHide(False) self.tabWidget.setObjectName("tabWidget") self.tab_illum = QtWidgets.QWidget() self.tab_illum.setObjectName("tab_illum") self.tab_illum_label1 = QtWidgets.QLabel(self.tab_illum) self.tab_illum_label1.setGeometry(QtCore.QRect(-30, 40, 881, 281)) self.tab_illum_label1.setText("") self.tab_illum_label1.setObjectName("tab_illum_label1") self.tab_illum_label2 = QtWidgets.QLabel(self.tab_illum) self.tab_illum_label2.setGeometry(QtCore.QRect(20, 360, 411, 281)) self.tab_illum_label2.setText("") self.tab_illum_label2.setObjectName("tab_illum_label2") self.tab_illum_label3 = QtWidgets.QLabel(self.tab_illum) self.tab_illum_label3.setGeometry(QtCore.QRect(410, 330, 471, 311)) self.tab_illum_label3.setText("") self.tab_illum_label3.setObjectName("tab_illum_label3") self.illum_title_label_1 = QtWidgets.QLabel(self.tab_illum) self.illum_title_label_1.setGeometry(QtCore.QRect(20, 10, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.illum_title_label_1.setFont(font) self.illum_title_label_1.setObjectName("illum_title_label_1") self.illum_title_label_2 = QtWidgets.QLabel(self.tab_illum) self.illum_title_label_2.setGeometry(QtCore.QRect(20, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.illum_title_label_2.setFont(font) self.illum_title_label_2.setObjectName("illum_title_label_2") self.illum_title_label_3 = QtWidgets.QLabel(self.tab_illum) self.illum_title_label_3.setGeometry(QtCore.QRect(460, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.illum_title_label_3.setFont(font) self.illum_title_label_3.setObjectName("illum_title_label_3") self.tabWidget.addTab(self.tab_illum, "") self.tab_hum = QtWidgets.QWidget() self.tab_hum.setObjectName("tab_hum") self.tab_hum_label1 = QtWidgets.QLabel(self.tab_hum) self.tab_hum_label1.setGeometry(QtCore.QRect(-30, 40, 881, 281)) self.tab_hum_label1.setText("") self.tab_hum_label1.setObjectName("tab_hum_label1") self.hum_title_label_1 = QtWidgets.QLabel(self.tab_hum) self.hum_title_label_1.setGeometry(QtCore.QRect(20, 10, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.hum_title_label_1.setFont(font) self.hum_title_label_1.setObjectName("hum_title_label_1") self.hum_title_label_2 = QtWidgets.QLabel(self.tab_hum) self.hum_title_label_2.setGeometry(QtCore.QRect(20, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.hum_title_label_2.setFont(font) self.hum_title_label_2.setObjectName("hum_title_label_2") self.tab_hum_label2 = QtWidgets.QLabel(self.tab_hum) self.tab_hum_label2.setGeometry(QtCore.QRect(20, 360, 411, 281)) self.tab_hum_label2.setText("") self.tab_hum_label2.setObjectName("tab_hum_label2") self.tab_hum_label3 = QtWidgets.QLabel(self.tab_hum) self.tab_hum_label3.setGeometry(QtCore.QRect(410, 330, 471, 311)) self.tab_hum_label3.setText("") self.tab_hum_label3.setObjectName("tab_hum_label3") self.hum_title_label_4 = QtWidgets.QLabel(self.tab_hum) self.hum_title_label_4.setGeometry(QtCore.QRect(460, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.hum_title_label_4.setFont(font) self.hum_title_label_4.setObjectName("hum_title_label_4") self.tabWidget.addTab(self.tab_hum, "") self.tab_temp = QtWidgets.QWidget() self.tab_temp.setObjectName("tab_temp") self.tab_temp_label1 = QtWidgets.QLabel(self.tab_temp) self.tab_temp_label1.setGeometry(QtCore.QRect(-30, 40, 881, 281)) self.tab_temp_label1.setText("") self.tab_temp_label1.setObjectName("tab_temp_label1") self.tab_temp_label3 = QtWidgets.QLabel(self.tab_temp) self.tab_temp_label3.setGeometry(QtCore.QRect(410, 330, 471, 311)) self.tab_temp_label3.setText("") self.tab_temp_label3.setObjectName("tab_temp_label3") self.tab_temp_label2 = QtWidgets.QLabel(self.tab_temp) self.tab_temp_label2.setGeometry(QtCore.QRect(20, 360, 411, 281)) self.tab_temp_label2.setText("") self.tab_temp_label2.setObjectName("tab_temp_label2") self.temp_title_label_1 = QtWidgets.QLabel(self.tab_temp) self.temp_title_label_1.setGeometry(QtCore.QRect(20, 10, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.temp_title_label_1.setFont(font) self.temp_title_label_1.setObjectName("temp_title_label_1") self.temp_title_label_2 = QtWidgets.QLabel(self.tab_temp) self.temp_title_label_2.setGeometry(QtCore.QRect(20, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.temp_title_label_2.setFont(font) self.temp_title_label_2.setObjectName("temp_title_label_2") self.temp_title_label_3 = QtWidgets.QLabel(self.tab_temp) self.temp_title_label_3.setGeometry(QtCore.QRect(460, 330, 131, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.temp_title_label_3.setFont(font) self.temp_title_label_3.setObjectName("temp_title_label_3") self.tabWidget.addTab(self.tab_temp, "") self.tab_co2 = QtWidgets.QWidget() self.tab_co2.setObjectName("tab_co2") self.tab_co2_label2 = QtWidgets.QLabel(self.tab_co2) self.tab_co2_label2.setGeometry(QtCore.QRect(20, 360, 411, 281)) self.tab_co2_label2.setText("") self.tab_co2_label2.setObjectName("tab_co2_label2") self.tab_co2_label3 = QtWidgets.QLabel(self.tab_co2) self.tab_co2_label3.setGeometry(QtCore.QRect(410, 330, 471, 311)) self.tab_co2_label3.setText("") self.tab_co2_label3.setObjectName("tab_co2_label3") self.co2_title_label_1 = QtWidgets.QLabel(self.tab_co2) self.co2_title_label_1.setGeometry(QtCore.QRect(20, 330, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.co2_title_label_1.setFont(font) self.co2_title_label_1.setObjectName("co2_title_label_1") self.tab_co2_label1 = QtWidgets.QLabel(self.tab_co2) self.tab_co2_label1.setGeometry(QtCore.QRect(-30, 40, 881, 281)) self.tab_co2_label1.setText("") self.tab_co2_label1.setObjectName("tab_co2_label1") self.co2_title_label_2 = QtWidgets.QLabel(self.tab_co2) self.co2_title_label_2.setGeometry(QtCore.QRect(460, 330, 171, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.co2_title_label_2.setFont(font) self.co2_title_label_2.setObjectName("co2_title_label_2") self.co2_title_label_3 = QtWidgets.QLabel(self.tab_co2) self.co2_title_label_3.setGeometry(QtCore.QRect(20, 10, 241, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.co2_title_label_3.setFont(font) self.co2_title_label_3.setObjectName("co2_title_label_3") self.tabWidget.addTab(self.tab_co2, "") self.frame = QtWidgets.QFrame(self.centralwidget) self.frame.setGeometry(QtCore.QRect(10, 20, 371, 681)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.groupBox_currentState = QtWidgets.QGroupBox(self.frame) self.groupBox_currentState.setEnabled(True) self.groupBox_currentState.setGeometry(QtCore.QRect(10, 10, 351, 261)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.groupBox_currentState.setFont(font) self.groupBox_currentState.setObjectName("groupBox_currentState") self.groupBox_illum = QtWidgets.QGroupBox(self.groupBox_currentState) self.groupBox_illum.setGeometry(QtCore.QRect(30, 40, 131, 91)) font = QtGui.QFont() font.setFamily("等线") font.setPointSize(10) font.setBold(True) font.setWeight(75) font.setKerning(True) self.groupBox_illum.setFont(font) self.groupBox_illum.setObjectName("groupBox_illum") self.label_illum = QtWidgets.QLabel(self.groupBox_illum) self.label_illum.setGeometry(QtCore.QRect(10, 30, 111, 51)) self.label_illum.setTextFormat(QtCore.Qt.AutoText) self.label_illum.setObjectName("label_illum") self.groupBox_hum = QtWidgets.QGroupBox(self.groupBox_currentState) self.groupBox_hum.setGeometry(QtCore.QRect(190, 40, 131, 91)) font = QtGui.QFont() font.setFamily("等线") font.setBold(True) font.setWeight(75) self.groupBox_hum.setFont(font) self.groupBox_hum.setObjectName("groupBox_hum") self.label_hum = QtWidgets.QLabel(self.groupBox_hum) self.label_hum.setGeometry(QtCore.QRect(10, 30, 111, 51)) self.label_hum.setTextFormat(QtCore.Qt.AutoText) self.label_hum.setObjectName("label_hum") self.groupBox_temp = QtWidgets.QGroupBox(self.groupBox_currentState) self.groupBox_temp.setGeometry(QtCore.QRect(30, 150, 131, 91)) font = QtGui.QFont() font.setFamily("等线") font.setPointSize(10) font.setBold(True) font.setWeight(75) font.setKerning(True) self.groupBox_temp.setFont(font) self.groupBox_temp.setObjectName("groupBox_temp") self.label_temp = QtWidgets.QLabel(self.groupBox_temp) self.label_temp.setGeometry(QtCore.QRect(10, 30, 111, 51)) self.label_temp.setTextFormat(QtCore.Qt.AutoText) self.label_temp.setObjectName("label_temp") self.groupBox_co2 = QtWidgets.QGroupBox(self.groupBox_currentState) self.groupBox_co2.setGeometry(QtCore.QRect(190, 150, 131, 91)) font = QtGui.QFont() font.setFamily("等线") font.setPointSize(10) font.setBold(True) font.setWeight(75) font.setKerning(True) self.groupBox_co2.setFont(font) self.groupBox_co2.setObjectName("groupBox_co2") self.label_co2 = QtWidgets.QLabel(self.groupBox_co2) self.label_co2.setGeometry(QtCore.QRect(10, 30, 111, 51)) self.label_co2.setTextFormat(QtCore.Qt.AutoText) self.label_co2.setObjectName("label_co2") self.groupBox_Tools = QtWidgets.QGroupBox(self.frame) self.groupBox_Tools.setGeometry(QtCore.QRect(10, 290, 351, 151)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.groupBox_Tools.setFont(font) self.groupBox_Tools.setObjectName("groupBox_Tools") self.pushButton_water = QtWidgets.QPushButton(self.groupBox_Tools) self.pushButton_water.setGeometry(QtCore.QRect(30, 30, 131, 111)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.pushButton_water.setFont(font) self.pushButton_water.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) self.pushButton_water.setAutoFillBackground(False) self.pushButton_water.setStyleSheet("") self.pushButton_water.setFlat(False) self.pushButton_water.setObjectName("pushButton_water") self.pushButton_light = QtWidgets.QPushButton(self.groupBox_Tools) self.pushButton_light.setGeometry(QtCore.QRect(190, 30, 131, 111)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.pushButton_light.setFont(font) self.pushButton_light.setStyleSheet("") self.pushButton_light.setFlat(False) self.pushButton_light.setObjectName("pushButton_light") URPMainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(URPMainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1289, 26)) self.menubar.setObjectName("menubar") URPMainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(URPMainWindow) self.statusbar.setObjectName("statusbar") URPMainWindow.setStatusBar(self.statusbar) self.retranslateUi(URPMainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(URPMainWindow) def retranslateUi(self, URPMainWindow): _translate = QtCore.QCoreApplication.translate URPMainWindow.setWindowTitle(_translate("URPMainWindow", "MainWindow")) self.illum_title_label_1.setText(_translate("URPMainWindow", "近24h光照变化:")) self.illum_title_label_2.setText(_translate("URPMainWindow", "近7天光照平均值变化:")) self.illum_title_label_3.setText(_translate("URPMainWindow", "近24h光照分析:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_illum), _translate("URPMainWindow", "光照")) self.hum_title_label_1.setText(_translate("URPMainWindow", "近24h湿度变化:")) self.hum_title_label_2.setText(_translate("URPMainWindow", "近7天湿度平均值变化:")) self.hum_title_label_4.setText(_translate("URPMainWindow", "近24h湿度分析:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_hum), _translate("URPMainWindow", "湿度")) self.temp_title_label_1.setText(_translate("URPMainWindow", "近24h温度变化:")) self.temp_title_label_2.setText(_translate("URPMainWindow", "近7天温度平均值变化:")) self.temp_title_label_3.setText(_translate("URPMainWindow", "近24h温度分析:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_temp), _translate("URPMainWindow", "温度")) self.co2_title_label_1.setText(_translate("URPMainWindow", "近7天二氧化碳平均值变化:")) self.co2_title_label_2.setText(_translate("URPMainWindow", "近24h二氧化碳分析:")) self.co2_title_label_3.setText(_translate("URPMainWindow", "近24h二氧化碳变化:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_co2), _translate("URPMainWindow", "二氧化碳")) self.groupBox_currentState.setTitle(_translate("URPMainWindow", "Current State")) self.groupBox_illum.setTitle(_translate("URPMainWindow", "光照/lux")) self.label_illum.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Arial\'; font-size:20pt; color:#55aaff;\">NULL</span></p></body></html>")) self.groupBox_hum.setTitle(_translate("URPMainWindow", "湿度/%")) self.label_hum.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Arial\'; font-size:20pt; color:#55aaff;\">NULL</span></p></body></html>")) self.groupBox_temp.setTitle(_translate("URPMainWindow", "温度/℃")) self.label_temp.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Arial\'; font-size:20pt; color:#55aaff;\">NULL</span></p></body></html>")) self.groupBox_co2.setTitle(_translate("URPMainWindow", "二氧化碳/ppm")) self.label_co2.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Arial\'; font-size:20pt; color:#55aaff;\">NULL</span></p></body></html>")) self.groupBox_Tools.setTitle(_translate("URPMainWindow", "Tools")) self.pushButton_water.setText(_translate("URPMainWindow", "Booster Light")) self.pushButton_light.setText(_translate("URPMainWindow", "Watering")) import test_rc <file_sep>/GUI Part (Using PyQt)/README.md ### 2021.1.23说明 对该文件夹的部分说明: * appMain2.py为拓展界面并打开界面的主文件 * demo1.py由demo1.ui生成,为GUI初始文件 * test_rc.py无任何实质意义,其仅使得demo1.py得以正常运行而不报错 * test.db为数据库文件,当前已存储部分实例数据(为真实环境测得),相关程序可调用数据库并进行数据分析、数据展示等 ------------------------------------------------------------------------------------------- ### 2021.2.15说明 做出了以下改进: * 新增两个功能按钮,尚未置入功能 * 数据显示方式作出改进,使得每个页面可以统计三种类型的数据(曲线、柱状、饼状),暂时均为概念图 * 暂时取消了注释,并删除了之前文件,设立了新的文件夹 <file_sep>/Hardware Part (using Arduino)/README.md 2021.2.15说明: * 上传Arduino代码,使用Arduino IDE可以运行,实时获取Arduino数据 * 目前尚未进一步改进,仅能获得光照、湿度、温度、二氧化碳这四项目标数据(其余有机物数据非目标) * 目前期望增加反馈功能 <file_sep>/GUI Part (Using PyQt)/appMain2.py import sys from PyQt5 import QtCore from PyQt5.QtCore import pyqtSlot, QThread, QObject, QDateTime, QTimer, pyqtSignal from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout from demo1 import Ui_URPMainWindow import serial import time import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib.style as mplStyle import sqlite3 class BackendThread(QThread): serial_data = pyqtSignal(str) def __init__(self): super(BackendThread, self).__init__() def __del__(self): self.wait() def run(self): # ser = serial.Serial('com7', 9600) k = 0 while True: try: if k == 0: ser = serial.Serial('com10', 9600) if ser.isOpen(): print("open serial successfully") data = ser.readline() data = data.decode() data = data.strip("\r\n").split(" ") dataf = [float(x) for x in data] s_data = str(dataf[0]) + " " + str(dataf[1]) + " " + str(dataf[2]) + " " + str(dataf[4]) k = 1 else: print("can't open serial") s_data = "NULL NULL NULL NULL" k = 0 except: print("There is no serial!") s_data = "NULL NULL NULL NULL" k = 0 print(s_data) self.serial_data.emit(s_data) time.sleep(0.1) class Canvas_illum(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) self.axes.plot(datax_2, datay, linewidth = 2, marker = 'o', color = 'mediumturquoise') # self.axes.set_xlabel('X(m)') # self.axes.set_ylabel('lux') self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) # self.axes.spines['bottom'].set_visible(False) # self.axes.spines['left'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.set_ylim(min(datay)-0.05,max(datay)+0.05) self.axes.grid(axis="y",c = "lightsteelblue",alpha = 0.5, linewidth = 1.5) self.axes.tick_params(labelsize='small', colors = 'darkcyan') # self.axes.set_ylim([0, 300]) self.fig.tight_layout() self.draw() class Canvas_illum2(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) # self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.bar(datax_2, datay,color = 'mediumturquoise') for x,y in zip(datax_2,datay): self.axes.text(x, y, '%.1f' % float(y), ha='center',va='bottom', color = 'darkcyan' ) self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.tick_params(colors='darkcyan') # self.axes.set_title('Illumination in 7 Days') self.fig.tight_layout() self.draw() class Canvas_illum3(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) low = 0 mid = 0 high = 0 for i in range(len(datay)): if datay[i]<25: low = low+1 elif datay[i]<27: mid = mid+1 else: high = high+1 values = [low,mid,high] explode = [0.01, 0.01, 0.01] label = ['low','mid','high'] self.axes.pie(values, radius = 1, wedgeprops=dict(width=0.4,edgecolor='w'),explode=explode,colors = ['lightskyblue','mediumspringgreen','coral'],labels = label, autopct='%1.1f%%') # 绘制饼图 # self.axes.set_title("Statistics") self.fig.tight_layout() self.draw() class Canvas_hum(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1, 1, 1, label="plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3] + "/" + datax_1[i][4]) self.axes.plot(datax_2, datay, linewidth=2, marker='o', color='mediumturquoise') # self.axes.set_xlabel('X(m)') # self.axes.set_ylabel('%') self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) # self.axes.spines['bottom'].set_visible(False) # self.axes.spines['left'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.set_ylim(min(datay) - 0.05, max(datay) + 0.05) self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.tick_params(labelsize='small', colors='darkcyan') # self.axes.set_ylim([0, 300]) self.fig.tight_layout() self.draw() class Canvas_hum2(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) # self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.bar(datax_2, datay,color = 'mediumturquoise') for x,y in zip(datax_2,datay): self.axes.text(x, y, '%.1f' % float(y), ha='center',va='bottom', color = 'darkcyan' ) self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.tick_params(colors='darkcyan') # self.axes.set_title('Illumination in 7 Days') self.fig.tight_layout() self.draw() class Canvas_hum3(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) low = 0 mid = 0 high = 0 for i in range(len(datay)): if datay[i]<25: low = low+1 elif datay[i]<27: mid = mid+1 else: high = high+1 values = [low,mid,high] explode = [0.01, 0.01, 0.01] label = ['low','mid','high'] self.axes.pie(values, radius = 1, wedgeprops=dict(width=0.4,edgecolor='w'),explode=explode,colors = ['lightskyblue','mediumspringgreen','coral'],labels = label, autopct='%1.1f%%') # 绘制饼图 # self.axes.set_title("Statistics") self.fig.tight_layout() self.draw() class Canvas_temp(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1, 1, 1, label="plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3] + "/" + datax_1[i][4]) self.axes.plot(datax_2, datay, linewidth=2, marker='o', color='mediumturquoise') # self.axes.set_xlabel('X(m)') # self.axes.set_ylabel('℃') self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) # self.axes.spines['bottom'].set_visible(False) # self.axes.spines['left'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.set_ylim(min(datay) - 0.05, max(datay) + 0.05) self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.tick_params(labelsize='small', colors='darkcyan') # self.axes.set_ylim([0, 300]) self.fig.tight_layout() self.draw() class Canvas_temp2(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) # self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.bar(datax_2, datay,color = 'mediumturquoise') for x,y in zip(datax_2,datay): self.axes.text(x, y, '%.1f' % float(y), ha='center',va='bottom', color = 'darkcyan' ) self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.tick_params(colors='darkcyan') # self.axes.set_title('Illumination in 7 Days') self.fig.tight_layout() self.draw() class Canvas_temp3(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) low = 0 mid = 0 high = 0 for i in range(len(datay)): if datay[i]<25: low = low+1 elif datay[i]<27: mid = mid+1 else: high = high+1 values = [low,mid,high] explode = [0.01, 0.01, 0.01] label = ['low','mid','high'] self.axes.pie(values, radius = 1, wedgeprops=dict(width=0.4,edgecolor='w'),explode=explode,colors = ['lightskyblue','mediumspringgreen','coral'],labels = label, autopct='%1.1f%%') # 绘制饼图 # self.axes.set_title("Statistics") self.fig.tight_layout() self.draw() class Canvas_co2(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1, 1, 1, label="plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3] + "/" + datax_1[i][4]) self.axes.plot(datax_2, datay, linewidth=2, marker='o', color='mediumturquoise') # self.axes.set_xlabel('X(m)') # self.axes.set_ylabel('ppm') self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) # self.axes.spines['bottom'].set_visible(False) # self.axes.spines['left'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.set_ylim(min(datay) - 0.05, max(datay) + 0.05) self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.tick_params(labelsize='small', colors='darkcyan') # self.axes.set_ylim([0, 300]) self.fig.tight_layout() self.draw() class Canvas_co22(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) # self.axes.grid(axis="y", c="lightsteelblue", alpha=0.5, linewidth=1.5) self.axes.bar(datax_2, datay,color = 'mediumturquoise') for x,y in zip(datax_2,datay): self.axes.text(x, y, '%.1f' % float(y), ha='center',va='bottom', color = 'darkcyan' ) self.axes.spines['right'].set_visible(False) self.axes.spines['top'].set_visible(False) self.axes.spines['bottom'].set_color('lightsteelblue') self.axes.spines['bottom'].set_alpha(0.7) self.axes.spines['bottom'].set_linewidth(1.5) self.axes.spines['left'].set_color('lightsteelblue') self.axes.spines['left'].set_alpha(0.7) self.axes.spines['left'].set_linewidth(1.5) self.axes.tick_params(colors='darkcyan') # self.axes.set_title('Illumination in 7 Days') self.fig.tight_layout() self.draw() class Canvas_co23(FigureCanvas): def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.axes = self.fig.add_subplot(1,1,1,label = "plot1") def draw_1(self, datax, datay): datax_1 = [] datax_2 = [] for i in range(len(datax)): datax_1.append(datax[i].split("/")) for i in range(len(datax_1)): datax_2.append(datax_1[i][3]+"/"+datax_1[i][4]) low = 0 mid = 0 high = 0 for i in range(len(datay)): if datay[i]<25: low = low+1 elif datay[i]<27: mid = mid+1 else: high = high+1 values = [low,mid,high] explode = [0.01, 0.01, 0.01] label = ['low','mid','high'] self.axes.pie(values, radius = 1, wedgeprops=dict(width=0.4,edgecolor='w'),explode=explode,colors = ['lightskyblue','mediumspringgreen','coral'],labels = label, autopct='%1.1f%%') # 绘制饼图 # self.axes.set_title("Statistics") self.fig.tight_layout() self.draw() class QmyMainWindow(QMainWindow): def __init__(self,parent=None): super().__init__(parent) self.ui = Ui_URPMainWindow() self.ui.setupUi(self) self.updateUI() self.query_SqlData() self.set_tab_illum_label1() self.set_tab_illum_label2() self.set_tab_illum_label3() self.set_tab_hum_label1() self.set_tab_hum_label2() self.set_tab_hum_label3() self.set_tab_temp_label1() self.set_tab_temp_label2() self.set_tab_temp_label3() self.set_tab_co2_label1() self.set_tab_co2_label2() self.set_tab_co2_label3() def query_SqlData(self): self.conn = sqlite3.connect('test.db') print("Open database successfully") self.cursor = self.conn.execute("SELECT * from demo") self.sqlData_time = [] self.sqlData_illum = [] self.sqlData_hum = [] self.sqlData_temp = [] self.sqlData_co2 = [] for it in self.cursor: self.sqlData_time.append(it[0]) self.sqlData_illum.append(it[1]) self.sqlData_hum.append(it[2]) self.sqlData_temp.append(it[3]) self.sqlData_co2.append(it[4]) def set_tab_illum_label1(self): self.plot1 = Canvas_illum() self.plot1.draw_1(self.sqlData_time,self.sqlData_illum) layout = QVBoxLayout() layout.addWidget(self.plot1) self.ui.tab_illum_label1.setLayout(layout) self.ui.tab_illum_label1.show() def set_tab_illum_label2(self): self.plot11 = Canvas_illum2() self.plot11.draw_1(self.sqlData_time,self.sqlData_illum) layout = QVBoxLayout() layout.addWidget(self.plot11) self.ui.tab_illum_label2.setLayout(layout) self.ui.tab_illum_label2.show() def set_tab_illum_label3(self): self.plot12 = Canvas_illum3() self.plot12.draw_1(self.sqlData_time,self.sqlData_illum) layout = QVBoxLayout() layout.addWidget(self.plot12) self.ui.tab_illum_label3.setLayout(layout) self.ui.tab_illum_label3.show() def set_tab_hum_label1(self): self.plot2 = Canvas_hum() self.plot2.draw_1(self.sqlData_time, self.sqlData_hum) layout = QVBoxLayout() layout.addWidget(self.plot2) self.ui.tab_hum_label1.setLayout(layout) self.ui.tab_hum_label1.show() def set_tab_hum_label2(self): self.plot21 = Canvas_hum2() self.plot21.draw_1(self.sqlData_time, self.sqlData_hum) layout = QVBoxLayout() layout.addWidget(self.plot21) self.ui.tab_hum_label2.setLayout(layout) self.ui.tab_hum_label2.show() def set_tab_hum_label3(self): self.plot22 = Canvas_hum3() self.plot22.draw_1(self.sqlData_time, self.sqlData_hum) layout = QVBoxLayout() layout.addWidget(self.plot22) self.ui.tab_hum_label3.setLayout(layout) self.ui.tab_hum_label3.show() def set_tab_temp_label1(self): self.plot3 = Canvas_temp() self.plot3.draw_1(self.sqlData_time, self.sqlData_temp) layout = QVBoxLayout() layout.addWidget(self.plot3) self.ui.tab_temp_label1.setLayout(layout) self.ui.tab_temp_label1.show() def set_tab_temp_label2(self): self.plot31 = Canvas_temp2() self.plot31.draw_1(self.sqlData_time, self.sqlData_temp) layout = QVBoxLayout() layout.addWidget(self.plot31) self.ui.tab_temp_label2.setLayout(layout) self.ui.tab_temp_label2.show() def set_tab_temp_label3(self): self.plot32 = Canvas_temp3() self.plot32.draw_1(self.sqlData_time, self.sqlData_temp) layout = QVBoxLayout() layout.addWidget(self.plot32) self.ui.tab_temp_label3.setLayout(layout) self.ui.tab_temp_label3.show() def set_tab_co2_label1(self): self.plot4 = Canvas_co2() self.plot4.draw_1(self.sqlData_time, self.sqlData_co2) layout = QVBoxLayout() layout.addWidget(self.plot4) self.ui.tab_co2_label1.setLayout(layout) self.ui.tab_co2_label1.show() def set_tab_co2_label2(self): self.plot41 = Canvas_co22() self.plot41.draw_1(self.sqlData_time, self.sqlData_co2) layout = QVBoxLayout() layout.addWidget(self.plot41) self.ui.tab_co2_label2.setLayout(layout) self.ui.tab_co2_label2.show() def set_tab_co2_label3(self): self.plot42 = Canvas_co23() self.plot42.draw_1(self.sqlData_time, self.sqlData_co2) layout = QVBoxLayout() layout.addWidget(self.plot42) self.ui.tab_co2_label3.setLayout(layout) self.ui.tab_co2_label3.show() def updateUI(self): self.thread = BackendThread() self.thread.serial_data.connect(self.showData) self.thread.start() def showData(self,s_data): self.Lab = s_data.split(" ") _translate = QtCore.QCoreApplication.translate self.Lab_illum = self.Lab[0] self.Lab_hum = self.Lab[1] self.Lab_temp = self.Lab[2] self.Lab_co2 = self.Lab[3] self.ui.label_illum.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:10pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:20pt; color:#55aaff;\">%s</span></p></body></html>") % self.Lab_illum) self.ui.label_hum.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:10pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:20pt; color:#55aaff;\">%s</span></p></body></html>") % self.Lab_hum) self.ui.label_temp.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:10pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:20pt; color:#55aaff;\">%s</span></p></body></html>") % self.Lab_temp) self.ui.label_co2.setText(_translate("URPMainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'Arial\'; font-size:10pt; font-weight:400; font-style:normal;\">\n" "<p align=\"center\" style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:20pt; color:#55aaff;\">%s</span></p></body></html>") % self.Lab_co2) # def draw_in_illum1(self): # x = [1,2,3,4,5] # y = [1,2,3,4,5] # plt.plot(x,y) # plt.title("DEMO") # self.ui.tab_illum_label1.canvas.draw() if __name__=="__main__": app = QApplication(sys.argv) form = QmyMainWindow() form.setWindowTitle("基于环境监测的物联网系统") form.show() # myWidget.btnClose.setText("不关闭了") sys.exit(app.exec_())
68158aaf5356766c566197be170f1c12e0672348
[ "Markdown", "Python", "C++" ]
5
C++
Kaihua-Chen/URP-Application-of-IoT-in-Agriculture
f7e57b55c8cad83f1e45368d7b9f168725fed4d8
659f382922827571453599eb50d11c9e5cd6f4b3
refs/heads/master
<repo_name>yang0010/ddns<file_sep>/src/main.cpp #include"alisdk.h" #include"unistd.h" #include"cstring" int main(int argc,char *argv[]){ if(argc==2 && strcmp(*(argv+1),"ipv4")==0){ cout<<Ddns::ipv4()<<endl; return 0; } else if(argc==2 && strcmp(*(argv+1),"ipv6")==0){ cout<<Ddns::ipv6()<<endl; return 0; } else if(argc==7 && strcmp(*(argv+1),"d")==0){ Ddns ddns(*(argv+2),*(argv+3),*(argv+4),*(argv+5),*(argv+6)); if(!ddns.ipinfo()){ if(ddns.update()) cout<<"更新成功!"<<endl; return 0; } else{ cout<<"本机和域名解析ip一致!"<<endl; return 0; } } else{ if(argc>1){ cout<<"指令输入错误,请输入参数 help 获取帮助!"<<endl; return 0; } } cout<<"使用说明 :"<<endl; cout<<"程序参数:(如何使用:比如 ./ddns ipv4 即可返回本机ipv4信息)"<<endl; cout<<"ipv4 返回ipv4地址"<<endl; cout<<"ipv6 返回ipv6地址"<<endl; cout<<"d AccessKeyID AccessKeySecret 你的顶级域名 解析记录类型AAAA或者A 你的子域名 此参数为临时单次解析,可不需要设置配置文件,可配合crontab之内的配合使用!"<<endl; cout<<"比如: ./ddns d xxx xxx baidu.com AAAA www"<<endl; /*Ddns dns; while(1){ if(!dns.ipinfo()){ cout<<"本机ip和域名ip不一致,正在更新......."<<endl; if(dns.update()) cout<<"更新成功,一分钟后将再次检查!"<<endl; else{ cout<<"ip更新失败,正在尝试重试!"<<endl; continue; } } else cout<<"ip一致,一分钟后将再次检查!"<<endl; sleep(60); } return 0;*/ }<file_sep>/README.md # 基于阿里云sdk c++ ddns #### 介绍 本程序用于动态ip解析到域名的ddns程序,采用c++编写,可在不同架构处理器上工作。支持ipv4,ipv6解析。 如有任何问题或者建议可联系作者,qq:1261424813 #### 软件架构 软件架构说明: 本程序支持arm,arm64,x64架构,请根据设备自行修改CMakeLists.txt对应动态库链接目录编译 #### 安装教程 1. 编译之前请先打开CMakeLists.txt文件修改link_directories(${catkin_LIB_DIRS} arm64_lib) 对应系统的库文件目录,默认为arm64_lib,如果你系统是arm就输入arm_lib,x64就输入x64_lib。占时不支持windows。 2. 请使用命令cmake .构建编译环境,然后输入命令make即可编译 #### 使用说明 1. 首次使用ddns程序会在当前运行目录生成setting.dat配置文件,请根据提示操作并修改适合你自己的配置文件,你需要有阿里云的顶级域名和生成了AccessKeyID和AccessKeySecret 2. 程序参数:(如何使用:比如 ./ddns ipv4 即可返回本机ipv4信息) 2. ipv4 返回ipv4地址 3. ipv6 返回ipv6地址 4. d AccessKeyID AccessKeySecret 你的顶级域名 解析记录类型AAAA或者A 你的子域名 此参数为临时单次解析,可不需要设置配置文件,可配合crontab之内的配合使用 如: ./ddns d xxx xxx baidu.com AAAA www #### 参与贡献 1. Fork 本仓库 2. 新建 Feat_xxx 分支 3. 提交代码 4. 新建 Pull Request #### 特技 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md 2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) 6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) <file_sep>/include/class_client.h #ifndef __Client #define __Client #include<stdio.h> #include<stdlib.h> #include<netdb.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<sys/wait.h> #include <arpa/inet.h> #include"unistd.h" #include<iostream> using std::cout; using std::endl; using std::string; class Client{ public: Client(string str,const char *port); Client(); ~Client(){ close(sockfd); } static string recv(void); static int send(string str); int socket_status();//返回socket状态,0为连接超时,小于0为连接错误 void sclose(void); int fd(void); void restart(string argv,int ch=0); private: void freeaddr(void); char ipaddr[INET6_ADDRSTRLEN]; struct sockaddr_in *dest_addr; struct sockaddr_in6 *dest_addrv6; struct addrinfo hints,*res=NULL; string buf; static int sockfd; static unsigned int buf_max; int client_ipv4(); int client_ipv6(); }; #endif<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.6.0) project(Main) include_directories( ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ) file(GLOB SRCS "${PROJECT_SOURCE_DIR}/include/*" "${PROJECT_SOURCE_DIR}/src/*" ) #link_libraries(./arm64_lib) #link_directories(${catkin_LIB_DIRS} arm64_lib) add_executable(ddns ${SRCS}) target_link_libraries(ddns alibabacloud-sdk-core alibabacloud-sdk-alidns curl jsoncpp)<file_sep>/include/alisdk.h #ifndef __ALISDK__ #define __ALISDK__ #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <alibabacloud/core/AlibabaCloud.h> #include <alibabacloud/core/CommonRequest.h> #include <alibabacloud/core/CommonClient.h> #include <alibabacloud/core/CommonResponse.h> using namespace std; using namespace AlibabaCloud; class Ddns{ public: Ddns(); Ddns(string,string,string,string,string); ~Ddns(){ AlibabaCloud::ShutdownSdk(); } static string ipv4(); static string ipv6(); bool update(void);//更新域名解析 bool info(void);//输出域名信息并检查ip是否匹配 bool ipinfo(void);//检查本地ip和域名ip是否匹配 bool empty(void);//检查setting保存在内存的信息是否完整 private: string AccessKeyID; string AccessKeySecret; string domainName;//主域名 string type;//记录类型,ipv6为AAAA string subDomainName;//子域名 string fileinfo;//setting.dat配置文件存储 string domainnameinfo;//所有域名解析记录存储 string value;//ip地址 string localip;//本机ip string recordId;//域名记录id //string domaininfo;//主域名 AlibabaCloud::ClientConfiguration configuration; void info_setting(void); void re(void); string GetDomainRecords(void); void re2(void); }; #endif<file_sep>/src/class_client.cpp #include"class_client.h" #include"sys/ioctl.h" int Client::sockfd=0; unsigned int Client::buf_max=3333;//最大接受数据长度 int socket_timeout(int,int); Client::Client(string str,const char *port){ bzero(&hints,sizeof(hints)); hints.ai_socktype = SOCK_STREAM; //hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ int err = getaddrinfo(str.c_str(),port,&hints,&res); if(err) { printf("error %d: %s\n",err,gai_strerror(err)); exit(0); } if(res->ai_family==AF_INET6){ dest_addrv6=(struct sockaddr_in6 *)res->ai_addr; inet_ntop(AF_INET6,&dest_addrv6->sin6_addr,ipaddr,INET6_ADDRSTRLEN); //cout<<"正在连接到ipv6服务器: "<<ipaddr<<endl; client_ipv6(); } else{ dest_addr=(struct sockaddr_in *)res->ai_addr; inet_ntop(AF_INET,&dest_addr->sin_addr,ipaddr,INET_ADDRSTRLEN); //cout<<"正在连接到ipv4服务器: "<<ipaddr<<endl; client_ipv4(); } } Client::Client():ipaddr(""),buf(""){ } int Client::client_ipv4(){ sockfd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);/*建立socket*/ if(sockfd==-1){ printf("socket failed:%d",errno); return -1; } int ul=1; int timeout=5000; ioctl(sockfd,FIONBIO,&ul);//设置非阻塞 if(connect(sockfd,res->ai_addr,res->ai_addrlen)==1){//连接方法,传入句柄,目标地址和大小 // 设置为阻塞 ul = 0; ioctl(sockfd, FIONBIO, &ul); setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(int)); return sockfd; } if(socket_timeout(sockfd,3)<=0){ cout<<"连接超时!"<<endl; close(sockfd); exit(0); } ul = 0; ioctl(sockfd, FIONBIO, &ul);//设置为阻塞 setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(int)); freeaddr(); return sockfd; } int Client::client_ipv6(){ sockfd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);/*建立socket*/ if(sockfd==-1){ printf("socket failed:%d",errno); return -1; } int ul=1; int timeout=5000; ioctl(sockfd,FIONBIO,&ul);//设置非阻塞 if(connect(sockfd,res->ai_addr,res->ai_addrlen)==1){//连接方法,传入句柄,目标地址和大小 // 设置为阻塞 ul = 0; ioctl(sockfd, FIONBIO, &ul); setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(int)); return sockfd; } if(socket_timeout(sockfd,3)<=0){ cout<<"连接超时!"<<endl; close(sockfd); exit(0); } ul = 0; ioctl(sockfd, FIONBIO, &ul);//设置为阻塞 setsockopt(sockfd,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(int)); freeaddr(); return sockfd; } int socket_timeout(int sockfd, int s) { int re = 0; fd_set set; struct timeval tm; int len; int error = -1; tm.tv_sec = s; tm.tv_usec = 0; FD_ZERO(&set); FD_SET(sockfd, &set); re = select(sockfd + 1, NULL, &set, NULL, &tm); if(re > 0){//select超时返回0,发生错误返回-1 len = sizeof(int); // 获取socket状态 getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len); if(error == 0){ re = 1; }else{ re = -3; } }else{ //cout<<"超时"<<endl; re = 0; } return re; } int Client::socket_status(){ return sockfd; } string Client::recv(){ char buf[buf_max]; int len=::recv(sockfd,buf,buf_max,0); if(len){ buf[len]='\0'; return buf; } else{ close(sockfd); cout<<"远端服务器以关闭,退出程序!"<<endl; } return "\0"; } int Client::send(string str){ return ::send(sockfd,str.c_str(),str.size(),0); } void Client::sclose(void){ close(sockfd); } int Client::fd(void){ return sockfd; } void Client::freeaddr(void){ freeaddrinfo(res); } void Client::restart(string argv,int ch){ char *str[]={(char *)argv.c_str(),(char *)"4",(char *)0};//此为execv argv参数 sclose(); switch(ch){ case 0: { char *str[]={(char *)argv.c_str(),(char *)0}; execv("/proc/self/exe",str);//exe为自身运行程序的路径,str为参数, break; } case 4: { //char *str[]={(char *)argv.c_str(),"4",(char *)0}; execv("/proc/self/exe",str); break; } case 6: { //char *str[]={(char *)argv.c_str(),"6",(char *)0}; str[1]=(char *)"6"; execv("/proc/self/exe",str); break; } } exit(0); }<file_sep>/src/ddns.cpp #include"alisdk.h" //#include"class_client.h" #include"json/json.h" #include"curl/curl.h" #include"regex" #include"stdio.h" #include"vector" Ddns::Ddns():configuration( "cn-hangzhou" ){ configuration.setConnectTimeout(1500); configuration.setReadTimeout(4000); info_setting(); re(); } Ddns::Ddns(string AccessKeyID,string AccessKeySecret,string domainName,string type,string subDomainName):configuration( "cn-hangzhou" ){ configuration.setConnectTimeout(1500); configuration.setReadTimeout(4000); this->AccessKeyID=AccessKeyID; this->AccessKeySecret=AccessKeySecret; this->domainName=domainName; this->type=type; this->subDomainName=subDomainName; } void Ddns::info_setting(void){ ifstream ddns_setting("./setting.dat"); if(!ddns_setting.is_open()){ cout<<"文件打开失败或未发现配置文件!"<<endl; cout<<"正在重新生成配置文件......."<<endl; string tmpinfo="AccessKeyID=\"xxx\"\nAccessKeySecret=\"xxx\"\ndomainName=\"你的顶级域名\"\ntype=\"AAAA或者A记录\"\nsubDomainName=\"你的子域名比如www\""; ofstream setting("./setting.dat"); setting.write(tmpinfo.c_str(),tmpinfo.size()); setting.close(); cout<<"配置文件生成成功,请设置好配置文件后再运行此程序!"<<endl; exit(0); } stringstream buff; buff<<ddns_setting.rdbuf(); fileinfo=buff.str(); ddns_setting.close(); } void Ddns::re(void){ regex r("\"([\\w\\.]+)\""); sregex_iterator pos(fileinfo.cbegin(),fileinfo.cend(),r); sregex_iterator end; vector<string> info; for (;pos!=end;++pos) info.push_back(pos->str(1)); if (info.size()!=5){ cout<<"配置文件读取不完整,请仔细设置setting文件,程序即将退出!"<<endl; exit(0); } AccessKeyID=info[0]; AccessKeySecret=info[1]; domainName=info[2]; type=info[3]; subDomainName=info[4]; } void Ddns::re2(void){ ostringstream res; res<<"\\{\"RR\":\"("<<subDomainName<<")\",\"Line\":\"default\",\"Status\":\"[\\w]+\",\"Locked\":false,\"Type\":\"("<<type<<")\",\"DomainName\":\"("<<domainName<<")\",\"Value\":\"([\\w:]+)\",\"RecordId\":\"([\\d]+)\",\"TTL\":600,\"Weight\":1\\}"; regex r(res.str()); //("\\{\"RR\":\"[\\w]+\",\"Line\":\"default\",\"Status\":\"[\\w]+\",\"Locked\":false,\"Type\":\"[\\w]{4}\",\"DomainName\":\"[\\w\\.]+\",\"Value\":\"[\\w:]+\",\"RecordId\":\"[\\d]+\",\"TTL\":600,\"Weight\":1\\}"); domainnameinfo=GetDomainRecords(); sregex_iterator pos(domainnameinfo.cbegin(),domainnameinfo.cend(),r),end; /*for(int i=1;i<pos->size();++i) cout<<pos->str(i)<<endl;*/ if(pos->size()){ value=pos->str(4); recordId=pos->str(5); } else{ cout<<"未从域名解析记录中获取到你的域名信息记录,请检查配置文件域名是否正确或者AccessKeyID!"<<endl; exit(0); } } bool Ddns::info(void){ if(recordId.empty()) re2(); cout<<"主域名: "<<domainName<<endl; cout<<"子域名: "<<subDomainName<<endl; cout<<"记录类型: "<<type<<endl; cout<<"记录id: "<<recordId<<endl; if(type=="AAAA"){ localip=ipv6(); cout<<"本机ip: "<<localip<<endl; } else{ localip=ipv4(); cout<<"本机ip: "<<localip<<endl; } cout<<"解析域名ip: "<<value<<endl; if(localip==value){ cout<<"本机ip和解析域名ip一致,无需更新!"<<endl; return true; } else{ cout<<"本机ip和解析域名ip不一致,请更新!"<<endl; return false; } } bool Ddns::ipinfo(){ if(recordId.empty()) re2(); if(type=="AAAA") localip=ipv6(); else localip=ipv4(); if(localip==value) return true; else return false; } size_t save_html(void *buffer, size_t size, size_t count, void *p){ string *tmp=(string *)p; size_t sz=size*count; tmp->append((char*)buffer,sz); return size*count; } string Ddns::ipv6(void){ CURL *curl=curl_easy_init(); string html; if(curl){ curl_easy_setopt(curl,CURLOPT_URL,"https://ipv6.jsonip.com"); curl_easy_setopt(curl,CURLOPT_NOSIGNAL,1L); curl_easy_setopt(curl,CURLOPT_TIMEOUT,5L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,save_html); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &html); curl_easy_setopt(curl,CURLOPT_USERAGENT,R"(User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36)"); curl_easy_perform(curl); curl_easy_cleanup(curl); string err; Json::Value root; Json::CharReaderBuilder reader; unique_ptr<Json::CharReader> jsonreader(reader.newCharReader()); jsonreader->parse(html.c_str(),html.c_str()+html.size(),&root,NULL); //cout<<html<<endl; return root["ip"].asString(); } return "\0"; } string Ddns::ipv4(void){ CURL *curl=curl_easy_init(); string html; if(curl){ curl_easy_setopt(curl,CURLOPT_URL,"https://ipv4.jsonip.com"); curl_easy_setopt(curl,CURLOPT_NOSIGNAL,1L); curl_easy_setopt(curl,CURLOPT_TIMEOUT,5L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,save_html); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &html); curl_easy_setopt(curl,CURLOPT_USERAGENT,R"(User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36)"); curl_easy_perform(curl); curl_easy_cleanup(curl); string err; Json::Value root; Json::CharReaderBuilder reader; unique_ptr<Json::CharReader> jsonreader(reader.newCharReader()); jsonreader->parse(html.c_str(),html.c_str()+html.size(),&root,NULL); //cout<<html<<endl; return root["ip"].asString(); } return "\0"; } /*string Ddns::ipv6addr(void){ string url="geoip.neu.edu.cn"; Client get(url,"80"); string requestHeader; requestHeader = "GET / HTTP/1.1\r\n"; requestHeader += "Host: " +url + "\r\n";*/ //requestHeader += "Accept: */*\r\n"; /*requestHeader += "User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"; //requestHeader += "X-Requested-With\":\"mark.via"; requestHeader += "connection:Keep-Alive\r\n"; requestHeader += "\r\n"; get.send(requestHeader); usleep(200000); string html=get.recv(); //cout<<html<<endl; regex r("<p class=\"text-info lead\"> ([\\w\\.:]{15,39})"); smatch m; regex_search(html,m,r); //cout<<m.str(1)<<endl; return m.str(1); } string Ddns::ipv4addr(void){ string url="ip.neu.edu.cn"; Client get(url,"80"); string requestHeader; requestHeader = "GET / HTTP/1.1\r\n"; requestHeader += "Host: " +url + "\r\n";*/ //requestHeader += "Accept: */*\r\n"; /*requestHeader += "User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"; //requestHeader += "X-Requested-With\":\"mark.via"; requestHeader += "connection:Keep-Alive\r\n"; requestHeader += "\r\n"; get.send(requestHeader); usleep(200000); string html=get.recv(); //cout<<html<<endl; regex r("<p class=\"text-info lead\"> ([\\d\\.]+) </p>"); smatch m; regex_search(html,m,r); return m.str(1); }*/ bool Ddns::empty(void){ vector<int> tmp({AccessKeyID.empty(),AccessKeySecret.empty(),domainName.empty(),type.empty(),subDomainName.empty()}); int num=0; for(int i: tmp) num+=i; return (num==5)?false:true; } string Ddns::GetDomainRecords(){ // specify timeout when create client. //configuration.setConnectTimeout(1500); //configuration.setReadTimeout(4000); AlibabaCloud::CommonClient client(AccessKeyID.c_str(), AccessKeySecret.c_str(), configuration ); AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern); request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post); request.setDomain("alidns.cn-hangzhou.aliyuncs.com"); request.setVersion("2015-01-09"); request.setQueryParameter("Action", "DescribeDomainRecords"); request.setQueryParameter("Lang", "cn_hangzhou"); request.setQueryParameter("DomainName",domainName.c_str()); auto response = client.commonResponse(request); string info; if (response.isSuccess()) { //printf("request success.\n"); //printf("result: %s\n", response.result().payload().c_str()); info=response.result().payload().c_str(); } else { printf("error: %s\n", response.error().errorMessage().c_str()); printf("request id: %s\n", response.error().requestId().c_str()); info=""; } return info; } bool Ddns::update(void){ AlibabaCloud::CommonClient client(AccessKeyID.c_str(),AccessKeySecret.c_str(),configuration); AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern); request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post); request.setDomain("alidns.cn-hangzhou.aliyuncs.com"); request.setVersion("2015-01-09"); request.setQueryParameter("Action", "UpdateDomainRecord"); request.setQueryParameter("Lang", "cn-hangzhou"); request.setQueryParameter("RecordId", recordId.c_str()); request.setQueryParameter("RR", subDomainName.c_str()); request.setQueryParameter("Type", type.c_str()); request.setQueryParameter("Value", localip.c_str()); request.setQueryParameter("TTL", "600"); auto response = client.commonResponse(request); if (response.isSuccess()) { /*printf("request success.\n"); printf("result: %s\n", response.result().payload().c_str());*/ value=localip; return true; } else { printf("error: %s\n", response.error().errorMessage().c_str()); printf("request id: %s\n", response.error().requestId().c_str()); return false; } }
4cff439a8bae15aebe63141929658f2c994a496f
[ "Markdown", "CMake", "C++" ]
7
C++
yang0010/ddns
20582ba699e901a4425682ab13fe5e6ca49efa7c
04d464d92f002f3e8807e9726f7b1afec44204f9
refs/heads/master
<file_sep>import { ProxyState } from "../AppState.js" import Pokemon from "../Models/Pokemon.js" import { pokemonApi } from "./AxiosService.js" class PokemonApiService { async getAll() { let res = await pokemonApi.get('/pokemon?limit=30') ProxyState.apiPokemon = res.data.results } async getDetails(name) { let res = await pokemonApi.get(`pokemon/${name}`) ProxyState.activePokemon = new Pokemon(res.data) } } const pokemonApiService = new PokemonApiService() export default pokemonApiService
9514795753eb761dbb76dc7dd27c60a198d9de8c
[ "JavaScript" ]
1
JavaScript
kelseybcrow/pokemon-api
ec8cdeab56831c989d056784aacbffbd18456868
102c1fe6d7d4ba815ee6925132ec17e8b5d46d0d
refs/heads/master
<repo_name>showgames/C_programming3<file_sep>/game.c #include <stdio.h> #include "game.h" /*探索ライン*/ const int LINE[8][3] = { {0,1,2}, {3,4,5}, {6,7,8}, /*横のライン*/ {0,3,6}, {1,4,7}, {2,5,8}, /*縦のライン*/ {0,4,8}, {2,4,6},}; /*斜めのライン*/ void init(GAME_STATE* game){ /*ゲーム開始状態に初期化する*/ game->teban = 1; game->tesuu = 0; game->te = 0; int i; for(i = 0; i < BLOCK_NUMBER; i++){ game->board[i] = EMPTY; } } void disp_board(GAME_STATE* game){ int i; int row_count; for(i = 0, row_count = 1; i < BLOCK_NUMBER; i++, row_count++){ printf("%d ",game->board[i]); if(row_count == 3){ /*3マス表示したら改行する*/ printf("\n"); row_count = 0; } } printf("\n"); } void get_move(GAME_STATE* game){ char buf[256]; game->te = 0; /*1から9までの数値の入力を受け付けるので0で初期化しておく*/ while(!(game->te >= 1 && game->te <= 9)){ fgets(buf, sizeof(buf), stdin); sscanf(buf, "%d", &(game->te)); } } int check_legal_move(GAME_STATE* game){ if(game->board[(game->te - 1)] == EMPTY){ return 1; /*置ける*/ }else{ return 0; /*置けない*/ } } void make_move(GAME_STATE* game){ game->board[(game->te - 1)] = game->teban; /*盤面に置く*/ game->tesuu++; /*手数を一増やす*/ } int check_finish_game(GAME_STATE* game){ int i; for(i = 0; i < 8; i++){/*8つのどれかのライン上に3つの連続した数字があれば試合終了*/ if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == game->teban && game->board[(LINE[i][2])] == game->teban){ return 1; } } if(game->tesuu == MAX_TESUU){ /*手数が9手ならば試合終了*/ return 1; } return 0; } void change_teban(GAME_STATE* game){ game->teban = 3 - game->teban; } void think_move(GAME_STATE* game){ int i; int human = (3-game->teban); /*自分にリーチがかかっている*/ /*横のライン*/ for(i = 0; i < 3; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] ==game->teban && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == game->teban && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*縦のライン*/ for(i = 3; i < 6; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] ==game->teban && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == game->teban && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*斜めのライン*/ for(i = 6; i < 8; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] ==game->teban && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == game->teban){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == game->teban && game->board[(LINE[i][1])] == game->teban && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*相手の勝ちを阻止する*/ /*横のライン*/ for(i = 0; i < 3; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*縦のライン*/ for(i = 3; i < 6; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*斜めのライン*/ for(i = 6; i < 8; i++){ if(game->board[(LINE[i][0])] == EMPTY && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][0] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == EMPTY && game->board[(LINE[i][2])] == human){ game->te = (LINE[i][1] + 1); return; } if(game->board[(LINE[i][0])] == human && game->board[(LINE[i][1])] == human && game->board[(LINE[i][2])] == EMPTY){ game->te = (LINE[i][2] + 1); return; } } /*相手にも自分にもリーチがかかっていなかった場合*/ for(i = 0; i < 9; i++){ if(game->board[i] == EMPTY){ game->te = (i + 1); return; } } } <file_sep>/main.c #include <stdio.h> #include <stdlib.h> #include "game.h" int main(int argc, char** argv){ GAME_STATE game; /*ゲーム構造体*/ int legal_move = 0; /*1なら合法手*/ int finish = 0; /*1になるとゲームが終了となる*/ /*ゲーム状態の初期化*/ init(&game); /*ディスプレイに盤面を出力*/ disp_board(&game); /*ループ*/ while(finish != 1){ legal_move = 0; while(legal_move != 1){ if(game.teban == 1){ get_move(&game); /*人間側*/ }else{ think_move(&game); /*コンピュータ側*/ } /*その手が合法手かを判定*/ legal_move = check_legal_move(&game); } /*手によって盤面の状態を変更する*/ make_move(&game); /*ディスプレイに盤面を表示*/ disp_board(&game); /*終局判定*/ finish = check_finish_game(&game); /*手番を交代する*/ change_teban(&game); } exit(0); } <file_sep>/README.md # 三目並べ * make mainでコンパイル * マス目の位置を入力して手を打つ * マス目の位置は左上から右下にかけて1,2,3.....9となる * 対コンピュータ用 * AI自体は簡単だが負けにくいと思う <file_sep>/Makefile #Makefile main: main.c game.c game.h gcc -Wall -o main main.c game.c <file_sep>/game.h #define BLOCK_NUMBER 9 /*盤面のサイズ*/ #define MAX_TESUU 9 /*手数の最大値(盤面は9マスなので)*/ #define EMPTY 0 /*空マス*/ typedef struct _game_state{ int board[BLOCK_NUMBER]; /*盤面*/ int teban; /*手番*/ int tesuu; /*手数*/ int te; /*手*/ }GAME_STATE; /*ゲーム状態を操作する関数群*/ void init(GAME_STATE* game); /*ゲームを初期化する関数*/ void get_move(GAME_STATE* game); /*プレイヤーが手を入力する関数*/ int check_legal_move(GAME_STATE* game); /*合法手を判定する関数*/ void make_move(GAME_STATE* game);/*手によって状態を変更する関数*/ void disp_board(GAME_STATE* game); /*ディスプレイに盤面の状態を出力する関数*/ int check_finish_game(GAME_STATE* game); /*ゲームの終局を判定する関数*/ void change_teban(GAME_STATE* game); /*手番を交代する*/ /*AIの関数*/ void think_move(GAME_STATE* game); /*コンピュータが手を選ぶ関数*/
fe06e302aee134f50f896322c086337a8e041950
[ "Markdown", "C", "Makefile" ]
5
C
showgames/C_programming3
3cd61eb84cb746e0a386d77a1e8bc004f5ca29e2
64938b9eafe5aca9e34080694a2e7fcd2241ddbe
refs/heads/main
<repo_name>EnzoMeertens/RichGetRicher-Clarity<file_sep>/README.md # RichGetRicher-Clarity A simple lobby that can host multiple games. <file_sep>/tests/richgetricher_test.ts import { Clarinet, Tx, Chain, Account, types } from 'https://deno.land/x/clarinet@v0.6.0/index.ts'; import { assertEquals } from 'https://deno.land/std@0.90.0/testing/asserts.ts'; Clarinet.test ({ name: "Ensure that lobbies and games can be created.", async fn(chain: Chain, accounts: Map<string, Account>) { let wallet_deployer = accounts.get("deployer"); let wallet_1 = accounts.get("wallet_1")!; let wallet_2 = accounts.get("wallet_2")!; let wallet_3 = accounts.get("wallet_3")!; let block = chain.mineBlock ([ /*0:*/ Tx.contractCall("richgetricher", "get-lobby", [], wallet_1.address), /*1:*/ Tx.contractCall("richgetricher", "create-lobby", [types.ascii("My lobby name"), types.uint(10)], wallet_1.address), /*2:*/ Tx.contractCall("richgetricher", "get-lobby", [], wallet_1.address), /*3:*/ Tx.contractCall("richgetricher", "create-game", [types.ascii("My game name"), types.uint(50), types.uint(180)], wallet_2.address), /*4:*/ Tx.contractCall("richgetricher", "get-lobby", [], wallet_3.address), ]); assertEquals(block.height, 2); block.receipts[0].result .expectErr(); block.receipts[1].result .expectOk() .expectAscii("My lobby name"); block.receipts[2].result .expectErr(); block.receipts[3].result .expectOk() .expectUint(1); block.receipts[4].result .expectOk() .expectList() .map((e: String) => e.expectTuple()); }, }); Clarinet.test ({ name: "Ensure that games can be played.", async fn(chain: Chain, accounts: Map<string, Account>) { let wallet_deployer = accounts.get("deployer"); let wallet_1 = accounts.get("wallet_1")!; let wallet_2 = accounts.get("wallet_2")!; let wallet_3 = accounts.get("wallet_3")!; let wallet_4 = accounts.get("wallet_4")!; let block = chain.mineBlock ([ /*0:*/ Tx.contractCall("richgetricher", "create-lobby", [types.ascii("My lobby name"), types.uint(50)], wallet_1.address), /*1:*/ Tx.contractCall("richgetricher", "create-game", [types.ascii("My game name"), types.uint(100), types.uint(1)], wallet_4.address), /*2:*/ Tx.contractCall("richgetricher", "create-game", [types.ascii("My second game name"), types.uint(500), types.uint(1)], wallet_4.address), /*3:*/ Tx.contractCall("richgetricher", "get-lobby", [], wallet_2.address), /*4:*/ Tx.contractCall("richgetricher", "get-game", [types.uint(1)], wallet_2.address), /*5:*/ Tx.contractCall("richgetricher", "participate", [types.uint(1), types.uint(1000), types.ascii("I'm the leader now!")], wallet_2.address), /*6:*/ Tx.contractCall("richgetricher", "get-game", [types.uint(1)], wallet_3.address), /*7:*/ Tx.contractCall("richgetricher", "participate", [types.uint(1), types.uint(1001), types.ascii("No! I'm the leader now!")], wallet_3.address), /*8:*/ Tx.contractCall("richgetricher", "get-game", [types.uint(1)], wallet_2.address), ]); assertEquals(block.height, 2); block.receipts[0].result .expectOk() .expectAscii("My lobby name"); block.receipts[1].result .expectOk() .expectUint(1); block.receipts[2].result .expectOk() .expectUint(2); block.receipts[3].result .expectOk() .expectList() .map((e: String) => e.expectTuple()); block.receipts[4].result .expectOk() .expectTuple(); block.receipts[5].result .expectOk() .expectBool(true); console.log(`\r\n\r\n${block.height}: ${block.receipts[6].result}`) block.receipts[6].result .expectOk() .expectTuple(); block.receipts[7].result .expectOk() .expectBool(true); console.log(`\r\n${block.height}: ${block.receipts[8].result}`) block.receipts[8].result .expectOk() .expectTuple(); block = chain.mineBlock ([ /*0:*/ Tx.contractCall("richgetricher", "get-game", [types.uint(1)], wallet_2.address), /*1:*/ Tx.contractCall("richgetricher", "participate", [types.uint(1), types.uint(1000), types.ascii("I'm the leader again!")], wallet_2.address), ]); assertEquals(block.height, 3); block.receipts[0].result .expectOk() .expectTuple(); console.log(`\r\n\r\n${block.height}: ${block.receipts[0].result}`) block.receipts[1].result .expectOk(); block = chain.mineBlock ([ /*0:*/ Tx.contractCall("richgetricher", "get-game", [types.uint(1)], wallet_2.address), /*1:*/ Tx.contractCall("richgetricher", "participate", [types.uint(1), types.uint(1000), types.ascii("No! I'm the leader again!")], wallet_3.address), ]); assertEquals(block.height, 4); block.receipts[0].result .expectOk() .expectTuple(); console.log(`\r\n\r\n${block.height}: ${block.receipts[0].result}`) block.receipts[1].result .expectErr(); let result = chain.getAssetsMaps(); console.log(result); console.log(`Wallet_1 ${result.assets["STX"][wallet_1.address]}`); console.log(`Wallet_2 ${result.assets["STX"][wallet_2.address]}`); console.log(`Wallet_3 ${result.assets["STX"][wallet_3.address]}`); console.log(`Wallet_4 ${result.assets["STX"][wallet_4.address]}`); }, });<file_sep>/Clarinet.toml [project] name = "richgetricher" [contracts] [contracts.richgetricher] path = "contracts/richgetricher.clar" depends_on = [] [notebooks]
45664d22abe65f489a461827ccf578a6da295205
[ "Markdown", "TOML", "TypeScript" ]
3
Markdown
EnzoMeertens/RichGetRicher-Clarity
f516de2baf6fce6849172d7cc502ec72acfce431
d512d74cc1b1baa39e217d7ca7d68c901f2b0f74
refs/heads/master
<file_sep>package org.usfirst.frc.team1160.robot.subsystems; import org.usfirst.frc.team1160.robot.OI; import org.usfirst.frc.team1160.robot.RobotMap; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.Joystick.AxisType; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Shooter extends Subsystem implements RobotMap { public static Shooter instance; protected final CANTalon big; protected final ModTal small; private double rpm, angleSec, finalRPM, smallRPM, largeRPM, logVel; private Timer time; private Vision vision; public static Shooter getInstance() { if (instance == null) { instance = new Shooter(); } return instance; } private Shooter() { big = new CANTalon(S_FLYWHEEL_LARGE); small = new ModTal(S_FLYWHEEL_SMALL); big.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); small.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); small.configEncoderCodesPerRev(1024); big.configEncoderCodesPerRev(1024); SmartDashboard.putNumber("TEST_DISTANCE", TEST_DISTANCE); time = new Timer(); vision = Vision.getInstance(); } protected void initDefaultCommand() { } public void potBoy() { // ?? OI.getInstance().getAutoInput().getAxis(AxisType.kThrottle); } public void setBig(double speed) { big.set(speed); } public void setSmall(double speed) { small.set(speed); } public void setFlywheel(double speed) { big.set(speed); small.set(-speed); } public double speedFromDistance(double distance) { angleSec = 1 / Math.cos(SHOOTER_ANGLE_RADIANS); rpm = ((distance * angleSec * Math.sqrt((GRAVITATIONAL_ACCEL) / (2 * (BALL_VERTICAL_DISPLACEMENT - distance * Math.tan(SHOOTER_ANGLE_RADIANS))))) / SHOOTER_WHEEL_CIRCUMFERENCE) * 60; return rpm; } public double velocity(double distance) { angleSec = 1 / Math.cos(SHOOTER_ANGLE_RADIANS); logVel = FT_TO_M * (distance * angleSec * Math.sqrt((GRAVITATIONAL_ACCEL) / (2 * (BALL_VERTICAL_DISPLACEMENT - distance * Math.tan(SHOOTER_ANGLE_RADIANS))))); SmartDashboard.putNumber("Goal Velocity Set At: ", logVel); return logVel; } public double addEnergy() { //finalRPM = speedFromDistance(vision.getDistance()) + 102.788 * velocity(vision.getDistance()); finalRPM = speedFromDistance(SmartDashboard.getNumber("TEST_DISTANCE")) + 102.788 * velocity(SmartDashboard.getNumber("TEST_DISTANCE")); SmartDashboard.putNumber("Goal RPM: ", finalRPM * 1.25); return finalRPM * 1.25; } public void getRevolutions() { smallRPM = small.getSpeed(); largeRPM = big.getSpeed(); System.out.println("SmallRPM: " + smallRPM); System.out.println("LargeRPM: " + largeRPM); SmartDashboard.putNumber("SmallRPM: ", smallRPM); SmartDashboard.putNumber("LargeRPM: ", largeRPM); } public void testFire() { System.out.println("Top rev: " + big.getPosition()); System.out.println("Bot rev: " + small.getPosition()); } public void startTime() { time.reset(); time.start(); } public double getTime() { return time.get(); } public double getSmall() { return small.get(); } } <file_sep>package org.usfirst.frc.team1160.robot.subsystems; import java.io.IOException; import org.usfirst.frc.team1160.robot.RobotMap; import org.usfirst.frc.team1160.robot.commands.Distance; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Vision extends Subsystem implements RobotMap { private static Vision instance; private double[] width, centerX, defaultValue; private double distance, alignmentCenterX, abc; private int index; public NetworkTable table; private final NetworkTable grip = NetworkTable.getTable("grip"); public static Vision getInstance() { if (instance == null) { instance = new Vision(); } return instance; } public boolean aligned() { table = NetworkTable.getTable("GRIP/myContoursReport"); centerX = table.getNumberArray("centerX", defaultValue); if (centerX[0] - 160 <= Math.abs(10)) { return true; } return false; } private Vision() { table = NetworkTable.getTable("GRIP/myContoursReport"); defaultValue = new double[0]; centerX = new double[defaultValue.length]; runGrip(); } public boolean alignCheck() { /* table = NetworkTable.getTable("GRIP/myContoursReport"); centerX = table.getNumberArray("centerX", defaultValue); centerY = table.getNumberArray("centerY", defaultValue); alignmentCenterX = (X_MAX + X_MIN) / 2; if (centerX.length > 1) { for (int i = 0; i < centerX.length; i++) { if (Math.abs(centerX[i] - alignmentCenterX) < Math.abs(centerX[0] - alignmentCenterX)) { centerX[0] = centerX[i]; } } } System.out.println(centerX[0]); if (centerX[0] <= X_MAX && centerX[0] >= X_MIN) { System.out.println("Aligned"); return true; } return false; */ return true; } public int getAlign() { /* table = NetworkTable.getTable("GRIP/myContoursReport"); centerX = table.getNumberArray("centerX", defaultValue); alignmentCenterX = (X_MAX + X_MIN) / 2; if (centerX.length > 1) { for (int i = 0; i < centerX.length; i++) { if (Math.abs(centerX[i] - alignmentCenterX) < Math.abs(centerX[0] - alignmentCenterX)) { centerX[0] = centerX[i]; } } } if (centerX[0] < alignmentCenterX - px_margin_error) { return 1; } else if (centerX[0] > alignmentCenterX + px_margin_error) { return 2; } else { */ return 0; } public void runGrip() { /* Run GRIP in a new process */ try { new ProcessBuilder("/home/lvuser/grip").inheritIO().start(); } catch (IOException e) { e.printStackTrace(); } } /************************************************************************************************** * http://www.pyimagesearch.com/2015/01/19/find-distance-camera-objectmarker * -using-python-opencv/ Basically fractions: uses apparent size of image * (pixels) uses actual size of object (inches) uses focal length of camera * (preset conditions) **************************************************************************************************/ public double getDistance() { width = NetworkTable.getTable("GRIP").getNumberArray("targets/width", defaultValue); centerX = table.getNumberArray("centerX", defaultValue); table.putNumber("borked? ", 8732); for (double area : NetworkTable.getTable("GRIP").getNumberArray("targets/width", new double[0])) { //System.out.println("Got contour with width=" + area); } //System.out.println("size of networktable array: " + NetworkTable.getTable("GRIP").getNumberArray("targets/width", new double[0]).length); alignmentCenterX = (X_MAX + X_MIN) / 2; if(width.length == 0){ //System.out.println("HAH BORKED"); return 7; } for (int i = 0; i < centerX.length; i++) { if (Math.abs(centerX[i] - alignmentCenterX) < Math.abs(centerX[0] - alignmentCenterX)) { index = i; } } if(width.length == 0){ //System.out.println("nooooo :("); return 7; } System.out.println(width[0]); distance = FOCAL_X * WIDTH_ACTUAL / width[0]; SmartDashboard.putNumber("Distance Recorded as: ", distance / 12); //System.out.println("distance: " + distance / 12); return distance / 12; } protected void initDefaultCommand() { setDefaultCommand(new Distance()); } } <file_sep>package org.usfirst.frc.team1160.robot.commands; import org.usfirst.frc.team1160.robot.Robot; import edu.wpi.first.wpilibj.command.Command; public class Aim extends Command { private int index; public Aim() { requires(Robot.see); requires(Robot.dt); requires(Robot.air); } @Override protected void initialize() { // TODO Auto-generated method stub Robot.air.pivotIn(); } @Override protected void execute() { // TODO Auto-generated method stub index = Robot.see.getAlign(); if (index == 1) { Robot.dt.slowLeft(); System.out.println("LEFT"); } else if (index == 2) { Robot.dt.slowRight(); System.out.println("RIGHT"); } } @Override protected boolean isFinished() { return Robot.see.alignCheck(); } @Override protected void end() { // TODO Auto-generated method stub } @Override protected void interrupted() { // TODO Auto-generated method stub } } <file_sep>package org.usfirst.frc.team1160.robot.subsystems; import org.usfirst.frc.team1160.robot.RobotMap; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.command.Subsystem; public class PID extends Subsystem implements RobotMap { private CANTalon motor, fMotor; public PID(CANTalon lMotor, CANTalon fmotor) { //CHANGE FOR FINAL VV fMotor = lMotor; motor = fmotor; //CHANGE FOR FINAL ^^ motor.changeControlMode(CANTalon.TalonControlMode.Position); fMotor.changeControlMode(CANTalon.TalonControlMode.Follower); motor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); motor.setPID(P, I, D); motor.configEncoderCodesPerRev(DT_GEAR_RATIO); } public void setD(double distance) { fMotor.set(motor.getDeviceID()); motor.set(distance); } public void deAuto(){ motor.changeControlMode(CANTalon.TalonControlMode.PercentVbus); fMotor.changeControlMode(CANTalon.TalonControlMode.PercentVbus); motor.set(0); fMotor.set(0); } public double getPosition(){ return motor.getPosition(); } protected void initDefaultCommand() { } }<file_sep>package org.usfirst.frc.team1160.robot.commands.air; // PATENTED CODE tm import org.usfirst.frc.team1160.robot.Robot; import edu.wpi.first.wpilibj.command.Command; public class ShootPosition extends Command{ public ShootPosition(){ requires(Robot.air); } protected void initialize() { Robot.air.pivotIn(); System.out.println("In Position"); } protected void execute() { } protected boolean isFinished() { return true; } protected void end() { } protected void interrupted() { } } <file_sep>package org.usfirst.frc.team1160.robot.subsystems; import org.usfirst.frc.team1160.robot.RobotMap; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Subsystem; public class Pneumatics extends Subsystem implements RobotMap { private static Pneumatics instance; private Timer time; protected final Compressor comp; protected final DoubleSolenoid pivot, hold; @Override protected void initDefaultCommand() { setDefaultCommand(null); } public static Pneumatics getInstance() { if (instance == null) { instance = new Pneumatics(); } return instance; } private Pneumatics() { comp = new Compressor(COMPRESSOR); comp.start(); pivot = new DoubleSolenoid(S_PIVOT_A, S_PIVOT_B); hold = new DoubleSolenoid(S_HOLD_A, S_HOLD_B); time = new Timer(); } public void pivotOut() { pivot.set(EXT); } public void pivotIn() { pivot.set(RET); } public void release() { hold.set(EXT); } public void contain() { hold.set(RET); } public void start() { time.reset(); time.start(); } public double getTime() { return time.get(); } } <file_sep>package org.usfirst.frc.team1160.robot.commands.Shoot; import org.usfirst.frc.team1160.robot.Robot; import edu.wpi.first.wpilibj.command.Command; public class StopWheels extends Command{ public StopWheels(){ requires(Robot.shoot); } @Override protected void initialize() { Robot.shoot.setFlywheel(0); System.out.println("Wheels Stopped"); //Robot.shoot.disabler(); } @Override protected void execute() { } @Override protected boolean isFinished() { return true; } @Override protected void end() { } @Override protected void interrupted() { } } <file_sep>package org.usfirst.frc.team1160.robot.commands.auto; import org.usfirst.frc.team1160.robot.RobotMap; import org.usfirst.frc.team1160.robot.commands.Drive; import org.usfirst.frc.team1160.robot.commands.Rotate; import org.usfirst.frc.team1160.robot.commands.Wait; import org.usfirst.frc.team1160.robot.commands.Shoot.FireSequence; import org.usfirst.frc.team1160.robot.commands.air.PickupPosition; import edu.wpi.first.wpilibj.command.CommandGroup; public class Cheval extends CommandGroup implements RobotMap{ public Cheval(double rotationTime, boolean turnDirection) { addSequential(new PickupPosition()); addSequential(new Wait(1)); addSequential(new Drive(CHEVAL_A_DISTANCE)); addSequential(new Drive(CHEVAL_B_DISTANCE)); //addSequential(new Rotate(rotationTime,turnDirection)); //addSequential(new FireSequence()); } } <file_sep>package org.usfirst.frc.team1160.robot; import edu.wpi.first.wpilibj.Joystick; public class ModifiedJoystick extends Joystick{ public ModifiedJoystick(int port) { super(port); } public double getCubeX(){ return Math.pow(super.getX(), 3); } public double getCubeY(){ return Math.pow(super.getY(), 3); } public double getCubeZ(){ return Math.pow(super.getZ(), 3); } public double getQuintX(){ return Math.pow(super.getX(), 5); } public double getQuintY(){ return Math.pow(super.getY(), 5); } public double getHalfQuintZ(){ return (Math.pow(super.getZ(), 5)/3); } public double getModZ(){ return Math.pow(super.getZ(), 4.2); } } <file_sep> package org.usfirst.frc.team1160.robot; import org.usfirst.frc.team1160.robot.commands.auto.Moat; import org.usfirst.frc.team1160.robot.subsystems.DriveTrain; import org.usfirst.frc.team1160.robot.subsystems.Pneumatics; import org.usfirst.frc.team1160.robot.subsystems.Shooter; import org.usfirst.frc.team1160.robot.subsystems.Vision; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; public class Robot extends IterativeRobot implements RobotMap{ public static OI oi; public static DriveTrain dt; public static Shooter shoot; public static Vision see; public static Pneumatics air; public static DeployConfirm dc; public static AutoSelection autochoose; Command autonomousCommand; SendableChooser chooser; public void robotInit() { //dt = DriveTrain.getInstance(); shoot = Shooter.getInstance(); see = Vision.getInstance(); air = Pneumatics.getInstance(); oi = OI.getInstance(); dc = new DeployConfirm(); } public void disabledInit(){ } public void disabledPeriodic() { Scheduler.getInstance().run(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example) * or additional comparisons to the switch structure below with additional strings & commands. */ public void autonomousInit() { //autonomousCommand = new Moat(0, false); //autonomousCommand.start(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { //Scheduler.getInstance().run(); } public void teleopInit() { if (autonomousCommand != null) autonomousCommand.cancel(); //dt.noMoreAuto(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { //System.out.println("oh yes"); Scheduler.getInstance().run(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); } } <file_sep>2016-Stronghold ================= FRC Team 1160's code for 2016 season -- #####Features: - [ ] Vision - [ ] PID - [ ] Autonomous - [x] Flywheel Shooter - [x] Pickup <file_sep>package org.usfirst.frc.team1160.robot.commands.auto; import org.usfirst.frc.team1160.robot.RobotMap; import org.usfirst.frc.team1160.robot.commands.Drive; import org.usfirst.frc.team1160.robot.commands.Rotate; import org.usfirst.frc.team1160.robot.commands.Shoot.FireSequence; import edu.wpi.first.wpilibj.command.CommandGroup; public class Ramparts extends CommandGroup implements RobotMap{ public Ramparts(double rotationTime, boolean turnDirection) { addSequential(new Drive(RAMPART_DISTANCE)); //addSequential(new Rotate(rotationTime,turnDirection)); //addSequential(new FireSequence()); } } <file_sep>package org.usfirst.frc.team1160.robot.commands.auto; import org.usfirst.frc.team1160.robot.RobotMap; import org.usfirst.frc.team1160.robot.commands.Drive; import org.usfirst.frc.team1160.robot.commands.Rotate; import org.usfirst.frc.team1160.robot.commands.Shoot.FireSequence; import edu.wpi.first.wpilibj.command.CommandGroup; public class Moat extends CommandGroup implements RobotMap{ public Moat(double rotationTime, boolean turnDirection) { addSequential(new Drive(MOAT_DISTANCE)); //addSequential(new Rotate(rotationTime,turnDirection)); //addSequential(new FireSequence()); } } <file_sep>To do: Double check motor directions to ensure PID output - see DriveTrain:50 Start testing PID when drivetrain is done Finish vision Link vision distancing to flywheel motor input - Vision/Shooter subsystems, consider making a commandgroup to execute? RetroTape height: 1ft RetroTape length: 1ft 8in Bottom of tape: 6ft 11in Top of tape: 7ft 1in DONE: Drive train <file_sep>package org.usfirst.frc.team1160.robot.commands.auto; import org.usfirst.frc.team1160.robot.RobotMap; import org.usfirst.frc.team1160.robot.commands.Drive; import org.usfirst.frc.team1160.robot.commands.Rotate; import org.usfirst.frc.team1160.robot.commands.Wait; import org.usfirst.frc.team1160.robot.commands.Shoot.FireSequence; import org.usfirst.frc.team1160.robot.commands.air.PickupPosition; import edu.wpi.first.wpilibj.command.CommandGroup; public class LowBar extends CommandGroup implements RobotMap{ public LowBar() { addSequential(new PickupPosition()); addSequential(new Wait(2)); addSequential(new Drive(LOWBAR_DISTANCE)); addSequential(new Rotate(A_TIME, false)); addSequential(new FireSequence()); } } <file_sep>package org.usfirst.frc.team1160.robot.commands; import org.usfirst.frc.team1160.robot.Robot; import org.usfirst.frc.team1160.robot.RobotMap; import edu.wpi.first.wpilibj.command.Command; public class Rotate extends Command implements RobotMap{ private double duration, timeElapsed; private boolean direction; public Rotate(double time, boolean Direction){ duration = time; direction = Direction; requires(Robot.dt); requires(Robot.shoot); } @Override protected void initialize() { // TODO Auto-generated method stub Robot.shoot.startTime(); } @Override protected void execute() { // TODO Auto-generated method stub if(direction){ Robot.dt.slowLeft(); } else{ Robot.dt.slowRight(); } timeElapsed = Robot.shoot.getTime(); } @Override protected boolean isFinished() { if(timeElapsed>duration){ return true; } return false; } @Override protected void end() { // TODO Auto-generated method stub } @Override protected void interrupted() { // TODO Auto-generated method stub } }
da1300798b5fccac6bc6186ae804d0764cf5eccc
[ "Markdown", "Java", "Text" ]
16
Java
FRC-Team-1160/2016-Stronghold
bc0d7fc11d8e4af88029b9c4817b914995d6e4dd
58fececaee0889d4288b7ef97f5eb3c07be58739
refs/heads/master
<repo_name>VioletGiraffe/websearch<file_sep>/crawler/src/cmainwindow.h #ifndef CMAINWINDOW_H #define CMAINWINDOW_H #include "compiler/compiler_warnings_control.h" #include "cmyhtmlparser.h" #include "cwebdownloader.h" DISABLE_COMPILER_WARNINGS #include <QMainWindow> RESTORE_COMPILER_WARNINGS namespace Ui { class CMainWindow; } class CMainWindow : public QMainWindow { public: explicit CMainWindow(QWidget *parent = 0); ~CMainWindow(); private: Ui::CMainWindow *ui; CWebDownloader _downloader; CMyHtmlParser _parser; }; #endif // CMAINWINDOW_H <file_sep>/README.md # Websearch A toy web search engine. <file_sep>/crawler/src/cmainwindow.cpp #include "cmainwindow.h" #include "uri-parser/UriParser.hpp" DISABLE_COMPILER_WARNINGS #include "ui_cmainwindow.h" #include <QDebug> RESTORE_COMPILER_WARNINGS CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); connect(ui->_urlLine, &QLineEdit::editingFinished, [this](){ const QString url = ui->_urlLine->text(); if (url.isEmpty()) return; const auto& result = _parser.parse(_downloader.download(url)); ui->_list->clear(); for (const auto& tag : result) { if (tag.type == MyHTML_TAG_A) { const QString href = tag.attributeValue("href"); if (!href.isEmpty()) { ui->_list->addItem(href); std::string stdUrl = href.toStdString(); const http::url parsed = http::ParseHttpUrl(stdUrl); qDebug() << "Host:" << QString::fromStdString(parsed.host); qDebug() << "Path:" << QString::fromStdString(parsed.path); } } } }); } CMainWindow::~CMainWindow() { delete ui; }
3dd9253a34905f4fffaeba7491a671ddb850e645
[ "Markdown", "C++" ]
3
C++
VioletGiraffe/websearch
f6e615664a8536160cc853c383627d1523c52ea0
9ddef391ceda3dd0446ef3e526709a69a509bca7
refs/heads/master
<repo_name>daucloudlab/Django_Demo_Site<file_sep>/article/forms.py #-*- coding: utf-8 -*- from django.forms import ModelForm, Textarea, TextInput from models import Comments class CommentForm(ModelForm): class Meta: model = Comments fields = ['comments_text'] widgets = { 'comments_text':Textarea(attrs={'cols':80, 'rows':20}), } labels = { 'comments_text':'Комментаридің мәтіні' } <file_sep>/article/views.py #-*-coding: utf-8 -*- from django.shortcuts import render, redirect from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template.loader import get_template from django.template import Context from article.models import Article, Comments from django.core.urlresolvers import reverse from forms import CommentForm # Create your views here. def basic_one(request): view = "basic_one" html = "<html><body>This is %s view</body></html>" % view return HttpResponse(html) def template_two(request): t = get_template('myview.html') c = Context({'name':"Template Two"}) return HttpResponse(t.render(c)) def template_three(request): return render(request, 'myview.html', {'name': 'Template Three'}) def articles(request): return render(request, 'articles.html', {'articles':Article.objects.all()}) def article(request, article_id = 1): comment_form = CommentForm() args = {} args['article'] = Article.objects.get(pk = article_id) args['comments'] = Comments.objects.filter(comments_article_id = article_id) args['form'] = comment_form return render(request, 'article.html', args) def addlike(request, article_id): try: article_object = Article.objects.get(pk = article_id) article_object.article_likes += 1 article_object.save() except Article.DoesNotExist: raise Http404("Объект табылмады") return HttpResponseRedirect(reverse('article:all')) def addcomment(request, article_id): if request.POST: form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) # form.comments_article_id = article_id form.comments_article = Article.objects.get(pk = article_id) form.save() return HttpResponseRedirect(reverse('article:detail',args = (article_id,)))<file_sep>/article/templates/article.html {% extends "main.html" %} {% block title %} Статья {% endblock %} {% block article %} <h1>{{ article.article_title }}</h1> <p>{{ article.article_text }}</p> <ul> {% for comment in comments %} <li>{{ comment.comments_text }}</li> {% endfor %} </ul> <form action="{% url 'article:addcomment' article.id %}" method="POST"> {% csrf_token %} {{ form.as_p }} <p> <input type = "submit" value="Добавить"> </p> </form> {% endblock %}<file_sep>/article/urls.py from django.conf.urls import include, url from views import * urlpatterns = [ url(r'^1/$', basic_one, name="basic_one"), url(r'^2/$', template_two, name = "template_two"), url(r'^3/$', template_three, name = "template_three"), url(r'^$', articles, name = "all"), url(r'^get/(?P<article_id>\d+)/$',article, name = "detail"), url(r'^addlike/(?P<article_id>\d+)/$',addlike, name = 'addlike' ), url(r'^addcomment/(?P<article_id>\d+)/$', addcomment, name = 'addcomment') ]
352e34225ef3766ef9ab279f1fbf30cc9e766bfb
[ "Python", "HTML" ]
4
Python
daucloudlab/Django_Demo_Site
6a61fc84d7c32f80f5d38aa34256cfb1ed5fac23
3a0f50b2e9caadd954bd0dfe8052137f81e68387
refs/heads/master
<repo_name>heyu-rise/ig<file_sep>/ig-core/src/main/java/org/heyu/ig/core/service/impl/UipRecordServiceImpl.java package org.heyu.ig.core.service.impl; import lombok.extern.slf4j.Slf4j; import org.heyu.ig.core.UipRequestRecord; import org.heyu.ig.core.service.UipRecordService; import org.heyu.ig.core.util.JsonUtil; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; /** * @author heyu * @date 2021/3/30 */ @Slf4j @Service public class UipRecordServiceImpl implements UipRecordService { private final LinkedBlockingQueue<UipRequestRecord> recordQueue = new LinkedBlockingQueue<>(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); @PostConstruct private void record(){ Thread thread = new Thread(this::recordLog); thread.setDaemon(true); executorService.execute(thread); } @Override public void add(UipRequestRecord record) { recordQueue.offer(record); } private void recordLog() { while (true) { try { UipRequestRecord uipRequestRecord = recordQueue.take(); log.info(JsonUtil.obj2json(uipRequestRecord)); } catch (Exception e) { e.printStackTrace(); } } } }
8c2f2e81d1752ad36371bf6462602b56c899c28a
[ "Java" ]
1
Java
heyu-rise/ig
9ad9f04e6ba54bc4963c927ac459e95b45016e32
a08eed53772c07e56218739d72b52fc01a2ab8b1
refs/heads/master
<file_sep>#!/bin/bash echo $REDIRECT > ./redirects.json go-wrapper run <file_sep># qr-platform-docker Very simple docker container to run qr-platform. It is an exercise for the user to figure out how they want to get redirects.json into the docker container. I am currently using an environment variable to pass in the JSON that I need. This isn't exactly scalable, but for now it will work. The ideal solution if scale is required would be to move to something like MongoDB and store all of the redirects there. <file_sep>FROM golang:latest RUN apt-get update && apt-get install -y git --no-install-recommends \ && rm -rf /var/lib/apt/lists/* WORKDIR /go/src/app RUN git clone https://github.com/BasiliskLabs/qr-platform.git WORKDIR /go/src/app/qr-platform RUN go-wrapper download RUN go-wrapper install EXPOSE 80 COPY ./entrypoint.sh . RUN chmod +x entrypoint.sh CMD ["./entrypoint.sh"]
1dfefc301655f197c5a57f3e0fceda9fc565d3c3
[ "Markdown", "Dockerfile", "Shell" ]
3
Shell
BasiliskLabs/qr-platform-docker
bdf16f552795348f4d8b3ceb2f40627ee122d35b
55889d251ae00709c314f64a485b48ff2f9c6cea
refs/heads/master
<repo_name>rubaimushtaq/intellij<file_sep>/src/SquareRoot.java public class SquareRoot { public static void main(String[] args) { double a; a = root(2); System.out.println(a); } static double root(int x) { return Math.sqrt(x); } } <file_sep>/src/CircleArea.java public class CircleArea { public static void main(String[] args) { // funtry(); float a, b; b=5.5f; a = area(b); //funtry(); System.out.println(a); System.out.println(area(5)); //funtry(); } static float area(float x) { System.out.println("In float"); final float pi = (float) 3.14; return (pi * x * x); } static float area(int x) { System.out.println("In int"); final float pi = (float) 3.14; return (pi * x * x); } /*static void funtry(){ System.out.println("Fun"); }*/ } <file_sep>/src/concat.java public class concat { public static void main(String[] args) { String name = "Rubai"; String lname = "Mushtaq"; System.out.println(name+" "+lname); } }<file_sep>/src/Addition.java import java.util.Scanner; public class Addition { public static void main(String[] args) { System.out.println("Enter 2 nos."); var scanner = new Scanner(System.in); var x = scanner.nextInt(); var y = scanner.nextInt(); var z = x + y; System.out.println(z); } } <file_sep>/src/AscToCh.java import java.util.Scanner; public class AscToCh { public static void main(String[] args) { System.out.println("Enter a number."); var sc = new Scanner(System.in); var a = sc.nextInt(); var ch = (char) a; System.out.println("Ascii char" + ch); } } <file_sep>/src/SpecChar.java public class SpecChar { public static void main(String[] args) { String txt = "Rubai\'s \"book\" is very good"; System.out.println(txt); } }<file_sep>/src/FirstProgram.java import java.util.Scanner; public class FirstProgram { public static void main(String[] args) { var sc = new Scanner(System.in); System.out.println("Enter a number"); var x = sc.nextInt(); System.out.println("Test" + x); System.out.println("Enter a float"); var a = sc.nextFloat(); System.out.println("Test" + a); } }
129602b62d350bf5a9ad3d00458f872a917ca748
[ "Java" ]
7
Java
rubaimushtaq/intellij
6fc1a10739dabc2ef07dedf23094af845800e5fe
866774c2212f3779f5bb9049179d09f37cf0035b
refs/heads/master
<file_sep><?php namespace DarkGhostHunter\Captchavel\Http\Middleware; use Closure; use DarkGhostHunter\Captchavel\Captchavel; class VerifyReCaptchaV2 extends BaseReCaptchaMiddleware { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string $variant * @param string $input * @return mixed * @throws \Illuminate\Validation\ValidationException */ public function handle($request, Closure $next, $variant, $input = Captchavel::INPUT) { if ($this->isEnabled() && $this->isReal()) { $this->validateRequest($request, $input); $this->processChallenge($request, $variant, $input); } return $next($request); } /** * Process a real challenge and response from reCAPTCHA servers. * * @param \Illuminate\Http\Request $request * @param string $variant * @param string $input * @throws \Illuminate\Validation\ValidationException */ protected function processChallenge($request, $variant, $input) { $this->dispatch($request, $response = $this->retrieve($request, $input, 2, $variant)); $this->validateResponse($response, $input); } } <file_sep><?php namespace Tests; use LogicException; use Orchestra\Testbench\TestCase; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Response; use DarkGhostHunter\Captchavel\Captchavel; use GuzzleHttp\Psr7\Response as GuzzleResponse; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class CaptchavelTest extends TestCase { use RegistersPackage; public function test_uses_v2_test_credentials_by_default() { $mock = $this->mock(Factory::class); $mock->shouldReceive('asForm')->withNoArgs()->times(3)->andReturnSelf(); $mock->shouldReceive('withOptions')->with(['version' => 2.0])->times(3)->andReturnSelf(); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => Captchavel::TEST_V2_SECRET, 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->times(3) ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, 'foo' => 'bar', ])))); $instance = app(Captchavel::class); $this->assertNull($instance->getResponse()); $checkbox = $instance->useCredentials(2, 'checkbox')->retrieve('token', '127.0.0.1'); $this->assertSame($checkbox, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $checkbox); $this->assertTrue($checkbox->success); $this->assertSame(0.5, $checkbox->score); $this->assertSame('bar', $checkbox->foo); $invisible = $instance->useCredentials(2, 'invisible')->retrieve('token', '127.0.0.1'); $this->assertSame($invisible, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $invisible); $this->assertTrue($invisible->success); $this->assertSame(0.5, $invisible->score); $this->assertSame('bar', $invisible->foo); $android = $instance->useCredentials(2, 'android')->retrieve('token', '127.0.0.1'); $this->assertSame($android, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $android); $this->assertTrue($android->success); $this->assertSame(0.5, $android->score); $this->assertSame('bar', $android->foo); } public function test_uses_v2_custom_credentials() { config(['captchavel.credentials.v2' => [ 'checkbox' => ['secret' => 'secret-checkbox'], 'invisible' => ['secret' => 'secret-invisible'], 'android' => ['secret' => 'secret-android'], ]]); $mock = $this->mock(Factory::class); $mock->shouldReceive('asForm')->withNoArgs()->times(3)->andReturnSelf(); $mock->shouldReceive('withOptions')->with(['version' => 2.0])->times(3)->andReturnSelf(); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => 'secret-checkbox', 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->once() ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, 'foo' => 'bar', ])))); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => 'secret-invisible', 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->once() ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, 'foo' => 'bar', ])))); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => 'secret-android', 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->once() ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, 'foo' => 'bar', ])))); $instance = app(Captchavel::class); $this->assertNull($instance->getResponse()); $checkbox = $instance->useCredentials(2, 'checkbox')->retrieve('token', '127.0.0.1'); $this->assertSame($checkbox, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $checkbox); $this->assertTrue($checkbox->success); $this->assertSame(0.5, $checkbox->score); $this->assertSame('bar', $checkbox->foo); $invisible = $instance->useCredentials(2, 'invisible')->retrieve('token', '127.0.0.1'); $this->assertSame($invisible, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $invisible); $this->assertTrue($invisible->success); $this->assertSame(0.5, $invisible->score); $this->assertSame('bar', $invisible->foo); $android = $instance->useCredentials(2, 'android')->retrieve('token', '127.0.0.1'); $this->assertSame($android, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $android); $this->assertTrue($android->success); $this->assertSame(0.5, $android->score); $this->assertSame('bar', $android->foo); } public function test_exception_if_no_v3_secret_issued() { $this->expectException(LogicException::class); $this->expectExceptionMessage('The reCAPTCHA secret for [v3] doesn\'t exists.'); $instance = app(Captchavel::class); $instance->useCredentials(3)->retrieve('token', '127.0.0.1'); } public function test_exception_when_invalid_credentials_issued() { $this->expectException(LogicException::class); $this->expectExceptionMessage('The reCAPTCHA v2 variant must be [checkbox], [invisible] or [android].'); $instance = app(Captchavel::class); $instance->useCredentials(2, 'invalid')->retrieve('token', '127.0.0.1'); } public function test_receives_v3_secret() { config(['captchavel.credentials.v3.secret' => 'secret']); $mock = $this->mock(Factory::class); $mock->shouldReceive('asForm')->withNoArgs()->once()->andReturnSelf(); $mock->shouldReceive('withOptions')->with(['version' => 2.0])->once()->andReturnSelf(); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => 'secret', 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->once() ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, 'foo' => 'bar', ])))); $instance = app(Captchavel::class); $this->assertNull($instance->getResponse()); $score = $instance->useCredentials(3)->retrieve('token', '127.0.0.1'); $this->assertSame($score, $instance->getResponse()); $this->assertInstanceOf(ReCaptchaResponse::class, $score); $this->assertTrue($score->success); $this->assertSame(0.5, $score->score); $this->assertSame('bar', $score->foo); } } <file_sep><?php namespace DarkGhostHunter\Captchavel; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class CaptchavelFake extends Captchavel { /** * Sets a fake response. * * @param \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse $response * @return $this */ public function setResponse(ReCaptchaResponse $response) { $this->response = $response; return $this; } /** * Sets the correct credentials to use to retrieve the challenge results. * * @param int $version * @param string|null $variant * @return $this */ public function useCredentials(int $version, string $variant = null) { return $this; } /** * Retrieves the Response Challenge. * * @param string $challenge * @param string $ip * @return \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ public function retrieve(?string $challenge, string $ip) { return $this->response; } /** * Makes the fake Captchavel response with a fake score. * * @param float $score * @return $this */ public function fakeScore(float $score) { return $this->setResponse(new ReCaptchaResponse([ 'success' => true, 'score' => $score, 'action' => null, 'hostname' => null, 'apk_package_name' => null, ])); } /** * Makes a fake Captchavel response made by a robot with "0" score. * * @return $this */ public function fakeRobot() { return $this->fakeScore(0); } /** * Makes a fake Captchavel response made by a human with "1.0" score. * * @return $this */ public function fakeHuman() { return $this->fakeScore(1); } } <file_sep><?php use DarkGhostHunter\Captchavel\Captchavel; return [ /* |-------------------------------------------------------------------------- | Main switch |-------------------------------------------------------------------------- | | This switch enables the main Captchavel middleware that will detect all | challenges incoming. You should activate it on production environments | and deactivate it on local environments unless you to test responses. | */ 'enable' => env('CAPTCHAVEL_ENABLE', false), /* |-------------------------------------------------------------------------- | Fake on local development |-------------------------------------------------------------------------- | | Sometimes you may want to fake success or failed responses from reCAPTCHA | servers in local development. To do this, simply enable the environment | variable and then issue as a checkbox parameter is_robot to any form. | */ 'fake' => env('CAPTCHAVEL_FAKE', false), /* |-------------------------------------------------------------------------- | Constraints |-------------------------------------------------------------------------- | | These default constraints allows further verification of the incoming | response from reCAPTCHA servers. Hostname and APK Package Name are | required if these are not verified in your reCAPTCHA admin panel. | */ 'hostname' => env('RECAPTCHA_HOSTNAME'), 'apk_package_name' => env('RECAPTCHA_APK_PACKAGE_NAME'), /* |-------------------------------------------------------------------------- | Threshold |-------------------------------------------------------------------------- | | For reCAPTCHA v3, which is an score-driven interaction, this default | threshold is the slicing point between bots and humans. If a score | is below this threshold, it means the request was made by a bot. | */ 'threshold' => 0.5, /* |-------------------------------------------------------------------------- | Credenctials |-------------------------------------------------------------------------- | | The following is the array of credentials for each version and variant | of the reCAPTCHA services. You shouldn't need to edit this unless you | know what you're doing. On reCAPTCHA v2, it comes with testing keys. | */ 'credentials' => [ 'v2' => [ 'checkbox' => [ 'secret' => env('RECAPTCHA_V2_CHECKBOX_SECRET', Captchavel::TEST_V2_SECRET), 'key' => env('RECAPTCHA_V2_CHECKBOX_KEY', Captchavel::TEST_V2_KEY), ], 'invisible' => [ 'secret' => env('RECAPTCHA_V2_INVISIBLE_SECRET', Captchavel::TEST_V2_SECRET), 'key' => env('RECAPTCHA_V2_INVISIBLE_KEY', Captchavel::TEST_V2_KEY), ], 'android' => [ 'secret' => env('RECAPTCHA_V2_ANDROID_SECRET', Captchavel::TEST_V2_SECRET), 'key' => env('RECAPTCHA_V2_ANDROID_KEY', Captchavel::TEST_V2_KEY), ], ], 'v3' => [ 'secret' => env('RECAPTCHA_V3_SECRET'), 'key' => env('RECAPTCHA_V3_KEY'), ], ], ]; <file_sep><?php namespace DarkGhostHunter\Captchavel\Events; use Illuminate\Http\Request; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class ReCaptchaResponseReceived { /** * The HTTP Request. * * @var \Illuminate\Http\Request */ public $request; /** * The reCAPTCHA Response. * * @var \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ public $response; /** * Create a new event instance. * * @param \Illuminate\Http\Request $request * @param \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse $response */ public function __construct(Request $request, ReCaptchaResponse $response) { $this->request = $request; $this->response = $response; } } <file_sep><?php namespace DarkGhostHunter\Captchavel; use Illuminate\Http\Request; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\Config\Repository; use DarkGhostHunter\Captchavel\Http\Middleware\VerifyReCaptchaV2; use DarkGhostHunter\Captchavel\Http\Middleware\VerifyReCaptchaV3; class CaptchavelServiceProvider extends ServiceProvider { /** * Register the application services. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/captchavel.php', 'captchavel'); $this->app->singleton(Captchavel::class); } /** * Bootstrap the application services. * * @param \Illuminate\Routing\Router $router * @param \Illuminate\Contracts\Config\Repository $config * @return void */ public function boot(Router $router, Repository $config) { if ($this->app->runningInConsole()) { $this->publishes([ __DIR__.'/../config/captchavel.php' => config_path('captchavel.php'), ], 'config'); if ($this->app->runningUnitTests()) { $config->set('captchavel.fake', true); } } $router->aliasMiddleware('recaptcha.v2', VerifyReCaptchaV2::class); $router->aliasMiddleware('recaptcha.v3', VerifyReCaptchaV3::class); Request::macro('isRobot', [RequestMacro::class, 'isRobot']); Request::macro('isHuman', [RequestMacro::class, 'isHuman']); } } <file_sep><?php namespace DarkGhostHunter\Captchavel; use LogicException; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Response; use Illuminate\Contracts\Config\Repository as Config; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class Captchavel { /** * reCAPTCHA v2 secret for testing on "localhost". * * @var string */ public const TEST_V2_SECRET = '<KEY>'; /** * reCAPTCHA v2 site key for testing on "localhost". * * @var string */ public const TEST_V2_KEY = '<KEY>'; /** * The URL where the reCAPTCHA challenge should be verified. * * @var string */ public const RECAPTCHA_ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify'; /** * The name of the input for a reCAPTCHA frontend response. * * @var string */ public const INPUT = 'g-recaptcha-response'; /** * The available reCAPTCHA v2 variants name. * * @var string */ public const V2_VARIANTS = [ 'checkbox', 'invisible', 'android', ]; /** * Laravel HTTP Client factory. * * @var \Illuminate\Http\Client\Factory|\Illuminate\Http\Client\PendingRequest */ protected $httpFactory; /** * Config Repository. * * @var \Illuminate\Contracts\Config\Repository */ protected $config; /** * Secret to use with given challenge. * * @var string */ protected $secret; /** * The Captchavel Response created from the reCAPTCHA response. * * @var null|\DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ protected $response; /** * Create a new Captchavel instance. * * @param \Illuminate\Http\Client\Factory $httpFactory * @param \Illuminate\Contracts\Config\Repository $config */ public function __construct(Factory $httpFactory, Config $config) { $this->httpFactory = $httpFactory; $this->config = $config; } /** * Returns the Captchavel Response, if any. * * @return null|\DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ public function getResponse() { return $this->response; } /** * Check if the a response was resolved from reCAPTCHA servers. * * @return bool */ public function isNotResolved() { return $this->response === null; } /** * Sets the correct credentials to use to retrieve the challenge results. * * @param int $version * @param string|null $variant * @return $this */ public function useCredentials(int $version, string $variant = null) { if ($version === 2) { if (! in_array($variant, static::V2_VARIANTS, true)) { throw new LogicException("The reCAPTCHA v2 variant must be [checkbox], [invisible] or [android]."); } $this->secret = $this->config->get("captchavel.credentials.v2.{$variant}.secret"); } elseif ($version === 3) { $this->secret = $this->config->get('captchavel.credentials.v3.secret'); } if (! $this->secret) { $name = 'v' . $version . ($variant ? '-' . $variant : ''); throw new LogicException("The reCAPTCHA secret for [{$name}] doesn't exists."); } return $this; } /** * Retrieves the Response Challenge. * * @param string $challenge * @param string $ip * @return \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ public function retrieve(string $challenge, string $ip) { $response = $this->httpFactory->asForm() ->withOptions(['version' => 2.0]) ->post(static::RECAPTCHA_ENDPOINT, [ 'secret' => $this->secret, 'response' => $challenge, 'remoteip' => $ip, ]); return $this->parse($response); } /** * Parses the Response * * @param \Illuminate\Http\Client\Response $response * @return \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ protected function parse(Response $response) { return $this->response = new ReCaptchaResponse($response->json()); } } <file_sep><?php namespace DarkGhostHunter\Captchavel\Http; use LogicException; use Illuminate\Support\Fluent; /** * Class ReCaptchaResponse * * @package DarkGhostHunter\Captchavel\Http * * @property-read null|string $hostname * @property-read null|string $challenge_ts * @property-read null|string $apk_package_name * @property-read null|float $score * @property-read null|string $action * @property-read array $error_codes * @property-read bool $success */ class ReCaptchaResponse extends Fluent { /** * The threshold for reCAPTCHA v3. * * @var float */ protected $threshold; /** * Sets the threshold to check the response. * * @param float $threshold * @return $this */ public function setThreshold(float $threshold) { $this->threshold = $threshold; return $this; } /** * Returns if the response was made by a Human. * * @throws \LogicException * @return bool */ public function isHuman() { if ($this->score === null) { throw new LogicException('This is not a reCAPTCHA v3 response, or the score is absent.'); } return $this->score >= $this->threshold; } /** * Returns if the response was made by a Robot. * * @return bool */ public function isRobot() { return ! $this->isHuman(); } /** * Returns if the challenge is valid. * * @return bool */ public function isValid() { return $this->success && empty($this->error_codes); } /** * Returns if the challenge is invalid. * * @return bool */ public function isInvalid() { return ! $this->isValid(); } /** * Check if the hostname is different to the one issued. * * @param string|null $string * @return bool */ public function differentHostname(?string $string) { return $string && $this->hostname !== $string; } /** * Check if the APK name is different to the one issued. * * @param string|null $string * @return bool */ public function differentApk(?string $string) { return $string && $this->apk_package_name !== $string; } /** * Check if the action name is different to the one issued. * * @param null|string $action * @return bool */ public function differentAction(?string $action) { return $action && $this->action !== $action; } /** * Dynamically return an attribute as a property. * * @param $name * @return null|mixed */ public function __get($name) { // Minor fix for getting the error codes return parent::__get($name === 'error_codes' ? 'error-codes' : $name); } } <file_sep><?php namespace Tests\Http\Middleware; use Tests\RegistersPackage; use Illuminate\Http\Request; use Orchestra\Testbench\TestCase; use Illuminate\Http\Client\Factory; use Illuminate\Http\Client\Response; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Event; use DarkGhostHunter\Captchavel\Captchavel; use GuzzleHttp\Psr7\Response as GuzzleResponse; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; use DarkGhostHunter\Captchavel\Events\ReCaptchaResponseReceived; class ScoreMiddlewareTest extends TestCase { use RegistersPackage; use UsesRoutesWithMiddleware; protected function setUp() : void { $this->afterApplicationCreated(function () { $this->createsRoutes(); config(['captchavel.fake' => false]); }); parent::setUp(); } public function test_bypass_if_not_enabled() { config(['captchavel.enable' => false]); $event = Event::fake(); $this->mock(Captchavel::class)->shouldNotReceive('useCredentials', 'retrieve'); $this->post('v3/default')->assertOk(); $event->assertNotDispatched(ReCaptchaResponseReceived::class); } public function test_validates_if_real() { $mock = $this->mock(Captchavel::class); $event = Event::fake(); $mock->shouldReceive('useCredentials') ->with(3, null) ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'score' => 0.5, 'foo' => 'bar' ])); $this->post('v3/default', [ Captchavel::INPUT => 'token' ]) ->assertOk() ->assertExactJson([ 'success' => true, 'score' => 0.5, 'foo' => 'bar' ]); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->foo === 'bar' && $event->request instanceof Request; }); } public function test_fakes_human_response_automatically() { config(['captchavel.fake' => true]); $event = Event::fake(); $this->post('v3/default') ->assertOk() ->assertExactJson([ 'success' => true, 'score' => 1, 'action' => null, 'hostname' => null, 'apk_package_name' => null, ]); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); } public function test_fakes_robot_response_if_input_is_robot_present() { config(['captchavel.fake' => true]); $event = Event::fake(); $this->post('v3/default', ['is_robot' => 'on']) ->assertOk() ->assertExactJson([ 'success' => true, 'score' => 0, 'action' => null, 'hostname' => null, 'apk_package_name' => null, ]); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); } public function test_uses_custom_threshold() { $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->andReturnSelf(); $mock->shouldReceive('retrieve')->andReturn(new ReCaptchaResponse([ 'success' => true, 'score' => 0.7, 'foo' => 'bar' ])); $event = Event::fake(); Route::post('test', function (ReCaptchaResponse $response) { return [$response->isHuman(), $response->isRobot(), $response->score]; })->middleware('recaptcha.v3:0.7'); $this->post('test', [ Captchavel::INPUT => 'token' ]) ->assertOk() ->assertExactJson([ true, false, 0.7 ]); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); } public function test_uses_custom_input() { $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'score' => 0.7, 'foo' => 'bar' ])); $event = Event::fake(); Route::post('test', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,null,foo'); $this->post('test', [ 'foo' => 'token' ]) ->assertOk() ->assertExactJson([ 'success' => true, 'score' => 0.7, 'foo' => 'bar', ]); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); } public function test_exception_when_token_absent() { $event = Event::fake(); $this->post('v3/default', [ 'foo' => 'bar' ])->assertRedirect('/'); $this->postJson('v3/default', [ 'foo' => 'bar' ])->assertJsonValidationErrors(Captchavel::INPUT); $event->assertNotDispatched(ReCaptchaResponseReceived::class); } public function test_exception_when_response_invalid() { $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => false, ])); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertRedirect('/'); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === false && $event->request instanceof Request; }); $this->postJson('v3/default', [ 'foo' => 'bar' ])->assertJsonValidationErrors(Captchavel::INPUT); } public function test_no_error_if_not_hostname_issued() { config(['captchavel.hostname' => null]); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'foo', ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); } public function test_no_error_if_hostname_same() { config(['captchavel.hostname' => 'bar']); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'bar', ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->success === true && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); } public function test_exception_if_hostname_not_equal() { config(['captchavel.hostname' => 'bar']); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'foo', ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertRedirect('/'); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->hostname === 'foo' && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertJsonValidationErrors('hostname'); } public function test_no_error_if_no_apk_issued() { config(['captchavel.apk_package_name' => null]); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => 'foo', ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->apk_package_name === 'foo' && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); } public function test_no_error_if_apk_same() { config(['captchavel.apk_package_name' => 'foo']); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => 'foo', ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->apk_package_name === 'foo' && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertOk(); } public function test_exception_if_apk_not_equal() { config(['captchavel.apk_package_name' => 'bar']); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => null, ])); $event = Event::fake(); $this->post('v3/default', [ Captchavel::INPUT => 'token' ])->assertRedirect('/'); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->apk_package_name === null && $event->request instanceof Request; }); $this->postJson('v3/default', [ Captchavel::INPUT => 'token' ])->assertJsonValidationErrors('apk_package_name'); } public function test_no_error_if_no_action() { $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => null, 'action' => 'foo', ])); $event = Event::fake(); Route::post('test', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,null'); $this->post('test', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->action === 'foo' && $event->request instanceof Request; }); } public function test_no_error_if_action_same() { $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => null, 'action' => 'foo', ])); $event = Event::fake(); Route::post('test', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,foo'); $this->post('test', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatched(ReCaptchaResponseReceived::class, function ($event) { return $event->response->action === 'foo' && $event->request instanceof Request; }); } public function test_exception_if_action_not_equal() { $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials') ->andReturnSelf(); $mock->shouldReceive('retrieve') ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => null, 'action' => 'foo', ])); Route::post('test', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,bar'); $this->post('test', [ Captchavel::INPUT => 'token' ])->assertRedirect('/'); $this->postJson('test', [ Captchavel::INPUT => 'token' ])->assertJsonValidationErrors('action'); } public function test_checks_for_human_score() { config(['captchavel.credentials.v3.secret' => 'secret']); config(['captchavel.fake' => false]); $mock = $this->mock(Factory::class); $mock->shouldReceive('asForm')->withNoArgs()->times(4)->andReturnSelf(); $mock->shouldReceive('withOptions')->with(['version' => 2.0])->times(4)->andReturnSelf(); $mock->shouldReceive('post') ->with(Captchavel::RECAPTCHA_ENDPOINT, [ 'secret' => 'secret', 'response' => 'token', 'remoteip' => '127.0.0.1', ]) ->times(4) ->andReturn(new Response(new GuzzleResponse(200, ['Content-type' => 'application/json'], json_encode([ 'success' => true, 'score' => 0.5, ])))); Route::post('human_human', function (Request $request) { return $request->isHuman() ? 'true' : 'false'; })->middleware('recaptcha.v3:0.7'); Route::post('human_robot', function (Request $request) { return $request->isRobot() ? 'true' : 'false'; })->middleware('recaptcha.v3:0.7'); Route::post('robot_human', function (Request $request) { return $request->isHuman() ? 'true' : 'false'; })->middleware('recaptcha.v3:0.3'); Route::post('robot_robot', function (Request $request) { return $request->isRobot() ? 'true' : 'false'; })->middleware('recaptcha.v3:0.3'); $this->post('human_human', [Captchavel::INPUT => 'token'])->assertSee('false'); $this->post('human_robot', [Captchavel::INPUT => 'token'])->assertSee('true'); $this->post('robot_human', [Captchavel::INPUT => 'token'])->assertSee('true'); $this->post('robot_robot', [Captchavel::INPUT => 'token'])->assertSee('false'); } } <file_sep><?php namespace DarkGhostHunter\Captchavel\Http\Middleware; use Closure; use DarkGhostHunter\Captchavel\Captchavel; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class VerifyReCaptchaV3 extends BaseReCaptchaMiddleware { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $threshold * @param string|null $action * @param string $input * @return mixed * @throws \Illuminate\Validation\ValidationException */ public function handle($request, Closure $next, $threshold = null, $action = null, $input = Captchavel::INPUT) { if ($this->isEnabled()) { if ($this->isReal()) { $this->validateRequest($request, $input); } else { $this->fakeResponseScore($request); // We will disable the action name since it will be verified if we don't null it. $action = null; } $this->processChallenge($request, $threshold, $action, $input); } return $next($request); } /** * Process the response from reCAPTCHA servers. * * @param \Illuminate\Http\Request $request * @param null|string $threshold * @param null|string $action * @param string $input * @throws \Illuminate\Validation\ValidationException */ protected function processChallenge($request, $threshold, $action, $input) { $response = $this->retrieve($request, $input, 3); $response->setThreshold($this->normalizeThreshold($threshold)); $this->dispatch($request, $response); $this->validateResponse($response, $input, $this->normalizeAction($action)); // After we get the response, we will register the instance as a shared ("singleton"). // Obviously we will set the threshold set by the developer or just use the default. // The Response should not be available until the middleware runs, so this is ok. app()->instance(ReCaptchaResponse::class, $response); } /** * Normalize the threshold string. * * @param string|null $threshold * @return array|float|mixed */ protected function normalizeThreshold($threshold) { return $threshold === 'null' ? $this->config->get('captchavel.threshold') : (float)$threshold; } /** * Normalizes the action name, or returns null. * * @param null|string $action * @return null|string */ protected function normalizeAction($action) { return strtolower($action) === 'null' ? null : $action; } } <file_sep><?php namespace Tests\Http\Middleware; use Tests\RegistersPackage; use Orchestra\Testbench\TestCase; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Route; use DarkGhostHunter\Captchavel\Captchavel; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; use DarkGhostHunter\Captchavel\Events\ReCaptchaResponseReceived; class ChallengeMiddlewareTest extends TestCase { use RegistersPackage; use UsesRoutesWithMiddleware; protected function setUp() : void { $this->afterApplicationCreated(function () { $this->createsRoutes(); config(['captchavel.fake' => false]); }); parent::setUp(); } public function test_exception_if_no_challenge_specified() { Route::post('test', function () { return 'ok'; })->middleware('recaptcha.v2'); $this->post('test')->assertStatus(500); $this->postJson('test')->assertJson(['message' => 'Server Error']); } public function test_bypass_if_not_enabled() { config(['captchavel.enable' => false]); $event = Event::fake(); $this->mock(Captchavel::class)->shouldNotReceive('useCredentials', 'retrieve'); $this->post('v2/checkbox')->assertOk(); $this->post('v2/invisible')->assertOk(); $this->post('v2/android')->assertOk(); $event->assertNotDispatched(ReCaptchaResponseReceived::class); } public function test_fakes_success() { config(['captchavel.fake' => true]); $this->post('v2/checkbox')->assertOk(); $this->post('v2/checkbox/input_bar')->assertOk(); $this->post('v2/invisible')->assertOk(); $this->post('v2/invisible/input_bar')->assertOk(); $this->post('v2/android')->assertOk(); $this->post('v2/android/input_bar')->assertOk(); } public function test_validates_if_real() { $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'score' => 0.5, 'foo' => 'bar' ])); $this->post('v2/checkbox', [ Captchavel::INPUT => 'token' ])->assertOk(); $this->post('v2/invisible', [ Captchavel::INPUT => 'token' ])->assertOk(); $this->post('v2/android', [ Captchavel::INPUT => 'token' ])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_uses_custom_input() { $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'score' => 0.5, 'foo' => 'bar' ])); $this->post('v2/checkbox/input_bar', [ 'bar' => 'token' ])->assertOk(); $this->post('v2/invisible/input_bar', [ 'bar' => 'token' ])->assertOk(); $this->post('v2/android/input_bar', [ 'bar' => 'token' ])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_exception_when_token_absent() { $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldNotReceive('useCredentials', 'retrieve'); $this->post('v2/checkbox')->assertRedirect('/'); $this->postJson('v2/checkbox')->assertJsonValidationErrors(Captchavel::INPUT); $this->post('v2/invisible')->assertRedirect('/'); $this->postJson('v2/invisible')->assertJsonValidationErrors(Captchavel::INPUT); $this->post('v2/android')->assertRedirect('/'); $this->postJson('v2/android')->assertJsonValidationErrors(Captchavel::INPUT); $this->post('v2/checkbox/input_bar')->assertRedirect('/'); $this->postJson('v2/checkbox/input_bar')->assertJsonValidationErrors('bar'); $this->post('v2/invisible/input_bar')->assertRedirect('/'); $this->postJson('v2/invisible/input_bar')->assertJsonValidationErrors('bar'); $this->post('v2/android/input_bar')->assertRedirect('/'); $this->postJson('v2/android/input_bar')->assertJsonValidationErrors('bar'); $event->assertNotDispatched(ReCaptchaResponseReceived::class); } public function test_exception_when_response_invalid() { $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->twice()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(6) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => false, ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/checkbox', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors(Captchavel::INPUT); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/invisible', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors(Captchavel::INPUT); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/android', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors(Captchavel::INPUT); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 6); } public function test_no_error_if_not_hostname_issued() { config(['captchavel.hostname' => null]); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_no_error_if_not_hostname_same() { config(['captchavel.hostname' => 'foo']); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_exception_if_hostname_not_equal() { config(['captchavel.hostname' => 'bar']); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->twice()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(6) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'hostname' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/checkbox', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('hostname'); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/invisible', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('hostname'); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/android', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('hostname'); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 6); } public function test_no_error_if_no_apk_issued() { config(['captchavel.apk_package_name' => null]); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_no_error_if_no_apk_same() { config(['captchavel.apk_package_name' => 'foo']); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->once()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->once()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(3) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertOk(); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertOk(); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 3); } public function test_exception_if_apk_not_equal() { config(['captchavel.apk_package_name' => 'bar']); $event = Event::fake(); $mock = $this->mock(Captchavel::class); $mock->shouldReceive('useCredentials')->twice()->with(2, 'checkbox')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'invisible')->andReturnSelf(); $mock->shouldReceive('useCredentials')->twice()->with(2, 'android')->andReturnSelf(); $mock->shouldReceive('retrieve') ->times(6) ->with('token', '127.0.0.1') ->andReturn(new ReCaptchaResponse([ 'success' => true, 'apk_package_name' => 'foo' ])); $this->post('v2/checkbox', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/checkbox', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('apk_package_name'); $this->post('v2/invisible', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/invisible', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('apk_package_name'); $this->post('v2/android', [Captchavel::INPUT => 'token'])->assertRedirect('/'); $this->postJson('v2/android', [Captchavel::INPUT => 'token'])->assertJsonValidationErrors('apk_package_name'); $event->assertDispatchedTimes(ReCaptchaResponseReceived::class, 6); } } <file_sep><?php namespace Tests\Http; use LogicException; use Tests\RegistersPackage; use Orchestra\Testbench\TestCase; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; class ReCaptchaResponseTest extends TestCase { use RegistersPackage; public function test_exception_when_checking_non_score_response() { $this->expectException(LogicException::class); $this->expectExceptionMessage('This is not a reCAPTCHA v3 response, or the score is absent.'); (new ReCaptchaResponse([ 'success' => true, ]))->isHuman(); } } <file_sep><?php namespace Tests\Http\Middleware; use Illuminate\Support\Facades\Route; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; trait UsesRoutesWithMiddleware { protected function createsRoutes() { config(['captchavel.enable' => true]); Route::post('v3/default', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3'); Route::post('v3/threshold_1', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:1.0'); Route::post('v3/threshold_0', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:0'); Route::post('v3/action_foo', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,foo'); Route::post('v3/input_bar', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v3:null,null,bar'); Route::post('v2/checkbox', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:checkbox'); Route::post('v2/checkbox/input_bar', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:checkbox,bar'); Route::post('v2/invisible', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:invisible'); Route::post('v2/invisible/input_bar', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:invisible,bar'); Route::post('v2/android', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:android'); Route::post('v2/android/input_bar', function (ReCaptchaResponse $response) { return $response; })->middleware('recaptcha.v2:android,bar'); } } <file_sep><?php namespace DarkGhostHunter\Captchavel\Http\Middleware; use Illuminate\Http\Request; use DarkGhostHunter\Captchavel\Captchavel; use Illuminate\Config\Repository as Config; use Illuminate\Validation\ValidationException; use DarkGhostHunter\Captchavel\Http\ReCaptchaResponse; use DarkGhostHunter\Captchavel\Events\CaptchavelSuccessEvent; use DarkGhostHunter\Captchavel\Events\ReCaptchaResponseReceived; use DarkGhostHunter\Captchavel\Facades\Captchavel as CaptchavelFacade; abstract class BaseReCaptchaMiddleware { /** * Captchavel instance * * @var \DarkGhostHunter\Captchavel\Captchavel */ protected $captchavel; /** * Config Repository * * @var \Illuminate\Config\Repository */ protected $config; /** * VerifyReCaptchaV2 constructor. * * @param \DarkGhostHunter\Captchavel\Captchavel $captchavel * @param \Illuminate\Config\Repository $config */ public function __construct(Captchavel $captchavel, Config $config) { $this->captchavel = $captchavel; $this->config = $config; } /** * Determines if the reCAPTCHA verification should be enabled. * * @return bool */ protected function isEnabled() { return $this->config->get('captchavel.enable'); } /** * Check if the reCAPTCHA response can be faked on-demand. * * @return bool */ protected function isFake() { return $this->config->get('captchavel.fake'); } /** * Check if the reCAPTCHA response must be real. * * @return bool */ protected function isReal() { return ! $this->isFake(); } /** * Validate if this Request has the reCAPTCHA challenge string. * * @param \Illuminate\Http\Request $request * @param string $name * @return void * @throws \Illuminate\Validation\ValidationException */ protected function validateRequest($request, string $name) { if (! is_string($request->get($name))) { throw $this->validationException($name, 'The reCAPTCHA challenge is missing or has not been completed.'); } } /** * Retrieves the Captchavel response from reCAPTCHA servers. * * @param \Illuminate\Http\Request $request * @param string $input * @param int $version * @param string|null $variant * @return \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse */ protected function retrieve(Request $request, string $input, int $version, string $variant = null) { return $this->captchavel ->useCredentials($version, $variant) ->retrieve($request->input($input), $request->ip()); } /** * Fakes a v3 reCAPTCHA response. * * @param \Illuminate\Http\Request $request * @return void */ protected function fakeResponseScore($request) { // We will first check if the Captchavel instance was not already faked. If it has been, // we will hands out the control to the developer. Otherwise, we will manually create a // fake Captchavel instance and look for the "is_robot" parameter to set a fake score. if ($this->captchavel instanceof Captchavel && $this->captchavel->isNotResolved()) { $this->captchavel = $request->has('is_robot') ? CaptchavelFacade::fakeRobot() : CaptchavelFacade::fakeHuman(); } } /** * Validate the Hostname and APK name from the response. * * @param \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse $response * @param string $input * @param string|null $action * @throws \Illuminate\Validation\ValidationException */ protected function validateResponse(ReCaptchaResponse $response, $input = Captchavel::INPUT, ?string $action = null) { if ($response->differentHostname($this->config->get('captchavel.hostname'))) { throw $this->validationException('hostname', "The hostname [{$response->hostname}] of the response is invalid."); } if ($response->differentApk($this->config->get('captchavel.apk_package_name'))) { throw $this->validationException('apk_package_name', "The apk_package_name [{$response->apk_package_name}] of the response is invalid."); } if ($response->differentAction($action)) { throw $this->validationException('action', "The action [{$response->action}] of the response is invalid."); } if ($response->isInvalid()) { throw $this->validationException($input, "The reCAPTCHA challenge is invalid or was not completed."); } } /** * Creates a new Validation Exception instance. * * @param string $input * @param string $message * @return \Illuminate\Validation\ValidationException */ protected function validationException($input, $message) { return ValidationException::withMessages([$input => trans($message)])->redirectTo(back()->getTargetUrl()); } /** * Dispatch an event with the request and the Captchavel Response * * @param \Illuminate\Http\Request $request * @param \DarkGhostHunter\Captchavel\Http\ReCaptchaResponse $response */ protected function dispatch(Request $request, ReCaptchaResponse $response) { event(new ReCaptchaResponseReceived($request, $response)); } }
37cd6f372852125fbe16394543efeadac77d6b69
[ "PHP" ]
14
PHP
kaiusk/Captchavel
e660554c4fab4a2bbb341ac9d6bbb169eb34c734
14f2e6c33fdb461ec5eec915e1b8340465783ff2
refs/heads/master
<file_sep># coding: utf-8 # A sample Gemfile source "https://rubygems.org" gem 'sinatra' gem 'sinatra-contrib' gem 'sinatra-activerecord' gem 'sqlite3' gem 'rake' gem 'bcrypt' gem 'hirb' #sqlite3 見やすく group :development do gem 'sqlite3' end group :production do gem 'pg' end <file_sep>require 'bundler/setup' Bundler.require require 'sinatra/reloader' if development? require 'open-uri' require 'json' require 'net/http' require 'sinatra/activerecord' require './models' enable :sessions helpers do def current_user User.find_by(id: session[:user]) end end get '/' do @users = User.all erb :index end get '/signup' do erb :sign_up end post '/signup' do user = User.create( name: params[:name], password: params[:password], password_confirmation: params[:password_confirmation], developer_name: params[:developer_name], ) session[:user] = user.id redirect '/' end get '/signin' do erb :sign_in end post '/signin' do user = User.find_by(name: params[:name]) if user && user.authenticate(params[:password]) session[:user] = user.id end redirect '/' end get '/signout' do session[:user] = nil redirect '/' end get "/developer" do uri = URI("https://itunes.apple.com/search") uri.query = URI.encode_www_form({ term: params[:developer_name], media: 'software', entity: 'software', country: 'jp', lang: 'ja_jp' }) res = Net::HTTP.get_response(uri) json = JSON.parse(res.body) @datas = json # if json["results"] # response = {error: "No Station."} # else # response = { # next: json["results"]["station"][0]["next"], # prev: json["results"]["station"][0]["prev"] # } # end # json response erb :developer end <file_sep># itunes_api test iTunes API
f9e3cfe8933a4e62f261947328b95a9c941e87a0
[ "Markdown", "Ruby" ]
3
Ruby
hinatades/itunes_api
30ff32b6547a18455268f8f520202692293d7c70
9b9ab7b3bc81308b8afdd51e05e6b77a44283982
refs/heads/main
<repo_name>sarvesh873/clashrcbackend<file_sep>/rc/urls.py from django.urls import path from .views import login , signup urlpatterns = [ path('signup', signup, name='signup'), path('login',login, name='login'), # path('logout',logout, name='logout'), # path('result/',result), ]<file_sep>/rc/views.py from django.shortcuts import render,redirect from django.contrib import auth from django.contrib.auth.models import User from django.contrib import messages from django.http.response import HttpResponse, HttpResponseRedirect from django.db.models import Q from .models import extendeduser import re def login(request): if request.method == 'POST': user = auth.authenticate( username = request.POST['name'], password=request.POST['<PASSWORD>']) if user is not None: auth.login(request,user) datas = extendeduser.objects.filter(user = request.user) return render(request,'clash/result.html',{'data':datas}) # return render(request,'task3/result.html') else: return render(request, 'rc/login.html',{ 'error': "invalid login credentials"}) else: return render(request,'rc/login.html') def signup(request): if request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'rc/register.html',{'error': "username already exist"}) except User.DoesNotExist: # user = User.objects.create_user(username=request.POST['username'],password= request.POST['<PASSWORD>'],email= request.POST['email']) # user = User.objects.create_user(username=request.POST['username'],password= request.POST['<PASSWORD>1']) fst=request.POST['firstname'] lst=request.POST['lstname'] num=request.POST['number'] gender=request.POST['gender'] email= request.POST['email'] if (len(request.POST['password1'])<10): return render(request,'rc/register.html',{'error':"Password too Short, Should Contain ATLEAST 1 Uppercase,1 lowercase,1 special Character and 1 Numeric Value"}) elif not re.search(r"[\d]+",request.POST['password1']): return render(request,'rc/register.html',{'error':"Your Password must contain Atleast 1 Numeric value "}) elif not re.findall('[A-Z]', request.POST['password1']): return render(request,'rc/register.html',{'error':"Your Password must contain Atleast 1 UpperCase Letter "}) elif not re.findall('[a-z]',request.POST['password1']): return render(request,'rc/register.html',{'error':"Your Password must contain Atleast 1 lowercase Letter "}) elif not re.findall('[()[\]{}|\\`~!@#$%^&*_\-+=;:\'",<>./?]', request.POST['password1']): return render(request,'rc/register.html',{'error':"Your Password must contain Atleast 1 Specail character "}) else: if extendeduser.objects.filter(email=email): return render(request, 'rc/register.html',{'error': "email id already exist try using another one"}) elif extendeduser.objects.filter(number=num): return render(request, 'rc/register.html',{'error': "phonenumber already exist try using another one"}) else: user = User.objects.create_user(username=request.POST['username'],password= request.POST['<PASSWORD>']) newextendeduser = extendeduser(firstname=fst, lstname=lst,email=email ,number=num,gender=gender,user=user) newextendeduser.save() auth.login(request, user) messages.success(request, f'Your account has been Create!! Login Now') return redirect(login) else: return render(request, 'rc/register.html',{'error': "Password doesnot match"}) else: return render(request, "rc/register.html") def logout(request): return render(request, "rc/logout.html")<file_sep>/clash/views.py from django.http.response import HttpResponse from django.shortcuts import render from django.core.checks import messages import re def result(request): if(request.method == "POST"): input = request.POST['input'] formating_choice = request.POST['category'] if(formating_choice == 'num'): pattern = re.compile(r'[1-9]\d[1-9]\d*|[1-9]\d\d\d+') elif(formating_choice == 'date'): pattern = re.compile(r'([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])') elif(formating_choice == 'quote'): pattern = re.compile(r"'(.*)'") elif(formating_choice == 'ipadd'): pattern = re.compile(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}') match = pattern.findall(input)[0] if(0<=int(match[0:3])<=127): return render(request,'clash/result.html',{ 'addr':match,'class':'class A' }) elif(128<=int(match[0:3])<=191): return render(request,'clash/result.html',{ 'addr':match,'class':'class B' }) elif(192<=int(match[0:3])<=223): return render(request,'clash/result.html',{ 'addr':match,'class':'class C' }) elif(224<=int(match[0:3])<=239): return render(request,'clash/result.html',{ 'addr':match,'class':'class D' }) elif(240<=int(match[0:3])<=255): return render(request,'clash/result.html',{ 'addr':match,'class':'class E' }) else: return render(request,'clash/result.html',{ 'class':'Input ivalid select proper category.' }) elif(formating_choice == "macadd"): pattern = re.compile(r'[A-F0-9a-f]{2}[-:][A-F0-9a-f]{2}[-:][A-F0-9a-f]{2}[-:][A-F0-9a-f]{2}[-:][A-F0-9a-f]{2}[-:][A-F0-9a-f]{2}') elif(formating_choice == "snake"): def func(x): char = x.group(0) return "_"+char.lower() pattern = re.compile(r'([A-Z])') match = pattern.sub(func,input) return render(request,'clash/result.html',{'class':match}) match = pattern.findall(input) if(len(match) == 0): return render(request,'clash/result.html',{'class':'Input ivalid select proper category.'}) return render(request,"clash/result.html",{'output':match}) return render(request, "clash/result.html") <file_sep>/rc/models.py from django.db import models from django.contrib.auth.models import User GENDER_CHOICES = ( ("Male","Male"),("Female","Female"),("Other","Other") ) # Create your models here. class extendeduser(models.Model): email = models.EmailField(max_length=200,null=True,default="") firstname = models.CharField(max_length=200,null=True,default="") lstname = models.CharField(max_length=200,null=True,default="") number = models.CharField(max_length=20,null=True,default="") gender = models.CharField(max_length=20, choices=GENDER_CHOICES,null=True,default="") user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) <file_sep>/clash/urls.py from django.urls import path from .import views urlpatterns = [ path('result/',views.result, name='result'), ]<file_sep>/rc/apps.py from django.apps import AppConfig class RcConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'rc'
76793a19d746bde343832e65e516866ec7e91936
[ "Python" ]
6
Python
sarvesh873/clashrcbackend
7d5b33ff377fc220ed5191c73ae2c0109487c611
b90ea223990bf38462d1ef315b05098479ab8f86
refs/heads/master
<repo_name>chiragsharma991/GRN<file_sep>/app/src/main/java/com/gayatry/model/TaxListModel.java package com.gayatry.model; /** * Created by Admin on 04-May-16. */ public class TaxListModel { public String Amount; public String PrintName; public String getRate() { return Rate; } public void setRate(String rate) { Rate = rate; } public String getAmount() { return Amount; } public void setAmount(String amount) { Amount = amount; } public String getPrintName() { return PrintName; } public void setPrintName(String printName) { PrintName = printName; } public String getTax_ID() { return Tax_ID; } public void setTax_ID(String tax_ID) { Tax_ID = tax_ID; } public String getTax_Detail_ID() { return Tax_Detail_ID; } public void setTax_Detail_ID(String tax_Detail_ID) { Tax_Detail_ID = tax_Detail_ID; } public String Rate; public String Tax_Detail_ID; public String Tax_ID; } <file_sep>/app/src/main/java/com/gayatry/grn/fragment/GRNGeneralFragment.java package com.gayatry.grn.fragment; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import com.gayatry.R; import com.gayatry.grn.AddGRNActivity; import com.gayatry.model.PoNoModel; import com.gayatry.model.SupplierListModel; import com.gayatry.rest.JsonParser; import com.gayatry.storage.SharedPreferenceUtil; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.AsyncTaskCommon; import com.gayatry.utilz.AsyncTaskPostCommon; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Created by Admin on 06-Apr-16. */ public class GRNGeneralFragment extends Fragment implements View.OnClickListener{ private TextView txtGrnDate, txtChallanDate, txtInvoiceDate, txtLRDate, txtPoDate; private EditText edtGrnCode, edtChallanNo, edtInvoiceNo, edtCrPeriod, edtLRNo, edtVehicleNo, edtRemark; private List<SupplierListModel> mSupplierList; private List<PoNoModel> mPoNoList; private LinearLayout mLinParent; private Spinner mSpnrSupplier, mSpnrPoNo; private ProgressBar mProgressSupplier, mProgressPoNo; private String strGrnCode, strChallanNo, strInvoiceNo, strCrPeriod, strLRNo, strVehicleNo, strRemark, strGrnDate, strChallanDate, strInvoiceDate, strLRDate, strPoDate; private RadioGroup mRadioGrpGrnType; private GetPoNoAsync getPoNoAsync; private GetSupplierAsync getSupplierAsync; private AsyncTaskCommon asyncTaskCommon; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_add_general, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); getGeneratedGrnCode("PO"); mRadioGrpGrnType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radioGrnType = (RadioButton) getView().findViewById(checkedId); getGeneratedGrnCode(radioGrnType.getText().toString()); } }); mSpnrSupplier.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(AppUtils.isOnline(getContext())){ getPoNoAsync = new GetPoNoAsync(); getPoNoAsync.execute(getSelectedSupplierID(position)); }else{ AppUtils.showSnakbar(mLinParent, getString(R.string.error_internet)); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } void getGeneratedGrnCode(String grnType){ if(AppUtils.isOnline(getActivity())) { asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { if (result.length() > 0) { try { if (result != "") { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { edtGrnCode.setText(jsonArray.getJSONObject(0).getString("Tcode")); } else { AppUtils.showSnakbar(mLinParent, getString(R.string.no_data_available)); } } else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); } } else AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } }); asyncTaskCommon.execute(getString(R.string.get_grn_code_url) + "/" + ((AddGRNActivity) getActivity()).mProjectId + "/grn/" + SharedPreferenceUtil.getString(AppUtils.YEAR_CODE, "") + "/" + grnType); } } @Override public void onStop() { super.onStop(); if(getSupplierAsync != null && getSupplierAsync.getStatus() != AsyncTask.Status.FINISHED) { getSupplierAsync.cancel(true); } if(getPoNoAsync != null && getPoNoAsync.getStatus() != AsyncTask.Status.FINISHED) { getPoNoAsync.cancel(true); } if(asyncTaskCommon != null && asyncTaskCommon.getStatus() != AsyncTask.Status.FINISHED) { asyncTaskCommon.cancel(true); } } private String getSelectedSupplierID(int position) { return mSupplierList.get(position).getPartyID(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser){ if(AppUtils.isOnline(getContext())){ if(mSupplierList == null) { getSupplierAsync = new GetSupplierAsync(); getSupplierAsync.execute(); } }else{ AppUtils.showSnakbar(mLinParent, getString(R.string.error_internet)); } } } private void initView(View view) { txtGrnDate = (TextView) view.findViewById(R.id.txtGrnDate); txtChallanDate = (TextView) view.findViewById(R.id.txtChallanDate); txtInvoiceDate = (TextView) view.findViewById(R.id.txtInvoiceDate); txtLRDate = (TextView) view.findViewById(R.id.txtLRDate); txtPoDate = (TextView) view.findViewById(R.id.txtPoDate); mLinParent = (LinearLayout) view.findViewById(R.id.linParent); mSpnrSupplier = (Spinner) view.findViewById(R.id.spnrSupplier); mSpnrPoNo = (Spinner) view.findViewById(R.id.spnrPoNo); mProgressPoNo = (ProgressBar) view.findViewById(R.id.pono_progress); mProgressSupplier = (ProgressBar) view.findViewById(R.id.supplier_progress); edtGrnCode = (EditText) view.findViewById(R.id.edtGrnCode); edtChallanNo = (EditText) view.findViewById(R.id.edtChallanNo); edtInvoiceNo = (EditText) view.findViewById(R.id.edtInvoiceNo); edtCrPeriod = (EditText) view.findViewById(R.id.edtCrPeriod); edtLRNo = (EditText) view.findViewById(R.id.edtLRNo); edtVehicleNo = (EditText) view.findViewById(R.id.edtVehicleNo); edtRemark = (EditText) view.findViewById(R.id.edtRemark); mRadioGrpGrnType = (RadioGroup) view.findViewById(R.id.radioGroupGrnType); txtGrnDate.setOnClickListener(this); txtChallanDate.setOnClickListener(this); txtInvoiceDate.setOnClickListener(this); txtLRDate.setOnClickListener(this); txtPoDate.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.txtGrnDate: DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt("dateFrom",1); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtChallanDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom",2); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtInvoiceDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom",3); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtLRDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom",4); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtPoDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom",5); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; } } public String getAllValues() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("GRN_ID", "0"); jsonObject.put("WC_Id", ""+((AddGRNActivity)getActivity()).mProjectId); jsonObject.put("YearCode", ""+ SharedPreferenceUtil.getString(AppUtils.YEAR_CODE, "")); jsonObject.put("GRN_Code", ""+strGrnCode); jsonObject.put("GRN_date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strGrnDate)); jsonObject.put("GRN_Type", ""+ getSelectedGrnType());//radio btn jsonObject.put("Order_ID", "0"); jsonObject.put("Party_ID", ""+getSelectedSupplierID(mSpnrSupplier.getSelectedItemPosition())); jsonObject.put("Challan_No", ""+strChallanNo); jsonObject.put("Challan_Date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strChallanDate)); jsonObject.put("Supp_Inv_No", ""+strInvoiceNo); jsonObject.put("Supp_Inv_Date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strInvoiceDate)); jsonObject.put("Credit_Period", ""+strCrPeriod); jsonObject.put("LR_No", ""+strLRNo); jsonObject.put("LR_Date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strLRDate)); jsonObject.put("Transporter", "0"); jsonObject.put("VehicleNo", ""+strVehicleNo); jsonObject.put("RegisterTypeID", "0"); jsonObject.put("AssessableAmount", ""+((AddGRNActivity)getActivity()).mAssessableAmount); jsonObject.put("TotalTaxValue", "0"); jsonObject.put("TotalGRNValue", "0"); jsonObject.put("Inspected_By", "1"); jsonObject.put("IsAccepted", "1"); jsonObject.put("Created_By", ""+SharedPreferenceUtil.getString(AppUtils.USER_ID, "")); jsonObject.put("Create_date", ""+AppUtils.getCurruntDate()); jsonObject.put("Modify_By", "0"); jsonObject.put("Modify_date", "1990-01-01"); jsonObject.put("IsCancelled", "0"); jsonObject.put("Remark", ""+strRemark); } catch (JSONException e) { e.printStackTrace(); } return jsonObject.toString(); } private String getSelectedGrnType() { int selectedId = mRadioGrpGrnType.getCheckedRadioButtonId(); RadioButton radioGrnType = (RadioButton) getView().findViewById(selectedId); return radioGrnType.getText().toString(); /* if(radioGrnType.getText().toString().equals("PO")){ return "0"; }else { return "1"; }*/ } public boolean isValidate() { strGrnCode = edtGrnCode.getText().toString().trim(); strChallanNo = edtChallanNo.getText().toString().trim(); strInvoiceNo = edtInvoiceNo.getText().toString().trim(); strCrPeriod = edtCrPeriod.getText().toString().trim(); strLRNo = edtLRNo.getText().toString().trim(); strVehicleNo = edtVehicleNo.getText().toString().trim(); strRemark = edtRemark.getText().toString().trim(); strGrnDate = txtGrnDate.getText().toString(); strChallanDate = txtChallanDate.getText().toString(); strInvoiceDate = txtInvoiceDate.getText().toString(); strLRDate = txtLRDate.getText().toString(); strPoDate = txtPoDate.getText().toString(); if (TextUtils.isEmpty(strGrnCode)) { edtGrnCode.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strChallanNo)) { edtChallanNo.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strInvoiceNo)) { edtInvoiceNo.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strCrPeriod)) { edtCrPeriod.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strLRNo)) { edtLRNo.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strVehicleNo)) { edtVehicleNo.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strRemark)) { edtRemark.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strGrnDate)) { txtGrnDate.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strChallanDate)) { txtChallanDate.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strInvoiceDate)) { txtInvoiceDate.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strLRDate)) { txtLRDate.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strPoDate)) { txtPoDate.setError(getString(R.string.error_field_required)); return false; } return true; } @SuppressLint("ValidFragment") public class DatePickerDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { private boolean cancelDialog = false; private int year; private int month; private int day; private int dateFrom; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); dateFrom = getArguments().getInt("dateFrom"); DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day); //datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis()); return datePickerDialog; } public void setDatePickerDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); cancelDialog = true; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (!cancelDialog) { String mDatePick = AppUtils.formattedDate("yyyy MM dd", "dd MMMM yyyy", ""+year+" "+(month+1)+" "+day); switch (dateFrom){ case 1: txtGrnDate.setText(mDatePick); break; case 2: txtChallanDate.setText(mDatePick); break; case 3: txtInvoiceDate.setText(mDatePick); break; case 4: txtLRDate.setText(mDatePick); break; case 5: txtPoDate.setText(mDatePick); break; } } } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDatePickerDate(year, monthOfYear, dayOfMonth); } } class GetSupplierAsync extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { try{ JsonParser jsonParser = new JsonParser(); return jsonParser.getResponse(getString(R.string.get_supplier_list_url)+"/1"); }catch (Exception e){ e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); mProgressSupplier.setVisibility(View.GONE); handleSupplierResponse(response); } } private void handleSupplierResponse(String response) { try{ if(response!="") { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { mSupplierList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { SupplierListModel supplierListModel = new SupplierListModel(); supplierListModel.setParty_Type(jsonArray.getJSONObject(i).getString("Party_Type")); supplierListModel.setPartyID(jsonArray.getJSONObject(i).getString("PartyID")); supplierListModel.setPartyType_Id(jsonArray.getJSONObject(i).getString("PartyType_Id")); supplierListModel.setPartyName(jsonArray.getJSONObject(i).getString("PartyName")); mSupplierList.add(supplierListModel); } setSupplierSpinnerAdapter(); } else { AppUtils.showSnakbar(mLinParent, getString(R.string.no_data_available)); } }else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } }catch (Exception e){ e.printStackTrace(); /* if(mLinParent != null) AppUtils.showSnakbar(mLinParent, getString(R.string.error_server));*/ } } private void setSupplierSpinnerAdapter() { if(mSpnrSupplier!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getSupplierName()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrSupplier.setAdapter(adapter); } } public ArrayList<String> getSupplierName() { ArrayList<String> supplierName = new ArrayList<>(); for (SupplierListModel model : mSupplierList){ supplierName.add(model.getPartyName()); } return supplierName; } class GetPoNoAsync extends AsyncTask<String, Void, String>{ @Override protected void onPreExecute() { super.onPreExecute(); mProgressPoNo.setVisibility(View.VISIBLE); } @Override protected String doInBackground(String... params) { try{ JsonParser jsonParser = new JsonParser(); return jsonParser.getResponse(getString(R.string.get_PO_list_url)+"/"+params[0]+"/"+((AddGRNActivity)getActivity()).mProjectId+"/P/A"); }catch (Exception e){ e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); mProgressPoNo.setVisibility(View.GONE); try{ if(response!="") { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { mPoNoList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { PoNoModel poNoModel = new PoNoModel(); poNoModel.setPCode(jsonArray.getJSONObject(i).getString("PCode")); poNoModel.setPID(jsonArray.getJSONObject(i).getString("PID")); mPoNoList.add(poNoModel); } setPoNoSpinnerAdapter(); } else { if(mPoNoList != null) { mPoNoList.clear(); setPoNoSpinnerAdapter(); } AppUtils.showSnakbar(mLinParent, getString(R.string.no_data_available)); } }else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } }catch (Exception e){ e.printStackTrace(); /*if(mLinParent != null) AppUtils.showSnakbar(mLinParent, getString(R.string.error_server));*/ } } } private void setPoNoSpinnerAdapter() { if(mSpnrPoNo!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getPoCode()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrPoNo.setAdapter(adapter); } } public ArrayList<String> getPoCode() { ArrayList<String> poCode = new ArrayList<>(); for (PoNoModel model : mPoNoList){ poCode.add(model.getPCode()); } return poCode; } } <file_sep>/app/src/main/java/com/gayatry/report/adapter/AgingReportRecyclerAdapter.java package com.gayatry.report.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gayatry.R; import com.gayatry.model.AgingReportModel; import com.gayatry.report.fragment.AgingReportFragment; import java.util.List; /** * Created by Admin on 01-May-16. */ public class AgingReportRecyclerAdapter extends RecyclerView.Adapter<AgingReportRecyclerAdapter.ViewHolder> { private List<AgingReportModel> mDataset; private AgingReportFragment agingReportFragment; public AgingReportRecyclerAdapter(List<AgingReportModel> arrayList, AgingReportFragment agingReportFragment) { mDataset = arrayList; this.agingReportFragment = agingReportFragment; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView mTxtProductName, mTxtDay30, mTxtCategory, mTxtDay60, mTxtDay90, mTxtDay150, mTxtDay180, mTxtDayAbove180; public ViewHolder(View v) { super(v); mTxtProductName = (TextView) v.findViewById(R.id.txtProductName); mTxtDay30 = (TextView) v.findViewById(R.id.txtDay30); mTxtCategory = (TextView) v.findViewById(R.id.txtCategory); mTxtDay60 = (TextView) v.findViewById(R.id.txtDay60); mTxtDay90 = (TextView) v.findViewById(R.id.txtDay90); mTxtDay150 = (TextView) v.findViewById(R.id.txtDay150); mTxtDay180 = (TextView) v.findViewById(R.id.txtDay180); mTxtDayAbove180 = (TextView) v.findViewById(R.id.txtDayAbove180); } } @Override public AgingReportRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_aging_report, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.mTxtProductName.setText(mDataset.get(position).getProduct_Name()); holder.mTxtCategory.setText(mDataset.get(position).getProduct_Category_Name()); holder.mTxtDay30.setText("<=30 : "+mDataset.get(position).getDays30_Qty()); holder.mTxtDay60.setText(">30 & <=60 : "+mDataset.get(position).getDays3060_Qty()); holder.mTxtDay90.setText(">60 & <=90 : "+mDataset.get(position).getDays6090_Qty()); holder.mTxtDay150.setText(">90 & <=150 : "+mDataset.get(position).getDays90150_Qty()); holder.mTxtDay180.setText(">150 & <=180 : "+mDataset.get(position).getDays150180_Qty()); holder.mTxtDayAbove180.setText(">180 : "+mDataset.get(position).getDays180_Qty()); } @Override public int getItemCount() { return mDataset.size(); } } <file_sep>/app/src/main/java/com/gayatry/gtn/fragment/EditGTNGeneralFragment.java package com.gayatry.gtn.fragment; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import com.gayatry.R; import com.gayatry.gtn.AddGTNActivity; import com.gayatry.gtn.EditGTNActivity; import com.gayatry.model.EditGTNModel; import com.gayatry.model.GTNListModel; import com.gayatry.model.ProjectListModel; import com.gayatry.storage.SharedPreferenceUtil; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.AsyncTaskCommon; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; /** * Created by Admin on 27-Apr-16. */ public class EditGTNGeneralFragment extends Fragment implements View.OnClickListener{ private EditText edtGtnCode, edtChallanNo, edtRemark; private TextView txtGtnDate, txtChallanDate; private Spinner mSpnrProject; private AsyncTaskCommon asyncTaskCommon; private ProgressBar mProductProgressBar; private LinearLayout mLinParent; private String strGtnCode, strChallanNo,strRemark, strGtnDate, strChallanDate; private String GTN_MODEL="gtn_model"; private GTNListModel gtnListModel; private ArrayList<ProjectListModel> mProjectList; private RadioGroup mRadioGrpGtnType; private ArrayList<EditGTNModel> mEditGTNModelList; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_add_gtn_general, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); gtnListModel = (GTNListModel) getArguments().getSerializable(GTN_MODEL); mEditGTNModelList = ((EditGTNActivity)getActivity()).mEditGTNModelList; initView(view); setValues(); mRadioGrpGtnType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton radioGrnType = (RadioButton) getView().findViewById(checkedId); getGeneratedGtnCode(radioGrnType.getText().toString()); } }); } void getGeneratedGtnCode(String grnType){ if(AppUtils.isOnline(getActivity())) { asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { if (result.length() > 0) { try { if (result != "") { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { edtGtnCode.setText(jsonArray.getJSONObject(0).getString("Tcode")); } else { AppUtils.showSnakbar(mLinParent, getString(R.string.no_data_available)); } } else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); } } else AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } }); asyncTaskCommon.execute(getString(R.string.get_grn_code_url) + "/" + ((EditGTNActivity) getActivity()).mProjectId + "/gtn/" + SharedPreferenceUtil.getString(AppUtils.YEAR_CODE, "") + "/" + grnType); } } private void setValues() { edtGtnCode.setText(mEditGTNModelList.get(0).getGTN_Code()); edtChallanNo.setText(mEditGTNModelList.get(0).getChallan_No()); edtRemark.setText(mEditGTNModelList.get(0).getRemark()); txtGtnDate.setText(AppUtils.formattedDate("MM/dd/yyyy", "dd MMMM yyyy", mEditGTNModelList.get(0).getGTN_date().split(" ")[0])); txtChallanDate.setText(AppUtils.formattedDate("MM/dd/yyyy", "dd MMMM yyyy", mEditGTNModelList.get(0).getChallan_Date().split(" ")[0])); mRadioGrpGtnType.check(mEditGTNModelList.get(0).getGTN_Type().equalsIgnoreCase("GTN") ? R.id.radioPO : R.id.radioDirect); } private void initView(View view) { edtGtnCode = (EditText) view.findViewById(R.id.edtGtnCode); edtChallanNo = (EditText) view.findViewById(R.id.edtChallanNo); edtRemark = (EditText) view.findViewById(R.id.edtRemark);; txtGtnDate = (TextView) view.findViewById(R.id.txtGtnDate); txtChallanDate = (TextView) view.findViewById(R.id.txtChallanDate);; mSpnrProject = (Spinner) view.findViewById(R.id.spnrProject); mLinParent = (LinearLayout) view.findViewById(R.id.linParent); mProductProgressBar = (ProgressBar) view.findViewById(R.id.project_progress); mRadioGrpGtnType = (RadioGroup) view.findViewById(R.id.radioGroupGtnType); txtGtnDate.setOnClickListener(this); txtChallanDate.setOnClickListener(this); } @Override public void onStop() { super.onStop(); if(asyncTaskCommon != null && asyncTaskCommon.getStatus() != AsyncTask.Status.FINISHED) { asyncTaskCommon.cancel(true); } } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser){ if(AppUtils.isOnline(getContext())){ getProjectList(); }else{ AppUtils.showSnakbar(mLinParent, getString(R.string.error_internet)); } } } void getProjectList(){ asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { if(result.length() > 0){ handleProjects(result); }else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); mProductProgressBar.setVisibility(View.GONE); } } }); asyncTaskCommon.execute(getString(R.string.get_project_list_gtn_url)); } private void handleProjects(String result) { mProductProgressBar.setVisibility(View.GONE); try{ if(result!="") { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { mProjectList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { ProjectListModel projectListModel = new ProjectListModel(); projectListModel.setName(jsonArray.getJSONObject(i).getString("Name")); projectListModel.setExcise_Opening(jsonArray.getJSONObject(i).getString("Excise_Opening")); projectListModel.setNonExcise_Opening(jsonArray.getJSONObject(i).getString("NonExcise_Opening")); projectListModel.setWC_ID(jsonArray.getJSONObject(i).getString("WC_ID")); mProjectList.add(projectListModel); } setProductSpinnerAdapter(); } else { AppUtils.showSnakbar(mLinParent, getString(R.string.no_data_available)); } }else { AppUtils.showSnakbar(mLinParent, getString(R.string.error_server)); } }catch (Exception e){ e.printStackTrace(); } } private void setProductSpinnerAdapter() { if(mSpnrProject!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getProjectName()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrProject.setAdapter(adapter); mSpnrProject.setSelection(getProjectSeletedId()); } } private int getProjectSeletedId() { for (int i = 0; i < mProjectList.size(); i++) { if(mEditGTNModelList.get(0).getProduct_ID().equals(mProjectList.get(i).getWC_ID())) return i; } return 0; } public ArrayList<String> getProjectName() { ArrayList<String> product = new ArrayList<>(); for (ProjectListModel model : mProjectList){ product.add(model.getName()); } return product; } public boolean isValidate() { strGtnCode = edtGtnCode.getText().toString().trim(); strChallanNo = edtChallanNo.getText().toString().trim(); strRemark = edtRemark.getText().toString().trim(); strGtnDate = txtGtnDate.getText().toString(); strChallanDate = txtChallanDate.getText().toString(); if (TextUtils.isEmpty(strGtnCode)) { edtGtnCode.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strChallanNo)) { edtChallanNo.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strRemark)) { edtRemark.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strGtnDate)) { txtGtnDate.setError(getString(R.string.error_field_required)); return false; }else if (TextUtils.isEmpty(strChallanDate)) { txtChallanDate.setError(getString(R.string.error_field_required)); return false; } return true; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.txtGtnDate: DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt("dateFrom", 1); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtChallanDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom", 2); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; } } public String getAllValues() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("GTN_ID", ""+((EditGTNActivity)getActivity()).mEditGTNModelList.get(0).getGTN_ID()); //jsonObject.put("WC_Id", ""+((EditGTNActivity)getActivity()).mProjectId); //jsonObject.put("YearCode", ""+ SharedPreferenceUtil.getString(AppUtils.YEAR_CODE, "")); //jsonObject.put("GTN_Code", ""+strGtnCode); jsonObject.put("GTN_date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strGtnDate)); //jsonObject.put("GTN_Type", ""+getSelectedGtnType()); jsonObject.put("Challan_No", ""+strChallanNo); jsonObject.put("Challan_Date", ""+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", strChallanDate)); //jsonObject.put("Project_ID", ""+getProjectId(mSpnrProject.getSelectedItemPosition())); jsonObject.put("TotalGTNValue", ""+((EditGTNActivity)getActivity()).mAssesableAmount); jsonObject.put("Modify_By", ""+SharedPreferenceUtil.getString(AppUtils.USER_ID, "")); jsonObject.put("Remark", ""+strRemark); } catch (JSONException e) { e.printStackTrace(); } return jsonObject.toString(); } private String getProjectId(int selectedItemPosition) { return mProjectList.get(selectedItemPosition).getWC_ID(); } private String getSelectedGtnType() { int selectedId = mRadioGrpGtnType.getCheckedRadioButtonId(); RadioButton radioGrnType = (RadioButton) getView().findViewById(selectedId); if(radioGrnType.getText().toString().equals("GTN")){ return "0"; }else { return "1"; } } @SuppressLint("ValidFragment") public class DatePickerDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { private boolean cancelDialog = false; private int year; private int month; private int day; private int dateFrom; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); dateFrom = getArguments().getInt("dateFrom"); DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day); //datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis()); return datePickerDialog; } public void setDatePickerDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); cancelDialog = true; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (!cancelDialog) { String mDatePick = AppUtils.formattedDate("yyyy MM dd", "dd MMMM yyyy", ""+year+" "+(month+1)+" "+day); switch (dateFrom){ case 1: txtGtnDate.setText(mDatePick); break; case 2: txtChallanDate.setText(mDatePick); break; } } } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDatePickerDate(year, monthOfYear, dayOfMonth); } } } <file_sep>/app/src/main/java/com/gayatry/model/ProductDetailModel.java package com.gayatry.model; /** * Created by Admin on 01-May-16. */ public class ProductDetailModel { public String Abbreviation; public String getProduct_Id() { return Product_Id; } public void setProduct_Id(String product_Id) { Product_Id = product_Id; } public String getAbbreviation() { return Abbreviation; } public void setAbbreviation(String abbreviation) { Abbreviation = abbreviation; } public String getProduct_Name() { return Product_Name; } public void setProduct_Name(String product_Name) { Product_Name = product_Name; } public String Product_Id; public String Product_Name; } <file_sep>/app/src/main/java/com/gayatry/grn/adapter/GRNRecyclerAdapter.java package com.gayatry.grn.adapter; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.gayatry.R; import com.gayatry.grn.GRNListActivity; import com.gayatry.model.GRNListModel; import java.util.ArrayList; import java.util.List; public class GRNRecyclerAdapter extends RecyclerView.Adapter<GRNRecyclerAdapter.ViewHolder> { private List<GRNListModel> mDataset; private GRNListActivity grnListActivity; private int lastPosition = 0; public GRNRecyclerAdapter(ArrayList<GRNListModel> arrayList, GRNListActivity grnListActivity) { mDataset=arrayList; this.grnListActivity = grnListActivity; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView mTxtPartyName, mTxtGrnType, mTxtDate, mTxtGrnCode, mTxtEdit, mTxtDelete; public CardView mCardView; public ViewHolder(View v) { super(v); mTxtPartyName = (TextView) v.findViewById(R.id.txtPartyName); mTxtGrnType = (TextView) v.findViewById(R.id.txtGrnType); mTxtDate = (TextView) v.findViewById(R.id.txtDate); mTxtGrnCode = (TextView) v.findViewById(R.id.txtGrnCode); mTxtEdit = (TextView) v.findViewById(R.id.txtEdit); mTxtDelete = (TextView) v.findViewById(R.id.txtDelete); mCardView = (CardView) v.findViewById(R.id.card_view); } } @Override public GRNRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_grn, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.mTxtPartyName.setText(mDataset.get(position).getPartyName()); holder.mTxtDate.setText(mDataset.get(position).getGRN_date()); holder.mTxtGrnCode.setText(mDataset.get(position).getGRN_Code()); holder.mTxtGrnType.setText(mDataset.get(position).getGRN_Type()); holder.mTxtDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { grnListActivity.openAlertDialog(mDataset.get(position), position); } }); holder.mTxtEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { grnListActivity.onEditClick(mDataset.get(position)); } }); animate(holder.mCardView, position); } @Override public int getItemCount() { return mDataset.size(); } /* @Override public void onViewDetachedFromWindow(ViewHolder holder) { super.onViewDetachedFromWindow(holder); ((ViewHolder)holder).mCardView.clearAnimation(); }*/ private void setAnimation(View viewToAnimate, int position) { if (position > lastPosition) { Animation animation = AnimationUtils.loadAnimation(grnListActivity, android.R.anim.slide_in_left); viewToAnimate.startAnimation(animation); lastPosition = position; } } private void animate(View view, final int pos) { if (pos > lastPosition) { view.animate().cancel(); view.setTranslationY(100); view.setAlpha(0); view.animate().alpha(1.0f).translationY(0).setDuration(300).setStartDelay(100); lastPosition = pos; } } }<file_sep>/app/src/main/java/com/gayatry/utilz/ClickListnerOwn.java package com.gayatry.utilz; /** * Created by Admin on 08-Aug-16. */ public interface ClickListnerOwn { void onClick(String msg); } <file_sep>/app/src/main/java/com/gayatry/gtn/adapter/GTNRecyclerAdapter.java package com.gayatry.gtn.adapter; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gayatry.R; import com.gayatry.gtn.GTNListActivity; import com.gayatry.model.GTNListModel; import com.gayatry.utilz.AppUtils; import java.util.ArrayList; import java.util.List; /** * Created by Admin on 23-Apr-16. */ public class GTNRecyclerAdapter extends RecyclerView.Adapter<GTNRecyclerAdapter.ViewHolder> { private List<GTNListModel> mDataset; private GTNListActivity gtnListActivity; private int lastPosition = 0; public GTNRecyclerAdapter(ArrayList<GTNListModel> arrayList, GTNListActivity gtnListActivity) { mDataset=arrayList; this.gtnListActivity = gtnListActivity; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView mTxtProjectName, mTxtChallanNo, mTxtDate, mTxtGtnCode, mTxtEdit, mTxtDelete; public CardView mCardView; public ViewHolder(View v) { super(v); mTxtProjectName = (TextView) v.findViewById(R.id.txtProjectName); mTxtChallanNo = (TextView) v.findViewById(R.id.txtChallanNo); mTxtDate = (TextView) v.findViewById(R.id.txtDate); mTxtGtnCode = (TextView) v.findViewById(R.id.txtGtnCode); mCardView = (CardView) v.findViewById(R.id.card_view); mTxtEdit = (TextView) v.findViewById(R.id.txtEdit); mTxtDelete = (TextView) v.findViewById(R.id.txtDelete); } } @Override public GTNRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_gtn, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.mTxtProjectName.setText(mDataset.get(position).getProjectName()); holder.mTxtDate.setText(AppUtils.formattedDate("dd/MM/yyyy", "dd MMM yyyy", mDataset.get(position).getGTN_date())); holder.mTxtGtnCode.setText(mDataset.get(position).getGTN_Code()); holder.mTxtChallanNo.setText(mDataset.get(position).getChallan_No()); holder.mTxtDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gtnListActivity.openAlertDialog(mDataset.get(position), position); } }); holder.mTxtEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gtnListActivity.onEditClick(mDataset.get(position)); } }); animate(holder.mCardView, position); } @Override public int getItemCount() { return mDataset.size(); } private void animate(View view, final int pos) { if (pos > lastPosition) { view.animate().cancel(); view.setTranslationY(100); view.setAlpha(0); view.animate().alpha(1.0f).translationY(0).setDuration(300).setStartDelay(100); lastPosition = pos; } } }<file_sep>/app/src/main/java/com/gayatry/utilz/AppUtils.java package com.gayatry.utilz; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.ColorDrawable; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.os.Build; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.gayatry.R; import com.gayatry.prelogin.LoginFragment; import com.gayatry.storage.SharedPreferenceUtil; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by Admin on 05-Apr-16. */ public class AppUtils { public static final String IS_LOGIN = "is_login"; public static final String USER_ID = "user_id"; public static final String USER_NAME = "user_name"; public static final String PROFILE_PIC = "profile_pic"; public static final String ROLE_USER = "role"; public static final String YEAR_CODE = "year_code"; public static final String USER_FULL_NAME = "user_full_name"; public static final int REQUEST_CODE_ADD_GRN = 101; private static Dialog dialog; public static void closeKeyBoard(Activity context) { View view = context.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public static boolean isOnline(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Network[] networks = connectivityManager.getAllNetworks(); NetworkInfo networkInfo; for (Network mNetwork : networks) { networkInfo = connectivityManager.getNetworkInfo(mNetwork); if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) { return true; } } }else { if (connectivityManager != null) { NetworkInfo[] info = connectivityManager.getAllNetworkInfo(); if (info != null) { for (NetworkInfo anInfo : info) { if (anInfo.getState() == NetworkInfo.State.CONNECTED) { return true; } } } } } return false; } public final static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } public static void showSnakbar(View view, String msg){ if(view != null) { Snackbar snackbar = Snackbar .make(view, msg, Snackbar.LENGTH_LONG); snackbar.show(); } } public static void showAlertDialog(Context context, String title, String msg){ AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AppCompatAlertDialogStyle); builder.setTitle(title); builder.setMessage(title); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); /* builder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } });*/ builder.show(); } public static String formattedDate(String inputFormat, String outputFormat, String inputDate){ if(inputFormat.equals("")){ inputFormat = "yyyy-MM-dd hh:mm:ss"; } if(outputFormat.equals("")){ outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; } Date parsed = null; String outputDate = ""; SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault()); SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault()); try { parsed = df_input.parse(inputDate); outputDate = df_output.format(parsed); } catch (Exception e) { e.printStackTrace(); } return outputDate; } public static String getCurruntDate(){ Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = df.format(c.getTime()); return formattedDate; } public static void showProgressDialog(Context context) { if (dialog != null) { if (dialog.isShowing()) dialog.dismiss(); dialog = null; } dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(false); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); dialog.setContentView(R.layout.dialog_loader); dialog.show(); } public static void stopProgressDialog() { if (dialog != null) { if (dialog.isShowing()) dialog.dismiss(); dialog = null; } } } <file_sep>/app/src/main/java/com/gayatry/report/fragment/AgingReportFragment.java package com.gayatry.report.fragment; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Spinner; import com.gayatry.R; import com.gayatry.model.AgingReportModel; import com.gayatry.model.PaymentReportModel; import com.gayatry.model.ProductListModel; import com.gayatry.report.adapter.AgingReportRecyclerAdapter; import com.gayatry.report.adapter.PaymentReportRecyclerAdapter; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.AsyncTaskCommon; import com.gayatry.utilz.floatingMenu.FloatingActionButton; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.Arrays; /** * Created by Admin on 01-May-16. */ public class AgingReportFragment extends Fragment{ private RecyclerView mRecyclerView; private AgingReportRecyclerAdapter agingReportRecyclerAdapter; private FloatingActionButton mGenerateReport; private Spinner mSpnrProduct; private ProgressBar mProgress, mProductProgress; private String PartyId = "PartyId"; private String PartyName = "PartyName"; private final String ProjectId = "projectId"; private ArrayList<ProductListModel> mProductList; private RelativeLayout mRelParent; private ArrayList<AgingReportModel> mListAging; private AsyncTaskCommon asyncTaskCommon; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_aging_report, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); mGenerateReport.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mProductList != null && mProductList.size() > 0){ getAgingReportList(getSelectedPartyId(mSpnrProduct.getSelectedItemPosition())); } } }); } private String getSelectedPartyId(int selectedItemPosition) { return mProductList.get(selectedItemPosition).getProduct_Category_Id(); } private void setRecyclerAdapter() { final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); agingReportRecyclerAdapter = new AgingReportRecyclerAdapter(mListAging, AgingReportFragment.this); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(false); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setAdapter(agingReportRecyclerAdapter); } private void initView(View view) { mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mGenerateReport = (FloatingActionButton) view.findViewById(R.id.btnGenerateReport); mSpnrProduct = (Spinner) view.findViewById(R.id.spnrProductName); mProgress = (ProgressBar) view.findViewById(R.id.progress); mProductProgress = (ProgressBar) view.findViewById(R.id.product_progress); mRelParent = (RelativeLayout) view.findViewById(R.id.relParent); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser){ if(AppUtils.isOnline(getContext())){ if(mProductList == null) getProductList(); }else{ AppUtils.showSnakbar(mRelParent, getString(R.string.error_internet)); } } } @Override public void onStop() { super.onStop(); if(asyncTaskCommon != null && asyncTaskCommon.getStatus() != AsyncTask.Status.FINISHED) { asyncTaskCommon.cancel(true); } } private void getProductList() { asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { mProductProgress.setVisibility(View.GONE); if (result.length() > 0) { try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { mProductList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { ProductListModel productListModel = new ProductListModel(); productListModel.setAbbreviation(jsonArray.getJSONObject(i).getString("Abbreviation")); productListModel.setDescription(jsonArray.getJSONObject(i).getString("Description")); productListModel.setIs_Active(jsonArray.getJSONObject(i).getString("Is_Active")); productListModel.setProduct_Category_Id(jsonArray.getJSONObject(i).getString("Product_Category_Id")); productListModel.setProduct_Category_Name(jsonArray.getJSONObject(i).getString("Product_Category_Name")); mProductList.add(productListModel); } setSpinnerAdapter(); } } catch (Exception e) { e.printStackTrace(); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } }else { mProductProgress.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } }); asyncTaskCommon.execute(getString(R.string.get_product_category_url)+"/0"); } private void setSpinnerAdapter() { if(mSpnrProduct!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getProductName()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrProduct.setAdapter(adapter); } } private ArrayList<String> getProductName() { ArrayList<String> productName = new ArrayList<>(); for (ProductListModel model : mProductList){ productName.add(model.getProduct_Category_Name()); } return productName; } private void getAgingReportList(String partyId) { mProgress.setVisibility(View.VISIBLE); AsyncTaskCommon asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { mProgress.setVisibility(View.GONE); if(result.length() > 0){ try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { mListAging = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { AgingReportModel agingReportModel = new AgingReportModel(); agingReportModel.setDays180_Qty(jsonArray.getJSONObject(i).getString("Days180_Qty")); agingReportModel.setDays3060_Qty(jsonArray.getJSONObject(i).getString("Days3060_Qty")); agingReportModel.setDays6090_Qty(jsonArray.getJSONObject(i).getString("Days6090_Qty")); agingReportModel.setDays90150_Qty(jsonArray.getJSONObject(i).getString("Days90150_Qty")); agingReportModel.setProduct_Category_Name(jsonArray.getJSONObject(i).getString("Product_Category_Name")); agingReportModel.setProduct_Id(jsonArray.getJSONObject(i).getString("Product_Id")); agingReportModel.setProduct_Name(jsonArray.getJSONObject(i).getString("Product_Name")); agingReportModel.setDays150180_Qty(jsonArray.getJSONObject(i).getString("Days150180_Qty")); agingReportModel.setDays30_Qty(jsonArray.getJSONObject(i).getString("days30_Qty")); mListAging.add(agingReportModel); } setRecyclerAdapter(); }else { mProgress.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_data_unavailable)); } } catch (JSONException e) { e.printStackTrace(); } }else { mProgress.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } }); asyncTaskCommon.execute(getString(R.string.aging_report_url)+"/"+partyId+"/"+getArguments().getString(ProjectId)); } } <file_sep>/app/src/main/java/com/gayatry/report/adapter/StockReportRecyclerAdapter.java package com.gayatry.report.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.gayatry.R; import com.gayatry.grn.GRNListActivity; import com.gayatry.model.GRNListModel; import com.gayatry.model.StockReportModel; import com.gayatry.report.fragment.StockReportFragment; import java.util.ArrayList; import java.util.List; /** * Created by Admin on 01-May-16. */ public class StockReportRecyclerAdapter extends RecyclerView.Adapter<StockReportRecyclerAdapter.ViewHolder> { private List<StockReportModel> mDataset; private StockReportFragment stockReportFragment; public StockReportRecyclerAdapter(List<StockReportModel> arrayList, StockReportFragment stockReportFragment) { mDataset = arrayList; this.stockReportFragment = stockReportFragment; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView mTxtProductName, mTxtConsumption, mTxtCategory, mTxtOpening, mTxtClosing, mTxtPurchase; public ViewHolder(View v) { super(v); mTxtProductName = (TextView) v.findViewById(R.id.txtProductName); mTxtConsumption = (TextView) v.findViewById(R.id.txtConsumption); mTxtCategory = (TextView) v.findViewById(R.id.txtCategory); mTxtPurchase = (TextView) v.findViewById(R.id.txtPurchase); mTxtOpening = (TextView) v.findViewById(R.id.txtOpening); mTxtClosing = (TextView) v.findViewById(R.id.txtClosing); } } @Override public StockReportRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.list_item_stock_report, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.mTxtProductName.setText(mDataset.get(position).getProduct_Name()); holder.mTxtCategory.setText(mDataset.get(position).getProduct_Type()); holder.mTxtConsumption.setText(mDataset.get(position).getConsp_Qty()); holder.mTxtOpening.setText(mDataset.get(position).getOP_Qty()); holder.mTxtClosing.setText(mDataset.get(position).getCl_Qty()); holder.mTxtPurchase.setText(mDataset.get(position).getPur_Qty()); } @Override public int getItemCount() { return mDataset.size(); } } <file_sep>/app/src/main/java/com/gayatry/gtn/GTNListActivity.java package com.gayatry.gtn; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.gayatry.R; import com.gayatry.base.BaseActivity; import com.gayatry.grn.EditGRNActivity; import com.gayatry.gtn.adapter.GTNRecyclerAdapter; import com.gayatry.model.EditGRNModel; import com.gayatry.model.EditGTNModel; import com.gayatry.model.GRNListModel; import com.gayatry.model.GTNListModel; import com.gayatry.rest.JsonParser; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.AsyncTaskCommon; import com.gayatry.utilz.Callbaks; import com.gayatry.utilz.floatingMenu.AddFloatingActionButton; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; /** * Created by Admin on 23-Apr-16. */ public class GTNListActivity extends BaseActivity implements View.OnClickListener{ private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private AddFloatingActionButton mAddBtn; private ProgressBar mProgressBar; private LinearLayout mLinInternet; private RelativeLayout mRelParent; private final String ProjectId = "projectId"; private TextView mTxtErrorMsg; private ImageView mImgRetry; private GetGTNListAsync getGTNListAsync; private String GTN_MODEL="gtn_model"; private ArrayList<GTNListModel> mGtnList; private AsyncTaskCommon asyncTaskCommon; private String GTN_LIST_MODEL = "gtn_list"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gtn_list); initView(); getGTNList(); } private void getGTNList() { if(isOnline(this)){ getGTNListAsync = new GetGTNListAsync(); getGTNListAsync.execute(); } else { visibleErrorMsg(getString(R.string.error_internet)); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.imgRetry: hideErrorMsg(); getGTNList(); break; case R.id.btnAdd: startActivityForResult(new Intent(GTNListActivity.this, AddGTNActivity.class).putExtra(ProjectId, getIntent().getExtras().getString(ProjectId)), AppUtils.REQUEST_CODE_ADD_GRN); //startActivity(new Intent(GTNListActivity.this, AddGTNActivity.class)); break; } } @Override public void onStop() { super.onStop(); if(getGTNListAsync != null && getGTNListAsync.getStatus() != AsyncTask.Status.FINISHED) { getGTNListAsync.cancel(true); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ if (requestCode == AppUtils.REQUEST_CODE_ADD_GRN) { getGTNList(); } } } public void openAlertDialog(final GTNListModel grnListModel, final int position) { android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle("Confirm"); builder.setMessage("Are you sure want to Delete?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteGrnList(grnListModel, position); dialog.cancel(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.show(); } void deleteGrnList(GTNListModel grnListModel, final int position){ if(AppUtils.isOnline(this)) { AppUtils.showProgressDialog(GTNListActivity.this); asyncTaskCommon = new AsyncTaskCommon(this, new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { AppUtils.stopProgressDialog(); mGtnList.remove(position); mAdapter.notifyDataSetChanged(); if(mGtnList.size() == 0){ mLinInternet.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); mTxtErrorMsg.setText(getString(R.string.no_data_available)); } /* if (result.length() > 0) { try { if (result != "") { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { } } else { AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); } } else AppUtils.showSnakbar(mRelParent, getString(R.string.error_server));*/ } }); asyncTaskCommon.execute(getString(R.string.delete_gtn_master)+"/"+grnListModel.getGTN_ID()); }else{ AppUtils.showSnakbar(mRelParent, getString(R.string.error_internet)); } } public void onEditClick(GTNListModel grnListModel) { getAllEditGtnData(grnListModel); } void getAllEditGtnData(final GTNListModel gtnListModel){ if(AppUtils.isOnline(this)) { AppUtils.showProgressDialog(this); asyncTaskCommon = new AsyncTaskCommon(this, new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { AppUtils.stopProgressDialog(); if (result.length() > 0) { try { if (result != "") { JSONObject jsonObject = new JSONObject(result); JSONArray jsonArray = jsonObject.getJSONArray("lst_GTN_Report1_Class"); ArrayList<EditGTNModel> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object = jsonArray.getJSONObject(i); EditGTNModel editGTNModel = new EditGTNModel(); editGTNModel.setAmount(object.getString("Amount")); editGTNModel.setProduct_Name(object.getString("Product_Name")); editGTNModel.setProduct_Category_Name(object.getString("Product_Category_Name")); editGTNModel.setProduct_Category_ID(object.getString("Product_Category_ID")); editGTNModel.setChallan_No(object.getString("Challan_No")); editGTNModel.setProduct_ID(object.getString("Product_ID")); editGTNModel.setChallan_Date(object.getString("Challan_Date")); editGTNModel.setRate(object.getString("Rate")); editGTNModel.setUnit_Id(object.getString("Unit_Id")); editGTNModel.setUnit(object.getString("Unit")); editGTNModel.setGTN_Code(object.getString("GTN_Code")); editGTNModel.setGTN_date(object.getString("GTN_date")); editGTNModel.setGTN_ID(object.getString("GTN_ID")); editGTNModel.setGTN_Type(object.getString("GTN_Type")); editGTNModel.setIsCancelled(object.getString("IsCancelled")); editGTNModel.setNet_Qty(object.getString("Net_Qty")); editGTNModel.setQty(object.getString("Qty")); editGTNModel.setRemark(object.getString("Remark")); editGTNModel.setTotalGTNValue(object.getString("TotalGTNValue")); editGTNModel.setWC_Id(object.getString("WC_Id")); editGTNModel.setWC_Name(object.getString("WC_Name")); editGTNModel.setYearCode(object.getString("YearCode")); list.add(editGTNModel); } if(list.size() > 0){ Intent intent = new Intent(GTNListActivity.this, EditGTNActivity.class); intent.putExtra(GTN_MODEL, gtnListModel); intent.putExtra(ProjectId, getIntent().getExtras().getString(ProjectId)); intent.putParcelableArrayListExtra(GTN_LIST_MODEL, list); startActivity(intent); }else{ AppUtils.showSnakbar(mRelParent, getString(R.string.no_data_available)); } } else { AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); } } else AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } }); asyncTaskCommon.execute(getString(R.string.edit_gtn_url)+"/"+gtnListModel.getGTN_ID()); } } private class GetGTNListAsync extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); showProgress(true); } @Override protected String doInBackground(String... params) { try{ JsonParser jsonParser = new JsonParser(); return jsonParser.getResponse(getString(R.string.get_gtn_list_url)+"/0/"+ getIntent().getExtras().getString(ProjectId)); }catch (Exception e){ e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); showProgress(false); handleResponse(response); } } private void handleResponse(String response) { try{ if(response!="") { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { hideErrorMsg(); mGtnList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { GTNListModel gtnListModel = new GTNListModel(); gtnListModel.setChallan_Date(jsonArray.getJSONObject(i).getString("Challan_Date")); gtnListModel.setChallan_No(jsonArray.getJSONObject(i).getString("Challan_No")); gtnListModel.setGTN_Code(jsonArray.getJSONObject(i).getString("GTN_Code")); gtnListModel.setGTN_date(jsonArray.getJSONObject(i).getString("GTN_date")); gtnListModel.setGTN_ID(jsonArray.getJSONObject(i).getString("GTN_ID")); gtnListModel.setGTN_No(jsonArray.getJSONObject(i).getString("GTN_No")); gtnListModel.setIsCancelled(jsonArray.getJSONObject(i).getString("IsCancelled")); gtnListModel.setProject_ID(jsonArray.getJSONObject(i).getString("Project_ID")); gtnListModel.setProjectName(jsonArray.getJSONObject(i).getString("ProjectName")); gtnListModel.setYearCode(jsonArray.getJSONObject(i).getString("YearCode")); gtnListModel.setWC_Id(jsonArray.getJSONObject(i).getString("WC_Id")); gtnListModel.setWC_Name(jsonArray.getJSONObject(i).getString("WC_Name")); gtnListModel.setTotalGTNValue(jsonArray.getJSONObject(i).getString("TotalGTNValue")); mGtnList.add(gtnListModel); } setAdapter(mGtnList); } else { visibleErrorMsg(getString(R.string.no_data_available)); } }else { visibleErrorMsg(getString(R.string.error_server)); } }catch (Exception e){ e.printStackTrace(); visibleErrorMsg(getString(R.string.error_server)); } } private void setAdapter(ArrayList<GTNListModel> arrayList) { mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new GTNRecyclerAdapter(arrayList, this); mRecyclerView.setAdapter(mAdapter); } private void initView() { initToolbar(); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mAddBtn = (AddFloatingActionButton) findViewById(R.id.btnAdd); mProgressBar = (ProgressBar) findViewById(R.id.progress); mLinInternet = (LinearLayout) findViewById(R.id.linInternet); mRelParent = (RelativeLayout) findViewById(R.id.relParent); mTxtErrorMsg = (TextView) findViewById(R.id.txtErrorMsg); mImgRetry = (ImageView) findViewById(R.id.imgRetry); mImgRetry.setOnClickListener(this); mAddBtn.setOnClickListener(this); } private void hideErrorMsg() { mLinInternet.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE); } private void visibleErrorMsg(String msg) { mLinInternet.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); mTxtErrorMsg.setText(msg); AppUtils.showSnakbar(mRelParent, "" + msg); } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mRecyclerView.setVisibility(show ? View.GONE : View.VISIBLE); mRecyclerView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mRecyclerView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); mProgressBar.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); mProgressBar.setVisibility(show ? View.GONE : View.VISIBLE); } } } <file_sep>/app/src/main/java/com/gayatry/report/fragment/StockReportFragment.java package com.gayatry.report.fragment; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import com.gayatry.R; import com.gayatry.model.ProductListModel; import com.gayatry.model.ProductNameModel; import com.gayatry.model.StockReportModel; import com.gayatry.report.adapter.StockReportRecyclerAdapter; import com.gayatry.rest.JsonParser; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.AsyncTaskCommon; import com.gayatry.utilz.floatingMenu.FloatingActionButton; import org.json.JSONArray; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Created by Admin on 01-May-16. */ public class StockReportFragment extends Fragment implements View.OnClickListener{ private RecyclerView mRecyclerView; private StockReportRecyclerAdapter stockReportRecyclerAdapter; private FloatingActionButton mGenerateReport; private TextView mTxtProjectName, mTxtFromDate, mTxtToDate; private final String ProjectId = "projectId"; private final String ProjectName = "projectName"; private Spinner mSpnrProductCat, mSpnrProductName; private ArrayList<ProductListModel> mProductList; private ArrayList<ProductNameModel> mProductNameList; private RelativeLayout mRelParent; private ProgressBar mProgressProductCat, mProgressProductName, mReport_progress; private ArrayList<StockReportModel> mStockReportList; private GetProductAsync getProductAsync; private AsyncTaskCommon asyncTaskCommon; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_stock_report, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); mTxtProjectName.setText("Project (Site) : "+getArguments().getString(ProjectName)); mSpnrProductCat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { getProductNameWs(getSelectedProductCatName(mSpnrProductCat.getSelectedItemPosition())); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private String getSelectedProductCatName(int selectedItemPosition) { return mProductList.get(selectedItemPosition).getProduct_Category_Name(); } private String getSelectedProductCatId(int selectedItemPosition) { return mProductList.get(selectedItemPosition).getProduct_Category_Id(); } private String getSelectedProductId(int selectedItemPosition) { return mProductNameList.get(selectedItemPosition).getProduct_Id(); } void getProductNameWs(String name){ if(AppUtils.isOnline(getActivity())) { mProgressProductName.setVisibility(View.VISIBLE); asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { if (result.length() > 0) { try { if (result != "") { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { mProductNameList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { ProductNameModel productListModel = new ProductNameModel(); productListModel.setProduct_Id(jsonArray.getJSONObject(i).getString("Product_Id")); productListModel.setProduct_Name(jsonArray.getJSONObject(i).getString("Product_Name")); mProductNameList.add(productListModel); } setSpinnerProductNameAdapter(); } } else { mProgressProductName.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); } } else { AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); mProgressProductName.setVisibility(View.GONE); } } }); asyncTaskCommon.execute(getString(R.string.get_product_master_report_url)+"/0/0/"+name); }else{ mProgressProductName.setVisibility(View.GONE); } } private void setSpinnerProductNameAdapter(){ mProgressProductName.setVisibility(View.GONE); if(mSpnrProductName!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getProductName()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrProductName.setAdapter(adapter); } } private ArrayList<String> getProductName() { ArrayList<String> productName = new ArrayList<>(); for (ProductNameModel model : mProductNameList){ productName.add(model.getProduct_Name()); } return productName; } void getStockReport(){ if(AppUtils.isOnline(getActivity())) { mReport_progress.setVisibility(View.VISIBLE); asyncTaskCommon = new AsyncTaskCommon(getActivity(), new AsyncTaskCommon.AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result) { if (result.length() > 0) { try { if (result != "") { mReport_progress.setVisibility(View.GONE); JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() > 0) { mStockReportList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { StockReportModel stockReportModel = new StockReportModel(); stockReportModel.setProduct_Id(jsonArray.getJSONObject(i).getString("Product_Id")); stockReportModel.setProduct_Name(jsonArray.getJSONObject(i).getString("Product_Name")); stockReportModel.setCl_Qty(jsonArray.getJSONObject(i).getString("Cl_Qty")); stockReportModel.setConsp_Qty(jsonArray.getJSONObject(i).getString("Consp_Qty")); stockReportModel.setOP_Qty(jsonArray.getJSONObject(i).getString("OP_Qty")); stockReportModel.setProd_Qty(jsonArray.getJSONObject(i).getString("Prod_Qty")); stockReportModel.setProduct_Type(jsonArray.getJSONObject(i).getString("Product_Type")); stockReportModel.setPur_Qty(jsonArray.getJSONObject(i).getString("Pur_Qty")); mStockReportList.add(stockReportModel); } setRecyclerAdapter(); } } else { mReport_progress.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); mReport_progress.setVisibility(View.GONE); } } else { mReport_progress.setVisibility(View.GONE); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } }); asyncTaskCommon.execute(getString(R.string.get_stock_report_url)+"/"+getArguments().getString(ProjectId)+"/"+ AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", mTxtFromDate.getText().toString())+"/"+AppUtils.formattedDate("dd MMMM yyyy", "yyyy-MM-dd", mTxtToDate.getText().toString())+"/"+ getSelectedProductCatId(mSpnrProductCat.getSelectedItemPosition())+"/"+ getSelectedProductId(mSpnrProductName.getSelectedItemPosition())); //project id/from/to/product/product type } } private void setRecyclerAdapter() { final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); stockReportRecyclerAdapter = new StockReportRecyclerAdapter(mStockReportList, StockReportFragment.this); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(false); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setAdapter(stockReportRecyclerAdapter); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser){ if(AppUtils.isOnline(getContext())){ if(mProductList == null){ getProductAsync = new GetProductAsync(); getProductAsync.execute(); } }else{ AppUtils.showSnakbar(mRelParent, getString(R.string.error_internet)); } } } @Override public void onStop() { super.onStop(); if(getProductAsync != null && getProductAsync.getStatus() != AsyncTask.Status.FINISHED) { getProductAsync.cancel(true); } if(asyncTaskCommon != null && asyncTaskCommon.getStatus() != AsyncTask.Status.FINISHED) { asyncTaskCommon.cancel(true); } } private void initView(View view) { mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mGenerateReport = (FloatingActionButton) view.findViewById(R.id.btnGenerateReport); mTxtProjectName = (TextView) view.findViewById(R.id.txtProjectName); mTxtFromDate = (TextView) view.findViewById(R.id.txtFromDate); mTxtToDate = (TextView) view.findViewById(R.id.txtToDate); mSpnrProductCat = (Spinner) view.findViewById(R.id.spnrProductCat); mSpnrProductName = (Spinner) view.findViewById(R.id.spnrProductName); mRelParent = (RelativeLayout) view.findViewById(R.id.relParent); mProgressProductCat = (ProgressBar) view.findViewById(R.id.product_cat_progress); mProgressProductName = (ProgressBar) view.findViewById(R.id.product_name_progress); mReport_progress = (ProgressBar) view.findViewById(R.id.report_progress); mGenerateReport.setOnClickListener(this); mTxtFromDate.setOnClickListener(this); mTxtToDate.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnGenerateReport: if(isValidate()){ getStockReport(); } break; case R.id.txtFromDate: DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment(); Bundle bundle = new Bundle(); bundle.putInt("dateFrom",1); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; case R.id.txtToDate: datePickerDialogFragment = new DatePickerDialogFragment(); bundle = new Bundle(); bundle.putInt("dateFrom",2); datePickerDialogFragment.setArguments(bundle); datePickerDialogFragment.show(getChildFragmentManager(), "datePicker"); break; } } private boolean isValidate() { if (!AppUtils.isOnline(getActivity())) { AppUtils.showSnakbar(mRelParent, getString(R.string.error_internet)); return false; }else if (TextUtils.isEmpty(mTxtFromDate.getText().toString())) { AppUtils.showSnakbar(mRelParent, "Please select From date"); return false; }else if (TextUtils.isEmpty(mTxtToDate.getText().toString())) { AppUtils.showSnakbar(mRelParent, "Please select To date"); return false; }else if (mProductNameList == null && mProductNameList.size() <= 0 && mProductList.size() <= 0 && mProductList == null) { AppUtils.showSnakbar(mRelParent, "Please select product"); return false; } return true; } @SuppressLint("ValidFragment") public class DatePickerDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { private boolean cancelDialog = false; private int year; private int month; private int day; private int dateFrom; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); dateFrom = getArguments().getInt("dateFrom"); DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day); return datePickerDialog; } public void setDatePickerDate(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); cancelDialog = true; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (!cancelDialog) { String mDatePick = AppUtils.formattedDate("yyyy MM dd", "dd MMMM yyyy", "" + year + " " + (month + 1) + " " + day); switch (dateFrom) { case 1: mTxtFromDate.setText(mDatePick); break; case 2: mTxtToDate.setText(mDatePick); break; } } } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDatePickerDate(year, monthOfYear, dayOfMonth); } } class GetProductAsync extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try{ JsonParser jsonParser = new JsonParser(); return jsonParser.getResponse(getString(R.string.get_product_category_url)+"/0"); }catch (Exception e){ e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); mProgressProductCat.setVisibility(View.GONE); handleResponse(response); } } private void handleResponse(String response) { try{ if(response!="") { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { mProductList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { ProductListModel productListModel = new ProductListModel(); productListModel.setAbbreviation(jsonArray.getJSONObject(i).getString("Abbreviation")); productListModel.setDescription(jsonArray.getJSONObject(i).getString("Description")); productListModel.setIs_Active(jsonArray.getJSONObject(i).getString("Is_Active")); productListModel.setProduct_Category_Id(jsonArray.getJSONObject(i).getString("Product_Category_Id")); productListModel.setProduct_Category_Name(jsonArray.getJSONObject(i).getString("Product_Category_Name")); mProductList.add(productListModel); } setSpinnerAdapter(); } else { AppUtils.showSnakbar(mRelParent, getString(R.string.no_data_available)); } }else { AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } }catch (Exception e){ e.printStackTrace(); AppUtils.showSnakbar(mRelParent, getString(R.string.error_server)); } } private void setSpinnerAdapter(){ if(mSpnrProductCat!= null) { ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getProductNameCat()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpnrProductCat.setAdapter(adapter); } } private ArrayList<String> getProductNameCat() { ArrayList<String> productName = new ArrayList<>(); for (ProductListModel model : mProductList){ productName.add(model.getProduct_Category_Name()); } return productName; } } <file_sep>/app/src/main/java/com/gayatry/report/ReportActivity.java package com.gayatry.report; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.widget.TextView; import com.gayatry.R; import com.gayatry.base.BaseActivity; import com.gayatry.grn.fragment.GRNGeneralFragment; import com.gayatry.grn.fragment.GRNProductFragment; import com.gayatry.report.fragment.AgingReportFragment; import com.gayatry.report.fragment.PaymentReportFragment; import com.gayatry.report.fragment.StockReportFragment; /** * Created by Admin on 01-May-16. */ public class ReportActivity extends BaseActivity { private TabLayout tabLayout; private ViewPager viewPager; private TextView mTextToolbar; private StockReportFragment stockReportFragment; private PaymentReportFragment paymentReportFragment; private AgingReportFragment agingReportFragment; private final String ProjectId = "projectId"; private final String ProjectName = "projectName"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_grn); initView(); setupViewPager(viewPager); tabLayout.setupWithViewPager(viewPager); } private void initView() { initToolbar(); viewPager = (ViewPager) findViewById(R.id.viewpager); tabLayout = (TabLayout) findViewById(R.id.tabs); mTextToolbar = (TextView) toolbar.findViewById(R.id.txtToolbar); mTextToolbar.setText("Report"); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(adapter); viewPager.setOffscreenPageLimit(3); } class ViewPagerAdapter extends FragmentStatePagerAdapter { public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { if(position == 0){ stockReportFragment = new StockReportFragment(); Bundle bundle = new Bundle(); bundle.putString(ProjectName,""+getIntent().getExtras().getString(ProjectName)); bundle.putString(ProjectId,""+getIntent().getExtras().getString(ProjectId)); stockReportFragment.setArguments(bundle); return stockReportFragment; }else if(position == 1){ paymentReportFragment = new PaymentReportFragment(); Bundle bundle = new Bundle(); bundle.putString(ProjectId,""+getIntent().getExtras().getString(ProjectId)); paymentReportFragment.setArguments(bundle); return paymentReportFragment; }else if(position == 2){ agingReportFragment = new AgingReportFragment(); Bundle bundle = new Bundle(); bundle.putString(ProjectId,""+getIntent().getExtras().getString(ProjectId)); agingReportFragment.setArguments(bundle); return agingReportFragment; } return null; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { if(position == 0){ return "Stock"; }else if(position == 1){ return "Payment"; }else if(position == 2){ return "Aging"; } return ""; } } } <file_sep>/app/src/main/java/com/gayatry/model/ProductNameModel.java package com.gayatry.model; /** * Created by Admin on 04-Aug-16. */ public class ProductNameModel { public String getProduct_Name() { return Product_Name; } public void setProduct_Name(String product_Name) { Product_Name = product_Name; } public String getProduct_Id() { return Product_Id; } public void setProduct_Id(String product_Id) { Product_Id = product_Id; } public String Product_Name; public String Product_Id; } <file_sep>/app/src/main/java/com/gayatry/prelogin/ProjectFragment.java package com.gayatry.prelogin; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Dialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.gayatry.R; import com.gayatry.grn.GRNListActivity; import com.gayatry.gtn.GTNListActivity; import com.gayatry.model.ProjectModel; import com.gayatry.prelogin.adapter.ProjectGridAdapter; import com.gayatry.report.ReportActivity; import com.gayatry.rest.JsonParser; import com.gayatry.storage.SharedPreferenceUtil; import com.gayatry.utilz.AppUtils; import com.gayatry.utilz.DialogUtils; import org.json.JSONArray; import java.util.ArrayList; /** * Created by Admin on 04-Apr-16. */ public class ProjectFragment extends Fragment implements View.OnClickListener { public static final String TAG = "ProjectFragment"; private RecyclerView recyclerView; private DialogUtils dialogUtils; private RelativeLayout mRelParent; private ProgressBar mProgressBar; private LinearLayout mLinInternet; private ImageView mImgRetry; private TextView mTxtErrorMsg; private final String ProjectId = "projectId"; private final String ProjectName = "projectName"; private GetProjectAsync getProjectAsync; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); return inflater.inflate(R.layout.fragment_project, container, false); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_logout).setVisible(true); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); getProjectList(); dialogUtils = new DialogUtils(getContext()); } private void getProjectList() { if (AppUtils.isOnline(getContext())){ getProjectAsync = new GetProjectAsync(); getProjectAsync.execute(); } else { visibleErrorMsg(getString(R.string.error_internet)); } } @Override public void onStop() { super.onStop(); if(getProjectAsync != null && getProjectAsync.getStatus() != AsyncTask.Status.FINISHED) { getProjectAsync.cancel(true); } } @Override public void onDestroy() { super.onDestroy(); if(getProjectAsync != null && getProjectAsync.getStatus() != AsyncTask.Status.FINISHED) { getProjectAsync.cancel(true); } } private void initView(View view) { recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); mRelParent = (RelativeLayout) view.findViewById(R.id.relParent); mProgressBar = (ProgressBar) view.findViewById(R.id.progress); mLinInternet = (LinearLayout) view.findViewById(R.id.linInternet); mImgRetry = (ImageView) view.findViewById(R.id.imgRetry); mTxtErrorMsg = (TextView) view.findViewById(R.id.txtErrorMsg); mImgRetry.setOnClickListener(this); } private void setAdapter(ArrayList<ProjectModel> arrayList) { //recyclerView.addItemDecoration(new MarginDecoration(getActivity())); recyclerView.setHasFixedSize(true); final GridLayoutManager manager = new GridLayoutManager(getActivity(), 2); recyclerView.setLayoutManager(manager); View header = LayoutInflater.from(getContext()).inflate(R.layout.header_project_activity, recyclerView, false); TextView txtUser = (TextView) header.findViewById(R.id.txtUser); txtUser.setText(SharedPreferenceUtil.getString(AppUtils.USER_FULL_NAME, "")); header.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); final ProjectGridAdapter adapter = new ProjectGridAdapter(header, arrayList, ProjectFragment.this); recyclerView.setAdapter(adapter); manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return adapter.isHeader(position) ? manager.getSpanCount() : 1; } }); } public void openMenu(final ProjectModel model) { final Dialog dialog = dialogUtils.setupCustomeDialogFromBottom(R.layout.dialog_project_menu); LinearLayout linGtn = (LinearLayout) dialog.findViewById(R.id.linGtn); LinearLayout linGrn = (LinearLayout) dialog.findViewById(R.id.linGrn); LinearLayout linReport = (LinearLayout) dialog.findViewById(R.id.linReport); linGtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); getActivity().startActivity(new Intent(getActivity(), GRNListActivity.class). putExtra(ProjectId, model.getProjectId())); } }); linGrn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); getActivity().startActivity(new Intent(getActivity(), GTNListActivity.class). putExtra(ProjectId, model.getProjectId())); } }); linReport.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); getActivity().startActivity(new Intent(getActivity(), ReportActivity.class). putExtra(ProjectId, model.getProjectId()). putExtra(ProjectName, model.getProjectName())); } }); dialog.show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.imgRetry: hideErrorMsg(); getProjectList(); break; } } private class GetProjectAsync extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); showProgress(true); } @Override protected String doInBackground(String... params) { try { JsonParser jsonParser = new JsonParser(); return jsonParser.getResponse(getString(R.string.project_url) + "/" + SharedPreferenceUtil.getString(AppUtils.USER_ID, "")); } catch (Exception e) { e.printStackTrace(); } return ""; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); showProgress(false); handleResponse(response); } } private void handleResponse(String response) { try { if (response != "") { JSONArray jsonArray = new JSONArray(response); if (jsonArray.length() > 0) { hideErrorMsg(); ArrayList<ProjectModel> arrayList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { ProjectModel projectModel = new ProjectModel(); projectModel.setProjectId(jsonArray.getJSONObject(i).getString("Project_ID")); projectModel.setProjectName(jsonArray.getJSONObject(i).getString("Project_Name")); arrayList.add(projectModel); } setAdapter(arrayList); } else { visibleErrorMsg(getString(R.string.no_data_available)); } } else { visibleErrorMsg(getString(R.string.error_server)); } } catch (Exception e) { e.printStackTrace(); visibleErrorMsg(getString(R.string.error_server)); } } private void hideErrorMsg() { mLinInternet.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } private void visibleErrorMsg(String msg) { mLinInternet.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.GONE); mTxtErrorMsg.setText(msg); AppUtils.showSnakbar(mRelParent, "" + msg); } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); recyclerView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); mProgressBar.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); mProgressBar.setVisibility(show ? View.GONE : View.VISIBLE); } } } <file_sep>/app/src/main/java/com/gayatry/base/BaseFragment.java package com.gayatry.base; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; /** * Created by Admin on 23-Apr-16. */ public abstract class BaseFragment extends Fragment { protected void showSnakbar(View view, String msg){ Snackbar snackbar = Snackbar .make(view, msg, Snackbar.LENGTH_LONG); snackbar.show(); } protected void showToast(Context context, String msg){ Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); } protected void closeKeyBoard(Activity context) { View view = context.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } protected boolean isOnline(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } } <file_sep>/app/src/main/java/com/gayatry/model/ProjectListModel.java package com.gayatry.model; /** * Created by Admin on 29-Jul-16. */ public class ProjectListModel { public String Excise_Opening; public String Name; public String NonExcise_Opening; public String getWC_ID() { return WC_ID; } public void setWC_ID(String WC_ID) { this.WC_ID = WC_ID; } public String getExcise_Opening() { return Excise_Opening; } public void setExcise_Opening(String excise_Opening) { Excise_Opening = excise_Opening; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getNonExcise_Opening() { return NonExcise_Opening; } public void setNonExcise_Opening(String nonExcise_Opening) { NonExcise_Opening = nonExcise_Opening; } public String WC_ID; }
2694a8135b996409f7cef4b7ce026359f74c726f
[ "Java" ]
18
Java
chiragsharma991/GRN
8f52cd8614e552c8a44e146443228b290922495d
9c01b206b2d6c44aaca5665f54819208df904999
refs/heads/master
<file_sep>import pygtk pygtk.require('2.0') import gtk import server labelText = """ Webrift server running at ws://localhost:1981. Close this window to exit the server.""" class WebRiftApp: def delete_event(self, widget, event, data=None): return False def destroy(self, widget, data=None): gtk.main_quit() def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title(title="Webrift Server") self.window.connect("delete_event", self.delete_event) self.window.connect("destroy", self.destroy) self.window.set_border_width(10) self.window.show() label = gtk.Label(labelText) label.show() self.window.add(label) def main(self): gtk.main() if __name__ == "__main__": app = WebRiftApp() server.start() app.main()<file_sep># Webrift Webrift is a Linux/Windows websocket server and javascript library that allows you to use the Oculus Rift in 3D web applications and games. http://wwwtyro.github.io/webrift/ <file_sep> import time import json import multiprocessing as mp import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import pyrift clients = [] class RiftHandler(tornado.websocket.WebSocketHandler): def open(self): clients.append(self) def on_message(self, message): pass def on_close(self): clients.remove(self) def update(self): pass class QuaternionHandlerCSV(RiftHandler): def update(self): x, y, z, w = pyrift.get_orientation_quaternion() data = "%f,%f,%f,%f" % (w,x,y,z) self.write_message(data) class QuaternionHandlerJSON(RiftHandler): def update(self): x, y, z, w = pyrift.get_orientation_quaternion() data = json.dumps(dict(w=w, x=x, y=y, z=z)) self.write_message(data) class EulerHandlerJSON(RiftHandler): def update(self): yaw, pitch, roll = pyrift.get_orientation() data = json.dumps(dict(yaw = yaw, pitch = pitch, roll=roll)) self.write_message(data) def update(): for client in clients: client.update() application = tornado.web.Application([ (r'/', QuaternionHandlerCSV), (r'/csv/quat', QuaternionHandlerCSV), (r'/json/quat', QuaternionHandlerJSON), (r'/json/euler', EulerHandlerJSON), ]) def main(): pyrift.initialize() http_server = tornado.httpserver.HTTPServer(application) http_server.listen(1981) callback = tornado.ioloop.PeriodicCallback(update, 1000/120.0) callback.start() tornado.ioloop.IOLoop.instance().start() def start(): proc = mp.Process(target = main) proc.daemon = True proc.start() if __name__ == "__main__": start() while True: time.sleep(1)
7f363c9e43204939deb0ceb1929f728dbbe8e7ae
[ "Markdown", "Python" ]
3
Python
brianpeiris/webrift
90b91acfb4204524fef71782702443db8eb79800
247800bbdd421be0621586c1218dbe4744054242
refs/heads/master
<repo_name>mbyse/WarCardGame<file_sep>/Deck.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MegaChallengeWarGame { public class Deck { public string Suit { get; set; } public int Value { get; set; } public string Card { get; set; } public int Draw { get; set; } public List<Deck> Hand { get; set;} public List<Deck> CreateDeck() { List<Deck> deck = new List<Deck>(); for (int i = 2; i < 15; i++) { string num = i.ToString(); if (i == 11) num = "Jack"; else if (i == 12) num = "Queen"; else if (i == 13) num = "King"; else if (i == 14) num = "Ace"; deck.Add(new Deck{ Value = i, Suit = num+" of Hearts" }); deck.Add(new Deck { Value = i, Suit = num+" of Spades" }); deck.Add(new Deck { Value = i, Suit = num+" of Diamonds" }); deck.Add(new Deck { Value = i, Suit = num+" of Clubs" }); }; return deck; /* foreach (var Deck in deck) { resultLabel.Text += String.Format("{0} of {1} <br>", Deck.Value, Deck.Suit); }*/ } } }<file_sep>/Default.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MegaChallengeWarGame { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void okButton_Click(object sender, EventArgs e) { //Create Players Player player1 = new Player(); player1.Name = "Steve"; player1.Hand = new List<Deck>(); Player player2 = new Player(); player2.Name = "George"; player2.Hand = new List<Deck>(); //Create CardDeck Deck deck = new Deck(); List<Deck> cardDeck = new List<Deck>(); cardDeck = deck.CreateDeck(); //Deal Cards Random random = new Random(); while (cardDeck.Count()>0) { int index = random.Next(cardDeck.Count()); player1.Hand.Add(new Deck { Value = cardDeck[index].Value, Suit = cardDeck[index].Suit }); resultLabel.Text += String.Format("Player 1: {0}", cardDeck[index].Suit); cardDeck.RemoveAt(index); index = random.Next(cardDeck.Count()); player2.Hand.Add(new Deck { Value = cardDeck[index].Value, Suit = cardDeck[index].Suit }); resultLabel.Text += String.Format("&nbsp;&nbsp;Player 2: {0}<br>", cardDeck[index].Suit); cardDeck.RemoveAt(index); }; //Battle for (int i = 0; i < 21 && i<player1.Hand.Count() && i<player2.Hand.Count(); i++) { if (player1.Hand[i].Value > player2.Hand[i].Value) { resultLabel.Text += String.Format("Bounty goes to {0}: {1} & {2}<br>", player1.Name, player1.Hand[i].Suit, player2.Hand[i].Suit); player1.Hand.Add(new Deck { Value = player2.Hand[i].Value, Suit = player2.Hand[i].Suit }); player2.Hand.RemoveAt(i); } else if (player2.Hand[i].Value > player1.Hand[i].Value) { resultLabel.Text += String.Format("Bounty goes to {0}: {1} & {2}<br>", player2.Name, player1.Hand[i].Suit, player2.Hand[i].Suit); player2.Hand.Add(new Deck { Value = player1.Hand[i].Value, Suit = player1.Hand[i].Suit }); player1.Hand.RemoveAt(i); } else if (player1.Hand[i].Value == player2.Hand[i].Value) { resultLabel.Text += String.Format("******** War ********<br>"); if (player1.Hand[i + 4].Value > player2.Hand[i + 4].Value) { resultLabel.Text += String.Format("Bounty goes to {0}: {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, & {10}<br>", player1.Name, player1.Hand[i].Suit, player2.Hand[i].Suit, player1.Hand[i + 1].Suit, player2.Hand[i + 1].Suit, player1.Hand[i + 2].Suit, player2.Hand[i + 2].Suit, player1.Hand[i + 3].Suit, player2.Hand[i + 3].Suit, player1.Hand[i + 4].Suit, player2.Hand[i + 4].Suit); player1.Hand.Add(new Deck { Value = player2.Hand[i].Value, Suit = player2.Hand[i].Suit }); player1.Hand.Add(new Deck { Value = player2.Hand[i + 1].Value, Suit = player2.Hand[i + 1].Suit }); player1.Hand.Add(new Deck { Value = player2.Hand[i + 2].Value, Suit = player2.Hand[i + 2].Suit }); player1.Hand.Add(new Deck { Value = player2.Hand[i + 3].Value, Suit = player2.Hand[i + 3].Suit }); player1.Hand.Add(new Deck { Value = player2.Hand[i + 4].Value, Suit = player2.Hand[i + 4].Suit }); player2.Hand.RemoveRange(i, 5); } else if (player2.Hand[i + 4].Value > player1.Hand[i + 4].Value) { resultLabel.Text += String.Format("Bounty goes to {0}: {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, & {10}<br>", player2.Name, player1.Hand[i].Suit, player2.Hand[i].Suit, player1.Hand[i + 1].Suit, player2.Hand[i + 1].Suit, player1.Hand[i + 2].Suit, player2.Hand[i + 2].Suit, player1.Hand[i + 3].Suit, player2.Hand[i + 3].Suit, player1.Hand[i + 4].Suit, player2.Hand[i + 4].Suit); player2.Hand.Add(new Deck { Value = player1.Hand[i].Value, Suit = player1.Hand[i].Suit }); player2.Hand.Add(new Deck { Value = player1.Hand[i + 1].Value, Suit = player1.Hand[i + 1].Suit }); player2.Hand.Add(new Deck { Value = player1.Hand[i + 2].Value, Suit = player1.Hand[i + 2].Suit }); player2.Hand.Add(new Deck { Value = player1.Hand[i + 3].Value, Suit = player1.Hand[i + 3].Suit }); player2.Hand.Add(new Deck { Value = player1.Hand[i + 4].Value, Suit = player1.Hand[i + 4].Suit }); player1.Hand.RemoveRange(i, 5); } } }; //Winner if (player1.Hand.Count() > player2.Hand.Count()) { resultLabel.Text += String.Format("<br>{0}'s Score: {1} {2}'s Score: {3}<br>Winner is: {0}", player1.Name, player1.Hand.Count(), player2.Name, player2.Hand.Count()); } else { resultLabel.Text += String.Format("<br>{0}'s Score: {1} {2}'s Score: {3}<br>Winner is: {2}", player1.Name, player1.Hand.Count(), player2.Name, player2.Hand.Count()); } } } }
7add59d12213177a6d86f9c9ce5a9e34a5431ab8
[ "C#" ]
2
C#
mbyse/WarCardGame
3565f2fc2cead70c092ea13ddd879bf9e1d8d677
af0b81b71f067727923d0c11bda5f3db25f1ef8e
refs/heads/master
<repo_name>tahir-u/js-data-structures<file_sep>/README.md ### Data Structures in JavaScript #### The Array Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Array_data_structure): *An Array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. The simplest type of data structure is a linear array, also called a one-dimensional array.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(1) | O(n) | O(1) | O(n) | #### The Hash Table Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Hash_table): *A Hash Table (Hash Map) is a data structure used to implement an associative array, a structure that can map keys to values. A Hash Table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | - | O(1) | O(1) | O(1) | #### The Set Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Set_(abstract_data_type)): *A Set is an abstract data type (ADT) that can store certain values, wihout any particular order, with no repeated values. It is a computer implementation of the mathematical concept of a finite Set.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | - | O(n) | O(n) | O(n) | #### The Singly Linked List Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Linked_list): *A Singly Linked List is a linear collection of data elements, called nodes, pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes, which together represent a sequence. Under the simplest form, each node is composed of data and a reference (link) to the next node in the sequence.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(n) | O(n) | O(1) | O(1) | #### The Doubly Linked List Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list): *A Doubly Linked List is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and next nodes in the sequence of nodes.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(n) | O(n) | O(1) | O(1) | #### The Stack Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)): *A Stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed. The order in which elements come off a Stack gives rise to its alternative name, **LIFO** (for **last in**, **first out**).* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(n) | O(n) | O(1) | O(1) | #### The Queue Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)): *A Queue is a particular kind of abstract data type or collection, in which the entities in the collection are kept in order and the principal operations are the addition of entities to the rear terminal position (enqueue), and removal of entities from the front terminal position (dequeue). This makes Queue a FIFO (**first in**, **first out**) data structure.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(n) | O(n) | O(1) | O(n) | #### The Tree Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Tree_(data_structure)): *A Tree is a widely used data structure that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node. A Tree data structure can be defined recursively as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of references to nodes (the "children"), with the constraints that no reference is duplicated, and no children point to the root node.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(n) | O(n) | O(n) | O(n) | ## The Binary Search Tree Data Structure From [Wikipedia](https://en.wikipedia.org/wiki/Binary_search_tree): *A Binary Search Tree (BST) data structure is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value), and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search tree property, which states that the key in each node must be greater than all keys stored in the left sub-tree, and smaller that all keys in the right sub-tree.* Complexity: | Access | Search | Insertion | Deletion | | -------|--------|-----------|--------- | | O(*log*(n)) | O(*log*(n)) | O(*log*(n)) | O(*log*(n)) | <file_sep>/ds-set/DSSet.js class DSSet { constructor() { this.values = [] this.numberOfValues = 0 } add = (value) => { if (this.values.indexOf(value) !== -1) { this.values.push(value) this.numberOfValues++ } } remove = (value) => { let index = this.values.indexOf(value) if (index !== -1) { this.values.splice(index, 1) this.numberOfValues-- } } contains = (value) => { return this.values.indexOf(value) !== -1 } union = (set) => { let newSet = new Set() set.values.forEach((value) => { newSet.add(value) }) this.values.forEach((value) => { newSet.add(value) }) return newSet } intersect = (set) => { let newSet = new Set() this.values.forEach((value) => { if (set.contains(value)) { newSet.add(value) } }) return newSet } difference = (set) => { let newSet = new Set() this.values.forEach((value) => { if (!set.contains(value)) { newSet.add(value) } }) return newSet } isSubset = (set) => { return set.values.every((value) => { return this.contains(value) }, this) } length = () => { return this.numberOfValues } print = () => { return this.values.join(" ") } } export default DSSet<file_sep>/ds-singly-linked-list/DSSinglyLinkedList.js class Node { constructor(data) { this.data = data this.next = null } } class DSSinglyLinkedList { constructor() { this.head = null this.tail = null this.numberOfValues = 0 } add = (data) => { let node = new Node(data) if (!this.head) { this.head = node this.tail = node } else { this.tail.next = node this.tail = node } this.numberOfValues++ } remove = (data) => { let previous = this.head let current = this.head while (current) { if (current.data === data) { if (current === this.head) { this.head = this.head.next } if (current === this.tail) { this.tail = previous } previous.next = current.next this.numberOfValues-- } else { previous = current } current = current.next } } insertAfter = (data, toNodeData) => { let current = this.head while (current) { if (current.data === toNodeData) { let node = new Node(data) if (current === this.tail) { this.tail.next = node this.tail = node } else { node.next = current.next current.next = node } this.numberOfValues++ } current = current.next } } traverse = (callback) => { let current = this.head while (current) { if (callback) { callback(current) } current = current.next } } length = () => { return this.numberOfValues } print = () => { let string = "" let current = this.head while (current) { string += current.data + " " current = current.next } return string.trim() } } export default DSSinglyLinkedList<file_sep>/ds-tree/DSTree.js class Node { constructor(data) { this.data = data this.children = [] } } class DSTree { constructor() { this.root = null } findBFS = (data) => { let queue = [this.root] while (queue.length) { let node = queue.shift() let i if (node.data === data) { return node } for (i = 0; i < node.children.length; i++) { queue.push(node.children[i]) } } return null } add = (data, toNodeData) => { let node = new Node(data) let parent = toNodeData ? this.findBFS(toNodeData) : null if (parent) { parent.children.push(node) } else { if (!this.root) { this.root = node } else { return null } } } remove = (data) => { if (this.root.data === data) { this.root = null } let queue = [this.root] while (queue.length) { let node = queue.shift() for (let i = 0; i < node.children.length; i++) { if (node.children[i].data === data) { node.children.splice(i, 1) } else { queue.push(node.children[i]) } } } } contains = (data) => { return this.findBFS(data) ? true : false } _preOrder = (node, callback) => { if (node) { if (callback) { callback(node) } for (let i = 0; i < node.children.length; i++) { this._preOrder(node.children[i], callback) } } } _postOrder = (node, callback) => { if (node) { for (let i = 0; i < node.children.length; i++) { this._postOrder(node.children[i], callback) } if (callback) { callback(node) } } } traverseDFS = (callback, method) => { let current = this.root if (method) { this["_" + method](current, callback) } else { this._preOrder(current, callback) } } traverseBFS = (callback) => { let queue = [this.root] while (queue.length) { let node = queue.shift() if (callback) { callback(node) } for (let i = 0; i < node.children.length; i++) { queue.push(node.children[i]) } } } print = () => { if (!this.root) { return null } let newline = new Node("|") let queue = [this.root, newline] let string = "" while (queue.length) { let node = queue.shift() string += node.data.toString() + " " if (node === newline && queue.length) { queue.push(newline) } for (let i = 0; i < node.children.length; i++) { queue.push(node.children[i]) } } return string.slice(0, -2).trim() } printByLevel = () => { if (!this.root) { return null } let newline = new Node("\n") let queue = [this.root, newline] let string = "" while (queue.length) { let node = queue.shift() string += node.data.toString() + (node.data !== "\n" ? " " : "") if (node === newline && queue.length) { queue.push(newline) } for (let i = 0; i < node.children.length; i++) { queue.push(node.children[i]) } } return string.trim() } } export default DSTree<file_sep>/ds-queue/DSQueue.js class DSQueue { constructor() { this.queue = [] } enqueue = (value) => { this.queue.push(value) } dequeue = () => { return this.queue.shift() } peek = () => { return this.queue[0] } length = () => { return this.queue.length } print = () => { return this.queue.join(" ") } } export default DSQueue<file_sep>/ds-hash-table/DSHashTable.js class DSHashTable { constructor(size) { this.values = {} this.numberOfValues = 0 this.size = size } calculateHash = (key) => { return key.toString().length % this.size } add = (key, value) => { let hash = this.calculateHash(key) if (!this.values.hasOwnProperty(hash)) { this.values[hash] = {} } if (!this.values[hash].hasOwnProperty(key)) { this.numberOfValues++ } this.values[hash][key] = value } remove = (key) => { let hash = this.calculateHash(key) if (this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) { delete this.values[hash][key] this.numberOfValues-- } } search = (key) => { let hash = this.calculateHash(key) if (this.values.hasOwnProperty(hash) && this.values[hash].hasOwnProperty(key)) { return this.values[hash][key] } else { return null } } length = () => { return this.numberOfValues } print = () => { let output = "" for (let value in this.values) { for (let key in this.values[value]) { output += this.values[value][key] + " " } } return output } } export default DSHashTable
fcc421beafd528f2f52d7b4b517a0b76053b80ea
[ "Markdown", "JavaScript" ]
6
Markdown
tahir-u/js-data-structures
233b516e8933d89b4f3e584bc6be40805b45c5d7
bacdf7e570a47265acae34a1ca9108a57c802925
refs/heads/master
<file_sep> var expect = chai.expect var assert = chai.assert describe('Test para reservar un horario', function(){ it('Eliminar Horario reservado', ()=>{ aplicacion.listado.reservarUnHorario(1, "13:00") var restaurante = listado.buscarRestaurante(1) expect(restaurante.horarios).to.not.include('13:00') }) it('disminuir el arreglo', ()=>{ aplicacion.listado.reservarUnHorario(1, "13:00") var restaurante = listado.buscarRestaurante(1) assert.lengthOf(restaurante.horarios, 2) }) it('Mantener el arreglo si el horario no existe', function(){ aplicacion.listado.reservarUnHorario(2, "12:00") var restaurante = listado.buscarRestaurante(2) assert.lengthOf(restaurante.horarios, 3) }) it('Arreglo se mantiene igual', () =>{ var restaurante = listado.buscarRestaurante(2) var horarios = restaurante.horarios aplicacion.listado.reservarUnHorario(2,"22:30" ) for(var i=0; i<(horarios.length-1); i++){ horarios[i] == restaurante.horarios[i] } }) it('reservar horario sin parametro', ()=>{ aplicacion.listado.reservarUnHorario(3, "") var restaurante = listado.buscarRestaurante(3) assert.lengthOf(restaurante.horarios, 3) }) }) describe('Test para puntuaciones', () =>{ it('test para Puntuaciones', ()=>{ var restaurant = listado.buscarRestaurante(2) var puntuacion = restaurant.obtenerPuntuacion() function calcularPromedio(arr){ var sumatoria = 0 for(var i = 0; i<arr.length; i++){ sumatoria+= arr[i] } var promedio = sumatoria/arr.length; return Math.round(promedio*10)/10; } var promedio = calcularPromedio(restaurant.calificaciones) expect(puntuacion).to.equal(promedio) }); it('restaurante sin Calificacion, puntuación = 0', () =>{ var restaurante = listado.buscarRestaurante(2); restaurante.calificaciones = [] var puntuacion = restaurante.obtenerPuntuacion() expect(puntuacion).to.equal(0) }); it('testear nueva calificacion dentro del rango', () =>{ var restaurant = listado.buscarRestaurante(3) restaurant.calificar(5) var ultimaCal = restaurant.calificaciones[restaurant.calificaciones.length -1] expect(ultimaCal).to.equal(5) }) it('nueva calificacion superior al rango', () =>{ var restaurant = listado.buscarRestaurante(2) var califAnterior = restaurant.calificaciones.length restaurant.calificar(130) var qdeCalif = restaurant.calificaciones.length expect(qdeCalif).to.equal(califAnterior) }) it('nueva Calificacion = 0 ', () =>{ var restaurant = listado.buscarRestaurante(2) var califAnterior = restaurant.calificaciones.length restaurant.calificar(0) var qdeCalif = restaurant.calificaciones.length expect(qdeCalif).to.equal(califAnterior) }) it('nueva Calificacion menos que cero', () =>{ var restaurant = listado.buscarRestaurante(2) var califAnterior = restaurant.calificaciones.length restaurant.calificar(-30) var qdeCalif = restaurant.calificaciones.length expect(qdeCalif).to.equal(califAnterior) }) }) describe('testeo funcion buscar restaurante por id', () =>{ it('buscar id existente', () =>{ var restaurant = listado.buscarRestaurante(2) var restaurantEncontrado = listadoDeRestaurantes[1] expect(restaurant).to.equal(restaurantEncontrado) }) it('buscar id no existente positiva', () =>{ var restaurant = listado.buscarRestaurante(75) expect(restaurant).to.be.a('string') }) it('buscar id no existente, 0', () =>{ var restaurant = listado.buscarRestaurante(0) expect(restaurant).to.be.a('string') }) it('buscar id no existente, negativo', () =>{ var restaurant = listado.buscarRestaurante(-10) expect(restaurant).to.be.a('string') }) }) describe('testeo obtener restaurante', ()=>{ it('buscar restaurante por rubro',()=>{ var restauranteRubro = listado.obtenerRestaurantes('Asiática', null, null) var resultadoManual = listadoDeRestaurantes.filter(restaurant => restaurant.rubro == 'Asiática'); expect(restauranteRubro).to.eql(resultadoManual) }) it('buscar restaurante por Ubicacion',()=>{ var restauranteUbicacion = listado.obtenerRestaurantes(null, 'Nueva York', null) var resultadoManual = listadoDeRestaurantes.filter(restaurant => restaurant.ubicacion == 'Nueva York'); expect(restauranteUbicacion).to.eql(resultadoManual) }) it('buscar restaurante por Horario',()=>{ var restauranteHorario = listado.obtenerRestaurantes(null, null,'15:30') var resultadoManual = listadoDeRestaurantes.filter(res => { return res.horarios.some(horario => horario == '15:30'); }); expect(restauranteHorario).to.eql(resultadoManual) }) it('buscar combinacion de parametros sin resultado',()=>{ var restaurante = listado.obtenerRestaurantes('Berlín', 'Hamburguesa', '13:00') expect(restaurante).to.eql([]) }) }) describe('Testear Nueva Reserva', ()=>{ it('calcular precio total sobre reserva1', ()=>{ var reserva1 = new Reserva (new Date(2018, 7, 24, 11, 00), 8, 350, "DES1") expect(reserva1.calcularPrecioTotal()).to.equal(2450) }) it('calcular precio total sobre reserva2', ()=>{ var reserva2 = new Reserva (new Date(2018, 7, 27, 14, 100), 2, 150, "DES200") expect(reserva2.calcularPrecioTotal()).to.equal(100) }) it('calcular precio base reserva1',()=>{ var reserva1 = new Reserva (new Date(2018, 7, 24, 11, 00), 8, 350, "DES1") expect(reserva1.calcularPrecioBase()).to.equal(2800) }) it('calcular precio base reserva2', ()=>{ var reserva2 = new Reserva (new Date(2018, 7, 27, 14, 100), 2, 150, "DES200") expect(reserva2.calcularPrecioTotal()).to.equal(100) }) })
848cc83cb4b6ef0fa6684815a6628aad2c473732
[ "JavaScript" ]
1
JavaScript
catalinasy/reservando
08b7226e2ba0849dec37fdb17c3aaa1dbcd8e21a
d61130c0e344fafc565e38caffaa181987e82d7a
refs/heads/master
<file_sep>[package] name = "lc3vm" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] getch = "0.2.0" byteorder = "1" nix = "*" ctrlc = "*" rustyline="3.0.0" nom = "^4.1"<file_sep>// Parser for debugger commands // st print PC and COND // p R[0-7] direct print // p x[addr] // p @R[0-7] indirect print // p @x[addr] // b x[addr] set breakpoint at addr // lb list breakpoints // l list around pc // l x[addr] list around addr // l x[from] x[to] list from addr to addr // n next use std::fmt; use std::str::FromStr; named!(newline<&str, &str>, tag!("\n")); named!(space1<&str, char>, one_of!(" \t")); named!(space<&str, &str>, recognize!(many1!(space1))); named!(toeol<&str, &str>, recognize!(tuple!(many0!(space1), newline))); #[macro_export] macro_rules! sslist( ($i:expr, $submac:ident!( $($args:tt)* )) => ( many0!($i, preceded!(space, $submac!($($args)*))); ); ($i:expr, $f:expr) => ( sslist!!($i, call!($f)); ); ); #[derive(Debug)] pub enum Item { Reg(u8), Addr(u16), } impl fmt::Display for Item { fn fmt(&self, fmt:&mut fmt::Formatter) -> fmt::Result { match self { Item::Reg(n) => write!(fmt, "R{}", n), Item::Addr(a) => write!(fmt, "x{}", a) } } } #[derive(Debug)] pub enum Command { Print(bool, Item), PrintRegisters, Break(u16), ListBreak, List(Option<Item>, Option<Item>), Next, Status, Continue, Quit, } fn from_hex(input: &str) -> Result<u16, std::num::ParseIntError> { u16::from_str_radix(input, 16) } fn is_hex_digit(c: char) -> bool { c.is_digit(16) } named!(hex_primary<&str, u16>, map_res!(take_while_m_n!(1, 4, is_hex_digit), from_hex) ); // Register parser (Rx) named!(regx<&str, Item>, do_parse!(tag!("R") >> reg: one_of!("01234567") >> (Item::Reg(u8::from_str(&reg.to_string()).unwrap())) ) ); // Address parser (hex - xXXXX) named!(addr<&str, Item>, do_parse!(tag!("x") >> n: hex_primary >> (Item::Addr(n)) ) ); // p R[0-7] direct print // p x[addr] // p @R[0-7] indirect print // p @x[addr] named!(print_cmd<&str, Command>, do_parse!( one_of!("pP") >> is_a!(" \t") >> a: opt!(char!('@')) >> it: alt!(regx | addr) >> (Command::Print(a != None, it)) ) ); named!(print_regs_cmd<&str, Command>, do_parse!( tag!("pr") >> toeol >> (Command::PrintRegisters))); // l list around pc // l x[addr] list around addr // l x[from] x[to] list from addr to addr named!(pub list_cmd<&str, Command>, do_parse!( one_of!("lL") >> res: sslist!(alt!(addr | regx)) >> (match &res[..] { [] => Command::List(None, None), [Item::Addr(a)] => Command::List(Some(Item::Addr(*a)), None), [Item::Addr(a1), Item::Addr(a2)] => Command::List(Some(Item::Addr(*a1)), Some(Item::Addr(*a2))), _ => Command::List(None, None) })) ); // st print PC and COND named!(st_cmd<&str, Command>, do_parse!(tag!("st") >> (Command::Status) )); // lb list breakpoints named!(lb_cmd<&str, Command>, do_parse!(tag!("lb") >> (Command::ListBreak) )); // b x[addr] set breakpoint at addr named!(break_cmd<&str, Command>, do_parse!( one_of!("bB") >> is_a!(" \t") >> a: addr >> (match a { Item::Addr(a) => Command::Break(a), _ => panic!("Wrong break command") }) )); // n next named!(next_cmd<&str, Command>, do_parse!( tag!("n") >> (Command::Next) )); // q quit named!(quit_cmd<&str, Command>, do_parse!( one_of!("qQ") >> toeol >> (Command::Quit) )); // c continue named!(continue_cmd<&str, Command>, do_parse!( tag!("c") >> toeol >> (Command::Continue) )); named!(pub cmd<&str, Command>, do_parse!( cmd: alt!(print_cmd | lb_cmd | list_cmd | st_cmd | break_cmd | next_cmd | quit_cmd | continue_cmd | print_regs_cmd) >> (cmd) )); <file_sep> extern crate nix; use nix::sys::termios; extern crate rustyline; // buffer input using a channel fn with_terminal<T>(f:impl FnOnce()->T) -> T { // Querying original as a separate, since `Termios` does not implement copy let orig_term = termios::tcgetattr(0).unwrap(); let mut term = termios::tcgetattr(0).unwrap(); // Unset canonical mode, so we get characters immediately term.local_flags.remove(termios::LocalFlags::ICANON); // Don't generate signals on Ctrl-C and friends // term.local_flags.remove(termios::LocalFlags::ISIG); // Disable local echo term.local_flags.remove(termios::LocalFlags::ECHO); termios::tcsetattr(0, termios::SetArg::TCSADRAIN, &term).unwrap(); let res = f(); termios::tcsetattr(0, termios::SetArg::TCSADRAIN, &orig_term).unwrap(); res } pub fn getch() -> u8 { use std::io::Read; with_terminal(|| { std::io::stdin().bytes().next().unwrap().ok().unwrap() }) } pub fn check_input() -> bool { with_terminal(|| { use nix::sys::select; use nix::sys::time; use nix::sys::time::TimeValLike; let mut timeout = time::TimeVal::milliseconds(0); let mut readfds = select::FdSet::new(); readfds.insert(0); let res = select::select(None, Some(&mut readfds), None, None, Some(&mut timeout)); match res.ok() { None => false, Some(0) => false, Some(_) => true, } }) } <file_sep>extern crate nix; extern crate rustyline; use std::num::Wrapping; use std::sync::Arc; // use std::sync::atomic; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use crate::kbd; use crate::debugger::{ Command, Item }; use crate::debugger; use std::collections::HashSet; pub struct LC3Vm { mem: [Word; MEM_SIZE], reg: [Word; 8], pc: Word, cnd: u16, running: bool, debug: Arc<AtomicBool>, rl: rustyline::Editor<()>, bps: HashSet<u16>, } impl LC3Vm { const PC_START: u16 = 0x3000; const MMIO_START:usize = 0xFE00; const MMIO_KBDSR:usize = 0xFE00; const MMIO_KBDDR:usize = 0xFE01; pub fn new() -> LC3Vm { LC3Vm { mem: [Wrapping(0); MEM_SIZE], reg: [Wrapping(0); 8], pc: Wrapping(0), cnd: 0, running: false, debug: Arc::new(AtomicBool::new(false)), rl: rustyline::Editor::new(), bps: HashSet::new(), } } fn maybe_break(&self) { if self.bps.contains(&self.pc.0) { self.debug.store(true, Ordering::SeqCst); } else { println!("Skipping {:04x}", self.pc.0); } } pub fn run(&mut self) { self.pc = Wrapping(LC3Vm::PC_START); self.running = true; while self.running { self.maybe_break(); self.step(); if self.debug.load(Ordering::Relaxed) { self.debug_prompt(); } } } fn step(&mut self) { let instr_word = self.mem[self.pc.0 as usize]; let op = bits(instr_word.0, 12, 4); self.pc += Wrapping(1); match op { op::BR => self.br(instr_word), op::ADD => self.add(instr_word), op::LD => self.ld(instr_word), op::ST => self.st(instr_word), op::JSR => self.jsr(instr_word), op::AND => self.and(instr_word), op::LDR => self.ldr(instr_word), op::STR => self.str(instr_word), op::RTI => self.rti(instr_word), op::NOT => self.not(instr_word), op::LDI => self.ldi(instr_word), op::STI => self.sti(instr_word), op::JMP => self.jmp(instr_word), op::RES => self.res(instr_word), op::LEA => self.lea(instr_word), op::TRAP => self.trap(instr_word), _ => panic!("Impossible opcode!") } } // Instructions fn add_and(&mut self, args: Word, op: fn(Word, Word) -> Word) { let dr = bits(args.0, 9, 3) as usize; let sr1 = bits(args.0, 6, 3) as usize; let mode = bit(args.0, 5); let op2 = match mode { 0 => self.reg[bits(args.0, 0, 3) as usize], _ => Wrapping(sextbits(args.0, 0, 5)), }; self.reg[dr] = op(self.reg[sr1], op2); self.cnd = self.update_flags(self.reg[dr]); } fn br(&mut self, args:Word) { let nzp = bits(args.0, 9, 3); if nzp & self.cnd != 0 { self.pc += Wrapping(sextbits(args.0, 0, 9)); } } fn add(&mut self, args: Word) { self.add_and(args, |x, y| x + y); } fn ld(&mut self, args: Word) { let dr = bits(args.0, 9, 3) as usize; let off9 = Wrapping(sextbits(args.0, 0, 9)); let addr = self.pc + off9; let val = self.mem_read(addr.0); self.reg[dr] = val; self.cnd = self.update_flags(val); } fn st(&mut self, args: Word) { let dr = bits(args.0, 9, 3) as usize; let off9 = Wrapping(sextbits(args.0, 0, 9)); let val = self.reg[dr]; self.mem_write((self.pc + off9).0, val.0); } fn jsr(&mut self, args: Word) { let mode = bit(args.0, 11); self.reg[7] = self.pc; self.pc = match mode { 0 => self.reg[bits(args.0, 6, 3) as usize], _ => self.pc + Wrapping(sextbits(args.0, 0, 11)) } } fn and(&mut self, args: Word) { self.add_and(args, { |x,y| x & y }); } fn ldr(&mut self, args: Word) { let dr = bits(args.0, 9, 3) as usize; let br = bits(args.0, 6, 3) as usize; let off6 = Wrapping(sextbits(args.0, 0, 6)); self.reg[dr] = self.mem_read((self.reg[br] + off6).0); self.cnd = self.update_flags(self.reg[dr]) } fn str(&mut self, args: Word) { let sr = bits(args.0, 9, 3) as usize; let br = bits(args.0, 6, 3) as usize; let off6 = Wrapping(sextbits(args.0, 0, 6)); self.mem_write((self.reg[br] + off6).0, self.reg[sr].0); } fn rti(&mut self, _args: Word) { panic!("RTI called from non trap contexst"); } fn not(&mut self, args: Word) { let dr = bits(args.0, 9, 3) as usize; let sr = bits(args.0, 6, 3) as usize; let val = !self.reg[sr]; self.reg[dr] = val; self.cnd = self.update_flags(val); } fn ldi(&mut self, args: Word) { let dr = bits(args.0, 9, 3) as usize; let off9 = Wrapping(sextbits(args.0, 0, 9)); let addr = self.mem_read((self.pc + off9).0); let val = self.mem_read(addr.0); self.reg[dr] = val; self.cnd = self.update_flags(val); } fn sti(&mut self, args: Word) { let sr = bits(args.0, 9, 3) as usize; let off9 = Wrapping(sextbits(args.0, 0, 9)); let addr = self.mem_read((self.pc + off9).0); self.mem_write(addr.0, self.reg[sr].0); } fn jmp(&mut self, args: Word) { let br = bits(args.0, 6, 3) as usize; self.pc = self.reg[br] } fn res(&mut self, _args: Word) { panic!("Invalid opcode") } fn lea(&mut self, args: Word) { let dr = bits(args.0, 9, 3); let off9 = Wrapping(sextbits(args.0, 0, 9)); let val = self.pc + off9; self.reg[dr as usize] = val; self.cnd = self.update_flags(val) } fn trap(&mut self, args: Word) { let trapv8 = bits(args.0, 0, 8); match trapv8 { trap::GETC => self.trap_getc(), trap::OUT => self.trap_out(), trap::IN => self.trap_in(), trap::PUTS => self.trap_puts(), trap::PUTSP => self.trap_putsp(), trap::HALT => self.trap_halt(), _ => panic!("unknown trapvector") } } // traps fn trap_getc(&mut self) { let ch = kbd::getch(); self.reg[0].0 = ch as u16; self.update_flags(self.reg[0]); } fn trap_out(&mut self) { use std::io::Write; let ascii = self.reg[0].0 as u8 as char; print!("{}", ascii); std::io::stdout().flush().ok(); } fn trap_in(&mut self) { println!("Enter a character"); self.trap_getc(); } fn trap_puts(&mut self) { use std::io::Write; let baseaddr = self.reg[0].0 as usize; let charv: Vec<char> = self.mem[baseaddr..] .iter() .take_while(|w| ((**w).0 & 0xFF) != 0) .map(|w| (*w).0 as u8 as char) .collect(); let s: String = charv .into_iter() .collect(); print!("{}", s); std::io::stdout().flush().ok(); } fn trap_putsp(&mut self) { use std::io::Write; let baseaddr = self.reg[0].0 as usize; let s:String = self.mem[baseaddr..].into_iter() .take_while(|w| (**w).0 != 0u16) .flat_map(|w| { let c1 = (w.0 & 0xFF) as u8 as char; let c2 = (w.0 >> 8) as u8 as char; vec![c1, c2] }) .collect(); print!("{}", s); std::io::stdout().flush().ok(); } fn trap_halt(&mut self) { self.running = false; } fn update_flags(&self, val: Wrapping<u16>) -> u16 { match val { Wrapping(0) => flags::ZRO, Wrapping(n) if bit(n, 15) == 0 => flags::POS, _ => flags::NEG } } fn update_kbd(&mut self) { if kbd::check_input() { let b = kbd::getch(); self.mem[LC3Vm::MMIO_KBDSR] = Wrapping(1 << 15); self.mem[LC3Vm::MMIO_KBDDR] = Wrapping(b as u16); } else { self.mem[LC3Vm::MMIO_KBDSR] = Wrapping(0); } } // Memory and MMIO.0 fn mmio(&mut self, addr:u16) { match addr as usize { LC3Vm::MMIO_KBDSR => self.update_kbd(), _ => () } } fn mem_read(&mut self, addr:u16) -> Wrapping<u16> { if addr >= LC3Vm::MMIO_START as u16 { self.mmio(addr) } self.mem[addr as usize] } fn mem_write(&mut self, addr:u16, value:u16) { self.mem[addr as usize] = Wrapping(value); } pub fn load_image_file(&mut self, path:&str) { use byteorder::{BigEndian, ReadBytesExt}; let f = std::fs::File::open(path).expect("Could not open file"); let mut rd = std::io::BufReader::new(f); let origin = rd.read_u16::<BigEndian>().ok().unwrap(); println!("Loading file {} @ x{:04X}\r", path, origin); for addr in origin..std::u16::MAX { match rd.read_u16::<BigEndian>() { Ok(w) => { println!("x{:04X} {:04X}\r", addr, w); self.mem[addr as usize] = Wrapping(w); }, Err(_e) => { break; }, } } println!("{}", "-".repeat(80)); } // Debug // pub fn toggle_debug(&self) -> () { // self.debug.fetch_or(true, Ordering::SeqCst); // } fn print_registers(&self) { println!("{}", "-".repeat(80)); for i in 0..4 { println!("R{} = x{:04x} R{} = x{:04x}", i, self.reg[i], 4 + i, self.reg[4+i]); } println!("PC = x{:04x}", self.pc ); println!(" nzp"); println!("COND = {:03b}", self.cnd ); } fn prnchar(ch:u8) -> char { if "\n\t\0".contains(ch as char) { '.' } else if ch <= 31 || [0x7fu8].contains(&ch){ ' ' } else { ch as char } } fn print_mem(&self, before:Option<u16>, after:Option<u16>) { let (bef, aft) = match before { None => (self.pc - Wrapping(10), self.pc + Wrapping(20)), Some(n) => match after { None => (Wrapping(n) - Wrapping(10), Wrapping(n) + Wrapping(20)), Some(m) => (Wrapping(n), Wrapping(m)), } }; println!("{}..{}", bef.0, aft.0); for i in bef.0..aft.0 { let iw = self.mem[i as usize % MEM_SIZE]; println!("{} x{:04x} x{:04x} [{}{}] {}", if (i + 1) == self.pc.0 {">"} else {" "}, i, iw.0, LC3Vm::prnchar((iw.0 >> 8) as u8), LC3Vm::prnchar((iw.0 & 0xFF) as u8), isa::decode(iw.0)); } } pub fn getdebug(&self) -> Arc<AtomicBool> { self.debug.clone() } pub fn debug_prompt(&mut self) { self.print_mem(Some(self.pc.0 - 3), Some(self.pc.0 + 3)); loop { let readline = self.rl.readline("lc3db> "); match readline { Ok(line) => { let input = format!("{}\n", line); let cmd = debugger::cmd(&input); match cmd { Ok((_, cmd)) => match cmd { Command::Break(addr) => self.add_breakpoint(addr), Command::Continue => { self.debug.store(false, Ordering::SeqCst); break; }, Command::List(from, to) => match (from, to) { (None, None) => self.print_mem(None, None), (Some(Item::Addr(a)), None) => self.print_mem(Some(a), None), (Some(Item::Addr(a)), Some(Item::Addr(b))) => self.print_mem(Some(a), Some(b)), _ => println!("Wrong arguments for List"), }, Command::ListBreak => self.print_breakpoints(), Command::Next => break, Command::Print(indirect, item) => self.dbg_print(indirect, item), Command::Quit => std::process::exit(1), Command::Status => self.dbg_print_status(), Command::PrintRegisters => self.print_registers(), }, Err(_e) => println!("Not a command.") } } Err(e) => { println!("error {}", e); } } } } fn dbg_print(&self, indirect:bool, item:Item) { let tmp = match item { Item::Reg(n) => self.reg[n as usize], Item::Addr(a) => self.mem[a as usize], }; let val = if indirect { self.mem[tmp.0 as usize].0 } else { tmp.0 }; println!("{} => {:04x} ({:05}) {:016b}", item, val, val, val); } fn print_breakpoints(&self) { if self.bps.is_empty() { println!("No breakpoints."); } else { println!("Breakpoints:"); for (i, addr) in self.bps.iter().enumerate() { println!("{:>3}. x{:04x}", i, addr); } } } fn add_breakpoint(&mut self, addr:u16) { self.bps.insert(addr); } fn dbg_print_status(&self) { println!("PC = x{:04x}", self.pc ); println!(" nzp"); println!("COND = {:03b}", self.cnd ); } } type Word = Wrapping<u16>; pub mod op { pub const BR: u16 = 0x0; // branch pub const ADD: u16 = 0x1; // add pub const LD: u16 = 0x2; // load pub const ST: u16 = 0x3; // store pub const JSR: u16 = 0x4; // jump register pub const AND: u16 = 0x5; // bitwise and pub const LDR: u16 = 0x6; // load register pub const STR: u16 = 0x7; // store register pub const RTI: u16 = 0x8; // unused pub const NOT: u16 = 0x9; // bitwise not pub const LDI: u16 = 0xA; // load indirect pub const STI: u16 = 0xB; // store indirect pub const JMP: u16 = 0xC; // jump pub const RES: u16 = 0xD; // reserved (unused) pub const LEA: u16 = 0xE; // load effective address pub const TRAP: u16 = 0xF; // trap } #[allow(dead_code)] mod reg { pub const R0: u16 = 0; pub const R1: u16 = 1; pub const R2: u16 = 2; pub const R3: u16 = 3; pub const R4: u16 = 4; pub const R5: u16 = 5; pub const R6: u16 = 6; pub const R7: u16 = 7; } mod flags { pub const POS: u16 = 1; pub const ZRO: u16 = 2; pub const NEG: u16 = 4; } mod trap { pub const GETC: u16 = 0x20; pub const OUT: u16 = 0x21; pub const PUTS: u16 = 0x22; pub const IN: u16 = 0x23; pub const PUTSP: u16 = 0x24; pub const HALT: u16 = 0x25; } const MEM_SIZE:usize = 1 + std::u16::MAX as usize; #[allow(dead_code)] mod isa { use super::op; fn regf(reg: u16, start_bit: u16) -> u16 { (reg & 0b111) << start_bit } fn opc(op: u16) -> u16 { op << 12 } pub fn add(dr: u16, sr1: u16, sr2: u16) -> u16 { opc(op::ADD) | regf(dr, 9) | regf(sr1, 6) | sr2 & 0b111 } pub fn addi(dr: u16, sr1: u16, imm5: u16) -> u16 { opc(op::ADD) | regf(dr, 9) | regf(sr1, 6) | (1 << 5) | imm5 & 0x1F } pub fn and(dr: u16, sr1: u16, sr2: u16) -> u16 { opc(op::AND) | regf(dr, 9) | regf(sr1, 6) | sr2 & 0b111 } pub fn andi(dr: u16, sr1: u16, imm5: u16) -> u16 { opc(op::AND) | regf(dr, 9) | regf(sr1, 6) | (1 << 5) | imm5 & 0x1F } pub fn lea(dr:u16, off9: u16) -> u16 { opc(op::LEA) | regf(dr, 9) | off9 & 0x1FF } pub fn ld(dr:u16, off9:u16) -> u16 { opc(op::LD) | regf(dr, 9) | off9 & 0x1FF } pub fn decode(iw: u16) -> String { use crate::lc3::{bits, bit, sextbits}; let opc = iw >> 12; match opc { op::BR => { let mut nzps = String::new(); if bit(iw, 11) == 1 {nzps.push_str("n");} if bit(iw, 10) == 1 {nzps.push_str("z");} if bit(iw, 9) == 1 {nzps.push_str("p");} let off9 = sextbits(iw, 0, 9) as i16; format!("BR{} {:04x} ({})", nzps, off9, off9) }, op::ADD => { let dr = bits(iw, 9, 3); let sr1 = bits(iw, 6, 3); let imm = bit(iw, 5); if imm == 1 { let off5 = sextbits(iw, 0, 5) as i16; format!("ADD R{}, R{}, #{}", dr, sr1, off5) } else { let sr2 = bits(iw, 0, 3); format!("ADD R{}, R{}, R{}", dr, sr1, sr2) } }, op::AND => { let dr = bits(iw, 9, 3); let sr1 = bits(iw, 6, 3); let imm = bit(iw, 5); if imm == 1 { let imm5 = sextbits(iw, 0, 5) as i16; format!("AND R{}, R{}, #{}", dr, sr1, imm5) } else { let sr2 = bits(iw, 0, 3); format!("AND R{}, R{}, R{}", dr, sr1, sr2) } }, op::LEA => { let dr = bits(iw, 9, 3); let off9 = sextbits(iw, 0, 9) as i16; format!("LEA R{} x{:04x}", dr, off9) }, op::LD => { let dr = bits(iw, 9, 3); let off9 = sextbits(iw, 0, 9) as i16; format!("LD R{} x{:04x}", dr, off9) }, op::LDI => { let dr = bits(iw, 9, 3); let off9 = sextbits(iw, 0, 9) as i16; format!("LDI R{} x{:04x}", dr, off9) }, op::LDR => { let dr = bits(iw, 9, 3); let br = bits(iw, 6, 3); let off6 = sextbits(iw, 0, 6) as i16; format!("LDR R{} R{} x{:04x}", dr, br, off6) }, op::ST => { let sr = bits(iw, 9, 3); let off9 = sextbits(iw, 0, 9) as i16; format!("ST R{} x{:04x}", sr, off9) }, op::STI => { let sr = bits(iw, 9, 3); let off9 = sextbits(iw, 0, 9) as i16; format!("STI R{} x{:04x}", sr, off9) }, op::STR => { let dr = bits(iw, 9, 3); let br = bits(iw, 6, 3); let off6 = sextbits(iw, 0, 6) as i16; format!("STR R{} R{} x{:04x}", dr, br, off6) }, op::JSR => { let mode = bit(iw, 11); if mode == 1 { let off11 = sextbits(iw, 0, 11) as i16; format!("JSR x{:04x}", off11) } else { let br = bits(iw, 6, 3); format!("JSRR R{}", br) } }, op::JMP => { let br = bits(iw, 6, 3); format!("JMP R{}", br) }, op::RTI => { format!("RTI") }, op::TRAP => { use crate::lc3::trap; let trapv = bits(iw, 0, 8); match trapv { trap::GETC => "GETC".to_string(), trap::HALT => "HALT".to_string(), trap::IN => "IN".to_string(), trap::OUT => "OUT".to_string(), trap::PUTS => "PUTS".to_string(), trap::PUTSP => "PUTSP".to_string(), n => format!("TRAP x{:02x}", n) } }, op::RES => { format!("RES") }, op::NOT => { let dr = bits(iw, 9, 3); let sr = bits(iw, 6, 3); format!("NOT R{}, R{}", dr, sr) }, _ => format!(".fill x{:04x}", iw) } } } #[allow(dead_code)] mod programs { use super::isa::*; use super::reg::*; fn example_program() { let _ = [ lea( R0, 0), add( R1, R0, R2), andi( R1, R0, 7), and( R0, R0, 0), // clear R0 ld( R0, 0xFFFF), ]; } } fn bits(word: u16, start: u16, len: u32) -> u16 { let mask = 2u16.pow(len) - 1; mask & (word >> start) } fn bit(word:u16, n:u16) -> u16 { bits(word, n, 1) } fn sign_extend(word: u16, bitlen: u16) -> u16 { let msb = bits(word, bitlen - 1, 1); match msb { 0 => word, _ => { let mask = 0xFFFF << bitlen; word | mask } } } fn sextbits(word:u16, start:u16, len:u16) -> u16 { sign_extend(bits(word, start, len as u32), len) } #[cfg(test)] mod tests { use crate::lc3::isa; use std::num::Wrapping; #[test] fn add_immediate_works() { let mut vm = crate::lc3::LC3Vm::new(); vm.mem[0x3000] = Wrapping(isa::addi(0, 0, -5i16 as u16)); vm.pc = Wrapping(0x3000); vm.step(); assert_eq!(vm.reg[0], Wrapping(-5i16 as u16)); assert_eq!(vm.pc, Wrapping(0x3001)); assert_eq!(vm.cnd, 0b100); } #[test] fn add_works() { let mut vm = crate::lc3::LC3Vm::new(); vm.reg[0] = Wrapping(10); vm.reg[1] = Wrapping(-1i16 as u16); vm.mem[0x3000] = Wrapping(isa::add(2, 1, 0)); vm.pc = Wrapping(0x3000); vm.step(); assert_eq!(vm.reg[2], Wrapping(9)); assert_eq!(vm.pc, Wrapping(0x3001)); assert_eq!(vm.cnd, 0b001); } #[test] fn and_immediate_works() { let mut vm = crate::lc3::LC3Vm::new(); vm.reg[0].0 = 0b1100011; vm.mem[0x3000] = Wrapping(isa::andi(0, 0, 0b11)); vm.pc = Wrapping(0x3000); vm.step(); assert_eq!(vm.reg[0], Wrapping(0b11)); assert_eq!(vm.pc, Wrapping(0x3001)); assert_eq!(vm.cnd, 0b001); } #[test] fn and_works() { let mut vm = crate::lc3::LC3Vm::new(); vm.reg[0].0 = 0b1011101; vm.reg[1].0 = 0b1100011; vm.mem[0x3000] = Wrapping(isa::and(2, 1, 0)); vm.pc = Wrapping(0x3000); vm.step(); assert_eq!(vm.reg[2], Wrapping(0b1000001)); assert_eq!(vm.pc, Wrapping(0x3001)); assert_eq!(vm.cnd, 0b001); } #[test] fn add_works2() { let mut vm = crate::lc3::LC3Vm::new(); vm.reg[0].0 = 0x79; vm.reg[1].0 = 0xFF87; vm.mem[0x3000] = Wrapping(isa::add(2, 1, 0)); vm.pc = Wrapping(0x3000); vm.step(); assert_eq!(vm.reg[2], Wrapping(0)); assert_eq!(vm.pc, Wrapping(0x3001)); assert_eq!(vm.cnd, 0b010); } } <file_sep>#[macro_use] extern crate nom; extern crate ctrlc; mod kbd; mod lc3; mod debugger; use std::env; fn main() { let mut vm = lc3::LC3Vm::new(); let args = std::env::args(); let filename = args.skip(1).next(); let debug = vm.getdebug(); match env::var("DBG") { Ok(_) => debug.store(true, std::sync::atomic::Ordering::SeqCst), Err(_) => (), } ctrlc::set_handler(move || { println!("debug"); debug.store(true, std::sync::atomic::Ordering::SeqCst); }).expect("Error setting ctrl+c handler"); match filename { None => { println!("USAGE: lc3vm imagefile.obj"); }, Some(fname) => { vm.load_image_file(&fname); vm.run(); } } }
ca961f51241354cc2e154202ae491a3972bdb33e
[ "TOML", "Rust" ]
5
TOML
laynor/lc3
bbe63443fd47b44c2296587acad5db7942c1a48b
7a1d3fc78c7d91ca122b94b0403a517fa1105a62
refs/heads/master
<file_sep>#include <stdio.h> #include <math.h> #include "source.h" void simple_sum(void) { } void simple_math(void) { }
554b871aed4d005fe463bf071688a1c145e36bb3
[ "C" ]
1
C
calsaviour/aalto-c
f9cabbbb420a13ac9cec2e60ccc9ee48d82708b3
f2a09fd6a54a8ccca0be4142e2271fa7b7dd2d79
refs/heads/master
<file_sep>--[[ ScoreState Class Author: <NAME> <EMAIL> A simple state used to display the player's score before they transition back into the play state. Transitioned to from the PlayState when they collide with a Pipe. ]] ScoreState = Class{__includes = BaseState} --[[ When we enter the score state, we expect to receive the score from the play state so we know what to render to the State. ]] function ScoreState:enter(params) self.score = params.score end function ScoreState:update(dt) -- go back to play if enter is pressed if love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return') then gStateMachine:change('countdown') end end function ScoreState:render() -- simply render the score to the middle of the screen love.graphics.setFont(flappyFont) love.graphics.printf('Oof! You lost!', 0, 64, VIRTUAL_WIDTH, 'center') love.graphics.setFont(mediumFont) love.graphics.printf('Score: ' .. tostring(self.score), 0, 100, VIRTUAL_WIDTH, 'center') love.graphics.printf('Press Enter to Play Again!', 0, 160, VIRTUAL_WIDTH, 'center') -- AS1.3 - drawn medals according to score. if self.score > 4 then love.graphics.draw(rank_gold, VIRTUAL_WIDTH/2 - medal_width/2, 180, 0, medal_scaling, medal_scaling) elseif self.score > 2 then love.graphics.draw(rank_silver, VIRTUAL_WIDTH/2 - medal_width/2, 180, 0, medal_scaling, medal_scaling) elseif self.score > 0 then love.graphics.draw(rank_bronze, VIRTUAL_WIDTH/2 - medal_width/2, 180, 0, medal_scaling, medal_scaling) end end <file_sep>--[[ GD50 Breakout Remake -- Ball Class -- Author: <NAME> <EMAIL> Assignment 2.1 "Add a Powerup class to the game that spawns a powerup (images located at the bottom of the sprite sheet in the distribution code). This Powerup should spawn randomly, be it on a timer or when the Ball hits a Block enough times, and gradually descend toward the player. Once collided with the Paddle, two more Balls should spawn and behave identically to the original, including all collision and scoring points for the player. Once the player wins and proceeds to the VictoryState for their current level, the Balls should reset so that there is only one active again."" ]] -- AS2.1 - the Powerup class Powerup = Class{} function Powerup:init(x, y, keyValid) self.x = x self.y = y self.dx = 0 self.dy = 0 self.width = 16 self.height = 16 -- AS2.1 - type calculation -- AS2.3 - 80% chance to get key if needed if keyValid then self.type = 10 else self.type = math.random(1, 9) end self.collided = false -- AS2.1 -variables for the startup animation self.blinkTimer = 0 self.startupTimer = 0 self.visible = true end function Powerup:update(dt) if self.startupTimer < 3.4285 then self.startupTimer = self.startupTimer + dt self.blinkTimer = self.blinkTimer + dt -- AS2.1 Syncing the blink to the BPM of the music if self.blinkTimer > 0.4285 then self.blinkTimer = self.blinkTimer - 0.4285 self.visible = not self.visible end else self.y = self.y + 1 end end function Powerup:collides(target) -- first, check to see if the left edge of either is farther to the right -- than the right edge of the other if self.x > target.x + target.width or target.x > self.x + self.width then return false end -- then check to see if the bottom edge of either is higher than the top -- edge of the other if self.y > target.y + target.height or target.y > self.y + self.height then return false end -- if the above aren't true, they're overlapping return true end function Powerup:render() if self.visible then love.graphics.draw(gTextures['main'], gFrames['powerups'][self.type], self.x, self.y) end end -- AS2.3 - (static function) visual identifier for lasting powerups function Powerup.renderBar(key) local x = 4 local y = VIRTUAL_HEIGHT - 20 if key then love.graphics.draw(gTextures['main'], gFrames['powerups'][10], x, y) x = x + 16 end end <file_sep># cs50g-kurt Repo for CS50G assignments. These games are clones of other popular games, and were made for Harvard's CS50G (GD50) course. ## Course Link https://courses.edx.org/courses/course-v1:HarvardX+CS50G+Games/course/ ## Running All Assignments (Windows) 1. Download the .zip for the following repository: https://github.com/KurtYilmaz/cs50g-kurt-builds 2. Navigate though directories and double click the .exe file of any assignment you want to play. ## Building Assignments 1-7 (LÖVE, Windows, Mac, Linux) 1. [Download LÖVE, version 10.2 (I know it's outdated, the course uses libraries only compatible with 10.2)](https://bitbucket.org/rude/love/downloads/). 2. Install LÖVE. 3. Zip an assignment folder. 4. Rename the extension of the zipped folder from ".zip" to ".love". 5. Open the ".love" file. ## Building Assignments 8-11 (Unity, Windows, Mac, Linux) 1. [First, download Unity Hub](https://unity3d.com/get-unity/download). 2. Once installed, the sidebar on the left side should have an entry called "Installs". 3. Click the "Add" button on the link, direct to the official releases website, and download Unity 2018.1.0f2 for Unity Hub. 4. When Unity finishes installing, click on the sidebar entry called "Projects". 5. Click "Add" and navigate to the assignment folder. 6. Go to File->Build Settings, and select your target platform. 7. Click "Build," then make a folder called "Build". 8. Navigate to that folder and click on the executable. ## Controls ### Assignment 0 - Pong > Up arrow key - move up > Down arrow key - move down ### Assignment 1 - Flappy Bird > Space bar - fly up (slightly) &nbsp; ### Assignment 2 - Breakout > Left arrow key - move left > Right arrow key - move right &nbsp; ### Assignment 3 - Match 3 > Move mouse - move cursor > Left click - select ### Assignment 4 - <NAME>. > W - move up > A - move left > S - move down > D - move right > Space bar - jump &nbsp; ### Assignment 5 - Legend of Zelda > W - move up > A - move left > S - move down > D - move right > Space bar - action button (lift pots or attack) &nbsp; ### Assignment 6 - Angry Birds (coming soon) > Move mouse - move cursor > Left click - select and drag ### Assignment 7 - Pokemon > W - move up > A - move left > S - move down > D - move right > J - OK/confirm > K - back > H - heal > Enter - start ### Assignment 8 - 3D Helicopter Game > W - move up > A - move left > S - move down > D - move right ### Assignment 9 - Dreadhalls > Move mouse - move camera/change direction > W - move up > A - move left > S - move down > D - move right > Space - Jump ### Assignment 10 - Portal (coming soon) ### Final Project (coming soon)
6d3ebd52aa0cefb1d60025262511858589aadc63
[ "Markdown", "Lua" ]
3
Lua
nabeelmohammed1/cs50g-kurt
748245274b202a44335f32d247579660721fbc88
1b5b76ca2e21380e17a522340164abfc7803a57e
refs/heads/master
<file_sep>import java.awt.Color; import javax.swing.JFrame; public class Start extends JFrame { /** * */ private static final long serialVersionUID = 1L; Main parentMain = new Main(); public Start(){ World world = new World(this); add(world); setTitle("Tree Evolution"); setSize(1500, 1050); setResizable(false); setLocation(0, 0); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); setBackground(new Color(255, 255, 255)); } } <file_sep>import java.util.ArrayList; public class BranchNode { BranchNode parent; ArrayList<BranchNode> children = new ArrayList<BranchNode>(); boolean leaf_alive = true; public int leaf_age = 0; public int leaf_size = 1; public int x = World.WORLD_WIDTH/2; public int y = 0; public BranchNode(){ parent = null; } public BranchNode(int a, int b){ x = a; y = b; parent = null; } public BranchNode(BranchNode bn, int a, int b){ parent = bn; x = a; y = b; } public void addLeaf(Tree tree, Grid[][] map) { // assumes x and y are in the grid, only bound check x when leaves are // big for (int i = 0; i < tree.leaf_size; i++) { int l = x + i - tree.leaf_size / 2; if (l >= 0 && l < World.WORLD_WIDTH) { map[l][y].type = World.OBJ_LEAF; } } } public void killLeaf(Tree tree, Grid[][] map) { leaf_alive = false; for (int i = 0; i < tree.leaf_size; i++) { int l = x + i - tree.leaf_size / 2; if (l >= 0 && l < World.WORLD_WIDTH && map[l][y].type == World.OBJ_LEAF) { map[l][y].type = World.OBJ_EMPTY; } } map[x][y].type = World.OBJ_NODE; } } <file_sep>import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; public class Tree { private static final int WIDTH_VARIATION = 5; // how many grids each sector // the gene represents. private static final int HEIGHT_VARIATION = 5; // how many grids each // sector the gene // represents. private static final int GENE_TOTAL = 10; // must be multiple of 5. private static final int LEAF_LIFETIME = 1000; // number of frames before // a leaf dies. private static final int COLOR_CHANGE_TIME = 10; // number of frames before // a color changes private static final int INITIAL_HEALTH = 1000;// not sure if I want to use // this. private static final int OLD_AGE_FACTOR = 1000; // the bigger the number, // the slower it'll die. public int[] width_gene = { 2, 2, 2, 2, 2 }; // must add up to // GENE_TOTAL public int[] height_gene = { 2, 2, 2, 2, 2 }; // must add up to // GENE_TOTAL public int max_branch_per_node = 2; public int reproduce_time = 1000; public int grow_time = 100; public int health = 1000; public int leaf_size = 1; public int amount_of_tree = 1; public int age = 1; public int generation = 1; public int color = 255; BranchNode root; public Tree() { root = new BranchNode(); } public Tree(int x, int y, Grid[][] map) { root = new BranchNode(x, y); root.addLeaf(this, map); } public Tree(Grid[][] map) { root = new BranchNode(); root.addLeaf(this, map); } // Reproduce from parent public Tree(Tree parent, int x, int y, Grid[][] map) { // mutate! height_gene = parent.height_gene.clone(); if (World.BRANCH_HEIGHT_MUTATION) { int r = (int) (Math.random() * 5); height_gene[r] += 1; r = (int) (Math.random() * 5); while (height_gene[r] == 0) { r = (int) (Math.random() * 5); } height_gene[r] -= 1; } width_gene = parent.width_gene.clone(); if (World.BRANCH_WIDTH_MUTATION) { int r = (int) (Math.random() * 5); width_gene[r] += 1; r = (int) (Math.random() * 5); while (width_gene[r] == 0) { r = (int) (Math.random() * 5); } width_gene[r] -= 1; } reproduce_time = parent.reproduce_time; if (World.REPRODUCE_TIME_MUTATION) { int r = (int) (Math.random() * 11) - 5; if (reproduce_time + r >= 0) { reproduce_time += r; } } grow_time = parent.grow_time; if (World.GROW_TIME_MUTATION) { int r = (int) (Math.random() * 11) - 5; if (grow_time + r >= 0) { grow_time += r; } } leaf_size = parent.leaf_size; if (World.LEAF_SIZE_MUTATION) { int r = (int) (Math.random() * 3) - 1; if (leaf_size + r >= 0) { leaf_size += r; } } max_branch_per_node = parent.max_branch_per_node; if (World.MAX_BRANCH_PER_NODE_MUTATION) { int r = (int) (Math.random() * 3) - 1; if (max_branch_per_node + r > 0) { max_branch_per_node += r; } } generation = parent.generation + 1; health = INITIAL_HEALTH; root = new BranchNode(x, y); // make new leaf on new branch root.addLeaf(this, map); } public void paintTree(Graphics2D g2, int i) { // g2.setColor(new Color(139, 69, 19)); g2.setColor(new Color(color, color, color)); if (i == 0) { g2.setColor(Color.RED); } paintBranch(g2, root); } private void paintBranch(Graphics2D g2, BranchNode bn) { for (int i = 0; i < bn.children.size(); i += 1) { paintBranch(g2, bn.children.get(i)); } if (bn.parent != null) { g2.drawLine(bn.x * World.SQUARE_SIZE, (World.WORLD_HEIGHT - bn.y) * World.SQUARE_SIZE, bn.parent.x * World.SQUARE_SIZE, (World.WORLD_HEIGHT - bn.parent.y) * World.SQUARE_SIZE); } } public void processTree(Grid[][] map, ArrayList<Tree> trees) { // if conditions meet, grow! // if conditions meet, reproduce // update health // update age // killing is done by World class. // change color if (age % COLOR_CHANGE_TIME == 0 && color > 0) { color -= 1; } // /////////////I don't like it growing on timer//////////////////// if (age % grow_time == 0) { grow(map); } if (age % reproduce_time == 0) { reproduce(map, trees); } // update health based on how big the tree is, and how much light the // leaves are getting processNode(root, map); health -= amount_of_tree; health -= age / OLD_AGE_FACTOR; age += 1; } private void processNode(BranchNode bn, Grid[][] map) { // Process individual nodes here // Photo Synthesis if (bn.leaf_alive) { for (int i = 0; i < leaf_size; i++) { int l = bn.x + i - leaf_size / 2; if (l >= 0 && l < World.WORLD_WIDTH) { health += map[l][bn.y].sunlight; map[l][bn.y].sunlight -= World.LEAF_BLOCK; } } // Kill Leaf if the leaf is too old bn.leaf_age += 1; if (bn.leaf_age >= LEAF_LIFETIME) { bn.killLeaf(this, map); } } // If I really want to be safe, I should put a check for if bn.children.size() > 0 // But the for loop here checks it for me already. for (int i = 0; i < bn.children.size(); i++) { processNode(bn.children.get(i), map); } } public void reproduce(Grid[][] map, ArrayList<Tree> trees) { for (int i = 0; i < health/age; i++) { // not sure how many children each tree // should have... BranchNode bn = root; while (bn.children.size() > 0) { bn = bn.children .get((int) (Math.random() * bn.children.size())); } trees.add(new Tree(this, bn.x, 0, map)); } } public void kill(Grid[][] map) { removeLeaves(map, root); } private void removeLeaves(Grid[][] map, BranchNode bn) { if (bn.leaf_alive) { bn.killLeaf(this, map); } for (int i = 0; i < bn.children.size(); i++) { removeLeaves(map, bn.children.get(i)); } } public void grow(Grid[][] map) { // grows a new branch. // check if any given node is full capacity. if not, grow or move to // child. // using node as reference, make a new node. // update map as well // pick an existing node to grow from. BranchNode parent = root; while (parent.children.size() > 0) { if (parent.children.size() >= max_branch_per_node) { // if no more room at this branch parent = parent.children .get((int) (Math.random() * parent.children.size())); } else if (Math.random() < 0.5) { // if there is still room, picks randomly parent = parent.children .get((int) (Math.random() * parent.children.size())); } else { break; } } int newX, newY; // X and Y coordinates for the new node. int r = (int) (Math.random() * GENE_TOTAL); int gene_count = width_gene[0]; int width_select = 0; while (r > gene_count) { width_select += 1; gene_count += width_gene[width_select]; } r = (int) (Math.random() * WIDTH_VARIATION); newX = parent.x - WIDTH_VARIATION / 2 + (width_select - 2) * WIDTH_VARIATION + r; if (newX < 0) {// if goes off the grid, push back. newX = 0; } else if (newX >= World.WORLD_WIDTH) { newX = World.WORLD_WIDTH - 1; } r = (int) (Math.random() * GENE_TOTAL); gene_count = height_gene[0]; int height_select = 0; while (r > gene_count) { height_select += 1; gene_count += height_gene[height_select]; } r = (int) (Math.random() * HEIGHT_VARIATION); newY = parent.y + height_select * HEIGHT_VARIATION + r; if (newY >= World.WORLD_HEIGHT) { newY = World.WORLD_HEIGHT - 1; } // add the branch to the total body. amount_of_tree += (int) Math.sqrt((newX - parent.x) * (newX - parent.x) + (newY - parent.y) * (newY - parent.y)); BranchNode child = new BranchNode(parent, newX, newY); parent.children.add(child); if (parent.leaf_alive) { // kill leaf, because branch is growing off of it parent.killLeaf(this, map); } // make new leaf on new branch child.addLeaf(this, map); } } <file_sep> public class Grid { public int sunlight; public int type; public Grid(){ type = World.OBJ_EMPTY; sunlight = World.FULL_SUNLIGHT; } public Grid(int t, int s){ type = t; sunlight = s; } }
b33dc044ff01b504efb7811def4e2887bcaf39f4
[ "Java" ]
4
Java
alan850627/TreeEvolution
cf38e891bf291ebb96b4304249b9814555eb61e3
2f857d85efc930f6a92bbfcaa1e57e0a7dee2de5
refs/heads/master
<file_sep>#!/usr/bin/python3 # accept commands form cli import argparse import json def main(): inventory = {} if args.list: inventory = example_inventory() elif args.host: inventory = empty_inventory() else: inventory = empty_inventory() print(json.dumps(inventory)) def example_inventory(): return { 'group': { 'hosts': ['centurylink-webserver'] }, '_meta': { 'hostvars': { 'centurylink-webserver': { 'ansible_connection': 'local', 'ansible_host': 'localhost' } } } } def empty_inventory(): return {} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--list', action = 'store_true') parser.add_argument('--host', action = 'store') args = parser.parse_args() main()
b8aa9bb1d6f5488efce3fbe22fa43fdb1716a11d
[ "Python" ]
1
Python
cami2casi/20200323openstack
5d641d6942c3a1e64bebecb8d4b6bd3536fa1fc9
2e8cab629c19db00dcd7468e09917025c08ea974
refs/heads/master
<file_sep># News_Classification [![](https://img.shields.io/badge/pytorch-1.8.1GPU-orange "title")](https://pytorch.org/)[![](https://img.shields.io/badge/python-3.6-green "title")](https://www.python.org/) #### 介绍 基于pytorch实现的 TextCNN 模型 #### 环境 python 3.6 pytorch 1.8.1 jieba 0.42.1 gensim 4.0.1 #### 数据集 分类包括:'财经', '房产', '教育', '科技', '军事', '汽车', '体育', '游戏', '娱乐'共9类 #### 数据预处理 1.将原始新闻文本文件按行打乱 2.使用jieba对所有新闻正文内容进行分词,得到词库 3.使用word2vec训练词库生成词向量模型 4.将原始新闻文本进行分词后,替换为词向量模型中的索引 分类,正文 -----> (分类id, [2,3,4,..词索引]) #### 测试结果 对新闻测试集进行测试 最终平均准确率为 91.171% #### 项目结构 ``` NEWS_CLASSIFICATION | content.txt #预测文本内容 | main.py #预测content.txt中的分类 | \---src | data_loader.py #为模型训练和测试提供取样本函数,取的是dara/Samples下的样本集 | data_peprocessing.py #对 data/train_test_data.7z中的训练、测试数据进行预处理,弄完就没啥用了 | jieba_tool.py #对jieba分词封装 | model.py #TextCNN 模型的定义 | model_test.py #测试模型 | model_train.py #训练模型 | word_vector_tool.py #word2vec词向量工具封装 | +---data | | data.7z #原始样本 | | | +---testSamples | | sample-0.pth #预处理后的样本 | | ........... | | sample-69.pth | | | +---trainSamples | | sample-0.pth | | ........... | | sample-137.pth | | | \---word_vector | all_words.txt #词库 | cn_stopwords.txt #停用词 | words_vector.model #word2vec词向量模型 | words_vector.model.syn1neg.npy | words_vector.model.wv.vectors.npy | +---model_save | epoch.pth #已训练轮数 | model.pth #TextCNN模型 | ``` #### 参考论文 [1] Convolutional Neural Networks for Sentence Classification <file_sep>import random import torch from data_loader import labels from jieba_tool import get_key_words_all_step from word_vector_tool import file_to_sentences, add_sentences, get_vector_model, get_index # test_data的分类及数量 {'娱乐': 1000, '财经': 1000, '房地产': 1000, '旅游': 1000, '科技': 1000, '体育': 1000, '健康': 1000, '教育': 1000, # '汽车': 1000, '新闻': 1000, '文化': 1000, '女人': 1000} # 语料集是txt文件,如果用windows自带的记事本打开,会卡死,建议用notepad++打开,相当流畅 # train_data的分类及数量 '娱乐': 1934, '财经': 1877, '房地产': 1872, '旅游': 1998, '科技': 1988, '体育': 1978, '健康': 2000, '教育': 1979, # '汽车': 1996, '新闻': 1935, '文化': 1995, '女人': 1997 # 将原有的 pre.txt 打乱行写进新的shuffle_txt文件中 def shuffle_txt_data(pre_txt, shuffle_txt): # 用于将原有排序的数据打乱,方便后面训练 encoding = 'utf-8' with open(pre_txt, 'r', encoding=encoding) as lines: # 也可以 for line in lines: line_list.append(line) line_list = list(lines) # 打乱列表顺序 random.shuffle(line_list) with open(shuffle_txt, 'w', encoding=encoding) as file: for each_line in line_list: file.write(each_line) # souhu_train.txt 文件中每一行分为分类和正文, 两者以 '\t' 分隔,test也是如此 # 首先先要训练语料集中的词汇,使用word2vec建立词向量模型 # 将分词的结果以每一行一个词,保存在 split_txt中,后面直接将将该文件训练词向量 # 这个过程很慢,2万行数据花了我20多分钟吧 def split_words(news_txt, split_txt): with open(news_txt, 'r', encoding='utf-8') as lines: with open(split_txt, 'a', encoding='utf-8') as file: for line in lines: split = line.split('\t') label = split[0] #, 分类名 content = split[1] #len(content) 获取最大词汇,我想让词向量模型更全面些 keys = get_key_words_all_step(content, len(content)) for key in keys: file.write(key + '\n') # 原有词向量模型 model = get_vector_model() # split_txt 分词文件,上面那个函数的结果 def train_vector(model, split_txt): # build_model(file_to_sentences(split_txt)) 当model没有时 return add_sentences(model, file_to_sentences(split_txt)) # 先将每条新闻正文为 (label,[word1_index,word2_index,....]), label是labels词典中分类名对应的id, # [....]则是正文内容分词后,每个词在词向量模型中的index,一定要先split_word,后train_vector # 分词索引[..]长度固定为 50,,不足补0,如果不固定,[[49][50]....] 这种形状 torch.tensor()会出错 def package_news_data(news_txt, directory): sample_size = 100 # 每100个新闻为一个sample key_size = 50 # 关键词数量 model = get_vector_model() # 词向量模型 with open(news_txt, 'r', encoding='utf-8') as lines: sample_index = 0 # sample_序号 news_count = 0 # sample内的新闻数量 sample = [] # 保存sample_size个新闻 for line in lines: if '\ufeff' in line: continue sp = line.split('\t') label = labels[sp[0]] content = sp[1] # 分词 content_key = get_key_words_all_step(content, key_size) key_index = [get_index(model, key) for key in content_key] key_index.extend([0] * (key_size - len(key_index))) # 补0 # 加入样本集 sample.append((label, key_index)) news_count += 1 print('[sample %d ][ news %d ]' % (sample_index, news_count)) if news_count == sample_size: torch.save(sample, directory + 'sample-' + str(sample_index) + '.pth') print('[sample %d package done]' % sample_index) news_count = 0 sample.clear() sample_index += 1 if news_count > 0: # 未满sample_size torch.save(sample, directory + 'sample-' + str(sample_index) + '.pth') print('[sample %d package done]' % sample_index) if __name__ == '__main__': # pre_train_txt = './data/train.txt' after_train_txt = './data/train_shuffle.txt' # pre_test_txt = './data/test.txt' after_test_txt = './data/test_shuffle.txt' # words = './data/word_vector/all_words.txt' # shuffle_txt_data(pre_train_txt, after_train_txt) # shuffle_txt_data(pre_test_txt, after_test_txt) # split_words(pre_train_txt, words) # split_words(pre_train_txt, words) # model_save = get_vector_model() # train_vector(model_save, words) #package_news_data(after_train_txt, './data/trainSamples/') package_news_data(after_test_txt, './data/testSamples/') # index = 0 # with open('./data/test.txt',encoding='utf-8') as lines: # for line in lines: # #l= len(line.split('\t')) # if '\ufeff' in line: # print(index) # index += 1 print('done') <file_sep>import sys import torch import torch.nn.functional as F import src.model as m from src.data_loader import categories from src.jieba_tool import get_key_words_all_step from src.word_vector_tool import get_vector_model, get_index # 调用不同文件夹下的脚本要加这个 sys.path.append('src/') # 需要预测的新闻内容粘贴在content.txt中, 百度新闻还不错 if __name__ == '__main__': content = '' with open('content.txt', encoding='utf-8') as lines: for line in lines: content += line.lstrip().replace('\n', '') keys = get_key_words_all_step(content, len(content)) chosen = [] vector = get_vector_model() print('开始分词....') for key in keys: index = get_index(vector, key) if index > 0: print(key, end=', ') chosen.append(index) if len(chosen) == 50: break print('\n\n分词结束') x = torch.tensor([chosen]).to(m.device) print('load model...') net = m.get_trained_net() out = F.softmax(net(x), dim=1) _, pre = torch.max(out, dim=1) index = pre.item() print('类别:', categories[index], '\n概率: ', out[0][index].item()) <file_sep># coding:utf-8 import os import torch import torch.nn.functional as F from torch import nn from src.word_vector_tool import get_vector_model def get_trained_net(): net = torch.load(save_path.get('model')).to(device) net.eval() return net def get_epoch(): return torch.load(save_path.get('epoch')) def save_net_epoch(net, epoch): net.eval() torch.save(net, save_path.get('model')) torch.save(epoch, save_path.get('epoch')) # 模型和输入输出都会保存在这个device中 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # embedding_weight = get_vector_weight(get_vector_model()) # Config = { # # 'embedding_weight': get_vector_weight(model_save), 如果每次将这个config输入进去,之前的优化都失效了,只能让模型随机了 # 'kernel_size': (2, 3, 4), # 'output_channels': 300, # 'class_num': 10, # 'linear_one': 250, # 'linear_two': 120, # 'dropout': 0.5, # 'embedding_weight': embedding_weight # } module_path = os.path.dirname(__file__) Config = { 'kernel_size': (3, 4, 5), # 卷积核的不同尺寸 'output_channels': 200, # 每种尺寸的卷积核有多少个 'class_num': 9, # 分类数量,见data_loader.categories 'linear_one': 250, # 第一个全连接层的输出节点数 # 'linear_two': 120, 'dropout': 0.5, # 随机丢失节点占比 'vocab_size': 283750, 'vector_size': 100 # 每个词的词向量的长度, word = [.....] # 'embedding_weight': embedding_weight } # 模型保存路径 save_path = { 'model': module_path + '/model_save/model.pth', 'epoch': module_path + '/model_save/epoch.pth' } # in_channels 就是词向量的维度, out_channels则是卷积核(每个kernel_size都一样多)的数量 # 对于一种尺寸的卷积核 kernel_size = 3,in_channels=100,out_channels=50时, # 设 x = [32][100]即一个新闻数据, 进行卷积操作前,先对x维度进行变换->[100][32],即每一列是一个词向量,conv1d卷积层左右扫描即可 # x经过卷积操作后会得到[50][30], 分别对应50个卷积核分别对x运算得到的一维数据的结果,即[out_channels][in_channels-kernel_size + 1], # 然后进行 relu运算,形状不变 # 紧接着进行最大池化操作,每个卷积核运算结果中选出一个最大值,即[30]中选出一个, -> max = [50][1] # 接着将max转为一维数据 ->[50], 即[out_channels] # 由于有len(kernel_size)种尺寸的卷积核,所以经过卷积层,池化层有 len(kernel_size) * output_channels 个输出 class NewsModel(nn.Module): def __init__(self, config): super(NewsModel, self).__init__() self.kernel_size = config.get('kernel_size') self.output_channels = config.get('output_channels') self.class_num = config.get('class_num') self.liner_one = config.get('linear_one') # self.liner_two = config.get('linear_two') self.dropout = config.get('dropout') self.vocab_size = config.get('vocab_size') self.vector_size = config.get('vector_size') # 也可以这么写,不用调用 init_embedding方法,利用已有的word2vec预训练模型中初始化 # self.embedding = nn.Embedding.from_pretrained(torch.tensor(config.get('embedding_weight')), freeze=False) self.embedding = nn.Embedding(num_embeddings=self.vocab_size, embedding_dim=self.vector_size, padding_idx=0) # 这里是不同kernel_size的conv1d self.convs = [nn.Conv1d(in_channels=self.embedding.embedding_dim, out_channels=self.output_channels, kernel_size=size, stride=1, padding=0).to(device) for size in self.kernel_size] self.fc1 = nn.Linear(len(self.kernel_size) * self.output_channels, self.liner_one) # self.fc2 = nn.Linear(self.liner_one, self.liner_two) self.fc2 = nn.Linear(self.liner_one, self.class_num) self.dropout = nn.Dropout(self.dropout) # embedding_matrix就是word2vec的get_vector_weight def init_embedding(self, embedding_matrix): self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix).to(device)) # x = torch.tensor([[word1_index, word2_index,..],[],[]]) # forward这个函数定义了前向传播的运算 def forward(self, x): x = self.embedding(x) # 词索引经过词嵌入层转化为词向量, [word_index1,word_index2]->[[vector1][vector2]], x = x.permute(0, 2, 1) # 将(news_num, words_num, vector_size)换为(news_num,vector_size,word_num),方便卷积层运算 # 将所有经过卷积、池化的结果拼接在一起 x = torch.cat([self.conv_and_pool(x, conv) for conv in self.convs], 1) # 展开,[news_num][..] x = x.view(-1, len(self.kernel_size) * self.output_channels) x = self.dropout(x) x = F.relu(self.fc1(x)) return self.fc2(x) @staticmethod def conv_and_pool(x, conv): x = F.relu(conv(x)) x = F.max_pool1d(x, x.size(2)) # 最大池化 x = x.squeeze(2) # 只保存2维 return x <file_sep>import torch from torch import nn from data_loader import get_lw_of_train_sample, MAX_TRAIN_INDEX from model import device, NewsModel, Config, get_trained_net, get_epoch, save_net_epoch from word_vector_tool import get_vector_model, get_vector_weight # flag : True 从已有模型继续训练, False: 新建模型开始训练 # epoch_size : 训练多少轮 def train(flag, epoch_size): if flag: net = get_trained_net() epoch = get_epoch() else: net = NewsModel(Config).to(device) net.init_embedding(get_vector_weight(get_vector_model())) epoch = 0 # 我之前用的一直是 Adam,后面改成了 SGD, lr是学习率,可以理解成每一步优化的幅度,一开始可以较大,后面要逐渐变小 #optimizer = torch.optim.SGD(net.parameters(), lr=1e-4, momentum=0.9) optimizer = torch.optim.Adam(net.parameters(), lr=0.01) # CrossEntropyLoss 交叉熵损失,F.cross_entropy()也是,但前者会先进行softmax运算,后者不会, # 所以在我定义的模型最后没有显式使用return F.SoftMax(x),而是直接返回全连接的结果 # 如果在模型部分使用了softmax,那么此时应换成nn.NLLLoss() criterion = nn.CrossEntropyLoss().to(device) net.train() #训练也就是调参的过程,在卷积层,全连接层都有许多参数,训练的过程就是调整这些参数使得结果与真实值的差距逐渐缩小 print("Start Training...") for epoch_index in range(epoch, epoch + epoch_size): epoch += 1 for sample_index in range(0, MAX_TRAIN_INDEX + 1): labels, sentences = get_lw_of_train_sample(sample_index) # [32],[32][32] labels, sentences = torch.tensor(labels).to(device), torch.tensor(sentences).to(device) outputs = net(sentences) optimizer.zero_grad() loss = criterion(outputs, labels) loss.backward() optimizer.step() loss_value = loss.item() print('[epoch %d] [sample %d] loss: %.3f' % (epoch, sample_index + 1, loss_value)) save_net_epoch(net, epoch) print('Stop Training...') if __name__ == '__main__': train(True,2) <file_sep>import os import jieba import jieba.analyse # 如果直接写 /data/word_vector/cn_stopwords.txt # 假设不同目录下的py脚本调用该文件下的方法,就会导致文件路径出错,因为实际上import是将代码嵌入到了调用者部分,此时的./data...不存在 module_path = os.path.dirname(__file__) # 停用词 stop_words = module_path + '/data/word_vector/cn_stopwords.txt' stopwords = {}.fromkeys([line.rstrip() for line in open(stop_words, encoding='utf-8')]) # 提取关键词时允许的词性,具体: https://blog.csdn.net/hyfound/article/details/82700313 pos = ('n', 'nz', 'v', 'ns', 'vn', 'i', 'a', 'nt', 'b', 'vd', 't', 'ad', 'an', 'c', 'nr') jieba.analyse.set_stop_words(stop_words) # '字符串'->['词1',...] def jieba_split(sentence): cut = jieba.cut(sentence) return list(cut) # 将上面的['词1','词2'..] 去除其中的停用词返回 def remove_stop_words(words): result = [] for word in words: if word not in stopwords: result.append(word) return result # 上面的操作中去除停用词后,抽取其中num个关键词返回 def get_key_words(words, num): sentence = '' for word in words: sentence = sentence + ' ' + word key_words = jieba.analyse.extract_tags(sentence, topK=num, withWeight=False, allowPOS=pos) return list(key_words) # ('很长的一句话',20) # return ['key1','key2'...] def get_key_words_all_step(sentence, num): return get_key_words(remove_stop_words(jieba_split(sentence)), num) <file_sep>import multiprocessing import os import numpy from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence module_path = os.path.dirname(__file__) # 词向量模型 model_path = module_path + '/data/word_vector/words_vector.model' # 得到的词向量是ndArray类型的,不是list, .tolist() # vector_path = './data/all_words.txt' # 获取word2vec词向量模型 def get_vector_model(): return Word2Vec.load(model_path) # # 实际上 model_save.wv 也是一样的,而且更快 # def get_vector(): # return gensim.models.KeyedVectors.load_word2vec_format(vector_path, binary=False) # 先获取 model = get_vector_model(), 然后 sentences = words_to_sentences(['word1','word2'..])) # 或者 sentences = file_to_sentences(file_path) # 往已有模型中添加词汇 def add_sentences(model, sentences): model.build_vocab(sentences, update=True) model.train(sentences, total_words=model.corpus_count, epochs=model.epochs) model_save(model) return model # 没有模型,新建一个词向量模型 def build_model(sentences): model = Word2Vec(sentences=sentences, window=1, min_count=1, workers=multiprocessing.cpu_count(), sg=1) model_save(model) return model # ./data/all_words.txt def file_to_sentences(file): return LineSentence(file) # ['word1','word2'...] def words_to_sentences(words): return [words] # 获取词汇的词向量, 返回类型是 ndArray, 可以.tolist()转化为list def get_vector_of_text(model, text): if has_text(model, text): return model.wv.get_vector(text) return get_empty_vector() # 保存模型 def model_save(model): model.save(model_path) # 下面这个保存太占空间了 # model_save.wv.save_word2vec_format(vector_path, binary=True) # 空向量 def get_empty_vector(): v = numpy.zeros(100, dtype=float, order='C') return v # 词text在模型词库中的索引值 def get_index(model, text): if has_text(model, text): return model.wv.get_index(text) return 0 # 根据索引查找词 def get_text_of_index(model, index): # index_to_key 是list,key_to_index是dict return model.wv.index_to_key[index] # 给embedding层用,返回的是Word2Vec的权重参数 def get_vector_weight(model): return model.wv.vectors # 是否有这个词 def has_text(model, text): return model.wv.has_index_for(text) <file_sep>import torch from data_loader import MAX_TRAIN_INDEX, get_lw_of_train_sample, MAX_TEST_INDEX, get_lw_of_test_sample, categories from model import get_trained_net # sample_flag, True 用测试数据测试,False:用训练数据测试 def test(sample_flag): net = get_trained_net() total_acc = 0.0 first_sample = 0 if sample_flag: last_sample = MAX_TEST_INDEX + 1 else: last_sample = MAX_TRAIN_INDEX + 1 wrong_label = [0 for i in range(len(categories))] for sample_index in range(first_sample, last_sample): # 每个epoch有10个batch each_sample_acc_count = 0 if sample_flag: labels, words = get_lw_of_test_sample(sample_index) else: labels, words = get_lw_of_train_sample(sample_index) labels, words = torch.tensor(labels).cuda(), torch.tensor(words).cuda() _, pre = torch.max(net(words).data, 1) for pre_index in range(labels.size(0)): if pre[pre_index] == labels[pre_index]: each_sample_acc_count += 1 else: wrong_label[labels[pre_index].item()] += 1 each_sample_acc = each_sample_acc_count / len(labels) * 100 print('[ sample %d acc = %.3f ]' % (sample_index, each_sample_acc)) total_acc += each_sample_acc print('[ total_acc = %.3f ]' % (total_acc / (last_sample - first_sample))) dict = {} for i in range(len(wrong_label)): dict[categories[i]] = wrong_label[i] print(dict) if __name__ == '__main__': test(True) <file_sep>import os import torch # 本文件主要是给训练、测试过程提供便捷的取样本操作 categories = ['财经', '房产', '教育', '科技', '军事', '汽车', '体育', '游戏', '娱乐'] # 类别名对应的id labels = {'财经': 0, '房产': 1, '教育': 2, '科技': 3, '军事': 4, '汽车': 5, '体育': 6, '游戏': 7, '娱乐': 8} #这两个改成sample数量-1 MAX_TRAIN_INDEX = 136 MAX_TEST_INDEX = 70 # index 0~235 # labels = [..] n个标签, words = [[]..] n个[],[]内50个词索引 module_path = os.path.dirname(__file__) # 在./data/XXXsamples文件夹下,一个sample= [(),()....] 约100个() # 一个 () = (类别id,[word1_index, word2_index...]), [word1_index..]为新闻分词后,每个词在word2vec模型中对应的索引值 # 类别id见labels中定义的变量 # trainSamples 是训练数据 # testSamples 测试,从未训练过 # 100个新闻样本, tuple(list,list) # 第一个list 是100个样本对应的类别id, 后面的list则保存了每条新闻分词后每个词的索引,即[[新闻1的词索引..][新闻2..]] # return ([label_1,label_2,..,label_100], [[news_1_word_1_index,..,news_1_word_50_index]...[news_100_word_1_index,..] ) def get_lw_of_train_sample(index): file = module_path + '/data/trainSamples/sample-' + str(index) + '.pth' return get_lw_sample(file) def get_lw_of_test_sample(index): file = module_path + '/data/testSamples/sample-' + str(index) + '.pth' return get_lw_sample(file) def get_lw_sample(file): sample = torch.load(file) labels = [l for l, w in sample] # 提取label和words words = [w for l, w in sample] return labels, words if __name__ == '__main__': # 可以看看具体的数据 for i in range(0, MAX_TEST_INDEX + 1): l, w = get_lw_of_test_sample(i) print(l)
6330ecd271fd3a462c0a6909ae818b65bc3cda48
[ "Markdown", "Python" ]
9
Markdown
zzq142/News_Classification-master
d9039fc8c205991783e16acac3e7e3017e2da9c3
54efbdeda9d9ab0b2a9eb2fca5367027ee2744ad
refs/heads/master
<repo_name>kylehotchkiss/waypoints<file_sep>/readme.md ## Waypoints Game (for Arduino) A GPS-based Driving game built on Arduino [Check out the Project Page for project details and for the gameplay details!](http://kylehotchkiss.com/blog/waypoints/)<file_sep>/waypoints.ino /** * * Waypoints Game (for Arduino) * Copyright 2013 <NAME> (for Hotchkissmade) * Released under the GPL * * Reads GPS, outputs distance to waypoint to LCD. * Neat for Treasure Hunts * */ #define _USE_MATH_DEFINES #include <SoftwareSerial.h> //////////////////////////////////// // What Matters to you - Settings // //////////////////////////////////// // Where to? const double waypoint_lat = 37.7070794; const double waypoint_lon = -79.2889216; // Assumed average speed in MPH (Randomization indexer) const int avgSpeed = 30; /////////////////// // LCD Constants // /////////////////// const int lcd_pin = 3; // ASCII control codes const int lcd_clear = 12; const int lcd_lightOn = 17; const int lcd_lightOff = 18; const int lcd_newline = 13; /////////////////// // GPS Constants // /////////////////// const char gps_endline = 13; const int gps_maxchars = 82; //////////////////// // Math Constants // //////////////////// const double RADIANS = M_PI / 180; SoftwareSerial lcd = SoftwareSerial(255, lcd_pin); /////////////////// // Init Routines // /////////////////// void setup() { Serial.begin(4800); ////////////////////////////////////////// // GPS Setup: Stop showing so much crap // ////////////////////////////////////////// /*Serial.write("$PSRF105,1*3E\r\n"); Serial.write("$PSRF103,01,00,00,01*25\r\n"); Serial.write("$PSRF103,02,00,00,01*26\r\n"); Serial.write("$PSRF103,03,00,00,01*27\r\n"); Serial.write("$PSRF103,04,00,00,01*20\r\n"); Serial.write("$PSRF103,05,00,00,01*21\r\n");*/ //////////////// // LCD Setup // //////////////// pinMode(lcd_pin, OUTPUT); digitalWrite(lcd_pin, HIGH); lcd.begin(9600); delay(100); lcd.write( lcd_clear ); delay(500); } void loop() { double latitude = 0; double longitude = 0; double altitude = 0; if ( Serial.available() > 0 ) { int count = 0; char NMEA[gps_maxchars] = ""; count = Serial.readBytesUntil('\r', NMEA, gps_maxchars); //////////////////////// // Valid GPGGA Packet // //////////////////////// if ( count == 77 ) { // Changes with Altitude FIX ME FOR GPGGA FIX ME FOR 300ft+ int gps_checksum = 0; int calc_checksum = 0; char gps_checksum_hex[3]; /////////////////////////////////////// // Calculate Checksum for Validation // /////////////////////////////////////// for ( int i = 2; i < gps_maxchars; i++ ) { if ( NMEA[i] != '*') { calc_checksum ^= byte( NMEA[i] ); } else { break; } } for ( int i = 0; i < 2; i++ ) { gps_checksum_hex[i] = NMEA[ i + 75 ]; } gps_checksum_hex[2] = '\0'; gps_checksum = strtol(gps_checksum_hex, NULL, 16); //////////////////////////////////// // Checksums Passed, Data is Safe // //////////////////////////////////// if ( calc_checksum == gps_checksum ) { // // Assignment // double latitude_dec, latitude_min, longitude_dec, longitude_min; char char_latitude_dec[3], char_latitude_min[8], char_longitude_dec[4], char_longitude_min[8], char_altitude[6]; String gps_latitude_dec, gps_latitude_min, gps_longitude_dec, gps_longitude_min, gps_altitude, ns_indicator, ew_indicator; String NMEA_string = NMEA; // // Convert to Substrings // gps_latitude_dec = NMEA_string.substring(19, 21); gps_latitude_min = NMEA_string.substring(21, 28); gps_longitude_dec = NMEA_string.substring(31, 34); gps_longitude_min = NMEA_string.substring(34, 41); gps_altitude = NMEA_string.substring(53, 59); ns_indicator = NMEA_string.substring(29, 30); ew_indicator = NMEA_string.substring(42, 43); // // Back to Char Arrays // gps_latitude_dec.toCharArray(char_latitude_dec, 3); gps_latitude_min.toCharArray(char_latitude_min, 8); gps_longitude_dec.toCharArray(char_longitude_dec, 4); gps_longitude_min.toCharArray(char_longitude_min, 8); gps_altitude.toCharArray(char_altitude, 6); // // Properly null-terminate strings // char_latitude_dec[2] = '\0'; char_latitude_min[7] = '\0'; char_longitude_dec[3] = '\0'; char_longitude_min[7] = '\0'; char_altitude[5] = '\0'; // // Char arrays to Double // latitude_dec = atof( char_latitude_dec ); latitude_min = atof( char_latitude_min ); longitude_dec = atof( char_longitude_dec ); longitude_min = atof( char_longitude_min ); altitude = atof( char_altitude ); // // Convert Lat/Lon to Decimal Degrees // latitude = latitude_dec + ( latitude_min / 60 ); longitude = longitude_dec + ( longitude_min / 60 ); // // Negative assignment, where needed // if ( ns_indicator == "S" ) { latitude = latitude * -1; } if ( ew_indicator = "W" ) { longitude = longitude * -1; } } } } /////////////////////////////////////////// // GPS-Lock Confirmed | Engagement Layer // /////////////////////////////////////////// if ( latitude != 0 && longitude != 0 ) { lcd.write(212); lcd.write(220); delay(5); lcd.write( lcd_lightOn ); delay(5); lcd.write( lcd_clear ); delay(5); lcd.print("Distance:\r"); lcd.print( distance( latitude, longitude, waypoint_lat, waypoint_lon ), 4); lcd.print( "km" ); delay( 5000 ); lcd.write( lcd_clear ); delay(5); lcd.write( lcd_lightOff ); delay( 20000 ); } } ///////////////////////////////////////////// // Return Distance in Kilometers to Target // ///////////////////////////////////////////// double distance( double startLat, double startLon, double endLat, double endLon ) { double distanceLat = ( endLat - startLat ) * RADIANS; double distanceLon = ( endLon - startLon ) * RADIANS; double lat1 = startLat * RADIANS; double lat2 = endLat * RADIANS; double step1 = sin( distanceLat / 2 ) * sin( distanceLat / 2 ) + sin( distanceLon / 2 ) * sin( distanceLon / 2 ) * cos( lat1 ) * cos( lat2 ); double step2 = 2 * atan2( sqrt( step1 ), sqrt( 1 - step1 )); return 6367 * step2; }
878cbcc44fba81cfa45c0b14ff3c0ff726a6433b
[ "Markdown", "C++" ]
2
Markdown
kylehotchkiss/waypoints
61916685b6f5b9f1c652a1cc315d980cbcfca6dc
e8ba3e92a4534ca20d0ce6bd1c91b757c074ca2e
refs/heads/master
<repo_name>daaawx/test_django_microservice<file_sep>/pizza/admin.py from django.contrib import admin from pizza.models import Pizza @admin.register(Pizza) class PizzaAdmin(admin.ModelAdmin): pass <file_sep>/README.md # Test Django Microservice A test project where we build a pizza microservice with Django. <file_sep>/pizza/migrations/0002_auto_20200809_1555.py # Generated by Django 3.1 on 2020-08-09 13:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('pizza', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pizzeria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('address', models.CharField(max_length=512)), ('phone', models.CharField(max_length=40)), ], ), migrations.AddField( model_name='pizza', name='kind', field=models.CharField(choices=[('M', 'Meat'), ('VG', 'Vegetarian'), ('V', 'Vegan')], default='Meat', max_length=10), preserve_default=False, ), migrations.CreateModel( name='Likes', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pizza', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pizza.pizza')), ], ), ] <file_sep>/pizza/models.py from django.db import models # from user.models import UserProfile class Pizzeria(models.Model): # owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) address = models.CharField(max_length=512) phone = models.CharField(max_length=40) class Pizza(models.Model): CHOICES = [ ('M', 'Meat'), ('VG', 'Vegetarian'), ('V', 'Vegan'), ] title = models.CharField(max_length=120) description = models.CharField(max_length=240) kind = models.CharField(max_length=10, choices=CHOICES) class Likes(models.Model): # user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) <file_sep>/pizza/urls.py from django.contrib import admin from django.urls import path from pizza import views urlpatterns = [ path('<int:pid>', views.index, name='pizza'), path('random', views.random_pizza, name='random_pizza'), ] <file_sep>/pizza/views.py import random from django.http import HttpResponse, JsonResponse from django.shortcuts import render, get_object_or_404 from pizza.models import Pizza def index(request, pid): pizza = get_object_or_404(Pizza, id=pid) return JsonResponse({ 'id': pizza.id, 'title': pizza.title, 'description': pizza.description, }) def random_pizza(request): c = Pizza.objects.count() pizza = Pizza.objects.all()[random.randint(0, c - 1)] return JsonResponse({ 'id': pizza.id, 'title': pizza.title, 'description': pizza.description, })
504ccda3b0eaf78beb6ce8e098c34107982537f0
[ "Markdown", "Python" ]
6
Python
daaawx/test_django_microservice
a35b6b724c50aa59e8d3387a5bc86084bef74833
8ce85cb55845546d28ab371408cd2e23ddc17aca