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>yadavky/handlebar_JS<file_sep>/server.js 'use strict'; var http = require('http'); var port = process.env.PORT || 1337; //http.createServer(function (req, res) { // res.writeHead(200, { 'Content-Type': 'text/plain' }); // res.end('Hello World\n'); //}).listen(port); var express = require("express"); var app = express(); app.use("/static",express.static(__dirname + "/static")); app.get("/", function (req, res) { res.sendfile("index.html"); }); //app.get("/views", function (req, res) { // res.sendfile("views/index.html"); //}); //app.post("/views", function (req, res) { // res.send('success'); //}); app.listen(port, function () { console.log("Testing!!!"); });
68ce6b2f2344523dc6d48670322289ec00110eea
[ "JavaScript" ]
1
JavaScript
yadavky/handlebar_JS
edde5fb3617874ed227b29297c55d757ac30b9bd
c9155476b854055c9ae869059498e0b512047703
refs/heads/master
<repo_name>singhsamyak/jest-dabble<file_sep>/src/components/Counter.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Counter extends Component { render() { const { value, increment, decrement, reset } = this.props; return( <div> <p>Count: <span>{ value }</span> times</p> <button id='increment' onClick={ increment }>+</button> <button id='decrement' onClick={ decrement }>-</button> <button id='reset' onClick={ reset }>Reset</button> </div> ); } } Counter.PropTypes = { value: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired, reset: PropTypes.func.isRequired } export default Counter; <file_sep>/test/components/Counter.test.js import React from 'react'; import Counter from '../../src/components/Counter'; import renderer from 'react-test-renderer'; import { shallow } from 'enzyme'; /** * Mock Functions * --------------- * - Erases the actual implementation of a function * - Captures calls to the function * - Captures instances of constructor functions when instantiated with `new` * - Allows test-time configuration of return values */ describe('Snapshot Testing using Jest only', () => { it ('renders correctly', () => { const value = 0; const actions = { increment: jest.fn(), // jest.fn is a mock function decrement: jest.fn(), reset : jest.fn() } const tree = renderer.create( <Counter value={value} {...actions} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); function setup(value = 0) { const actions = { increment: jest.fn(), // jest.fn is a mock function decrement: jest.fn(), reset : jest.fn() } const counter = shallow( <Counter value={value} {...actions} /> ); return { counter : counter, actions : actions, incrBtn : counter.find('#increment'), decrBtn : counter.find('#decrement'), resetBtn : counter.find('#reset'), countVal : counter.find('span') }; } /** * Enzyme's Shallow Rendering * -------------------------- * - Helpful to test a component as a unit. * - Ensures test aren't asserting based on behavior of child components * - http://airbnb.io/enzyme/docs/api/shallow.html */ describe('DOM Testing using Enzyme', () => { it ('should initially have a count value of 0', () => { const { countVal } = setup(); expect(countVal.text()).toEqual('0'); }); it ('clicking + should invoke the increment callback', () => { const { actions, incrBtn } = setup(); incrBtn.simulate('click'); expect(actions.increment).toBeCalled(); expect(actions.decrement).not.toBeCalled(); }); it ('clicking - should invoke the decrement callback', () => { const { actions, decrBtn } = setup(); decrBtn.simulate('click'); expect(actions.decrement).toBeCalled(); expect(actions.increment).not.toBeCalled(); }); it ('clicking Reset should invoke the reset callback', () => { const { actions, resetBtn } = setup(); resetBtn.simulate('click'); expect(actions.reset).toBeCalled(); expect(actions.decrement).not.toBeCalled(); expect(actions.increment).not.toBeCalled(); }); }); <file_sep>/test/reducers/Counter.test.js import counterReducer from '../../src/reducers/Counter'; describe('Counter reducer tests', () => { it ('should provide an initial value of 0', () => { expect(counterReducer(undefined, {})).toBe(0); }); it ('should increment state value on INCREMENT', () => { const action = { type: 'INCREMENT' }; expect(counterReducer(undefined, action)).toBe(1); expect(counterReducer(1, action)).toBe(2); expect(counterReducer(2, action)).toBe(3); }); it ('should decrement state value on DECREMENT', () => { const action = { type: 'DECREMENT' }; expect(counterReducer(undefined, action)).toBe(-1); expect(counterReducer(1, action)).toBe(0); expect(counterReducer(2, action)).toBe(1); }); it ('should reset state value to 0 on RESET', () => { const action = { type: 'RESET' }; expect(counterReducer(undefined, action)).toBe(0); expect(counterReducer(1, action)).toBe(0); expect(counterReducer(2, action)).toBe(0); expect(counterReducer(-2, action)).toBe(0); }); }); <file_sep>/README.md # JestDabble Exploring Jest to test a sample React/Redux app. #### Installation ```sh $ cd jestDabble $ npm install ``` To run Jest tests ```sh $ npm test ```
e36b4ef3e7b134030bdc7791ad94f02cf1669acb
[ "JavaScript", "Markdown" ]
4
JavaScript
singhsamyak/jest-dabble
85122c544c44646160b70a700a5fa7d0fe51c665
b7947b9e475370f954b6cb3935d622cb33943e0f
refs/heads/master
<file_sep>// Sum of a Beach /* Beaches are filled with sand, water, fish, and sun. Create a function named sumOfABeach that takes a parameter (type: string). Given a string, calculate how many times the words "Sand", "Water", "Fish", and "Sun" appear without overlapping (regardless of the case). The input can be an empty string. Examples: console.log(sumOfABeach("WAtErSlIde")) // ==> 1 console.log(sumOfABeach("GolDeNSanDyWateRyBeaChSuNN")) // ==> 3 console.log(sumOfABeach("gOfIshsunesunFiSh")) // ==> 4 console.log(sumOfABeach("cItYTowNcARShoW")) // ==> 0 console.log(sumOfABeach("")) // ==> 0 */<file_sep>//! IMPORTANT: //! Create a repositary named coding-challenge1, then clone it in your //! Documents folder. Create 3 folders inside the newly created folder, //! Name them easy, medium and hard. //! Create ONE .js file PER coding challenge inside the relevant folder, named after the challenge. //! Copy the challlenge prompt and start your code after. //=============================================== /* Draw a diamond Create a function, named diamond, which takes an integer as a parameter and returns a diamond made of asterixes. The input integer will always be superior to 0. console.log(diamond(1)) // returns "* *" console.log(diamond(3)) // returns " * *** ***** *** *" console.log(diamond(5)) // returns " * *** ***** ******* ********* ******* ***** *** *" Note: Adding "\n" to a string creates a new line. */ <file_sep>/* FizzBuzz Create a function fizzBuzz which takes an positive integer as a parameter and returns an array of each integer from 1 up to this parameter included. Each number divisible by 3 will be replaced by "Fizz", each number divisible by 5 will be replaced by "Buzz", and each number divisible by 3 and 5 will be replaced by "FizzBuzz". The input will always be > 0. Examples: console.log(fizzBuzz(15)) // returns [1, 2, "Fizz", 4, "Buzz", "Fizz",7,8,"Fizz","Buzz", 11, "Fizz", 13, 14, "FizzBuzz"] */ function fizzBuzz(integer){ const }<file_sep>/* H4ck3r Sp34k Create a function that takes a string as an argument and returns a coded (h4ck3r 5p34k) version of the string. All input will be in lower case. Examples console.log(hackerSpeak("javascript is cool")) //➞ "j4v45cr1pt 15 c00l" console.log(hackerSpeak("programming is fun")) //➞ "pr0gr4mm1ng 15 fun" console.log(hackerSpeak("become a coder")) //➞ "b3c0m3 4 c0d3r" console.log(hackerSpeak("br")) //➞ "br" console.log(hackerSpeak("")) //➞ "" Notes In order to work properly, the function should replace all 'a's with 4, 'e's with 3, 'i's with 1, 'o's with 0, and 's's with 5. */ function hackerSpeak(str){ const speak = [ A, a = 4; E, e = 3; I, i = 1; O, o = 0; S, s = 5; ] if (str.length[i] = speak) }<file_sep>/* Area of a triangle Write a function named triArea that takes the base and height of a triangle and return its area. Examples console.log(triArea(3, 2)) //➞ 3 console.log(triArea(7, 4)) //➞ 14 console.log(triArea(10, 10)) //➞ 50 */ function triArea(x, y){ const area = (x * y)/2; console.log("Area: " + area); } triArea(0, 4);<file_sep>// Opposite Number /* Very simple. Write a function, named opposite, that given one parameter (type: integer) returns the opposite of the given number. A positive number becomes negative. A negative number becomes positive. The output is also an integer. Examples: console.log(opposite(1)) // output: -1 console.log(opposite(14)) // output: -14 console.log(opposite(-24)) // output: 24 console.log(opposite(0)) // ouput: 0 */ function opposite(integer){ const newInt = integer * -1; if (integer === 0){ console.log(0) } else { console.log(newInt); } } opposite(0);<file_sep>/* Draw a triangle Create a function, named triangle, which takes an integer as a parameter and returns a triangle made of asterixes. The input integer will always be superior to 0. console.log(triangle(1)) // returns "*" console.log(triangle(3)) // returns "* ** ***" console.log(triangle(5)) // returns "* ** *** **** *****" Note: Adding "\n" to a string creates a new line. */ function triangle(integer){ const flow = integer }<file_sep>const authorElement = document.getElementById("author"); const titleElement = document.getElementById("title"); const bodyTextElement = document.getElementById("bodyText"); const button = document.getElementById("submitButton"); button.addEventListener("click",updateDB); //Set database object here const database = firebase.database().ref(); /** * Updates the database with the username and message. */ function updateDB(event){ event.preventDefault(); const author = authorElement.value; const bodyText = blogElement.value; const title = titleElement.value; authorElement.value = ""; blogElement.value = ""; console.log(author + " : " + title); //Update database here const value={ NAME: author, TITLE: title, BLOG: blog }; database.push(value) } // Set database "child_added" event listener here database.on("child_added", addMessageBoard) const messageContainer=document.querySelector(".allMessages"); // document.querySelector("submitButton").addEventListener("click", updateDB); function addMessageBoard(rowData){ const row = rowData.val(); const name = row.NAME; const message = row.MESSAGE; const pElement = document.createElement("p") pElement.innerText = `${name}: ${message}` messageContainer.appendChild(pElement); }<file_sep>/* Draw a pyramid Create a function, named pyramid, which takes an integer as a parameter and returns a pyramid made of asterixes. The input integer will always be superior to 0. console.log(pyramid(1)) // returns "*" console.log(pyramid(3)) // returns " * *** *****" console.log(pyramid(5)) // returns " * *** ***** ******* *********" Note: Adding "\n" to a string creates a new line. It is easier to start with "-" then replace by " " while creating the function. */<file_sep>// Unlucky Days /* Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year. Find the number of Friday 13th in the given year. Create a function named unluckyDays with one parameter, years (type: integer). Have the function return: The Number of Black Fridays in the year as an integer. Examples: console.log(unluckyDays(2015)) //returns 3 console.log(unluckyDays(1986)) //returns 1 Note: JS week starts on Sunday. Check out how JS handles dates! */
d4c6c3bfe396d83392261e050cfd64426a686206
[ "JavaScript" ]
10
JavaScript
michaelnASC6/Week4
2ba6ed6e9d4aa138678838a12f59298daf9aee56
d1d81b4a310306383d65f1f15caebb8a88873680
refs/heads/master
<repo_name>jongwooo/the-road-to-learn-react-likelion<file_sep>/markdown/components-props.md Components 와 Props === Components? --- 개념적으로 <strong>컴포넌트</strong>는 JavaScript 함수와 유사합니다. <strong>props</strong> 라고 하는 임의의 입력을 받은 후, 화면에 어떻게 표시되는지를 기술하는 리액트 엘리먼트를 반환합니다. 함수 컴포넌트와 클래스 컴포넌트 --- 컴포넌트를 정의하는 가장 간단한 방법은 JavaScript 함수로 나타내는 것입니다. ~~~jsx const Welcome = props => { return <h1>Hello, {props.name}</h1>; } ~~~ 이 함수는 데이터를 가진 하나의 "props" 객체 인자를 받은 후 리액트 엘리먼트를 반환하므로 유효한 리액트 컴포넌트입니다. 이러한 함수 구조를 가진 컴포넌트를 말 그대로 <strong>함수 컴포넌트</strong>라고 호칭합니다. 컴포넌트는 ES6 문법의 `class`를 사용하여 정의할 수도 있습니다. 이러한 클래스형 구조를 가진 컴포넌트를 <strong>클래스 컴포넌트</strong>라고 호칭합니다. ~~~jsx class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } } ~~~ 리액트의 관점에서 볼 때 위의 두 가지 유형의 컴포넌트는 동일합니다. 컴포넌트 렌더링 --- 이전 교안에서 살펴보았던 예제를 살펴봅시다. ~~~jsx ReactDOM.render(<App />, document.getElementById('root')); ~~~ 위의 `<App />`은 사용자 정의 컴포넌트입니다. [App.js](../src/App.js) 의 반환값을 렌더링하라는 것이겠지요? 아래의 예제는 페이지에 "Hello, Lion"을 렌더링 할 수 있습니다. ~~~jsx // Welcome.js const Welcome = props => { return <h1>Hello, {props.name}</h1>; } // index.js const element = <Welcome name="Lion" />; ReactDOM.render(element, document.getElementById('root')); ~~~ 이 예시에서는 다음과 같은 일들이 일어납니다. 1. `<Welcome name="Lion" />` 엘리먼트로 `ReactDOM.render()`를 호출합니다. 2. React는 `{name: 'Lion'}` 를 props로 하여 `Welcome` 컴포넌트를 호출합니다. 3. `Welcome` 컴포넌트는 결과적으로 `<h1>Hello, Lion</h1>` 엘리먼트를 반환합니다. 4. 리액트 DOM은 `<h1>Hello, Lion</h1>` 엘리먼트와 일치하도록 DOM을 효율적으로 업데이트합니다. #### 주의: 컴포넌트의 이름은 항상 대문자로 시작합니다. React는 소문자로 시작하는 컴포넌트를 DOM 태그로 처리합니다. 예를 들어 `<div />`는 HTML div 태그를 나타내지만, `<Welcome />`은 컴포넌트를 나타내며 범위 안에 Welcome이 있어야 합니다. 컴포넌트 합성과 추출 --- 컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있습니다. 이는 모든 세부 단계에서 동일한 추상 컴포넌트를 사용할 수 있음을 의미합니다. 리액트 앱에서는 버튼, 폼, 다이얼로그, 화면 등의 모든 것들이 흔히 컴포넌트로 표현됩니다. 예를 들어 Welcome을 여러 번 렌더링하는 App 컴포넌트를 만들 수 있습니다. ~~~jsx // Welcome.js const Welcome = props => { return <h1>Hello, {props.name}</h1>; } // App,js const App = () => { return ( <div className="App"> <Welcome name="Sara" /> <Welcome name="Cahal" /> <Welcome name="Edite" /> </div> ); } // index.js ReactDOM.render(<App />, document.getElementById('root')); ~~~ 반대로, 컴포넌트를 여러 개의 작은 컴포넌트로 나눌 수도 있습니다. ~~~jsx const Comment = props => { return ( <div className="Comment"> <div className="UserInfo"> <img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} /> <div className="UserInfo-name">{props.author.name}</div> </div> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{props.date}</div> </div> ); }; ~~~ 위의 코드에서 className이 "Avatar"인 부분을 아래와 같이 추출하면 더욱 간결하게 코드를 작성할 수 있습니다. ~~~jsx // Avatar.js const Avatar = props => { return ( <img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} /> ); } // Comment.js const Comment = props => { return ( <div className="Comment"> <div className="UserInfo"> <Avatar user={props.author} /> <div className="UserInfo-name"> {props.author.name} </div> </div> <div className="Comment-text"> {props.text} </div> <div className="Comment-date"> {props.date} </div> </div> ); } ~~~ Avatar는 자신이 Comment 내에서 렌더링 된다는 것을 알 필요가 없습니다. 따라서 props의 이름을 author에서 더욱 일반화된 user로 변경하였습니다. props의 이름은 사용될 context가 아닌 컴포넌트 자체의 관점에서 짓는 것을 권장합니다. props는 읽기 전용 --- 함수 컴포넌트나 클래스 컴포넌트 모두 컴포넌트의 자체 props를 수정해서는 안 됩니다. 입력된 값을 바꾸려 하지 않고 항상 동일한 입력값에 대해 동일한 결과를 반환하는 함수를 <strong>순수함수</strong>라고 하는데, 모든 리액트 컴포넌트틑 자신의 props를 다룰 때 반드시 순수함수처럼 동작해야 합니다. ~~~javascript // 순수함수 const sum = (a, b) => { return a + b; } // 순수함수가 아님 const e = 20; const add = (c, d) => { return c + d + e; } ~~~ 물론 애플리케이션 UI는 동적이며 시간에 따라 변합니다. 다음 교안에서는 <strong>state</strong>라는 새로운 개념을 소개합니다. 리액트 컴포넌트는 state를 통해 위 규칙을 위반하지 않고 사용자 액션, 네트워크 응답 및 다른 요소에 대한 응답으로 시간에 따라 자신의 출력값을 변경할 수 있습니다. 마무리 --- 이번 교안에서는 리액트의 컴포넌트와 props에 대해 알아보았습니다. 다음 교안에서는 리액트 컴포넌트 안의 <strong>state</strong>와 <strong>Lifecycle</strong>에 대해 알아보도록 하겠습니다. <file_sep>/markdown/helloworld.md Hello World === Hello React! --- `리액트 (React)` 란 무엇일까요? 리액트는 페이스북에서 개발한 JavaScript UI 라이브러리입니다. 리액트는 현재 가장 주목받고 있는 JavaScript 라이브러리 중 하나로, 많은 유명 기업에서 사용되고 있습니다. 리액트는 기존 JavaScript 개발에서 발생하던 문제를 크게 줄일 수 있어 차세대 개발 기술이라고 할 수 있습니다. 페이스북은 리액트를 오픈 소스로 출시 하여 활발하게 개발이 진행되게 하였고, 이에 따라 리액트는 나날히 발전해 나가고 있습니다. 또한 세계적으로도 무척 관심을 많이 받는 기술로 알아둘 가치가 있습니다. 이번 교안에서는 리액트의 특징과 개발환경에 대해 알아보고 실제로 간단한 예제를 통해 리액트를 접해보도록 하겠습니다. 리액트의 특징 --- [리액트 공식 홈페이지](https://ko.reactjs.org) 에서는 리액트의 특징을 다음과 같이 설명하고 있습니다. ### 선언형 > React는 상호작용이 많은 UI를 만들 때 생기는 어려움을 줄여줍니다. 애플리케이션의 각 상태에 대한 간단한 뷰만 설계하세요. 그럼 React는 데이터가 변경됨에 따라 적절한 컴포넌트만 효율적으로 갱신하고 렌더링합니다. > 선언형 뷰는 코드를 예측 가능하고 디버그하기 쉽게 만들어 줍니다. ### 컴포넌트 기반 > 스스로 상태를 관리하는 캡슐화된 컴포넌트를 만드세요. 그리고 이를 조합해 복잡한 UI를 만들어보세요. > 컴포넌트 로직은 템플릿이 아닌 JavaScript로 작성됩니다. 따라서 다양한 형식의 데이터를 앱 안에서 손쉽게 전달할 수 있고, DOM과는 별개로 상태를 관리할 수 있습니다. ### 한 번 배워서 어디서나 사용하기 > 기술 스택의 나머지 부분에는 관여하지 않기 때문에, 기존 코드를 다시 작성하지 않고도 React의 새로운 기능을 이용해 개발할 수 있습니다. > React는 Node 서버에서 렌더링을 할 수도 있고, React Native를 이용하면 모바일 앱도 만들 수 있습니다. 개발환경 준비 --- 리액트 개발에 필요한 개발환경은 아래와 같습니다. - `Node.js` - 서버에서 JavaScript를 실행할 수 있는 환경입니다. - Node 등의 언어를 위한 패키지 등록 도구인 `NPM` 을 지원하며, Node 설치 프로그램에서 NPM 클라이언트를 함께 제공하므로 쉽게 패키지를 설치할 수 있습니다. - [Node.js 공식 홈페이지](https://nodejs.org/en/)에서 좌측의 LTS 버전으로 설치해주세요. - `Yarn` (선택사항) - [Yarn 공식 홈페이지](https://yarnpkg.com/en/docs/install)에서 설치해주세요. - `VSCode` 등의 코드 에디터 - 코드 에디터는 [VS Code](https://code.visualstudio.com/) 등 자유롭게 선택하여 설치해주세요. - `Git Bash` - Windows 를 사용하는 분은 [Git for Windows 공식 홈페이지](https://gitforwindows.org)에서 기본 옵션으로 설치해주세요. Windows 가 아니라면 설치하지 않으셔도 됩니다. 위의 개발환경이 준비가 되었다면 `create-react-app`을 설치해 보도록 하겠습니다. create-react-app은 리액트 개발 환경 설정들을 보다 손쉽게 하기 위해서 페이스북에서 만든 패키지입니다. 우리는 이 패키지를 통해 리액트 개발을 진행해 볼 예정입니다. 설치는 전역 노드 패키지에 진행하도록 하겠습니다. ~~~bash npm install -g create-react-app ~~~ 프로젝트 생성 --- 리액트 프로젝트를 생성하기 위해서는 아래와 같이 명령어를 실행합니다. ~~~bash create-react-app [프로젝트명] ~~~ 이번 교안에서는 `the-road-to-learn-react-likelion` 이라는 프로젝트를 생성해보겠습니다. ~~~bash create-react-app the-road-to-learn-react-likelion ~~~ 프로젝트가 생성되었으면 해당 디렉토리 내부로 이동 후, `yarn start` (또는 `npm start`) 명령어를 실행해보세요. ~~~bash cd react-app yarn start ~~~ <p align="center"><img src="./assets/images/proj_start.png" alt="프로젝트 초기 실행 화면" width="50%"></p> 실행을 하게 되면 [http://localhost:3000](http://localhost:3000) 에 create-react-app 초기 화면이 나타나게 됩니다. 이제 리액트를 시작할 준비를 다 마쳤습니다. 리액트 구조 --- 리액트 프로젝트 디렉토리 내부를 살펴봅시다. 다음은 `create-react-app` 을 통해 생성한 프로젝트 디렉토리의 모습입니다. <p align="center"><img src="./assets/images/folder.png" alt="디렉토리 구조" width="30%"></p> 먼저, `node_modules` 폴더에는 프로젝트에 필요한 Node.js 의 모듈이 설치됩니다. 새로운 모듈을 설치하고 싶을 때는 아래의 명령어를 실행하면 됩니다. ~~~bash npm install [모듈 이름] ~~~ 다음으로, `public` 폴더의 [index.html](public/index.html) 에는 우리가 마주하는 리액트 프로젝트의 root 태그가 있습니다. 리액트는 기본적으로 SPA(Single Page Application)를 만족하는데, 각 페이지의 기본적인 틀이 바로 이 [index.html](public/index.html) 입니다. 코드를 자세히 살펴봅시다. ~~~html <div id="root"></div> ~~~ id 의 값이 <strong>root</strong> 인 div 태그는 리액트 DOM이 렌더링 되는 태그입니다. 렌더링 된 화면이 우리가 보는 리액트의 화면이 되는 것입니다. 다음으로, `src` 폴더를 살펴봅시다. 먼저 [index.js](src/index.js)는 앞서 살펴본 [index.html](public/index.html)에 리액트 DOM을 렌더링 시키는 코드입니다. ~~~jsx const element = <h1>Hello, world!</h1>; ReactDOM.render(element, document.getElementById('root')); ~~~ 위의 코드는 h2 태그를 id 의 값이 <strong>root</strong> 인 태그에 렌더링 하라는 것입니다. 여기서 JavaScript 코드에 HTML 태그를 써도 되나 라는 의문이 들 수도 있습니다. 이것은 바로 페이스북에서 개발한 `JSX` 라는 JavaScript 확장 문법입니다. JSX 문법에 따라, 여기서 h2 태그의 내용은 엘리먼트라고 불리는 리액트 앱의 가장 작은 단위가 됩니다. 위 코드를 실행하면 화면에 "Hello, world!"가 보일 겁니다. 리액트의 엘리먼트는 불변객체입니다. 엘리먼트를 생성한 이후에는 해당 엘리먼트의 자식이나 속성을 변경할 수 없습니다. 엘리먼트는 영화에서 하나의 프레임과 같이 특정 시점의 UI를 보여줍니다. 지금까지 소개한 내용을 바탕으로 하면 UI를 업데이트하는 유일한 방법은 새로운 엘리먼트를 생성하고 이를 `ReactDOM.render()`로 전달하는 것입니다. 아래의 코드를 살펴봅시다. ~~~jsx const tick = () => { const element = ( <div> <h1>Hello, world!</h1> <h2>It is {new Date().toLocaleTimeString()}.</h2> </div> ); ReactDOM.render(element, document.getElementById('root')); } setInterval(tick, 1000); ~~~ 위의 코드에서는 `setInterval()` 콜백을 이용해 초마다 `ReactDOM.render()`를 호출합니다. 리액트 DOM은 해당 엘리먼트와 그 자식 엘리먼트를 이전의 엘리먼트와 비교하고 DOM을 원하는 상태로 만드는데 필요한 경우에만 DOM을 업데이트합니다. <p align="center"><img src="./assets/images/tick.gif" alt="tick 예제 실행화면" width="20%"></p> 매초 전체 UI를 다시 그리도록 엘리먼트를 만들었지만 React DOM은 내용이 변경된 텍스트 노드만 업데이트했습니다. ~~~jsx ReactDOM.render(<App />, document.getElementById('root')); ~~~ 위의 코드는 `<App />` 이라는 태그를 렌더링하라는 것이겠지요? 하지만 우리가 아는 HTML 태그 중에는 없는 태그입니다. 또한 위에서 살펴본 앨리면트와는 다른 개념입니다. 이러한 것은 바로 <strong>컴포넌트</strong>라고 불리는 것 입니다. 컴포넌트에 대해서는 다음 교안에서 더 자세하게 다루어 보도록 하겠습니다. 마지막으로, 남은 파일들을 살펴봅시다. 먼저 `.gitignore`는 Github에 올리지 않을 파일이나 폴더의 목록을 적는 파일입니다. create-react-app을 통해 생성된 리액트 프로젝트는 자동으로 gitignore 항목이 작성됩니다. `package.json` 과 `yarn.lock`은 각각 설치된 NPM 패키지 목록과 Yarn 패키지 목록이 작성됩니다. 이 파일들은 패키지 설치시 자동으로 업데이트 됩니다. 마무리 --- 이번 교안에서는 리액트의 특징과 개발환경에 대해 알아보고 실제로 간단한 예제를 통해 리액트를 접해보았습니다. 다음 교안에서는 리액트의 핵심인 <strong>컴포넌트</strong> 와 <strong>props</strong> 에 대해서 알아보도록 하겠습니다. <file_sep>/README.md 리액트 길라잡이 with Likelion ========================= ![Version](https://img.shields.io/badge/Version-0.0.1-green.svg?style=flat-square) ![Build](https://img.shields.io/badge/Build-Passing-success.svg?style=flat-square) ![React](https://img.shields.io/badge/JavaScript-React-9cf.svg?style=flat-square) ![University](https://img.shields.io/badge/University-MJU(Seoul)-blue.svg?style=flat-square) ![License](https://img.shields.io/badge/License-MIT-informational.svg?style=flat-square) ### 1. INFO --- #### [명지대학교(서울) 멋쟁이사자처럼](https://github.com/likelionmju) 8기 신규 운영진 리액트 교육 레파지토리 ### 2. Contents --- - 첫 번째 교안 : `Hello World` [바로가기](https://github.com/Jongwoo-Han/the-road-to-learn-react-likelion/wiki/Hello-World) - 두 번째 교안 : `Components and Props` [바로가기](https://github.com/Jongwoo-Han/the-road-to-learn-react-likelion/wiki/Components-와-Props) <file_sep>/src/components/Comment.js import React from "react"; import Avatar from "./Avatar"; /* const Comment = props => { return ( <div className="Comment"> <div className="UserInfo"> <img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} /> <div className="UserInfo-name">{props.author.name}</div> </div> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{props.date}</div> </div> ); }; */ const Comment = props => { return ( <div className="Comment"> <div className="UserInfo"> <Avatar user={props.author} /> <div className="UserInfo-name">{props.author.name}</div> </div> <div className="Comment-text">{props.text}</div> <div className="Comment-date">{props.date}</div> </div> ); }; export default Comment;
e769b6a6d8dca6436ae52f06a01407bb6aeacf97
[ "Markdown", "JavaScript" ]
4
Markdown
jongwooo/the-road-to-learn-react-likelion
2fffa336c92bd1c33016062127a53df70c58bb50
c27aed3945cb8fc0dce52b13e1a5644b8f1de9fd
refs/heads/master
<repo_name>Sernel/Gamejam_2021_RBTV<file_sep>/Assets/Code/AI/Jump.cs using System.Collections; using System.Collections.Generic; using Newtonsoft.Json.Serialization; using UnityEngine; public class Jump : MonoBehaviour { bool jumping = false; public float thrust; private float maxJumpPoint; private bool doubleJumpLocked = false; void Start() { jumping = false; maxJumpPoint = this.gameObject.transform.position.y + 2; } void Update() { if (Input.GetKeyDown("space")) { HandleInput((true)); } else if(Input.GetKeyUp(("space"))) { HandleInput(false); } if (jumping) { float gravity = this.gameObject.GetComponent<Rigidbody2D>().mass; if (maxJumpPoint - this.gameObject.transform.position.y > 0) { this.gameObject.GetComponent<Rigidbody2D>().gravityScale = gravity * ((maxJumpPoint - this.gameObject.transform.position.y )/100); } else { jumping = false; doubleJumpLocked = true; } } else { this.gameObject.GetComponent<Rigidbody2D>().gravityScale = 1 + ((maxJumpPoint - this.gameObject.transform.position.y )/100); if (this.gameObject.transform.position.y < maxJumpPoint - 1.8) doubleJumpLocked = false; } } private void HandleInput(bool spaceState) { if (spaceState && !jumping && !doubleJumpLocked) { jumping = true; maxJumpPoint = this.gameObject.transform.position.y + 2; this.gameObject.GetComponent<Rigidbody2D>().AddForce(transform.up * thrust); doubleJumpLocked = true; } if (!spaceState && jumping) { jumping = false; } } }
956d379dde2bbd0db946a5c9b9947fa2b97002a6
[ "C#" ]
1
C#
Sernel/Gamejam_2021_RBTV
8817d11aa1fd08551f0bdee14d27b21415559982
51ad8e216bc1822d918f1f122d10942fe6e6fe87
refs/heads/master
<repo_name>KyleABrown/KyleABrown.github.io<file_sep>/index.js var Login = { divs: { landing: 'landingDIV', signin: 'signinDIV', register: 'registerDIV', }, buttons: { guest: 'guestButton', login: 'loginButton', loginBack: 'loginBackButton', register: 'registerButton', registerBack: 'registerBackButton', registerLoginRedirect: 'registerLoginRedirectButton', }, submits: { login: 'loginSubmit', register: 'registerSubmit', }, } $( document ).ready(function() { $(function () { $('[data-toggle="popover"]').popover({ container: 'body', title: 'Why should you register?', content: 'Registering gives you full access to the site, comments, forums, and much much more!', trigger: 'focus' }); }) }); $('#' + Login.buttons.login).click(function() { $('#' + Login.divs.landing).fadeOut(); setTimeout( function() { $('#' + Login.divs.signin).fadeIn();}, 500); }); $('#' + Login.buttons.loginBack).click(function() { $('#' + Login.divs.signin).fadeOut(); setTimeout( function() { $('#' + Login.divs.landing).fadeIn();}, 500); }); $('#' + Login.buttons.register).click(function() { $('#' + Login.divs.landing).fadeOut(); setTimeout( function() { $('#' + Login.divs.register).fadeIn();}, 500); }); $('#' + Login.buttons.registerBack).click(function() { $('#' + Login.divs.register).fadeOut(); setTimeout( function() { $('#' + Login.divs.landing).fadeIn();}, 500); }); $('#' + Login.buttons.registerLoginRedirect).click(function() { $('#' + Login.divs.register).fadeOut(); setTimeout( function() { $('#' + Login.divs.signin).fadeIn();}, 500); }); $('#' + Login.buttons.guest).click(function() { window.location = "HTML/Homepage.html?prop=guest" }); $('#' + Login.buttons.signin).click(function() { window.location = "HTML/Homepage.html?prop=signin" });<file_sep>/README.md # KyleABrown.github.io<file_sep>/HTML/Projects/BillsToPay/Scripts/CalendarHelper.js $(document).ready(function() { /************************************************ FUNCTIONS ********************************************************/ function initilizePackages() { /* Initilize Calendar */ $('#mycalendar').monthly({ mode: 'event', //jsonUrl: 'events.json', //dataType: 'json' xmlUrl: '../Data/events.xml' }); /* Initilize DateTime Picker */ $(".form_datetime").datetimepicker({ format: 'yyyy-mm-dd', autoclose: true, minView: 2, todayHighlight: true, }); /* Mask for amount inputs */ $("#addTransactionAmount").maskMoney({allowZero:true, prefix: '$'}); $("#addBillAmount").maskMoney({allowZero:true, prefix: '$'}); $("#addIncomeAmount").maskMoney({allowZero:true, prefix: '$'}); $("#currentBalanceAmount").maskMoney({allowZero:true, allowNegative:true, prefix: '$'}); $("#editTransactionAmount").maskMoney({allowZero:true, prefix: '$'}); /* Add close button to event list div */ $(document).mouseup(function (e) { var container = $('.monthly-event-list'); if (!container.is(e.target) // if the target of the click isn't the container... && container.has(e.target).length === 0) // ... nor a descendant of the container { container.hide(); } }); } function sortTable(table) { var table = table, rows = $('tr', table); rows.sort(function(a, b) { var keyA = $('td',a).text(); var keyB = $('td',b).text(); return (keyA > keyB) ? 1 : 0; }); rows.each(function(index, row) { table.append(row); }); updateTotals(); } function updateTotals () { $('#transactionTable').each(function() { var total = 0; $('#transactionTable tr td:nth-child(3)').each(function() { var num = $(this).text().replace(' ','').replace('$','').replace(',',''); total = parseFloat(total, 10) + parseFloat(num, 10); }); $('#transactionTable').next().text(convertToCurrency(total)); }); $('#billTable').each(function() { var total = 0; $('#billTable tr td:nth-child(3)').each(function() { var num = $(this).text().replace(' ','').replace('$','').replace(',',''); total = parseFloat(total, 10) + parseFloat(num, 10); }); $('#billTable').next().text(convertToCurrency(total)); }); $('#incomeTable').each(function() { var total = 0; $('#incomeTable tr td:nth-child(3)').each(function() { var num = $(this).text().replace(' ','').replace('$','').replace(',',''); total = parseFloat(total, 10) + parseFloat(num, 10); }); $('#incomeTable').next().text(convertToCurrency(total)); }); }; function convertToCurrency(salary) { // round up to 2 decimal places var i = parseFloat(salary); if (isNaN(i)) { i = 0.00; } var minus = ''; if (i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if (s.indexOf('.') < 0) { s += '.00'; } if (s.indexOf('.') == (s.length - 2)) { s += '0'; } s = minus + s; // insert commas for every 3 positions s = s.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); // add $ if (s.includes('-')) { s = [s.slice(0, 1), '$', s.slice(1)].join(''); } else { s = ("$" + s); } return s; }; initilizePackages(); /******************************************* LOGIC TO UPDATE CURRENT BALANCE*********************************************/ $('#currentBalanceModal').modal('show'); $('#currentBalanceModalSave').click(function () { var newBal = $('#currentBalanceAmount').val(); if (newBal.includes('-')) { $('.monthly-today').append('<div class="monthly-day-total monthly-day-total-negative">'+ newBal +'</div>'); } else { $('.monthly-today').append('<div class="monthly-day-total monthly-day-total-positive">'+ newBal +'</div>'); } $('#currentBalanceModal').modal('hide'); }); /************************************************************************************************************************/ /************************************** Stuff I have to do with Bill Data *********************************************/ $('.transaction').each(function( index ) { $(this).click(function() { var date = ""; var name = ""; var amount = ""; $(this).children().each(function( index ) { console.log($(this).text()); if (index == 0) { date = $(this).text(); } else if (index == 1) { name = $(this).text(); } else if (index == 2) { amount = $(this).text(); } }); $('#editTransactionName').val(name); $('#editTransactionAmount').val(amount); $('#editTransactionStartDate').val(''); $('#editTransactionFrequency').val(''); $('#editTransactionModal').modal('show'); }) }); //$('.monthly-day-event:nth-child(2n)').append('<div class="monthly-day-total monthly-day-total-positive">+$1,233.76</div>'); //$('.monthly-day-event:nth-child(2n+1)').append('<div class="monthly-day-total monthly-day-total-negative">-$1,233.76</div>'); updateTotals(); /************************************************************************************************************************/ /************************************** THIS IS FOR ADDING TRANSACTIONS *************************************************/ $('#addTransactionModalSave').click(function () { var name = $('#addTransactionName').val(); var amount = $('#addTransactionAmount').val(); var startDate = $('#addTransactionStartDate').val(); startDate = startDate.split('-')[2]; var frequency = $('#addTransactionFrequency').val(); var type = ""; var typeSign = ""; if ($('#addTransactionType').val() == "Bill") { type = "transaction-negative"; typeSign = "-"; } else if($('#addTransactionType').val() == "Income") { type = "transaction-positive"; typeSign = "+"; } var pass = true; if (name == "" || name == undefined || name == null) { pass = false; $('#addTransactionName').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (type == "" || type == undefined || type == null) { pass = false; $('#addTransactionType').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (amount == "" || amount == undefined || amount == null) { pass = false; $('#addTransactionAmount').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (startDate == "" || startDate == undefined || startDate == null) { pass = false; $('#addTransactionStartDate').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (frequency == "" || frequency == undefined || frequency == null) { pass = false; $('#addTransactionFrequency').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (pass == true) { $('#transactionTable').append('<tr class="transaction '+ type +'" data-date='+ startDate + '><td>'+ startDate +'</td><td>'+ name +'</td><td>' + typeSign +' '+ amount +'</td></tr>'); sortTable($('#transactionTable')); $('#addTransactionModal').modal('hide'); } }); $('#addBillModalSave').click(function () { var name = $('#addBillName').val(); var amount = $('#addBillAmount').val(); var startDate = $('#addBillStartDate').val(); startDate = startDate.split('-')[2]; var frequency = $('#addBillFrequency').val(); var pass = true; if (name == "" || name == undefined || name == null) { pass = false; $('#addBillName').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (amount == "" || amount == undefined || amount == null) { pass = false; $('#addBillAmount').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (startDate == "" || startDate == undefined || startDate == null) { pass = false; $('#addBillStartDate').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (frequency == "" || frequency == undefined || frequency == null) { pass = false; $('#addBillFrequency').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (pass == true) { $('#billTable').append('<tr class="transaction transaction-negative" data-date='+ startDate + '><td>'+ startDate +'</td><td>'+ name +'</td><td>- '+ amount +'</td></tr>'); sortTable($('#billTable')); $('#addBillModal').modal('hide'); } }); $('#addIncomeModalSave').click(function () { var name = $('#addIncomeName').val(); var amount = $('#addIncomeAmount').val(); var startDate = $('#addIncomeStartDate').val(); startDate = startDate.split('-')[2]; var frequency = $('#addIncomeFrequency').val(); var pass = true; if (name == "" || name == undefined || name == null) { pass = false; $('#addIncomeName').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (amount == "" || amount == undefined || amount == null) { pass = false; $('#addIncomeAmount').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (startDate == "" || startDate == undefined || startDate == null) { pass = false; $('#addIncomeStartDate').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (frequency == "" || frequency == undefined || frequency == null) { pass = false; $('#addIncomeFrequency').css({ '-webkit-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', '-moz-box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', 'box-shadow': 'inset 0px 0px 38px 20px rgba(231,77,60,1)', }); } if (pass == true) { $('#incomeTable').append('<tr class="transaction transaction-positive" data-date='+ startDate + '><td>'+ startDate +'</td><td>'+ name +'</td><td>+ '+ amount +'</td></tr>'); sortTable($('#incomeTable')); $('#addIncomeModal').modal('hide'); } }); // Reset inputs and clear red highlight $('.addModal').on('hidden.bs.modal', function () { $('input').val(''); $('select').val(''); $('input').css({ '-webkit-box-shadow': 'none', '-moz-box-shadow': 'none', 'box-shadow': 'none', }); $('select').css({ '-webkit-box-shadow': 'none', '-moz-box-shadow': 'none', 'box-shadow': 'none', }); }) /**************************************************************************************************************************/ switch(window.location.protocol) { case 'http:': case 'https:': // running on a server, should be good. break; case 'file:': //alert('Just a heads-up, events will not work when run locally.'); } });<file_sep>/HTML/Projects/Sustainability/index.js $(function() { $('.slider').slider(); // ID of the Google Spreadsheet var spreadsheetID = "1MwNEfWZN6mvhgQP_D-tP5zAfOoN55OFEoMDafp8VR7Q"; // Make sure it is public or set to Anyone with link can view var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json"; $.getJSON(url, function(data) { var entry = data.feed.entry; console.log(entry); // $(entry).each(function(){ // // Column names are name, age, etc. // $('.results').prepend('<h2>'+this.gsx$name.$t+'</h2><p>'+this.gsx$age.$t+'</p>'); // }); }); var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets: [{ label: 'apples', data: [12, 19, 3, 17, 6, 3, 7], backgroundColor: "rgba(153,255,51,0.4)" }, { label: 'oranges', data: [2, 29, 5, 5, 2, 3, 10], backgroundColor: "rgba(255,153,0,0.4)" }] } }); });
49780314d9f0ccc00362c301b09b01ff8b7a29c0
[ "JavaScript", "Markdown" ]
4
JavaScript
KyleABrown/KyleABrown.github.io
a791c33edaf6b085171e0b56659bf71c5548fd3e
3647a04ca7db9dc7a2301b2b2c16d87fa4de6702
refs/heads/master
<repo_name>onikazu/Shevchenko<file_sep>/src/player12.py import player11 import threading import numpy as np from collections import deque class Player12(player11.Player11, threading.Thread): def __init__(self): super(Player12, self).__init__() self.name = "Crespo" # =============for machine learning # 入力値分割数 self.num_digitized = 6 self.goal_average_reward = 195 # この報酬を超えると学習終了(中心への制御なし) # 出力数 self.action_num = 7 self.action = 0 self.actions = ("(turn 0)", "(turn 60)", "(turn -60)", "(dash 100)", "(dash -100)", "(kick 100 0)", "(kick 50 0)") # 実行 def play_0(self): command = "(turn 0)" if self.checkInitialMode(): if self.checkInitialMode(): self.setKickOffPosition() command = \ "(move " + str(self.m_dKickOffX) + " " + str(self.m_dKickOffY) + ")" self.m_strCommand[self.m_iTime] = command else: # (コマンド生成)=================== self.m_strCommand[self.m_iTime] = command # ================================== def analyzeMessage(self, message): # 初期メッセージの処理 # print("p11:message:", message) if message.startswith("(init "): self.analyzeInitialMessage(message) # 視覚メッセージの処理 elif message.startswith("(see "): self.analyzeVisualMessage(message) # 体調メッセージの処理 elif message.startswith("(sense_body "): self.analyzePhysicalMessage(message) if self.m_iVisualTime < self.m_iTime: self.predict(self.m_iVisualTime, self.m_iTime) self.play_0() self.send(self.m_strCommand[self.m_iTime]) # 聴覚メッセージの処理 elif message.startswith("(hear "): self.analyzeAuralMessage(message) # サーバパラメータの処理 elif message.startswith("(server_param"): self.analyzeServerParam(message) # プレーヤーパラメータの処理 elif message.startswith("(player_param"): self.analyzePlayerParam(message) # プレーヤータイプの処理 elif message.startswith("(player_type"): self.analyzePlayerType(message) # print("player_type_message", message) # エラーの処理 else: print("p11 サーバーからエラーが伝えられた:", message) print("p11 エラー発生原因のコマンドは右記の通り :", self.m_strCommand[self.m_iTime]) def start_selfplay(self): if __name__ == "__main__": plays = [] for i in range(4): p = Player12() plays.append(p) teamname = str(p.__class__.__name__) if i < 11: teamname += "left" else: teamname += "right" plays[i].initialize((i % 2 + 1), teamname, "localhost", 6000) plays[i].start() <file_sep>/src/train.py class TrainPipeline(): def __init__(self): self.game_batch_num = 100 self.play_batch_size = 512 # 512試合を100回訓練 def collect_selfplay_data(self, n_games=1): """ 1バッチ分の処理、訓練 :param n_games: バッチ長 :return: none """ for i in range(n_games): # 結果を集める winner, play_data = self.game.start_self_play(self.mcts_player, temp=self.temp) play_data = list(play_data)[:] self.episode_len = len(play_data) # augment the data play_data = self.get_equi_data(play_data) self.data_buffer.extend(play_data) def run(self): """ 訓練させる :return:none """ try: for i in range(self.game_batch_num): # 集めた結果を回す self.collect_selfplay_data(self.play_batch_size) # エピソードの繰り返し print("batch i:{}, episode_len:{}".format( i + 1, self.episode_len)) # 最後の試合の勝敗つくまでのステップ数? if len(self.data_buffer) > self.batch_size: # まだ性能に余裕あれば? loss, entropy = self.policy_update() # 更新(まだモデルにコミットはしていない) # check the performance of the current model, # and save the model params if (i + 1) % self.check_freq == 0: print("current self-play batch: {}".format(i + 1)) win_ratio = self.policy_evaluate() self.policy_value_net.save_model('./current_policy.model') # 今回の学習のコミット(ベストでなくてもおk) if win_ratio > self.best_win_ratio: print("New best policy!!!!!!!!") self.best_win_ratio = win_ratio # update the best_policy self.policy_value_net.save_model('./best_policy.model')  # ベストコミット if (self.best_win_ratio == 1.0 and self.pure_mcts_playout_num < 5000): self.pure_mcts_playout_num += 1000 self.best_win_ratio = 0.0 except KeyboardInterrupt: print('\n\rquit') if __name__ == "__main__": train_pipeline = TrainPipeline() train_pipeline.run()<file_sep>/README.md # Shevchenko(未完) alpha zeroで作成するrobocup2Dサッカーエージェント ## メモ gamebatchnum が なんバッチやるか gamebatchsize が バッチあたりなん試合やるか エピソードのステップ数 一点入るまで それか3000秒立つまで 1エピソードをなんステップにする? ## 参考 https://github.com/junxiaosong/AlphaZero_Gomoku
a4e36887eadd41fa5aeed11e3db909af02aefcbc
[ "Markdown", "Python" ]
3
Python
onikazu/Shevchenko
2b4506e6e921864fc4453300363cbffdde691a7b
f83ed1e73ac3d0c38583a7c36dc6c83e5bcfca0b
refs/heads/master
<file_sep># morse_coder Encode text to morse code! <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> void cleanBuffer(){ int c = 0; while (c != '\n' && c != EOF) { c = getchar(); } } int getText(char *str, int size) { char *enterPosition = NULL; if (fgets(str, size, stdin) != NULL) { enterPosition = strchr(str, '\n'); if(enterPosition != NULL) { *enterPosition = 0; } else { cleanBuffer(); } return 1; } else { cleanBuffer(); return 0; } } int main(int argc, char* argv[]) { const char alpha_num[36] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; const char *morse[36] = {".-", "-...", "-.-.", "-..", ".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."}; char rawText[5000]; int i = 0; int isInArray = 0; printf("[Morse_coder]Text to encode >"); getText(rawText, 5000); while(tolower(rawText[i]) != '\0') { if (rawText[i] == ' ') { printf("%s", "|"); printf("%5s", " "); } for (int j=0; j <36; j++) { if (tolower(rawText[i]) == alpha_num[j]) { printf("%s", morse[j]); printf("%5s", " "); isInArray = 1; } } if(isInArray == 0 && rawText[i] != ' ') { printf("%c", rawText[i]); printf("%5s", " "); } i++; isInArray = 0; } return 0; }
835fb0a687f586c30ac07ec5627b5501dcc86c18
[ "Markdown", "C" ]
2
Markdown
s0nnyhu/morse_coder
93b9544c1cd0fd304dfeb4c811972e4ace37211e
8f9f63cee750d44b16ec38e82ecf8e4978885db0
refs/heads/master
<repo_name>Jacob234/Flask-hello-world<file_sep>/hello_world.py from flask import Flask, render_template from os import environ app = Flask(__name__) @app.route("/") @app.route("/hello") def say_hi(): return render_template('hello.html', person = "World") @app.route("/hello/<name>") def hi_person(name): given=name return render_template('hello.html', person = given.title()) @app.route("/hello/jedi/<first_name>/<last_name>") def jedi_name(first_name, last_name): first = first_name[0:2] last = last_name[0:3] jedi = str(last) + str(first) return render_template('hello.html', person = "Jedi " + jedi.title()) if __name__ == "__main__": app.run(host=environ['IP'], port=int(environ['PORT']))
1765037f3c6fb323eac310ccd00c93c24a48e988
[ "Python" ]
1
Python
Jacob234/Flask-hello-world
25ef471b6a07e56bbd1f7cca9b45e0edf87df411
65ade56d9233f633f5f60705d472eb0648a979a5
refs/heads/master
<repo_name>RdDvls/Database-To-Do<file_sep>/src/sample/Controller.java package sample; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import jodd.json.JsonParser; import jodd.json.JsonSerializer; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.ResourceBundle; import java.util.Scanner; public class Controller implements Initializable{ ToDoDatabase tdDatabase = new ToDoDatabase(); @FXML ListView todoList; @FXML TextField todoText; String fileName; String DB_URL = "jdbc:h2:./main"; ObservableList<ToDoItem> todoItems = FXCollections.observableArrayList(); ArrayList<ToDoItem> savableList = new ArrayList<ToDoItem>(); // String fileName = "todos.json"; public String username; @Override public void initialize(URL location, ResourceBundle resources) { System.out.print("Hit enter to begin..."); Scanner inputScanner = new Scanner(System.in); username = inputScanner.nextLine(); if (username != null && !username.isEmpty()) { fileName = username + ".json"; } // System.out.println("Checking existing list ..."); // ToDoItemList retrievedList = retrieveList(); // if (retrievedList != null) { // for (ToDoItem item : retrievedList.todoItems) { // todoItems.add(item); // } // } todoList.setItems(todoItems); try { selectToDosFromDatabase(); } catch (SQLException e) { e.printStackTrace(); } } public void selectToDosFromDatabase() throws SQLException{ Connection conn = DriverManager.getConnection(DB_URL); for(ToDoItem item : tdDatabase.selectToDos(conn)){ todoItems.add(item); } todoList.setItems(todoItems); } public void saveToDoList() { if (todoItems != null && todoItems.size() > 0) { System.out.println("Saving " + todoItems.size() + " items in the list"); savableList = new ArrayList<ToDoItem>(todoItems); System.out.println("There are " + savableList.size() + " items in my savable list"); saveList(); } else { System.out.println("No items in the ToDo List"); } } public void addItem() throws SQLException { System.out.println("Adding item ..."); todoItems.add(new ToDoItem(todoText.getText())); Connection conn = DriverManager.getConnection(DB_URL); tdDatabase.insertToDo(conn,todoText.getText()); todoText.setText(""); } public void removeItem() { ToDoItem todoItem = (ToDoItem)todoList.getSelectionModel().getSelectedItem(); System.out.println("Removing " + todoItem.text + " ..."); todoItems.remove(todoItem); } // public void toggleToDo(Connection conn, int id) throws SQLException { // PreparedStatement stmt = conn.prepareStatement("UPDATE todos SET is_done = NOT is_done WHERE id = ?"); // stmt.setInt(1, id); // stmt.execute(); // } public void toggleItem() throws SQLException { System.out.println("Toggling item ..."); Connection conn = DriverManager.getConnection(DB_URL); // tdDatabase.toggleToDo(conn, 1); ToDoItem todoItem = (ToDoItem) todoList.getSelectionModel().getSelectedItem(); tdDatabase.toggleToDo(conn, todoItem.id); if (todoItem != null) { todoItem.isDone = !todoItem.isDone; todoList.setItems(null); todoList.setItems(todoItems); } } // public void saveList() { try { // write JSON JsonSerializer jsonSerializer = new JsonSerializer().deep(true); String jsonString = jsonSerializer.serialize(new ToDoItemList(todoItems)); System.out.println("JSON = "); System.out.println(jsonString); File sampleFile = new File(fileName); FileWriter jsonWriter = new FileWriter(sampleFile); jsonWriter.write(jsonString); jsonWriter.close(); } catch (Exception exception) { exception.printStackTrace(); } } public ToDoItemList retrieveList() { try { Scanner fileScanner = new Scanner(new File(fileName)); fileScanner.useDelimiter("\\Z"); // read the input until the "end of the input" delimiter String fileContents = fileScanner.next(); JsonParser ToDoItemParser = new JsonParser(); ToDoItemList theListContainer = ToDoItemParser.parse(fileContents, ToDoItemList.class); System.out.println("=============================================="); System.out.println(" Restored previous ToDoItem"); System.out.println("=============================================="); return theListContainer; } catch (IOException ioException) { return null; } } }<file_sep>/src/sample/ToDoItemList.java package sample; import java.util.ArrayList; import java.util.List; public class ToDoItemList { public ArrayList<ToDoItem> todoItems = new ArrayList<ToDoItem>(); public ToDoItemList(List<ToDoItem> incomingList) { todoItems = new ArrayList<ToDoItem>(incomingList); } public ToDoItemList() { } }
662aede97923b758f07884aa95a10e9ae868778f
[ "Java" ]
2
Java
RdDvls/Database-To-Do
778fff9d84c5fb6648831443433c51ed6c17d883
6458bc29ffd1275b75b97bffae49cf5fcaa2d9b2
refs/heads/master
<file_sep># MongoDb **MongodB Demo**<file_sep>using System; using System.Collections.Generic; using System.Text; namespace MongoDbHelp { /// <summary> /// MongoDb配置消息 /// </summary> public class MongoDbConfigInfo { /// <summary> /// 连接 127.0.1:27017 /// </summary> public string ConnectionString { get; set; } /// <summary> /// 数据库 /// </summary> public string DatabaseName { get; set; } } } <file_sep>using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using MongoDB.Driver; using MongoDbHelp; using System; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// 对IService的扩展 /// </summary> public static class ServiceCollectionExtensions { /// <summary> /// 自定义配置 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="steup"></param> public static void AddMongoDBServer(this IServiceCollection services, IConfiguration configuration,Action<MongoDbConfigInfo> steup) { services.Configure(steup); services.Configure<MongoDbConfigInfo>(options => { configuration.GetSection("MongoDbOptions").Bind(options); }); services.AddSingleton<IMongoDatabase>(sp => { var options = sp.GetService<IOptions<MongoDbConfigInfo>>()?.Value ?? throw new ArgumentNullException(nameof(MongoDbConfigInfo)); return new MongoClient(options.ConnectionString).GetDatabase(options.DatabaseName); }); } /// <summary> /// 配置1 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> public static void AddMongoDBServer(this IServiceCollection services, IConfiguration configuration) { services.Configure<MongoDbConfigInfo>(options => { configuration.GetSection("MongoDbOptions").Bind(options); }); services.AddSingleton<IMongoDatabase>(sp => { var options = sp.GetService<IOptions<MongoDbConfigInfo>>()?.Value ?? throw new ArgumentNullException(nameof(MongoDbConfigInfo)); return new MongoClient(options.ConnectionString).GetDatabase(options.DatabaseName); }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using MongoDbDemoApi1.MongodbHepler; namespace MongoDbDemoApi1.Controllers { [ApiController] [Route("[controller]/[action]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; private readonly IMongoDbBase _mongoDbBase; public WeatherForecastController(ILogger<WeatherForecastController> logger, IMongoDbBase mongoDbBase) { _logger = logger; _mongoDbBase = mongoDbBase; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpGet] public IActionResult AddList() { List<MongoDBPostTest> list = new List<MongoDBPostTest>() { new MongoDBPostTest() { Id = "2", Body = "Test note 3", UpdatedOn = DateTime.Now, UserId = 1, HeaderImage = new NoteImage { ImageSize = 10, Url = "http://localhost/image1.png", ThumbnailUrl = "http://localhost/image1_small.png" } }, new MongoDBPostTest() { Id = "3", Body = "Test note 4", UpdatedOn = DateTime.Now, UserId = 1, HeaderImage = new NoteImage { ImageSize = 14, Url = "http://localhost/image3.png", ThumbnailUrl = "http://localhost/image3_small.png" } } }; try { var ss= _mongoDbBase.InsertManyAsync(list); } catch (Exception ex) { throw; } return Ok("成功"); } [HttpGet] public async Task<IEnumerable<MongoDBPostTest>> SelectSingle() { //无条件 var list =await _mongoDbBase.GetIEnumerableAsync<MongoDBPostTest>(e=>e.UserId==1); //有条件 //var list = _context.GetList<MongoDBPostTest>(a => a.Id == "1"); //得到单条数据,无条件 //var list = _context.GetSingle<MongoDBPostTest>(); //得到单条数据,有条件 //var list = _context.GetSingle<MongoDBPostTest>(a => a.Id == "3"); //ObjectId internalId = _mongoDbBase.GetInternalId("5bbf41651d3b66668cbb5bfc"); //var a = _context.GetSingle<MongoDBPostTest>(note => note.Id == "5bbf41651d3b66668cbb5bfc" || note.InternalId == internalId); //return ResHelper.Suc(1, list, "成功"); return list; } } } public class MongoDBPostTest { [BsonId] // standard BSonId generated by MongoDb public ObjectId InternalId { get; set; } public string Id { get; set; } public string Body { get; set; } = string.Empty; [BsonDateTimeOptions] public DateTime UpdatedOn { get; set; } = DateTime.Now; public NoteImage HeaderImage { get; set; } public int UserId { get; set; } = 0; } public class NoteImage { public string Url { get; set; } = string.Empty; public string ThumbnailUrl { get; set; } = string.Empty; public long ImageSize { get; set; } = 0L; }
c0b81c9b510cdfebcb06cff0c5e90e2142ab24f2
[ "Markdown", "C#" ]
4
Markdown
XZL-Github/MongoDb
e57a1e971e8cdc05dd5bf256513d04aff730fc59
a4ddabeb9e441d40dc4814911328e6951c36a657
refs/heads/master
<repo_name>francamacdowell/GSO<file_sep>/1 exercicio/gso.py from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop from random import random def GSO(input_number, n_neurons, fitness_value, max_iter, luci_enhancement, luci_decay, neigh_ray): dimension = (input_number * n_neurons) + (2 * n_neurons) + n_neurons glow_input_layer = [] glow_hidden_layer = [] glow_bias = [] luciferin = {} luciferin['input'] = [] luciferin['hidden'] = [] luciferin['bias'] = [] for glow_idx in range(input_number): glow_input_layer.append(random()) luciferin['input'].append(0) for glow_idx in range(n_neurons): glow_hidden_layer.append(random()) luciferin['hidden'].append(0) glow_bias.append(random()) luciferin['bias'].append(0) t = 0 while t < max_iter: print(str(t) + ' ITERATION:') # TO INPUT LAYER for glow_idx in range(input_number): luciferin[glow_idx] = ((1 - luci_decay) * luciferin['input'][glow_idx]) + (luci_enhancement * fitness_value) for glow_idx in range(input_number): neighbours = [] for glow_i in range(input_number): if glow_idx != glow_i: d = abs(glow_input_layer[glow_idx] - glow_input_layer[glow_i]) if d <= neigh_ray: neighbours.append([glow_i, luciferin['input'][glow_i]]) major_glow = [-1, -1] for n in neighbours: if n[1] > major_glow[1]: major_glow = n #Movment phase glow_input_layer[glow_idx] += abs(glow_input_layer[glow_idx] - glow_input_layer[major_glow[0]]) / 2 # TO HIDDEN LAYER for glow_idx in range(n_neurons): luciferin['hidden'][glow_idx] = ((1 - luci_decay) * luciferin['hidden'][glow_idx]) + (luci_enhancement * fitness_value) luciferin['bias'][glow_idx] = ((1 - luci_decay) * luciferin['bias'][glow_idx]) + (luci_enhancement * fitness_value) for glow_idx in range(n_neurons): neighbours = [] for glow_i in range(n_neurons): if glow_idx != glow_i: d = abs(glow_hidden_layer[glow_idx] - glow_hidden_layer[glow_i]) if d <= neigh_ray: neighbours.append([glow_i, luciferin['hidden'][glow_i]]) major_glow = [-1, -1] for n in neighbours: if n[1] > major_glow[1]: major_glow = n #Movment phase glow_hidden_layer[glow_idx] += abs(glow_hidden_layer[glow_idx] - glow_hidden_layer[major_glow[0]]) / 2 t += 1 return glow_input_layer, glow_hidden_layer, glow_bias if __name__ == "__main__": batch_size = 128 num_classes = 10 epochs = 1 INPUT_NUMBER = 784 N_NEURONS = 512 # the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, INPUT_NUMBER) x_test = x_test.reshape(10000, INPUT_NUMBER) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) model = Sequential() model.add(Dense(N_NEURONS, activation='relu', input_shape=(INPUT_NUMBER,))) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) accuracy = score[1] print('Test loss:', score[0]) print('Test accuracy:', score[1]) input_weigth, hidden_weigth, bias = GSO(INPUT_NUMBER, N_NEURONS, score[1], 10, 0.6, 0.4, 0.2) model2 = Sequential() model2.add(Dense(N_NEURONS, activation='relu', input_shape=(INPUT_NUMBER,))) model2.add(Dropout(0.2)) model2.add(Dense(num_classes, activation='softmax')) import numpy model2.summary() hidden_weigth = numpy.asarray(hidden_weigth) bias = numpy.asarray(bias) print('Input layer weigths:') print(input_weigth)<file_sep>/2 exercicio/build.py from shapely.geometry import Polygon from shapely.geometry.point import Point from shapely.ops import cascaded_union import pygame import sys from pygame.locals import * import math def create_points_2_poly(side, center, radius): angle = 2*math.pi/side points = [] for i in range(side): x = center[0] + radius*math.cos((i)*angle) y = center[1] + radius*math.sin((i)*angle) points.append((x, y)) return tuple(points) def create_city_points(centers, d) : Hx = [] for center in centers : Hx.append(create_points_2_poly(6, center, d)) return Hx def create_city(centers, d) : Hx = [] for center in centers : Hx.append(Polygon(create_points_2_poly(6, center, d))) return cascaded_union(Hx) def create_base_stations_points(centers, radius) : Bx = [] for center in centers : point = Point(center[0], center[1]) circle = point.buffer(radius) Bx.append(circle) return Bx def create_base_stations(centers, radius) : Bx = [] for center in centers : point = Point(center[0], center[1]) circle = point.buffer(radius) Bx.append(circle) return cascaded_union(Bx) def run_pygame(city, base_stations) : # inicia o pygame pygame.init() # inicia a janela windowSurface = pygame.display.set_mode((625, 625), 0, 32) # inicia as cores utilizadas BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 0, 0) PURPLE = (100, 0, 255) GRAY = (127, 127, 127) # inicia as fontes basicFont = pygame.font.SysFont(None, 48) # desenha o fundo branco windowSurface.fill(GREEN) # desenha um poligono verde na superficie for H in city : pygame.draw.polygon(windowSurface, GRAY, H) for B in base_stations : x,y = B.exterior.coords.xy points_base_stations = [] for i in range(len(x)) : points_base_stations.append([x[i], y[i]]) pygame.draw.polygon(windowSurface, PURPLE, points_base_stations) # desenha a janela na tela pygame.display.update() # roda o loop do jogo while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() return<file_sep>/2 exercicio/problem.py # -*- coding: utf-8 -*- from GSO import GSO import argparse import sys from shapely.geometry import Polygon from shapely.geometry.point import Point from shapely.ops import cascaded_union from build import run_pygame from build import create_base_stations from build import create_points_2_poly from build import create_city import math centers_1 = [(219, 287), (219, 393), (312, 234), (312, 234), (312, 340), (312, 448), (405, 287), (405, 393)] centers_2 = [(127,124), (127,231), (127,340), (127,448), (220,178), (220,286), (220,394), (220,502), (312,124), (312,231), (312,340), (312,448), (406,178), (406,286), (406,394), (406,502), (499,124), (499,231), (499,340), (499,448)] centers_3 = [(127,231), (127,340), (127,448), (220,178), (220,286), (220,394), (312,124), (312,231), (406,178), (406,286), (406,394), (499,231), (499,340), (499,448)] K = [7, 3, 6] D = [63, 63, 63] R = [63, 170, 126] centers = [centers_1, centers_2, centers_3] def main(): parser = argparse.ArgumentParser( description='GSO for optimizing basement problem') parser.add_argument('-p', '--population', default=100, type=int, help='Population size') parser.add_argument('-it', '--iterations', type=int, default=100, help='Number of iterations') parser.add_argument('-i', '--input', type=int, default=1, help='Input instace of the problem') parser.add_argument('-l', '--luciferin', type=float, default=0.2, help='Luciferin Enhancement coeficient') parser.add_argument('-r', '--ray', type=int, default=1000, help='Ray range distance') parser.add_argument('--step', type=float, default=0.5, help='Step coeficient') parser.add_argument('-s', '--show', type=bool, default=False, help='Show bases station') args = parser.parse_args(sys.argv[1:]) print("**************************************") print("* GSO for optimizing base stations *") print("**************************************") if args.input < 1 or args.input > 3 : print("The instance input doesn't exists") return low_boundary = 0 + R[args.input-1] upper_boundary = 625 - R[args.input-1] city = create_city(centers[args.input-1], D[args.input-1]) center_base_stations = GSO(low_boundary, upper_boundary, (K[args.input-1], 2), args.population, args.iterations, R[args.input-1], D[args.input-1], city, centers[args.input-1], args.show, args.luciferin, args.ray, args.step) if __name__ == "__main__": main()<file_sep>/2 exercicio/GSO.py # -*- coding: utf-8 -*- import random import numpy as np import math import time from shapely.geometry import Polygon from shapely.geometry.point import Point from shapely.ops import cascaded_union from build import create_base_stations from build import create_city from build import create_base_stations_points from build import create_city_points from build import run_pygame def calculate_fitness(worm, radius, city): circles = [] for center in worm: point = Point(center[0], center[1]) circles.append(point.buffer(radius)) base_stations_polygon = cascaded_union(circles) intersection_area = base_stations_polygon.intersection(city).area return base_stations_polygon.intersection(city).area / city.area def GSO(low_boundary, upper_boundary, dimension, population, iterations, radius, D, city, city_centers, show, luciferin_enhancement, ray, step): # Initialize the positions of search agents best_fitness = -999999 Positions = [] Luciferin = [] for i in range(population): Positions.append(np.zeros(dimension)) Luciferin.append(random.random()) for i in range(population): Positions[i][:, 0] = np.random.uniform( 0, 1, dimension[0]) * (upper_boundary - low_boundary) + low_boundary Positions[i][:, 1] = np.random.uniform( 0, 1, dimension[0]) * (upper_boundary - low_boundary) + low_boundary Convergence_curve = np.zeros(iterations) # Loop counter print("GSO is optimizing") worm_pos = [] # Main loop for l in range(iterations): for i in range(population): # Calculate objective function for each search agent fitness = calculate_fitness(Positions[i], radius, city) if fitness > best_fitness: best_fitness = fitness worm_pos = Positions[i].copy() # Lucinferin update phase: Luciferin[i] = (1 - random.random()) * Luciferin[i] + luciferin_enhancement * fitness # Movement Phase: for i in range(population): # Select neighbours with more luciferin inside the range neighbours = [] for j in range(population): if i != j: distance = np.linalg.norm(abs(Positions[j] - Positions[i])) if distance <= ray and Luciferin[j] >= Luciferin[i]: neighbours.append(j) # Selecting random glowworm to follow best_worm = -7 if len(neighbours) != 0: best_worm = random.choice(neighbours) # Update position phase d = np.linalg.norm(Positions[j] - Positions[i]) Positions[i] += step * d if (l % 1 == 0): print(['Iteration: ' + str(l+1) + ' the best fitness: ' + str(best_fitness)]) if show: run_pygame(create_city_points(city_centers, D), create_base_stations_points(worm_pos, radius)) if not show: run_pygame(create_city_points(city_centers, D), create_base_stations_points(worm_pos, radius)) print(best_fitness) return best_fitness
f3e708780ba456cd6165a0576f057c00999e77b0
[ "Python" ]
4
Python
francamacdowell/GSO
3cb579c2c93143ddc91f9411156be5ea71cd00fd
03d4eeb74ad7e2f93e010f91c7048b8c78a71e66
refs/heads/master
<repo_name>AdShEaTaKoRe/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-london-web-120919<file_sep>/nyc_pigeon_organizer.rb def nyc_pigeon_organizer(data) data[:gender].reduce({}) { |result, (k,v)| pigeon_names = v pigeon_names.each { |pigeon_name| result[pigeon_name] = { :color => get_keys_if_in_array(pigeon_name, data[:color]), :gender => [k.to_s], :lives => get_keys_if_in_array(pigeon_name, data[:lives]) } } result } end def get_keys_if_in_array(desired_name, obj) obj.reduce([]) { |memo, (k,v)| if v.any? { |name| desired_name == name} memo << k.to_s end memo } end
99942b644acc212342b249b53b85bb35e4f6f97c
[ "Ruby" ]
1
Ruby
AdShEaTaKoRe/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-london-web-120919
46d767387a49ee26be3036953156baec7814a695
fb8d1d7918df92e5ce9d2f37539714f211b8dda8
refs/heads/master
<file_sep>Page({ /** * 页面的初始数据 */ data: { headerIcon1: ['../images/icon-0_02.png', '../images/icon-0_04.png', '../images/icon-0_06.png','../images/icon-0_08.png'], headerIcon2: ['../images/icon-0_14.png', '../images/icon-0_15.png', '../images/icon-0_16.png','../images/icon-0_17.png'], headerText1:['天猫网店','京东网店','淘宝网店','天猫入驻'], headerText2: ['网店估价', '求购网店', '出售网店', '在线回答'], banners: ['../images/banner_2.png', '../images/banner_3.png', '../images/banner_4.png'], shopItems: [ // { title: '江浙沪地区女装天猫旗舰店,一千万营业额动态全红...', genre: '专营店', brand: 'B标',category:'3C数码',region:'华中地区', price:'123.4'}, // { title: '江浙沪地区女装天猫旗舰店,一千万营业额动态全红...', genre: '专营店', brand: 'B标', category: '3C数码', region: '华中地区 ', price: '123.4' }, // { title: '江浙沪地区女装天猫旗舰店,一千万营业额动态全红...', genre: '专营店', brand: 'B标', category: '3C数码', region: '华中地区 ', price: '123.4' }, // { title: '江浙沪地区女装天猫旗舰店,一千万营业额动态全红...', genre: '专营店', brand: 'B标', category: '3C数码', region: '华中地区 ', price: '123.4' }, // { title: '江浙沪地区女装天猫旗舰店,一千万营业额动态全红...', genre: '专营店', brand: 'B标', category: '3C数码', region: '华中地区 ', price: '123.4' } ], }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let _this = this; wx.request({ url: 'http://192.168.1.158:8080/miniIndex', //仅为示例,并非真实的接口地址 data: {}, header: { 'content-type': 'application/json' // 默认值 }, success(res) { _this.setData({ shopItems: JSON.parse(res.data) }) } }) setTimeout(()=>{ console.log(this.data.shopItems); },1000) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { // const query = wx.createSelectorQuery(); // query.selectAll(".banner-img").boundingClientRect(function (rect) { // console.log(rect); // console.log(rect[0]); // console.log(rect[0].height) // console.log(rect[0].width) // }); // query.selectAll(".banner-img").fields({ // size:true, // computedStyle:['height'] // },function(res){ // console.log(res); // console.log(res.height); // // 节点的高度 // }); // query.exec(); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, })<file_sep>// pages/particulars/particulars.js Page({ /** * 页面的初始数据 */ data: { isshade:false, shadeimg:'' }, bannertap:function(e){ let src=e.target.dataset.src; this.setData({ shadeimg:src, isshade:true }) }, shadetap:function(){ this.setData({ shadeimg: "", isshade: false }) }, shadeimgtap:function(){ }, skiptap:function(e){ let item=e.target.dataset.id; const query = wx.createSelectorQuery() query.select('.'+item).boundingClientRect() query.selectViewport().scrollOffset() query.exec(function (res) { let scrollTop = res[0].top + res[1].scrollTop; wx.pageScrollTo({ scrollTop: scrollTop, duration: 200 }) // res[0].top // #the-id节点的上边界坐标 // res[1].scrollTop // 显示区域的竖直滚动位置 }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
3682112f6aec0b493e46487337145fa132994cb3
[ "JavaScript" ]
2
JavaScript
ybchen292/wxdemo
3db02ae8b906af66167ba7af837cbc75b5a0a313
b8b7eebe7bcc79793a0374805c7bbd8053831adc
refs/heads/master
<file_sep>$(function(){ var key = getSearch("key"); // console.log(key); $('.search_input').val(key); $('.search_btn').click(function(){ render(); }) //点击排序的按钮,进行排序 $('.lt_sort li[data-type]').on('click',function(){ if($(this).hasClass('active')){ $(this).find('i').toggleClass('fa fa-angle-down').toggleClass('fa fa-angle-up') }else{ $(this).addClass('active').siblings().removeClass('active'); } render(); }) render(); function render(){ $('.lt_product').html('<div class="loading"></div>'); var obj = {}; obj.proName = $('.search_input').val(); obj.page = 1; obj.pageSize = 100; var $active = $('.lt_sort li.active'); if($active.length === 1){ //判断是升序还是降序 var sortName = $active.data('type'); // console.log(sortName); var sortValue = $active.find('i').hasClass('fa-angle-up')? '1' : '2'; obj[sortName] = sortValue; } setTimeout(function(){ $.ajax({ type:'get', url:'/product/queryProduct', data:obj, dataType:'json', success:function(info){ console.log(info); if(info.data.length == 0){ $('.lt_product').html('<p>没有这样的产品</p>'); }else{ $('.lt_product').html( template('tmp', info) ); } } }) },1000) } })<file_sep>$(function () { //1.获取存储的search_list 进行渲染 //2.删除单个搜索历史 //3.删除所有的搜索历史 //4.添加单个搜索历史 //1.功能一:获取所有的搜索历史,渲染页面 //从后台获取json字符串,再转成数组 render(); function getArr() { var jsonStr = localStorage.getItem('search_list') || '[]'; var arr = JSON.parse(jsonStr); return arr; } function render() { var arr = getArr(); var htmlStr = template('historyTmp', { list: arr }); $('.lt_history').html(htmlStr); } // 2.功能二:删除所有的搜索历史 //点击删除所有按钮,删除所有 $('.lt_history').on('click','.search_empty',function(){ // console.log(111); mui.confirm('你确定要清空历史记录吗?','温馨提示',['取消','确定'],function(e){ // console.log(e); if(e.index === 1){ localStorage.removeItem('search_list'); render(); } }) }) //3.功能三:点击删除,删除当前的记录 $('.lt_history').on('click','.btn_delete',function(){ // console.log(11); var arr = getArr(); var index = $(this).data('index'); // console.log(arr,index); arr.splice(index,1); // console.log(arr); //再转成json字符串,存入 var jsonStr = JSON.stringify(arr); localStorage.setItem('search_list',jsonStr); // console.log(localStorage); // 重新渲染 render(); }) //4.功能四:点击搜索按钮,添加搜索历史 $('.search_btn').on('click',function(){ // console.log(11); var txt = $('.search_input').val().trim(); // console.log(txt); if(txt === ''){ mui.toast('请输入搜索关键字') return; } var arr = getArr(); //有重复的项,先将重复的项删除,再在最前面添加 var index = arr.indexOf(txt); if(index !== -1){ arr.splice(index,1); } //如果超过10个,保留最前面的,删除最后一个 if(arr.length == 10){ arr.pop(arr.length - 1); } // console.log(arr); // 向前面添加数据 arr.unshift(txt); //转成json字符串 var jsonStr = JSON.stringify(arr); localStorage.setItem('search_list',jsonStr); render(); $('.search_input').val(''); location.href="searchList.html?key=" + txt; }) })<file_sep>$(function(){ mui('.mui-scroll-wrapper').scroll({ deceleration: 0.0005, //flick 减速系数,系数越大,滚动速度越慢,滚动距离越小,默认值0.0006 indicators:false }); var gallery = mui('.mui-slider'); gallery.slider({ interval:1000//自动轮播周期,若为0则不自动播放,默认为0; }); // 封装好的, 专门用于解析地址栏参数的方法 // 返回具体的参数值 }) function getSearch( k ) { var str = location.search; // 获取地址栏参数 // 解码成中文 str = decodeURI( str ); // "?key=耐克&age=18&desc=帅" // 去掉问号 // str.slice( start, end ) // (1) 包括start, 不包括end // (2) 如果end不写, 可以截取到最后 str = str.slice( 1 ); // "key=耐克&age=18&desc=帅" // str.split("&") 将字符串根据&分割成数组 var arr = str.split('&'); // ["key=耐克", "age=18", "desc=帅"] var obj = {}; // 遍历数组, 取得键和值 arr.forEach(function( v, i ) { // v 每一项 "age=18" var key = v.split("=")[0]; // age var value = v.split("=")[1]; // 18 obj[ key ] = value; }) return obj[ k ]; }<file_sep>$(function(){ render(); function render(){ $.ajax({ type:'get', url:'/cart/queryCart', dataType:'json', success:function(info){ console.log(info); $('.lt_main .mui-scroll').html( template('tmp',{list : info}) ); } }) } //删除购物车的信息 $('.lt_main').on('click','.btn_delete',function(){ // console.log(11); var id = $(this).parents('li').data('id'); // console.log(id); delRender(); function delRender(){ $.ajax({ type:'get', url:'/cart/deleteCart', dataType:'json', data:{ id:id }, success:function(info){ console.log(info); render(); } }) } }) })
f4187ab468ffcbba8d636657e7f556f7ebe74a74
[ "JavaScript" ]
4
JavaScript
wuailing/letao
0c178c1f3f550c26ede10a722fc186b11fd6f87f
6fde33aff82780f03010d9b3bc85fa3fe6ba37a5
refs/heads/master
<repo_name>RicardoRodriguezArg/face_detector<file_sep>/pre-trainning-setup/validation_image_script_test/image_validator_script.py import sys, getopt sys.path.insert(0,'../../../face_detector') sys.path.insert(0,'../../face_detector') sys.path.insert(0,'../face_detector') from utils.image_validator import ImageValidator def _execute(image_lists,directory_to_image): image_validator = ImageValidator() image_validator.load_file_list_from_file(image_lists) image_validator.create_histogram_from_file_names_list() #image_validator.verify_image_validation(directory_to_image) image_validator.verify_directory_image_vality(directory_to_image) if __name__ == '__main__': _execute(sys.argv[1], sys.argv[2]) <file_sep>/face_detector_manager.py #!/usr/local/bin/python import sys import os from optparse import OptionParser import subprocess from detectors.haar_face_detector.detector_haar import FaceDetector SCRIPT_VERSION = '1.0.0' #HARDCODED SECTION PATH_TO_PRE_TRAINNIGN_STEP_SCRIPT = 'pre-trainning-setup/image_downloader/gral_image_downloader.py' PATH_TO_TRAINNING_SCRIPT = 'trainning/haar_trainning/train_manager.py' PAT_TO_FACE_DETECTOR_SERVICE = 'service/detector_service.py' PYTHON_PREFIX = 'python' #END HARDCODE SECTION def _execute_cmd_shell(cmd_to_execute): p = subprocess.Popen(cmd_to_execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() def __create_parser(): parser = OptionParser(usage = 'usage: %prog [options] filename',\ version = '%prog '+ SCRIPT_VERSION ) parser.add_option('-t','--train_haar',\ action = "store",\ type = "string" ,\ dest = "train_haar_file_cfg_file",\ default = False,\ help = "Train Haar Detector using config file especified") parser.add_option('-r','--run_detector_haar',\ action = "store",\ type = "string" ,\ dest = "run_haar_detector_service",\ default = False,\ help = "Run detector Haar") parser.add_option('-p','--run_perf_test_haar',\ action = "store",\ type = "string" ,\ dest = "performance_test_cfg_file",\ default = False,\ help = "Run Performance test on Haar Detector") parser.add_option('-s','--run_pre_trainning_setup',\ action = "store",\ type = "string" ,\ dest = "run_pre_trainning_setup_cfg_file",\ default = False,\ help = "Run Pre setup steps for Detector Haar Trainning") parser.add_option('-d','--run_hog_detector',\ action = "store",\ type = "string" ,\ dest = "run_hog_detector",\ default = False,\ help = "Run HOG SVM FaceDetector") return parser def __process_option_project(options): if options.train_haar_file_cfg_file: __run_train_haar_classifier(options.train_haar_file_cfg_file) elif options.run_haar_detector_service: __run_clasiffier_haar_service(options.run_haar_detector_service) elif options.performance_test_cfg_file: __run_performance_test_on_haar(options.performance_test_cfg_file) elif options.run_pre_trainning_setup_cfg_file: __run_pre_trainning_steps(options.run_pre_trainning_setup_cfg_file) def __run_train_haar_classifier(cfg_file): _execute_cmd_shell(PYTHON_PREFIX+ ' '+PATH_TO_TRAINNING_SCRIPT+ ' ' + cfg_file) def __run_clasiffier_haar_service(cfg_file): _execute_cmd_shell(PYTHON_PREFIX + ' ' + PAT_TO_FACE_DETECTOR_SERVICE + ' ' + cfg_file) def __run_performance_test_on_haar(cfg_file): pass def __run_pre_trainning_steps(cfg_file): _execute_cmd_shell(PYTHON_PREFIX+ ' '+PATH_TO_PRE_TRAINNIGN_STEP_SCRIPT+ ' ' + cfg_file) if __name__ == '__main__': (options, args ) = __create_parser().parse_args() __process_option_project(options) <file_sep>/utils/image_database_downloader.py import urllib2 import imghdr from urllib2 import Request from urllib2 import urlopen, HTTPError import os import numpy as np import cv2 class ImageDownloader(object): FULL_RANGE_IMAGE_COUNT = -1 def __init__(self, image_prefix, urls_image, total_image_amount_to_download, negative_image_size = 100, positive_image_size = 50): self.__image_prefix = image_prefix self.__load_image_urls_from_file(urls_image) self.__crop_image_url(total_image_amount_to_download) self.__create_image_trainning_config_dic(int(positive_image_size), int(negative_image_size)) def __create_image_trainning_config_dic(self, positive_image_size, negative_image_size): self.__IMAGE_TRAINNING_TYPE= { "positive" : (positive_image_size, self.__resize_positive_image), "negative" : (negative_image_size, self.__resize_negative_image), } def __load_image_urls_from_file(self, file_name): if file_name: data = self.__load_data_from_file(file_name) self.__data_list = data.split('\n') def __load_data_from_file(self, file_name): data = "" with open(file_name, 'r') as image_file: data = image_file.read() return data def __verify_load_operation(self): if len(self.__data_list) == 0: raise Exception('Empty Image url File') def __crop_image_url(self, image_count): if image_count != -1: self.__data_list = self.__data_list[0:int(image_count)] def __verify_download_directory(self, directory): if not os.path.exists(directory): os.makedirs(directory) def __resize_positive_image(self, raw_image, filename): self.__resize_image(filename, raw_image, self.__IMAGE_TRAINNING_TYPE["positive"][0]) def __resize_negative_image(self, raw_image, filename): self.__resize_image(filename, raw_image, self.__IMAGE_TRAINNING_TYPE["negative"][0]) def __if_image_valid(self, filename): return self.__image_type in imghdr.what(filename) def __process_downloaded_image(self, filename): image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) resized_image = cv2.resize(image, (image_size, image_size)) cv2.imwrite(filename,resized_image) def __resize_image(self, filename, raw_image, image_size): if len(raw_image)>0: with open(filename, 'wb') as file: file.write(raw_image) if self.__if_image_valid(filename): self.__process_downloaded_image(filename) def download_files(self, directory_to_download, image_format_ext, image_trainning_type): self.__image_type = image_format_ext self.__verify_download_directory(directory_to_download) file_name_idx = 1 for image_url in self.__data_list: try: image_uri = directory_to_download+'/'+self.__image_prefix+str(file_name_idx)+image_format_ext file_name_idx += 1 print "downloading file to : {0}".format(image_uri) raw_image = urllib2.urlopen(image_url).read() self.__IMAGE_TRAINNING_TYPE[image_trainning_type][1](raw_image,image_uri) except Exception as e: print ("Error Processing image: {0}".format(str(e))) <file_sep>/utils/image_validator.py import numpy as np import cv2 import time import sys import os class ImageValidator(object): __VALID_THRESHOLD_VALUE = 500 def __init__(self, histogram_list = []): self.__histogram_list = histogram_list self.__histogram_result = {} def load_file_list_from_file(self, image_list_file_name): self.__file_name_list = [] with open(image_list_file_name, 'r') as raw_file_list: data = raw_file_list.read() self.__file_name_list = data.split('\n') self.__depure_input_image_list() def __depure_input_image_list(self): for item in self.__file_name_list: if len(item)==0: self.__file_name_list.remove(item) def create_histogram_from_file_names_list(self): for file_name in self.__file_name_list: histogram = None histogram = self.__get_image_histogram(file_name) if histogram is not None: self.__histogram_list.append(histogram) def verify_directory_image_vality(self, image_directory): #TODO: agregar opcion de acciones que se pueden realizar not_valid_image_count=0 total_amount_of_files_in_directory = len(os.listdir(image_directory)) for image_file_name in os.listdir(image_directory): if not self.verify_image_validation(image_directory+'/'+image_file_name): print "{0}\t--->imagen No valida".format(image_file_name) print "eliminando archivo: {0}".format(image_file_name) os.remove(image_directory+'/'+image_file_name) not_valid_image_count += 1 print "cantidad de imagenes no Validas: {0}".format(not_valid_image_count) print "cantidad total de imagenes en el directorio {0}".format(total_amount_of_files_in_directory) def verify_image_validation(self, image_to_validate): image_histogram = self.__get_image_histogram(image_to_validate) return self.__is_valida_image(image_histogram) def __is_valida_image(self, image_histogram): result = True for histogram in self.__histogram_list: d = cv2.compareHist(image_histogram, histogram, 1) print "Thresold value: {0}".format(d) if d < self.__VALID_THRESHOLD_VALUE: result = False break return result def __get_image_histogram(self, image_file_name): img = self.__load_image_from_filename(image_file_name) histogram = cv2.calcHist([img],[0],None,[256],[0,256]) cv2.normalize(histogram,histogram,0,255,cv2.NORM_MINMAX) return histogram def __load_image_from_filename(self, file_name): return cv2.imread(file_name) <file_sep>/pre-trainning-setup/image_downloader/gral_image_downloader.py import sys,os import subprocess import time def _execute_cmd_shell(cmd_to_execute): p = subprocess.Popen(cmd_to_execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() def _execute(): download_1_string='python image_downloader.py ./config/downloader.cfg' download_2_string='python image_downloader.py ./config/downloader-car.cfg' download_3_string='python image_downloader.py ./config/downloader-flora.cfg' download_4_string='python image_downloader.py ./config/downloader-landscape.cfg' path_to_not_valid_image = '/home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/tests/validation_image_script_test/image_not_valid_list.txt' path_to_positive_image_directory ='/home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/tests/positive_image/' path_to_negative_image_directory = '/home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/trainning/negative_images/' path_to_validator_script = '../validation_image_script_test/image_validator_script.py' clean_positive_image_cmd ='python '+path_to_validator_script+' '+ path_to_not_valid_image + ' ' +path_to_positive_image_directory clean_negative_image_cmd = 'python '+path_to_validator_script+' '+ path_to_not_valid_image + ' ' + path_to_negative_image_directory _execute_cmd_shell(download_1_string) _execute_cmd_shell(download_2_string) _execute_cmd_shell(download_3_string) _execute_cmd_shell(download_4_string) #image cleaning and validation _execute_cmd_shell(clean_positive_image_cmd) _execute_cmd_shell(clean_negative_image_cmd) def __extract_url_cfg_files_from_directory(image_url_directory_path): result_list = [] for cfg_file in os.listdir(image_url_directory_path): if cfg_file.split('.')[1] == 'cfg': print "loading config file for download : {0}".format(image_url_directory_path+'/'+cfg_file) result_list.append(image_url_directory_path+'/'+cfg_file) return result_list def _execute_using_cfg_file(cfg_file_): print "Loading data from cfg file {0}".format(cfg_file_) data = "" with open(cfg_file_,'r') as file: data =file.read() #setup initial variables data = data.split('\n') image_url_list = [] path_to_not_valid_image = '' path_to_positive_image_directory = '' path_to_negative_image_directory = '' path_to_image_validator_script = '' path_to_image_downloader_script = '' python_prefix = 'python' print "Parsing Config File....." #parsing cfg options for line in data: if line.split('=')[0].strip() == 'path_to_image_url_directory': image_url_list = __extract_url_cfg_files_from_directory(line.split('=')[1].strip()) elif line.split('=')[0].strip() == 'path_to_not_valid_image': path_to_not_valid_image = line.split('=')[1].strip() elif line.split('=')[0].strip() == 'path_to_positive_image_directory': path_to_positive_image_directory = line.split('=')[1].strip() elif line.split('=')[0].strip() == 'path_to_negative_image_directory': path_to_negative_image_directory = line.split('=')[1].strip() elif line.split('=')[0].strip() == 'path_to_image_validator_script': path_to_image_validator_script = line.split('=')[1].strip() elif line.split('=')[0].strip() == 'path_to_image_downloader_script': path_to_image_downloader_script = line.split('=')[1].strip() #download scritps executions print "Executing Downloading Step" image_downloader_script_prefix = python_prefix + ' ' + path_to_image_downloader_script for cfg_file in image_url_list: _execute_cmd_shell(image_downloader_script_prefix + ' ' +cfg_file) print "Cleannig and validating image downloaded" clean_positive_image_cmd ='python ' + path_to_image_validator_script + ' ' + path_to_not_valid_image + ' ' + path_to_positive_image_directory clean_negative_image_cmd = 'python ' + path_to_image_validator_script + ' ' + path_to_not_valid_image + ' ' +path_to_negative_image_directory print "cmd to execute: {0}".format(clean_positive_image_cmd) print "cmd to execute: {0}".format(clean_negative_image_cmd) _execute_cmd_shell(clean_positive_image_cmd) _execute_cmd_shell(clean_negative_image_cmd) if __name__ == '__main__': #_execute() _execute_using_cfg_file(sys.argv[1]) <file_sep>/detectors/haar_face_detector/detector_haar.py import sys import numpy as np import cv2 class HaarDetector(object): __IMAGE_SCALE_FACTOR = 1.2 __IMAGE_MIN_NEIGHBORS = 5 def __init__(self, xml_file_trainning_detector): self.__face_classifier = cv2.CascadeClassifier(xml_file_trainning_detector) self.__faces = None def __create_action_handler(self): self.__ACTION_HANDLER = { 'face_count',self.get_face_count} def get_face_count(self): return len(self.__faces) def face_detection_data(self, raw_image): self.__faces = None grey_image = self.__preprocess_image(raw_image) self.__faces = self.__face_classifier.detectMultiScale(grey_image, self.__IMAGE_SCALE_FACTOR , self.__IMAGE_MIN_NEIGHBORS, minSize=(50, 50)) def __preprocess_image(self, raw_image): gray_scale_image = cv2.cvtColor(raw_image , cv2.COLOR_BGR2GRAY) return gray_scale_image def __verify_image_size(self): pass def execute_action(self, action_to_execute): return self.__ACTION_HANDLER[action_to_execute]() if __name__ == '__main__': face_detector = HaarDetector(sys.argv[1]) face_detector.face_detection_data(cv2.imread(sys.argv[2])) print "cantidad de caras: {0}".format(face_detector.get_face_count())<file_sep>/README.md # face_detector Face Detector Service: Service used to detect the amount of faces in a image. At this moment this detector use HAAR Detector (opencv haar detector). It is trainning with custom images. rigth now it is not working correctly. Is in face of developing Dependency: flask OpenCv 3.1 (compiled from source) numpy Keras Command line Options: FaceDetector command line options: * Running Pre-setup trainning steps -This steps download and validate image urls specified in config files setting in directories <Directory_url_image> and have specific config file for managed this image. It contains the followings item: - path_to_image_downloader_script = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/pre-trainning-setup/image_downloader/image_downloader.py - path_to_image_url_directory = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/pre-trainning-setup/image_downloader/config - path_to_not_valid_image = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/pre-trainning-setup/validation_image_script_test/image_not_valid_list.txt - path_to_positive_image_directory = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/tests/positive_image - path_to_negative_image_directory = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/trainning/negative_images - path_to_image_validator_script = /home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/pre-trainning-setup/validation_image_script_test/image_validator_script.py -Image urls: All image used for trainnign propourses are specified in this directory: * /face_detector/pre-trainning-setup/image_downloader/config Each .cfg file contains optios to downlaod specific files .txt from the directory python face_detector_manager.py -s ./config/haar_detector/haar_trainning.cfg Trainning Help Running <file_sep>/service/detector_service.py import sys, getopt, os import uuid from uuid import uuid4 import cv2 import logging import time sys.path.insert(0,'../../../face_detector') sys.path.insert(0,'../../face_detector') sys.path.insert(0,'../face_detector') from flask import Flask, request, redirect, url_for, json from werkzeug.utils import secure_filename from detectors.haar_face_detector.detector_haar import FaceDetector app = Flask(__name__) logging.basicConfig(stream=sys.stdout, level=logging.INFO) app.config['UPLOAD_FOLDER']='/home/ricardo/Desktop/CODIGO/ComputerVision/face_detector/service/temporal' CONFIG_DATA_DICT = {} facedetector = None @app.route("/") def main(): return "Face Detector Service" @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST': file = request.files['file'] extension = os.path.splitext(file.filename)[1] f_name = str(uuid.uuid4()) + extension full_name = os.path.join(app.config['UPLOAD_FOLDER'], f_name) file.save(full_name) time.sleep(1) facedetector.face_detection_data(cv2.imread(full_name)) return json.dumps({'Amount Faces: ':str(facedetector.get_face_count())}) return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Detect Faces> </form> ''' def parse_cfg_option(cfg_file): with open(cfg_file, 'r') as cfg_file: data = cfg_file.read() data = data.split('\n') for line in data: if len(line)>0: if line.split('=')[0].strip() == 'weigth_path': CONFIG_DATA_DICT['weigth_path']=line.split('=')[1].strip() if __name__ == "__main__": parse_cfg_option(sys.argv[1]) facedetector = FaceDetector(CONFIG_DATA_DICT['weigth_path']) app.run(debug = True) <file_sep>/detectors/detector_manager/detector_manager.py from detector_package_manager import DetectorConfig class DetectorManager(object): def __init__(self, config_file): config = DetectorConfig(config_file) self.__detector_list = config.get_detectors_list() self.__config_return_data() def __config_return_data(self): for detector in self.__detector_list: self.__return_data[detector.feature]="" def process_data(self, raw_image): self.__return_data = {} for detector in self.__detector_list: self.__return_data[detector.feature] = str(detector.process_data(raw_image)) return self.__return_data <file_sep>/utils/image_utils.py import cv2 class ImageManipulation(object): def __init__(self): pass @staticmethod def histogram_esqualization(img, img_width, img_height): #Histogram Equalization img[:, :, 0] = cv2.equalizeHist(img[:, :, 0]) img[:, :, 1] = cv2.equalizeHist(img[:, :, 1]) img[:, :, 2] = cv2.equalizeHist(img[:, :, 2]) return img @staticmethod def rezize_image(img_width, img_height): #Image Resizing return cv2.resize(img, (img_width, img_height), interpolation = cv2.INTER_CUBIC)<file_sep>/trainning/haar_trainning/trainning_setup.py import os, sys class HaarSetupTools(object): NEGATIVE_FILE_NAME_STRING = 'bg.txt' POSITIVE_FILE_NAME_STRING = 'info.lst' EMPTY_STRING ="" POSITIVE_HAAR_SETUP_STRING = ' 1 0 0 50 50' def __init__(self, negative_directory, positive_directory): self.__negative_directory=negative_directory self.__positive_directory=positive_directory def create_setup_for_haar_samples(self ,work_directory, haar_setup_filename ,string_to_attach): string_to_store = "" file_count = 0 with open(haar_setup_filename,'a') as file_to_store: for file_name in os.listdir(work_directory): string_to_store = work_directory + '/' + file_name + string_to_attach +'\n' file_to_store.write(string_to_store) file_count += 1 print"Total Files: {0} in filename : {1} ".format(str(file_count), haar_setup_filename) def _execute(negative_directory, positive_directory): setup_tools = HaarSetupTools(negative_directory, positive_directory) setup_tools.create_setup_for_haar_samples(negative_directory,HaarSetupTools.NEGATIVE_FILE_NAME_STRING,HaarSetupTools.EMPTY_STRING) setup_tools.create_setup_for_haar_samples(positive_directory,HaarSetupTools.POSITIVE_FILE_NAME_STRING,HaarSetupTools.POSITIVE_HAAR_SETUP_STRING) if __name__ == '__main__': _execute(sys.argv[1], sys.argv[2])<file_sep>/Preprocessing/image_intensity_normalizer.py ''' Image normalizer based on this paper https://www.researchgate.net/publication/281118372_NumPy_SciPy_Recipes_for_Image_Processing_Intensity_Normalization_and_Histogram_Equalization ''' import numpy class ImageNormalizer(object): def __init__(self): <file_sep>/detectors/detector_manager/detector_package_manager.py from hog_detector import HOGDetector from haar_face_detector import HaarDetector from caffe_gender_detector import GenderDetector class DetectorConfig(object): __COMMENT_TOKEN = "#" __DETECTOR_LIST_TOKEN = "[detector_list]" __DETECTOR_CONF_TOKEN = "[conf]" def __init__(self, config_file): self.__detector_list = [] self.__parse_file(config_file) self.__detector_list_name =[] self.__detector_config_file_list = {} def __parse_file(self, config_file): with open(config_file, 'r') as input_file: data = input_file.readLines() data = data.split('\n') data = self.__remove_comment_lines(data) self.__get_detector_list(data) self.__get_config_files_for_detectors(data) self.__create_detector_from_config() def __remove_comment_lines(self, data): for line in data: if line.strip()[0] == self.__COMMENT_TOKEN: data.remove(line) return data def __get_detector_list(self, data): is_detector_list = False for item in data: if item.strip() == self.__DETECTOR_LIST_TOKEN: is_detector_list = True elif is_detector_list: self.__detector_list_name.append(item) elif is_detector_list == self.__DETECTOR_CONF_TOKEN: is_detector_list = False def __get_config_files_for_detectors(self, data): is_detector_config_token = False for item in data: if item.strip() == self.__DETECTOR_LIST_TOKEN: is_detector_config_token = True elif is_detector_list: self.__detector_config_file_list[item.strip().split("=")[0].strip()] = item.strip().split("=")[1].strip() elif is_detector_list == self.__DETECTOR_CONF_TOKEN: is_detector_config_token = False def __pre_check(self): if len(self.self.__detector_list_name) == 0: raise Exception("No Detector Process were found in config files!") if len(self.self.__detector_config_file_list) == 0: raise Exception("No Configuration file for Detector Process were found in config files!") if len(self.self.__detector_list_name) == len(self.self.__detector_config_file_list): raise Exception("Detector Process and config files have to come in pairs!") def __create_detector_from_config(self): self.__pre_check() for items in self.__detector_list_name: config_file = self.__detector_config_file_list[items.strip().split("=")[0]] if items.strip().split("=")[1] == "HOG": self.__detector_list(HOGDetector(config_file)) if items.strip().split("=")[1] == "CAFFE_GENDER": self.__detector_list(HOGDetector(config_file)) if items.strip().split("=")[1] == "HAAR": self.__detector_list(HaarDetector(config_file)) <file_sep>/detectors/hog_detector/hog_detector.py import sys import dlib from skimage import io import cv2 class HOGDetector(object): def __init__(self): self.__detector = dlib.get_frontal_face_detector() self.__faces = None def detect(self, raw_image): img = raw_image self.__faces = None self.__faces = self.__detector(img, 1) def face_count(self): return len(self.__faces) def get_faces_roi_list(self): return self.__faces if __name__ == '__main__': detector = HOGDetector() image = cv2.imread(sys.argv[1]) detector.detect(image) print "Cantidad de Caras: {0}".format(str(detector.face_count())) <file_sep>/pre-trainning-setup/image_downloader/image_downloader.py import sys, getopt sys.path.insert(0,'../../../face_detector') sys.path.insert(0,'../../face_detector') sys.path.insert(0,'../face_detector') from utils.image_database_downloader import ImageDownloader def _execute_download(image_prefix, imager_url, total_image_count , directory, image_format, trainning_type, negative_scale, positive_scale): downloader = ImageDownloader(image_prefix,imager_url, total_image_count, int(negative_scale), int(positive_scale)) downloader.download_files(directory, image_format, trainning_type) def __parse_config_file_and_execute(config_file_path): config_data = "" with open(config_file_path, 'r') as image_file: config_data = image_file.read() config_data = config_data.split('\n') diccionary_option = [] for item in config_data: item = item.strip() if len(item)>1: value = item.split('=') diccionary_option.append(value[1].strip()) _execute_download(*diccionary_option) #if __name__ == '__main__': # _execute_download(sys.argv[1],sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) if __name__ == '__main__': __parse_config_file_and_execute(sys.argv[1]) <file_sep>/trainning/haar_trainning/train_manager.py ''' opencv_createsamples -info info.lst -num 2000 -w 30 -h 30 -vec positives.vec opencv_traincascade -data data -vec positives.vec -bg bg.txt -numPos 1800 -numNeg 900 -numStages 15 -w 30 -h 30 & ''' import sys import subprocess class HaarTrainning(object): __OPENCV_CMD_TO_TRAIN = 'opencv_createsamples' __OPENCV_TO_TRAIN_HAAR = 'opencv_traincascade' __PRE_TRAINNING_SCRIPT = 'python trainning_setup.py' def __create_cmd_line_option_dict(self): self.__CMD_OPTIONS = { '-info' : '',\ '-num' : '',\ '-w' : '',\ '-h' : '',\ '-vec' : '',\ '-data':'',\ '-bg':'',\ '-numPos':'',\ '-numNeg':'',\ '-numStages':'',\ 'path_to_positive_image_directory' : '',\ 'path_to_negative_image_directory' : '' } def __init__(self, cfg_file): self.__CMD_TO_EXECUTE = "" self.__create_cmd_line_option_dict() self.__data_list = [] self.__load_data_from_cfg_file(cfg_file) def __execute_cmd_shell(self, cmd_to_execute): p = subprocess.Popen(cmd_to_execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, retval = p.wait() def train_haar_detector(self): self.__create_pretrainning_script_step() print "Cmd to execute: {0}".format(self.__CMD_TO_EXECUTE) self.__execute_cmd_shell('pwd; clear') self.__execute_cmd_shell(self.__CMD_TO_EXECUTE) self.__create_vect_cmd_from_options() print "Cmd to execute: {0}".format(self.__CMD_TO_EXECUTE) self.__execute_cmd_shell(self.__CMD_TO_EXECUTE) self.__create_trainning_cmd_from_options() print "Cmd to execute: {0}".format(self.__CMD_TO_EXECUTE) #self.__execute_cmd_shell(self.__CMD_TO_EXECUTE) def __process_line(self, string_to_compare, line): processed = False if string_to_compare == line.split('=')[0].strip(): self.__CMD_OPTIONS[line.split('=')[0].strip()] = line.split('=')[1].strip() processed = True return processed def __load_data_from_cfg_file(self, cfg_file): with open(cfg_file, 'r') as cfg_file: data= cfg_file.read() self.__data_list = data.split('\n') for line in self.__data_list: for key, values in self.__CMD_OPTIONS.iteritems(): if self.__process_line(key, line): break def __create_vect_cmd_from_options(self): self.__CMD_TO_EXECUTE = self.__OPENCV_CMD_TO_TRAIN +' -info '+self.__CMD_OPTIONS['-info'] \ + ' -num ' + self.__CMD_OPTIONS['-num']\ + ' -w ' + self.__CMD_OPTIONS['-w']\ + ' -h ' + self.__CMD_OPTIONS['-h']\ + ' -vec ' + self.__CMD_OPTIONS['-vec'] def __create_trainning_cmd_from_options(self): self.__CMD_TO_EXECUTE = self.__OPENCV_TO_TRAIN_HAAR + ' -data ' + self.__CMD_OPTIONS['-data']\ + ' -vec '+ self.__CMD_OPTIONS['-vec']\ + ' -bg '+ self.__CMD_OPTIONS['-bg']\ + ' -numPos '+ self.__CMD_OPTIONS['-numPos']\ + ' -numNeg '+ self.__CMD_OPTIONS['-numNeg']\ + ' -numStages '+ self.__CMD_OPTIONS['-numStages']\ + ' -w '+ self.__CMD_OPTIONS['-w']\ + ' -h '+ self.__CMD_OPTIONS['-h'] + ' &' def __create_pretrainning_script_step(self): self.__CMD_TO_EXECUTE = self.__PRE_TRAINNING_SCRIPT + ' '+ self.__CMD_OPTIONS['path_to_negative_image_directory'] \ + ' ' + self.__CMD_OPTIONS['path_to_positive_image_directory'] if __name__ == '__main__': haar_trainning = HaarTrainning(sys.argv[1]) haar_trainning.train_haar_detector() <file_sep>/detectors/caffe_gender_detector/caffe_gender_age_detector.py import numpy as np import cv2 import caffe import sys class GenderDetector(object): __NET_FILE_NAME = 'net_filename' __TRAINNED_WEIGTH_FILE_NAME = 'trainned_weigth_file_name' __TRANSFORMER_MEAN_FILE_NAME = 'transformer_mean_file_name' __TRANSFORMER_INPUT_BLOB_NAME = 'transformer_input_blob_name' __TRANSFORMER_INPUT_MEAN_IMAGE_FILE_NAME = 'transformer_input_image_mean_filename' __TRANSFORMER_TRANSPOSE_TUPLE = 'transformer_transpose_tuple' __TRANSFORMER_CHANNEL_SWAP_TUPLE = 'transformer_channel_swap_tuple' __TRANSFORMER_RAW_SCALE = 'transformer_raw_scale' __IMAGE_RESIZE_WIDTH = 'image_resize_width' __IMAGE_RESIZE_HEIGTH = 'image_resize_heigth' __IMAGE_BACTH_SIZE = 'image_batch_size' def __init__(self, config_diccionary_options): caffe.set_mode_cpu() if config_diccionary_options: self.__net =caffe.Load(config_diccionary_options[self.__NET_FILE_NAME]\ , config_diccionary_options[self.__TRAINNED_WEIGTH_FILE_NAME], caffe.TEST) self.__load_transformer_settings(config_diccionary_options) def __load_transformer_settings(self, config_dictionary_options): input_blob_name = config_dictionary_options[self.__TRANSFORMER_INPUT_BLOB_NAME] input_mean_image_file_name = config_dictionary_options[self.__TRANSFORMER_INPUT_MEAN_IMAGE_FILE_NAME] transpose_tuple = config_dictionary_options[self.__TRANSFORMER_TRANSPOSE_TUPLE] channel_swap_tuple = config_dictionary_options[self.__TRANSFORMER_TRANSPOSE_TUPLE] raw_scale = config_dictionary_options[self.__TRANSFORMER_RAW_SCALE] self.__transformer = caffe.io.Transformer({input_blob_name: net.blobs[input_blob_name].data.shape}) self.__transformer.set_mean(input_blob_name, np.load(input_mean_image_file_name).mean(1).mean(1)) self.__transformer.set_transpose(input_blob_name, transpose_tuple) self.__transformer.set_channel_swap(input_blob_name, channel_swap_tuple) self.__transformer.set_raw_scale(input_blob_name, raw_scale) def __reshape_input_blob(self, config_dictionary_options): image_width = int(config_dictionary_options[self.__IMAGE_RESIZE_WIDTH]) image_heigth = int(config_dictionary_options[self.__IMAGE_RESIZE_HEIGTH]) image_batch_size = int(config_dictionary_options[self.__IMAGE_BACTH_SIZE]) input_blob_name = config_dictionary_options[self.__TRANSFORMER_INPUT_BLOB_NAME] self.__net.blobs[input_blob_name].reshape(image_batch_size,3,image_width,image_heigth) def classify_image(self, image_file_name): im = caffe.io.load_image(image_file_name) image = cv2.imread(image_file_name) net.blobs['data'].data[...] = image out = net.forward() return out['prob'].argmax() if __name__ == '__main__': gender_detector = GenderDetector(None) <file_sep>/detectors/keras_detector/keras_detector.py from keras.models import Sequential from keras.layers.convolutional import Convolution2D from keras.layers.convolutional import MaxPooling2D from keras.layers.core import Activation from keras.layers.core import Flatten from keras.layers.core import Dense class KerasDetector(object): def __init__(self, width, heigth, depth, classes, path_to_weigth): self.__model= Sequential()
de675a6840693151a37df76dcf584ba0da64d37a
[ "Markdown", "Python" ]
18
Python
RicardoRodriguezArg/face_detector
9523cce0f6b87caa3fb21d7c7228eb19bc6ff1c4
2c3d3b674b769497656a81e1a29df03743fb197c
refs/heads/master
<file_sep>CHIP-8 ========================== [CHIP-8](http://en.wikipedia.org/wiki/CHIP-8) emulator -------------------------- This project is for my own educational purposes. <file_sep>#include <stdint.h> class c8{ private: uint16_t opcode; // unsigned short is 2 bytes uint8_t mem[4096]; // unsigned char is 1 byte uint8_t V[16]; uint16_t I; uint16_t PC; uint8_t gfx[64 * 32]; uint8_t delay_timer; uint8_t sound_timer; uint16_t stack[16]; uint16_t SP; uint8_t key[16]; uint8_t c8_font[80] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80 // F }; public: c8(); void setupEmulator(); void load(char* ROM); void tick(); void setKey(); void clearDisplay(); bool dFlag; };<file_sep>//#include <SDL.h> #include "chip8.h" int main(int argc, char **argv){ //setupGraphics(); //setupInput(); c8* myChip = new c8(); myChip->load(argv[0]); while (1){ myChip->tick(); //if (myChip->dFlag) myChip->drawGraphics(); myChip->setKey(); } return 0; }<file_sep>#include "chip8.h" #include <random> #include <iostream> using namespace std; c8::c8(){ setupEmulator(); } void c8::setupEmulator(){ PC = 0x200; opcode = 0; I = 0; SP = 0; /* Clear Memory and Graphics Display */ for (int i = 0; i < 4096; i++){ mem[i] = 0; if (i <= 2048){ gfx[i] = 0; } } /* Clear Stack, Registers, and Keypad */ for (int i = 0; i < 16; i++){ stack[i] = 0; V[i] = 0; key[i] = 0; } /* Load in fontset */ for (int i = 0; i < 80; i++){ mem[i] = c8_font[i]; } /* Reseting Timers */ delay_timer = 0; sound_timer = 0; } void c8::tick(){ /* Fetch Opcode */ opcode = mem[PC + 0]; opcode <<= 8; opcode |= mem[PC + 1]; switch ((opcode & 0xF000)){ cout << hex << opcode << endl; case 0x0000: // good luck, lad. break; case 0x1000: PC = opcode & 0x0FFF; break; case 0x2000: //hmmm stack[SP] = PC; SP++; PC = (opcode & 0x0FFF); break; case 0x3000: if (V[(opcode & 0x0F00) >> 8] == opcode & 0x00FF){ PC = PC + 4; } else{ PC = PC + 2; } break; case 0x4000: if (V[(opcode & 0x0F00) >> 8] != opcode & 0x00FF){ PC = PC + 4; }else{ PC = PC + 2; } break; case 0x5000: if (V[(opcode & 0x0F00) >> 8] == V[(opcode & 0x00F0) >> 4]){ PC = PC + 4; } else{ PC = PC + 2; } break; case 0x6000: V[(opcode & 0x0F00) >> 8] = opcode & 0x00FF; PC = PC + 2; break; case 0x7000: V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] + (opcode & 0x00FF); PC = PC + 2; break; case 0xA000: I = opcode & 0x0FFF; PC = PC + 2; break; case 0xB000: PC = (opcode & 0x0FFF) + V[0]; break; case 0xC000: V[(opcode & 0x0F00) >> 8] = ((rand() % 256) & (opcode & 0x00FF)); PC = PC + 2; break; case 0xD000: break; } switch((opcode & 0xF00F)){ cout << hex << opcode << endl; case 0x8000: V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; case 0x8001: V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] | V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; case 0x8002: V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] & V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; case 0x8003: V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] ^ V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; case 0x8004: V[(opcode & 0x0F00) >> 8] + V[(opcode & 0x00F0) >> 4] > 255 ? V[15] = 1 : V[15] = 0; V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] + V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; // hmmmm, should be fine. case 0x8005: V[(opcode & 0x0F00) >> 8] - V[(opcode & 0x00F0) >> 4] < 0 ? V[15] = 0 : V[15] = 1; V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x0F00) >> 8] - V[(opcode & 0x00F0) >> 4]; PC = PC + 2; break; case 0x8006: V[15] = V[(opcode & 0x0F00) >> 8] & 0x01; V[(opcode & 0x0F00) >> 8] = V[((opcode & 0x0F00) >> 8)] >> 1; PC = PC + 2; break; case 0x8007: V[(opcode & 0x00F0) >> 4] - V[(opcode & 0x0F00) >> 8] < 0 ? V[15] = 0 : V[15] = 1; V[(opcode & 0x0F00) >> 8] = V[(opcode & 0x00F0) >> 4] - V[(opcode & 0x0F00) >> 8]; PC = PC + 2; break; case 0x800E: V[15] = V[(opcode & 0x0F00) >> 8] & 0x80; V[(opcode & 0x0F00) >> 8] = V[((opcode & 0x0F00) >> 8)] << 1; PC = PC + 2; break; case 0x9000: V[(opcode & 0x0F00) >> 8] != V[(opcode & 0x00F0) >> 4] ? PC = PC + 4 : PC = PC + 2; break; } switch ((opcode & 0xF0FF)){ cout << hex << opcode << endl; case 0xE09E: key[V[(opcode & 0x0F00)>>8]] == 1 ? PC = PC + 4 : PC = PC + 2; break; case 0xE0A1: key[V[(opcode & 0x0F00)>>8]] == 0 ? PC = PC + 4 : PC = PC + 2; break; case 0xF007: V[(opcode & 0x0F00) >> 8] = delay_timer; PC = PC + 2; break; /* Only one key allowed to be pressed at a single time * */ case 0xF00A: for(int i = 0; i < 16; i++){ if(key[i] == 1){ V[(opcode & 0x0F00)>>8] = key[i]; } } PC = PC + 2; break; case 0xF015: delay_timer = V[((opcode & 0x0F00) >> 8)]; PC = PC + 2; break; case 0xF018: sound_timer = V[((opcode & 0x0F00) >> 8)]; PC = PC + 2; break; case 0xF01E: I = I + V[((opcode & 0x0F00) >> 8)]; PC = PC + 2; break; case 0xF029: break; case 0xF033: break; case 0xF055: for(int i = 0; i < (((opcode & 0x0F00) >> 8) + 1); i++){ mem[I+i] = V[i]; } PC = PC + 2; break; case 0xF065: break; } switch(opcode & 0xFFFF){ cout << hex << opcode << endl; case 0x00E0: for (int i = 0; i < 4096; i++){ gfx[i] = 0; } PC = PC + 2; break; case 0x00EE: break; } } void c8::load(char* a){ } void c8::clearDisplay(){ }
8692463f77868c3ed4d27b53d973863dec909725
[ "Markdown", "C++" ]
4
Markdown
salkj/chip8
a1e8ddaeea3ff68210e16745b461d5bf39973f64
a4d99b0e65da6815d7f2a2dbf16d623bf593e0b7
refs/heads/master
<repo_name>Chris-Chang/JavaSenior<file_sep>/jdbc_1/src/com/chang1/connection/ConnectionTest.java package com.chang1.connection; import org.junit.Test; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-08 10:23 */ public class ConnectionTest { //方式一 @Test public void connectionTest1() throws SQLException { //获取Driver的实现类对象 Driver driver = new com.mysql.jdbc.Driver(); String url = "jdbc:mysql://localhost:3306/test"; Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password","<PASSWORD>"); Connection conn = driver.connect(url, info); System.out.println(conn); } //方式二 @Test public void connectionTest2() throws Exception { //1.获取Driver的实现类对象,使用反射 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance(); //2.提供要连接的数据库 String url = "jdbc:mysql://localhost:3306/test"; //3.提供连接需要的用户名和密码 Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password","<PASSWORD>"); //4.获取连接 Connection conn = driver.connect(url, info); System.out.println(conn); } //方式三:使用DriverManager替换Driver @Test public void connectionTest3() throws Exception{ //1.提供另外三个连接的基本信息 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "<PASSWORD>"; //2.获取Driver的实现类对象,使用反射 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance(); //3.注册驱动 DriverManager.registerDriver(driver); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } //方式四:使用DriverManager替换Driver @Test public void connectionTest4() throws Exception{ //1.提供另外三个连接的基本信息 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "<PASSWORD>"; //2.加载Driver的实现类到内存,(静态代码块随着类的加载而执行) Class.forName("com.mysql.jdbc.Driver"); //相较于方式三可以省略如下操作 // Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance(); // //注册驱动 // DriverManager.registerDriver(driver); //为什么可以省略如上操作?在mysql实现类中,声明了如下操作 /** * *static { *try { *java.sql.DriverManager.registerDriver(new Driver()); *} catch (SQLException E) { *throw new RuntimeException("Can't register driver!"); *} *} */ //3. 获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } //方式五(final版):将数据库连接的四个基本信息声明在配置文件中,通过读取配置文件的方式获取连接 //实现了数据与代码的分离,实现了解耦 //如果修改配置文件信息,可以避免程序重新打包 @Test public void connectionTest5() throws Exception { //1.读取配置文件的基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } } <file_sep>/day12/src/com/chang/java4/Girl.java package com.chang.java4; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-06 17:06 */ public class Girl { private String name; @Override public String toString() { return "Girl{" + "name='" + name + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Girl() { } public Girl(String name) { this.name = name; } } <file_sep>/day10/src/com/chang/java1/TCPTest2.java package com.chang.java1; import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * 实现TCP的网络编程 * 例题2:客户端发送文件给服务端,服务端将文件保存到本地 * @Description * @Author <NAME> * @Version * @Time 2020-04-01 14:53 */ public class TCPTest2 { @Test public void client(){ Socket socket = null; OutputStream os = null; FileInputStream fis = null; try { //1. InetAddress inet = InetAddress.getByName("127.0.0.1"); socket = new Socket(inet,8848); //2返回此套接字的输出流。. os = socket.getOutputStream(); //3. fis = new FileInputStream(new File("book.jpg")); //4. byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1){ os.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void server(){ ServerSocket ss = null; Socket socket = null; InputStream is = null; FileOutputStream fops = null; try { //1. ss = new ServerSocket(8848); socket = ss.accept(); is = socket.getInputStream(); fops = new FileOutputStream(new File("book3.jpg")); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1){ fops.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fops != null){ try { fops.close(); } catch (IOException e) { e.printStackTrace(); } } if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(ss != null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } } <file_sep>/day11/src/com/chang/java2/ReflectionTest.java package com.chang.java2; import com.chang.java1.Person; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 调用运行时类中指定的结构:属性,方法,构造器 * @Description * @Author <NAME> * @Version * @Time 2020-04-04 9:47 */ public class ReflectionTest { /** * */ @Test public void testField() throws Exception { Class clazz= Person.class; //创建运行时类的对象 Person p = (Person)clazz.getDeclaredConstructor().newInstance(); //获取指定的属性 //通常不采用此方法 Field id = clazz.getField("id"); /** * 设置当前属性的值 * set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少 */ id.set(p, 1001); /** * 获取当前属性的值 * get():参数1:获取哪个对象的当前属性值 */ int pId = (int) id.get(p); System.out.println(pId); } /** * 如何操作运行时类中指定的属性--需要掌握 * @throws Exception */ @Test public void testField1() throws Exception{ Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.getDeclaredConstructor().newInstance(); //1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性 Field name = clazz.getDeclaredField("name"); //2. 保证当前属性是可访问的 name.setAccessible(true); //3.获取,设定指定对象的此属性值 name.set(p,"Chang"); System.out.println(name.get(p)); } /** * * 如何操作运行时类中指定的方法--需要掌握 * @throws Exception */ @Test public void testMethod() throws Exception{ Class clazz = Person.class; //创建运行时类的对象 Person p = (Person) clazz.getDeclaredConstructor().newInstance(); //1. getDeclaredMethod():参数1指明获取的方法名称 参数2指明获取的方法的形参列表 Method show = clazz.getDeclaredMethod("show", String.class); //2. 保证当前方法是可访问的 show.setAccessible(true); //调用方法的invoke():参数1:方法的调用者,参数2:给方法形参赋值的实参 //invoke()方法的返回值即为对应类中调用方法的返回值 Object returnValue = show.invoke(p, "中国"); System.out.println(returnValue); //获取静态方法 // private static void showDesc(){ Method showDesc = clazz.getDeclaredMethod("showDesc"); showDesc.setAccessible(true); //如果调用的运行时类中的方法没有返回值,则此invoke()返回null // Object returnVal = showDesc.invoke(null); Object returnVal = showDesc.invoke(clazz); System.out.println(returnVal); } @Test public void testConstructor() throws Exception{ Class clazz = Person.class; // private Person(String name, int age){ /** * 1. 获取指定的构造器 * getDeclaredConstructor(),参数:指明构造器的形参列表 * */ Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class); //2.保证此构造器是可访问的 constructor.setAccessible(true); //3.调用此构造器,创建运行时类的对象 Person p = (Person)constructor.newInstance("Tom", 18); System.out.println(p); } } <file_sep>/day12/src/com/chang/java3/StreamAPITest.java package com.chang.java3; import com.chang.java2.Employee; import com.chang.java2.EmployeeData; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; /** * 1.stream关注的是对数据的运算,与cpu打交道 * 集合关注的是数据的存储,与内存打交道 * * 2. * 2.1 Stream 自己不会存储元素 * 2.2 Stream不会改变源对象,相反,他们会返回一个持有结果的新Stream * 2.3 Stream操作是延迟执行的,这意味着他们会等到需要结果的时候才执行 * 3.Stream的执行流程 * 3.1 Stream 的实例化 * 3.2 一系列的中间操作(过滤、映射、、、) * 3.3 终止操作 * * 4.说明 * 4.1 一个中间操作链,对数据源的数据进行处理 * 4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用 * * * 测试Stream的实例化 * @Description * @Author <NAME> * @Version * @Time 2020-04-06 11:57 */ public class StreamAPITest { //创建Stream方式一:通过集合 @Test public void test1(){ List<Employee> employees = EmployeeData.getEmployees(); //返回一个顺序流 Stream<Employee> stream = employees.stream(); //返回一个并行流 Stream<Employee> parallelStream = employees.parallelStream(); } //创建Stream方式二:通过数组,调用Arrays.stream @Test public void test2(){ int[] arr = new int[]{1,2,3,4,5,6}; IntStream stream = Arrays.stream(arr); Employee e1 = new Employee(1001,"Tom"); Employee e2 = new Employee(1002,"Jerry"); Employee[] arr1 = new Employee[]{e1,e2}; Stream<Employee> stream1 = Arrays.stream(arr1); } //创建stream方式三:通过Stream的of @Test public void test3(){ Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); } //创建Stream方式四:创建无限流 @Test public void test4(){ //迭代 //遍历前10个偶数 Stream.iterate(0,t -> t+2).limit(10).forEach(System.out::println); //生成 Stream.generate(Math::random).limit(10).forEach(System.out::println); } } <file_sep>/jdbc_2/src/com/chang4/connection/C3P0Test.java package com.chang4.connection; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-10 9:24 */ public class C3P0Test { @Test public void testConnection() throws Exception { //获取c3p0数据库连接池 ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test" ); cpds.setUser("root"); cpds.setPassword("<PASSWORD>"); //通过设置相关的参数, 对数据库连接池进行管理 //设置初始时数据库连接池中的连接数 cpds.setInitialPoolSize(10); Connection conn = cpds.getConnection(); System.out.println(conn); //销毁c3p0连接池 DataSources.destroy(cpds); } //方式二:配置文件 @Test public void testConnection1() throws SQLException { ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0"); Connection conn = cpds.getConnection(); System.out.println(conn); } } <file_sep>/jdbc_2/src/com/chang3/dao/CustomerDAO.java package com.chang3.dao; import com.chang2.bean.Customer; import java.sql.Connection; import java.sql.Date; import java.util.List; /** * 此接口用于规范customer表的常用操作 * * @Description * @Author <NAME> * @Version * @Time 2020-04-09 20:37 */ public interface CustomerDAO { /** * 将cust对象添加到数据库中 * * @param conn * @param cust */ void insert(Connection conn, Customer cust); /** * 针对指定的Id删除表中的一条数据 * * @param conn * @param id */ void deleteById(Connection conn, int id); /** * 针对内存中的cust对象,去修改数据表中指定的记录 * * @param con * @param cust */ void update(Connection conn, Customer cust); /** * 针对指定的id查询得到对应的Customer对象 * * @param conn * @param id * @return */ Customer getCustomerById(Connection conn, int id); /** * 查询表中所有记录构成的集合 * * @param conn * @return */ List<Customer> getAll(Connection conn); /** * 返回数据表中数据的条目数 * * @param conn * @return */ Long getCount(Connection conn); /** * 返回数据表中最大生日 * * @param conn * @return */ Date getMaxBirth(Connection conn); } <file_sep>/jdbc_2/src/com/chang2/dao/junit/CustomerDAOImplTest.java package com.chang2.dao.junit; import org.junit.Test; import static org.junit.Assert.*; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-09 21:24 */ public class CustomerDAOImplTest { @Test public void insert() { } @Test public void deleteById() { } @Test public void update() { } @Test public void getCustomerById() { } @Test public void getAll() { } @Test public void getCount() { } @Test public void getMaxBirth() { } }<file_sep>/day13/src/com/chang/java1/Java10Test.java package com.chang.java1; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-07 15:47 */ public class Java10Test { /** * java10的新特性1:局部变量的类型推断 */ @Test public void test1(){ // int num = 10; //声明变量时,根据所赋的值,推断变量的类型 var num = 10; var list = new ArrayList<String>(); list.add("Tom"); //2.遍历操作 for(var i : list){ System.out.println(i); System.out.println(i.getClass()); } //3.普通遍历操作 for(var i = 0;i < 100;i++){ System.out.println(i); } } @Test public void test2(){ //1.局部变量不赋值就不能实现类型推断 // var num; //2. Lambda表达式中,左边的函数式接口不能声明为var // Supplier<Double> sup = () -> Math.random(); // var sup = () -> Math.random(); //3.方法引用中,左边的函数式接口不能声明为var // Consumer<String> con = System.out::print; // var con = System.out::print; //4.数组静态初始化中 int[] arr = new int[]{1,2,3,4}; var arr1 = new int[]{1,2,3,4}; int[] arr3 = {1,2,3,4}; // var arr2 = {1,2,3,4}; } @Test public void test3(){ //情况一:没有初始化的局部变量声明 // var s = null; //情况6:catch块 // try { // // }catch (var a){ // a.printStackTrace(); // } } //情况2:方法的返回值类型 // public var method1(){ // return 0; // } //情况3:方法的参数类型 // public void method1(var a){ // // } //情况4:构造器的参数类型 // public Java10Test(var i){ // // } //情况5:属性//因为属性有默认值 // var num = 19; //java10的新特性2:集合中新增的copyOf()用于创建一个只读的集合 @Test public void test6(){ //示例1: var list1 = List.of("Java","Pytho","C");//是只读的 var copy1 = List.copyOf(list1); System.out.println(copy1 == list1);//true //示例2: var list2 = new ArrayList<String>();//不是只读的 var copy2 = List.copyOf(list2); System.out.println(copy2 == list2);//false //示例1和示例2代码基本一致,为什么结果不一样 //结论:copyOf(Xxx col)如果参数col本身就是只读型,则copyOf()返回值即为本身col //如果参数col不是一个只读的集合,则colOf()返回一个新的集合,这个新集合是只读的 } } <file_sep>/day10/src/com/chang/java1/URLTest1.java package com.chang.java1; import org.junit.Test; import javax.net.ssl.HttpsURLConnection; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-03 11:48 */ public class URLTest1 { @Test public void test1(){ HttpsURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos = null; try { // 1.创建url对象 URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1585896031753&di=33cff879fd47a098b07a22ba21d5ee56&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D1484500186%2C1503043093%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1280%26h%3D853"); // 2.打开url并连接 urlConnection = (HttpsURLConnection)url.openConnection(); urlConnection.connect(); //3.获取连接以后得到一个输入流 is = urlConnection.getInputStream(); fos = new FileOutputStream(new File("lion.jpg")); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); } System.out.println("下载完成"); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } try { is.close(); } catch (IOException e) { e.printStackTrace(); } //关闭url连接 urlConnection.disconnect(); } } } <file_sep>/day11/jdbc.properties username=\u5F20\u4E09 password=<PASSWORD><file_sep>/day02/src/com/chang/bean/WindowTest1.java package com.chang.bean; /** * 例子:创建三个窗口卖票,总票数为100张,使用实现Runnable接口的方式 * * 1. 问题:卖票过程中,出现了重票、错票-->出现了线程 的安全问题 * 2. 问题出现的原因:当某个线程操作车票的过程中,尚未操作完成时,其他线程参与进来,也操作车票 * 3. 如何解决:当一个线程在操作ticket的时候,其他线程不能参加进来,直到线程a操作完ticket时,线程才可以 * 操作ticket。这种情况即使线程a出现了阻塞,也不能被改变 * 4. 在java中,通过同步机制,来解决线程安全问题 * * 方式一:同步代码块 * synchronized(同步监视器){ * //需要被同步的代码 * } * * 说明:1.操作共享数据的代码,即为需要被同步的代码 不能包含代码多了,也不能包含代码少了 * 2.共享数据:多个线程共同操作的变量。比如:ticket就是共享数据 * 3.同步监视器:俗称:锁。任何一个类的对象,都可以充当锁 * 要求:多个线程必须要共用同一把锁 * 补充:在实现Runnable接口创建多线程的方式中,我们可以考虑使用this充当同步监视器 * * 方式二:同步方法 * 如果操作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明为同步的 * 5.同步的方式,解决了线程的安全问题。---好处 * 操作同步代码时,只能有一个线程参与,其他线程等待。相当于是一个单线程的过程,效率低。---局限性 * @author chang * @create 2020-03-07 20:29 */ class Window1 implements Runnable{ private int ticket = 100; // Object obj = new Object(); @Override public void run() { while (true) { // synchronized (obj) { //方式一 synchronized (this){ //方式二 if (ticket > 0) { System.out.println(Thread.currentThread().getName() + ":卖票,票号为" + ticket); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } ticket--; } else { break; } } } } } public class WindowTest1 { public static void main(String[] args) { Window1 w = new Window1(); Thread t1 = new Thread(w); Thread t2 = new Thread(w); Thread t3 = new Thread(w); t1.setName("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); t1.start(); t2.start(); t3.start(); } } <file_sep>/day13/src/com/chang/java2/Java11Test.java package com.chang.java2; import org.junit.Test; import java.util.Optional; import java.util.function.Consumer; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-07 16:44 */ public class Java11Test { //java11特性1:String中新增的方法 @Test public void test1(){ //isBlank()//判断字符串是否为空白 System.out.println(" \t \n".isBlank());//true //strip()//去除收尾空白 System.out.println("---" + " \t abc \n".strip() + "------------"); System.out.println("---" + " \t abc \n".trim() + "------------"); //stripLeading 去除首部空格 System.out.println("---" + " \t abc \n".stripLeading() + "------------"); //stripTrailing 去除尾部空格 System.out.println("---" + " \t abc \n".stripTrailing() + "------------"); //repeat(int count) String str1 = "abc"; String str2 = str1.repeat(5); System.out.println(str2); //lines().count(): String str3 = "abc\ndefg"; System.out.println(str3.lines().count()); } //java11新特性二:Optional新增的方法 @Test public void test2(){ Optional<Object> op = Optional.empty(); System.out.println(op.isPresent());//判断内部value是否存在false System.out.println(op.isEmpty());//判断内部value是否为空true op = Optional.of("abc"); Object obj = op.orElseThrow(); System.out.println(obj); Optional<String> op1 = Optional.of("hello"); //or:value非空,返回对应的Optional:value为空,返回形参封装的Optional Optional<Object> op2 = op.or(() -> op1); System.out.println(op2); } //java11特性三:局部变量类型推断的升级 @Test public void test3(){ //错误的形式:必须要有类型,可以加上var // Consumer<String> con1 = (@Deprecated t) -> System.out.println(t.toUpperCase()); //正确的形式 //使用var的好处是在使用Lambda表达式时给参数加上注解 Consumer<String> con1 = (@Deprecated var t) -> System.out.println(t.toUpperCase()); } //java11特性四:httpClient @Test public void test4(){ } } <file_sep>/day10/src/com/chang/java1/InetAddressTest.java package com.chang.java1; import java.net.InetAddress; import java.net.UnknownHostException; /** * InetAddress类代表IP * 如何实例化InetAddress:两个方法:getByName(String host),getLocalHost() * 两个常用方法:getHostName()/getHostAddress() * @Description * @Author <NAME> * @Version * @Time 2020-04-01 13:42 */ public class InetAddressTest { public static void main(String[] args) { try { InetAddress inet1 = InetAddress.getByName("192.168.0.1"); InetAddress inet2 = InetAddress.getByName("www.changzhi.space"); InetAddress inet3 = InetAddress.getByName("127.0.0.1"); InetAddress localHost = InetAddress.getLocalHost(); String hostName = inet2.getHostName(); String hostAddress = inet2.getHostAddress(); System.out.println(inet1); System.out.println(inet2); System.out.println(inet3); System.out.println(localHost); System.out.println(hostName); System.out.println(hostAddress); } catch (UnknownHostException e) { e.printStackTrace(); } } } <file_sep>/day10/src/com/chang/java1/URLTest.java package com.chang.java1; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-03 11:27 */ public class URLTest { @Test public void test1(){ try { URL url = new URL("https://www.bilibili.com/video/BV1Kb411W75N?p=629"); //1.获取协议 https System.out.println(url.getProtocol()); //2.获取URL主机名 www.bilibili.com System.out.println(url.getHost()); //3.获取URL的端口号,未指定端口号时(即使用默认端口号),getport()返回-1 System.out.println(url.getPort()); //3.1 http协议默认端口号80,https协议默认端口号443 System.out.println(url.getDefaultPort()); //4.获取该URL的文件路径/video/BV1Kb411W75N System.out.println(url.getPath()); //5.获取该URL的文件名 /video/BV1Kb411W75N?p=629 System.out.println(url.getFile()); //获取该URL的查询名 p=629 System.out.println(url.getQuery()); } catch (MalformedURLException e) { e.printStackTrace(); } } } <file_sep>/day13/src/com/chang/java/OptionalTest.java package com.chang.java; import org.junit.Test; import java.util.Optional; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-07 9:59 */ public class OptionalTest { @Test public void test1(){ //empty():创建的Optional对象内部的value = null Optional<Object> op1 = Optional.empty(); if(!op1.isPresent()){//封装的数据是否包含对象 System.out.println("数据为空"); } System.out.println(op1);//Optional.empty System.out.println(op1.isEmpty());//true System.out.println(op1.isPresent());//false } @Test public void test2(){ String str = "Hello"; // str = null; //of(T t):封装数据t生成Optional对象,要求t非空,否则报错 Optional<String> op1 = Optional.of(str); //get()通常与of()搭配使用,用于获取内部封装的数据value String str1 = op1.get(); System.out.println(str1); } @Test public void test3(){ String str = "Hi"; str = null; //ofNullable(T t)封装数据t赋给Optional内部的Value,不要求t非空 Optional<String> op1 = Optional.ofNullable(str); //orElse(T t1):如果Optional内部的value非空,则返回此value值,如果value为空,则返回t1 String str1 = op1.orElse("你好"); System.out.println(str1); } } <file_sep>/day13/src/com/chang/java/MyInterface.java package com.chang.java; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-07 11:22 */ public interface MyInterface { //如下的三个方法的权限修饰符都是public void methodAbstract(); static void methodStatic(){ System.out.println("我是接口中的静态方法"); } default void methodDefault(){ System.out.println("我是接口中的默认方法"); methodPrivate(); } //java9 中允许接口定义私有的方法 private void methodPrivate(){ System.out.println("我是接口中的私有方法"); } } <file_sep>/day13/src/com/chang/java/Java9Test1.java package com.chang.java; import org.junit.Test; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.*; /** * @Description * @Author <NAME> * @Version * @Time 2020-04-07 12:28 */ public class Java9Test1 { //java8中的写法 @Test public void test1(){ List<String> namesList = new ArrayList<>(); namesList.add("Joe"); namesList.add("Bob"); namesList.add("Bill"); //返回的namesList是一个只读的集合 namesList = Collections.unmodifiableList(namesList); namesList.add("Mike"); System.out.println(namesList); } @Test public void test3(){ List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); //报异常 list.add(6); } //java9新特性八:集合工厂方法,创建只读集合 @Test public void test4(){ List<Integer> list = List.of(1, 2, 3, 4, 5); //不可添加 // list.add(6); System.out.println(list); Set<Integer> set = Set.of(33, 21, 344, 32, 3); //不可添加 // set.add(9); System.out.println(set); Map<String,Integer> map1 = Map.of("Tom",22,"Jerry",9); // map1.put("Lilei",22); System.out.println(map1); Map<String,Integer> map2 = Map.ofEntries(Map.entry("Tom",22),Map.entry("Jerry",33)); // map1.put("Lilei",22); System.out.println(map2); } //InputStream的新方法:tranferTo() @Test public void test2(){ ClassLoader classLoader = this.getClass().getClassLoader(); //getResourceAsStream默认在src下,如果文件不存在会报空指针异常 try(InputStream is = classLoader.getResourceAsStream("hello.txt"); OutputStream os = new FileOutputStream("src\\hello2.txt")){ is.transferTo(os);//把输入流中的所有数据直接自动地复制到输出流中 }catch (IOException e){ e.printStackTrace(); } } } <file_sep>/day03/src/com/chang/bean/StringMethodTest.java package com.chang.bean; import org.junit.Test; /** * @Description * @Author <NAME> * @Version * @Time 2020-03-18 9:41 */ public class StringMethodTest { /** * 替换: * String replace(char oldChar, char newChar):返回一个新的字符串,它是通过用newChar替换此字符串中出现的所有oldChar得到的 * String replace(CharSequence target, CharSequence replacement):使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的字符串 * String replaceAll(String regex, String replacement):使用给定的replacement替换此字符串所有匹配给定的正则表达式的子字符串 * String replaceFirst(String regex, String replacement):使用给定的replacement替换此字符串匹配给定的正则表达式的第一个子字符串 * * 匹配: * boolean matches(String regex):告知此字符串是否匹配给定的正则表达式 * *切片: * String[] split(String regex):根据给定正则表达式的匹配拆分此字符串 * String[] split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中 * */ @Test public void test4(){ } /** * boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束 * boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始 * boolean startsWith(String prefix, int toffset):测试此字符串从指定索引开始的子字符串是否为prefix * * boolean contains(CharSequence s):当且仅当此字符串包含指定的char值序列时,返回true * int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引, * int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始 * int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引 * int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定索引开始反向搜索 * 注: indexOf和lastIndexOf方法如果未找到都是返回-1 * * 什么情况下,indexOf(str)和lastIndexOf(str)返回值相同 * 情况一:存在唯一的一个str, 情况二:不存在str * */ /** * int length():返回字符串的长度:return value.length * char charAt(int index):返回某索引处的字符return value[index] * boolean isEmpty():判断是否是空字符串: return value.length == 0 * String toLowerCase():使用默认语言环境,将String中的所有字符转换为小写 * String toUpperCase():使用默认语言环境,将String中的所有字符转换为大写 * String trim():返回字符串的副本,忽略前导空白和尾部空白 * boolean equals(Object obj):比较字符串的内容是否相同 * boolean equalsIgnoreCase(String anotherString):与equals方法类似,忽略大小写 * String concat(String str):将指定字符串连接到此字符串的结尾,等价于用“+” * int compareTo(String anotherString):比较两个字符串的大小 * String substring(int beginIndex):返回一个新的字符串,它是此字符串的从beginIndex开始截取 * String substring(int beginIndex, int endIndex):返回一个新字符串, * 它是此字符串从beginIndex到endIndex(不包含)的一个子字符串 */ } <file_sep>/day04/src/com/chang/bean/StringDemo1.java package com.chang.bean; import org.junit.Test; /** * @Description * @Author <NAME> * @Version * @Time 2020-03-21 11:21 */ public class StringDemo1 { /** * 获取一个字符串在另一个字符串中出现的次数 * 比如:获取“ab"在"abkkcadkabkebfkabkskab"中出现的次数 */ public int getCount(String mainStr, String subStr){ int mainLength = mainStr.length(); int subLength = subStr.length(); int count = 0; int index = 0; if(mainLength > subLength){ //方式一 // while((index = mainStr.indexOf(subStr)) != -1){ // count++; // mainStr = mainStr.substring(index + subLength); // } //方式二:对方式一的改进 while((index = mainStr.indexOf(subStr, index)) != -1){ count++; index += subLength; } } return count; } @Test public void testGetCount(){ String mainStr ="abkkcadkabkebfkabkskab"; String subStr = "ab"; int count = getCount(mainStr, subStr); System.out.println(count); } } <file_sep>/day11/src/jdbc1.properties username=\u674E\u56DB password=<PASSWORD><file_sep>/jdbc_1/src/jdbc.properties driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true user=root password=<PASSWORD><file_sep>/day11/src/com/chang/bean/ReflectionTest.java package com.chang.bean; import org.junit.Test; import java.lang.annotation.ElementType; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 反射: * 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中用哪个? * 建议:直接new的方式 * 什么时候会使用反射的方式。反射的特性:动态性 * 疑问2:反射机制与面向对象中的封装性是不是矛盾?如何看待两个技术 * 不矛盾。封装性是建议你调用公有方法。反射是能不能调用的问题 * * @Description * @Author <NAME> * @Version * @Time 2020-04-03 15:52 */ public class ReflectionTest { @Test public void test1 (){ try { Class clazz = Person.class; //1.通过反射,创建Person类的对象 Constructor cons = clazz.getConstructor(String.class,int.class); Object obj = cons.newInstance("Tom",12); Person p = (Person)obj; //2.通过反射,调用对象指定的属性、方法 //调用属性 Field age = clazz.getDeclaredField("age"); age.set(p,10); System.out.println(p.toString()); //通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性 //调用私有构造器 Constructor cons1 = clazz.getDeclaredConstructor(String.class); cons1.setAccessible(true); Person p1 = (Person)cons1.newInstance("Jerry"); System.out.println(p1); //调用私有属性 Field name = clazz.getDeclaredField("name"); name.setAccessible(true); name.set(p1,"老韩"); System.out.println(p1); //调用私有方法 Method showNation = clazz.getDeclaredMethod("showNation",String.class); showNation.setAccessible(true); String nation = (String) showNation.invoke(p1, "中国");//相当于p1.showNation("中国") System.out.println(nation); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } /** * * 关于java.lang.Class类的理解 * 1.类的加载过程: * 程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾) * 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中, * 此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此运行时类,就作为Class的一个实例 * * 2.换句话说,Class的实例就对应着一个运行时类 * 3.我们加载到内存中的运行时类,会缓存一段时间,在此时间之内,我们可以通过不同的方式来获取运行时类 * (唯一存在) */ //获取Class的实例方式 @Test public void test2() throws ClassNotFoundException { //方式一:调用运行时类的属性:.class Class clazz1 = Person.class; System.out.println(clazz1); //方式二:通过运行时类的对象,调用getClass() Person p = new Person(); Class clazz2 = p.getClass(); System.out.println(clazz2); //方式三:调用Class的静态方法:forName(String classPath),此方式常用 Class clazz3 = Class.forName("com.chang.bean.Person"); // clazz3 = Class.forName("java.lang.String"); System.out.println(clazz3); System.out.println(clazz1 == clazz2); System.out.println(clazz2 == clazz3); //方式四:使用类的加载器:ClassLoader ClassLoader classLoader = ReflectionTest.class.getClassLoader(); Class clazz4 = classLoader.loadClass("com.chang.bean.Person"); System.out.println(clazz1 == clazz4); } /** * Class实例可以是哪些结构的说明 */ @Test public void test3(){ Class c1 = Object.class; Class c2 = Comparable.class; Class c3 = String[].class; Class c4 = int[][].class; Class c5 = ElementType.class; Class c6 = Override.class; Class c7 = int.class; Class c8 = void.class; Class c9 = Class.class; int[] a = new int[10]; int[] b = new int[100]; Class c10 = a.getClass(); Class c11 = b.getClass(); //只要元素类型与维度一样,就是同一个Class System.out.println(c10 == c11); } }
4f340c90ee031694287cdea3cf85079ae0a5d075
[ "Java", "INI" ]
23
Java
Chris-Chang/JavaSenior
83ad74a12134cbd21e0c820bb9d97d27c2c6c420
2766c567cf4eeef60c6008958c8a5ab4b9527814
refs/heads/main
<repo_name>timothy-sci/Exploratory-Data-Analysis<file_sep>/EDA.py #!/usr/bin/python3 # data set obtained from: # kaggle.com/kaggle/sf-salaries import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # In this example we interested in EDA on the salaries data path = 'Salaries/Salaries.csv' df = pd.read_csv(path) print(df.head()) print('~~~~~~~~~~~~~') print(df.shape) print('~~~~~~~~~~~~~') print(df.columns) print('~~~~~~~~~~~~~') print(df.isna().sum()) print ('~~~~~~~~~~~~') # Drop columns we not interested in df = df.drop(['Id','Notes','Status'],axis=1) # Convert jobtitles to uppercase # This is convernient for later when we select a particular # dataset to work with. It will help focus the business question # into a theme industry since the job titles range a lot. df['JobTitle'] = df['JobTitle'].str.upper() print(df.head()) print('~~~~~~~~~~~~') # Check variables print(df.JobTitle) # Check data type print(df.dtypes) print('~~~~~~~~~~~~') # Substitute unwanted values and convert data type # There is some incorrent entries in payment values # If later we are to build ML model to work further # on this data, incorrent entries must first be fixed df['BasePay'] = df['BasePay'].replace('Not Provided', np.nan) df['BasePay'] = df['BasePay'].replace(0, np.nan) df.BasePay = df.BasePay.astype('float64') df['OvertimePay'] = df['OvertimePay'].replace('Not Provided', np.nan) df['OvertimePay'] = df['OvertimePay'].replace(0, np.nan) df.BasePay = df.OvertimePay.astype('float64') df['OtherPay'] = df['OtherPay'].replace('Not Provided', np.nan) df['OtherPay'] = df['OtherPay'].replace(0, np.nan) df.BasePay = df.OtherPay.astype('float64') df['Benefits'] = df['Benefits'].replace('Not Provided', np.nan) df['Benefits'] = df['Benefits'].replace(0, np.nan) df.BasePay = df.Benefits.astype('float64') print('Describe data') print(df.OtherPay) print(df.dtypes) # Check for Duplicates based on job title df_duplicated = df[df['JobTitle'].duplicated()] print(df_duplicated.head()) print('~~~~~~~~~~~~') print(df_duplicated.shape) # Check for Uniqueness based on job title df_unique = df['JobTitle'].unique() print('~~~~~~~~~~~~') print(df_unique) # Select only certain job titles for analysis # We interested in jobs in the health sector df1 = df[df['JobTitle'].str.contains('ASSISTANT MEDICAL EXAMINER', regex=False)] df2 = df[df['JobTitle'].str.contains('SENIOR PHYSICIAN SPECIALIST', regex=False)] df3 = df[df['JobTitle'].str.contains('NURSING SUPERVISOR', regex=False)] df4 = df[df['JobTitle'].str.contains('ANESTHETIST', regex=False)] df5 = df[df['JobTitle'].str.contains('EPIDEMIOLOGIST', regex=False)] selected_jobs = ['ASSISTANT MEDICAL EXAMINER', 'SENIOR PHYSICIAN SPECIALIST', 'NURSING SUPERVISOR', 'ANETHETIST', 'NURSE MANAGER', 'SPECIAL NURSE', 'NURSE MIDWIFE', 'NURSE PRACTITIONER', 'PATIENT CARE ASSISTANT', 'HEALTH WORKER 3'] df6 = df[df.JobTitle.str.contains('|'.join(selected_jobs))] print(df1) selected_professions = ['CHEMIST', 'BIOLOGIST', 'EPIDEMIOLOGIST', 'NUTRITIONIST'] df7 = df[df.JobTitle.str.contains('|'.join(selected_professions))] # Try grouping by base pay df8 = df7.groupby(['TotalPay','JobTitle']).count()['EmployeeName'] print('~~~~~~~~~~~~~ Grouped by ~~~~~~~~~~~~~~~~~~~') print(df8) # Visualize #sns.set(font_scale=1.0) fig1 = plt.figure(figsize=(20,5)) chart1 = sns.barplot(x='JobTitle', y='TotalPay', data=df5, hue='Year', palette='Set1') chart1.set_xticklabels(chart1.get_xticklabels(), rotation=5) chart1.set_ylim(df5.TotalPayBenefits.min(),df5.TotalPayBenefits.max()) fig2 = plt.figure(figsize=(15,5)) chart2 = sns.boxplot(data=df5, x='JobTitle', y='TotalPay', hue='Year') chart2.set_xticklabels(chart2.get_xticklabels(), rotation=5) #chart2.set_ylim(df1.TotalPayBenefits.min(),df1.TotalPayBenefits.max()) fig3 = plt.figure(figsize=(15,5)) chart3 = sns.countplot(data=df5[df5['Year']==2011], # x='JobTitle', x='TotalPay', hue='JobTitle') chart3.set_xticklabels(chart3.get_xticklabels(), rotation=15) # Check for correlation between columns corr = df.corr() fig4 = plt.figure() chart4 = sns.heatmap(corr,annot=True) fig5,ax = plt.subplots(figsize=(15,7)) df8.unstack().plot(ax=ax) plt.show()
2fc67fba97cad1840d4dbf574cf5f761276ee828
[ "Python" ]
1
Python
timothy-sci/Exploratory-Data-Analysis
adea9886f719143a9e880ea5ca8ce9b277258c35
d175d8cb6fab01c410ef41fb77771192723fc548
refs/heads/master
<file_sep>package com.android.jni.ffmpeg; import android.app.Activity; import android.hardware.Camera; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; /** * Created by DELL on 2019/8/12. */ public class PushActivity extends Activity{ private static final String TAG= "PushActivity"; private SurfaceView surfaceview; private Camera mCamera; private SurfaceHolder holder; private FfmpegPlayer FfmpegPlayer; private Camera.PreviewCallback mPreviewCallbacx; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_push); FfmpegPlayer = new FfmpegPlayer(this); mPreviewCallbacx = new Camera.PreviewCallback() { @Override public void onPreviewFrame(byte[] arg0, Camera arg1) { // WSPlayer.start(arg0); FfmpegPlayer.cameraLiveStart(arg0); } }; surfaceview = findViewById(R.id.surfaceview); SurfaceHolder surfaceHolder = surfaceview.getHolder(); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); surfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { try{ if(mCamera!=null){ mCamera.setPreviewDisplay(surfaceHolder); holder=surfaceHolder; } }catch(IOException exception){ Log.e(TAG, "Error setting up preview display", exception); } } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { if(mCamera==null) return; Camera.Parameters parameters=mCamera.getParameters(); parameters.setPreviewSize(640,480); parameters.setPictureSize(640,480); mCamera.setParameters(parameters); try{ mCamera.startPreview(); holder=surfaceHolder; }catch(Exception e){ Log.e(TAG, "could not start preview", e); mCamera.release(); mCamera=null; } } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if(mCamera!=null) { mCamera.stopPreview(); surfaceview = null; holder = null; } } }); } @Override protected void onResume(){ super.onResume(); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD){ mCamera=Camera.open(0); }else { mCamera=Camera.open(); } mCamera.setDisplayOrientation(90); // WSPlayer.initialize(mCamera.getParameters().getPreviewSize().width,mCamera.getParameters().getPreviewSize().height,"rtmp://192.168.1.198:1935/live/live"); FfmpegPlayer.cameraLiveInit(mCamera.getParameters().getPreviewSize().width,mCamera.getParameters().getPreviewSize().height,"rtmp://192.168.1.198:1935/live/live"); mCamera.setPreviewCallback(mPreviewCallbacx); } @Override protected void onPause(){ super.onPause(); // WSPlayer.stop(); // WSPlayer.close(); FfmpegPlayer.cameraLiveStop(); FfmpegPlayer.cameraLiveClose(); if(mCamera!=null){ mCamera.release(); mCamera=null; } } @Override protected void onDestroy() { super.onDestroy(); // WSPlayer.stop(); // WSPlayer.close(); FfmpegPlayer.cameraLiveStop(); FfmpegPlayer.cameraLiveClose(); if(mCamera!=null){ mCamera.release(); mCamera=null; } } } <file_sep>// // Created by DELL on 2019/7/16. // #include "include/com_android_jni_ffmpeg_FfmpegPlayer.h" #include"include/libavformat/avformat.h" #include"include/libswscale/swscale.h" #include"include/libswresample/swresample.h" #include"include/libavcodec/avcodec.h" #include"include/libavutil/pixdesc.h" #include "include/libyuv.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <android/log.h> #include <android/native_window_jni.h> #include <android/native_window.h> #define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"jason",FORMAT,##__VA_ARGS__); #define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"jason",FORMAT,##__VA_ARGS__); #define MAX_AUDIO_FRME_SIZE 48000 * 4 AVFormatContext *ofmt_ctx; AVStream *video_st; AVCodecContext *pCodecCtx; AVCodec *pCodec; AVPacket enc_pkt; AVFrame *pFrameYUV; int framecnt = 0; int yuv_width; int yuv_height; int y_length; int uv_length; int64_t start_time; //Output FFmpeg's av_log() void custom_log(void *ptr, int level, const char *fmt, va_list vl) { FILE *fp = fopen("/storage/emulated/0/av_log.txt", "a+"); if (fp) { vfprintf(fp, fmt, vl); fflush(fp); fclose(fp); } } /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: init * Signature: ()V */ JNIEXPORT jstring JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_init (JNIEnv *env, jobject jo){ // (*env)-> return (*env)->NewStringUTF(env,"hello boy!"); } //视频解码保存 /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: videoDecode * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_videoDecode (JNIEnv *env, jobject jo, jstring input_jstr, jstring output_jstr){ const char* input_cstr = (*env)->GetStringUTFChars(env,input_jstr,NULL); const char* output_cstr = (*env)->GetStringUTFChars(env,output_jstr,NULL); //1.注册组件 av_register_all(); //封装格式上下文 AVFormatContext *pFormatCtx = avformat_alloc_context(); //2.打开输入视频文件 if(avformat_open_input(&pFormatCtx,input_cstr,NULL,NULL) != 0){ LOGE("%s","打开输入视频文件失败"); return; } //3.获取视频信息 if(avformat_find_stream_info(pFormatCtx,NULL) < 0){ LOGE("%s","获取视频信息失败"); return; } //视频解码,需要找到视频对应的AVStream所在pFormatCtx->streams的索引位置 int video_stream_idx = -1; int i = 0; for(; i < pFormatCtx->nb_streams;i++){ //根据类型判断,是否是视频流 if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){ video_stream_idx = i; break; } } //4.获取视频解码器 AVCodecContext *pCodeCtx = pFormatCtx->streams[video_stream_idx]->codec; AVCodec *pCodec = avcodec_find_decoder(pCodeCtx->codec_id); if(pCodec == NULL){ LOGE("%s","无法解码"); return; } //5.打开解码器 if(avcodec_open2(pCodeCtx,pCodec,NULL) < 0){ LOGE("%s","解码器无法打开"); return; } //编码数据 AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket)); //像素数据(解码数据) AVFrame *frame = av_frame_alloc(); AVFrame *yuvFrame = av_frame_alloc(); //只有指定了AVFrame的像素格式、画面大小才能真正分配内存 //缓冲区分配内存 uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodeCtx->width, pCodeCtx->height)); //初始化缓冲区 avpicture_fill((AVPicture *)yuvFrame, out_buffer, AV_PIX_FMT_YUV420P, pCodeCtx->width, pCodeCtx->height); //输出文件 FILE* fp_yuv = fopen(output_cstr,"wb"); //用于像素格式转换或者缩放 struct SwsContext *sws_ctx = sws_getContext( pCodeCtx->width, pCodeCtx->height, pCodeCtx->pix_fmt, pCodeCtx->width, pCodeCtx->height, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); int len ,got_frame, framecount = 0; //6.一阵一阵读取压缩的视频数据AVPacket while(av_read_frame(pFormatCtx,packet) >= 0){ //解码AVPacket->AVFrame len = avcodec_decode_video2(pCodeCtx, frame, &got_frame, packet); //Zero if no frame could be decompressed //非零,正在解码 if(got_frame){ //frame->yuvFrame (YUV420P) //转为指定的YUV420P像素帧 sws_scale(sws_ctx, frame->data,frame->linesize, 0, frame->height, yuvFrame->data, yuvFrame->linesize); //向YUV文件保存解码之后的帧数据 //AVFrame->YUV //一个像素包含一个Y int y_size = pCodeCtx->width * pCodeCtx->height; fwrite(yuvFrame->data[0], 1, y_size, fp_yuv); fwrite(yuvFrame->data[1], 1, y_size/4, fp_yuv); fwrite(yuvFrame->data[2], 1, y_size/4, fp_yuv); LOGI("解码%d帧",framecount++); } av_free_packet(packet); } fclose(fp_yuv); av_frame_free(&frame); avcodec_close(pCodeCtx); avformat_free_context(pFormatCtx); (*env)->ReleaseStringUTFChars(env,input_jstr,input_cstr); (*env)->ReleaseStringUTFChars(env,output_jstr,output_cstr); /** * 解码完成,返回提示 */ jclass jc = (*env)->GetObjectClass(env,jo); jmethodID id = (*env)->GetMethodID(env,jc,"showToast","(Ljava/lang/String;)V"); // jobject fieldjob = (*env)->GetObjectField(env,jo,id); (*env)->CallVoidMethod(env,jo,id,(*env)->NewStringUTF(env,"解码已完成,具体请看jason的log打印结果")); }; //视频解码播放 /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: videoDecodeDisplay * Signature: (Ljava/lang/String;Landroid/view/Surface;)V */ JNIEXPORT void JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_videoDecodeDisplay (JNIEnv *env, jobject jo, jstring input_jstr, jobject surface){ const char* input_cstr = (*env)->GetStringUTFChars(env,input_jstr,NULL); //1.注册组件 av_register_all(); //封装格式上下文 AVFormatContext *pFormatCtx = avformat_alloc_context(); //2.打开输入视频文件 if(avformat_open_input(&pFormatCtx,input_cstr,NULL,NULL) != 0){ LOGE("%s","打开输入视频文件失败"); return; } //3.获取视频信息 if(avformat_find_stream_info(pFormatCtx,NULL) < 0){ LOGE("%s","获取视频信息失败"); return; } //视频解码,需要找到视频对应的AVStream所在pFormatCtx->streams的索引位置 int video_stream_idx = -1; // int i = 0; // for(; i < pFormatCtx->nb_streams;i++){ // //根据类型判断,是否是视频流 // if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){ // video_stream_idx = i; // break; // } // } if(pFormatCtx->streams[0]->codec->codec_type == AVMEDIA_TYPE_VIDEO){ video_stream_idx = 0; } else{ return; } //4.获取视频解码器 AVCodecContext *pCodeCtx = pFormatCtx->streams[video_stream_idx]->codec; AVCodec *pCodec = avcodec_find_decoder(pCodeCtx->codec_id); if(pCodec == NULL){ LOGE("%s","无法解码"); return; } //5.打开解码器 if(avcodec_open2(pCodeCtx,pCodec,NULL) < 0){ LOGE("%s","解码器无法打开"); return; } //编码数据 AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket)); //像素数据(解码数据) AVFrame *yuv_frame = av_frame_alloc(); AVFrame *rgb_frame = av_frame_alloc(); //native绘制 //窗体 ANativeWindow* nativeWindow = ANativeWindow_fromSurface(env,surface); //绘制时的缓冲区 ANativeWindow_Buffer outBuffer; int len ,got_frame, framecount = 0; //6.一阵一阵读取压缩的视频数据AVPacket while(av_read_frame(pFormatCtx,packet) >= 0){ //解码AVPacket->AVFrame len = avcodec_decode_video2(pCodeCtx, yuv_frame, &got_frame, packet); //Zero if no frame could be decompressed //非零,正在解码 if(got_frame){ LOGI("解码%d帧",framecount++); //lock //设置缓冲区的属性(宽、高、像素格式) ANativeWindow_setBuffersGeometry(nativeWindow, pCodeCtx->width, pCodeCtx->height,WINDOW_FORMAT_RGBA_8888); ANativeWindow_lock(nativeWindow,&outBuffer,NULL); //设置rgb_frame的属性(像素格式、宽高)和缓冲区 //rgb_frame缓冲区与outBuffer.bits是同一块内存 avpicture_fill((AVPicture *)rgb_frame, outBuffer.bits, PIX_FMT_RGBA, pCodeCtx->width, pCodeCtx->height); //YUV->RGBA_8888 I420ToARGB(yuv_frame->data[0],yuv_frame->linesize[0], yuv_frame->data[2],yuv_frame->linesize[2], yuv_frame->data[1],yuv_frame->linesize[1], rgb_frame->data[0], rgb_frame->linesize[0], pCodeCtx->width,pCodeCtx->height); //unlock ANativeWindow_unlockAndPost(nativeWindow); usleep(1000 * 16); } av_free_packet(packet); } ANativeWindow_release(nativeWindow); av_frame_free(&yuv_frame); avcodec_close(pCodeCtx); avformat_free_context(pFormatCtx); (*env)->ReleaseStringUTFChars(env,input_jstr,input_cstr); /** * 解码完成,返回提示 */ jclass jc = (*env)->GetObjectClass(env,jo); jmethodID id = (*env)->GetMethodID(env,jc,"showToast","(Ljava/lang/String;)V"); // jobject fieldjob = (*env)->GetObjectField(env,jo,id); (*env)->CallVoidMethod(env,jo,id,(*env)->NewStringUTF(env,"解码已完成")); }; //音频解码 /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: soundDecode * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_soundDecode (JNIEnv *env, jobject jthiz, jstring input_jstr, jstring output_jstr){ const char* input_cstr = (*env)->GetStringUTFChars(env,input_jstr,NULL); const char* output_cstr = (*env)->GetStringUTFChars(env,output_jstr,NULL); LOGI("%s","sound"); //注册组件 av_register_all(); AVFormatContext *pFormatCtx = avformat_alloc_context(); //打开音频文件 if(avformat_open_input(&pFormatCtx,input_cstr,NULL,NULL) != 0){ LOGI("%s","无法打开音频文件"); return; } //获取输入文件信息 if(avformat_find_stream_info(pFormatCtx,NULL) < 0){ LOGI("%s","无法获取输入文件信息"); return; } //获取音频流索引位置 int i = 0, audio_stream_idx = -1; for(; i < pFormatCtx->nb_streams;i++){ if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){ audio_stream_idx = i; break; } } //获取解码器 AVCodecContext *codecCtx = pFormatCtx->streams[audio_stream_idx]->codec; AVCodec *codec = avcodec_find_decoder(codecCtx->codec_id); if(codec == NULL){ LOGI("%s","无法获取解码器"); return; } //打开解码器 if(avcodec_open2(codecCtx,codec,NULL) < 0){ LOGI("%s","无法打开解码器"); return; } //压缩数据 AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket)); //解压缩数据 AVFrame *frame = av_frame_alloc(); //frame->16bit 44100 PCM 统一音频采样格式与采样率 SwrContext *swrCtx = swr_alloc(); //重采样设置参数-------------start //输入的采样格式 enum AVSampleFormat in_sample_fmt = codecCtx->sample_fmt; //输出采样格式16bit PCM enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16; //输入采样率 int in_sample_rate = codecCtx->sample_rate; //输出采样率 int out_sample_rate = in_sample_rate; //获取输入的声道布局 //根据声道个数获取默认的声道布局(2个声道,默认立体声stereo) //av_get_default_channel_layout(codecCtx->channels); uint64_t in_ch_layout = codecCtx->channel_layout; //输出的声道布局(立体声) uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO; swr_alloc_set_opts(swrCtx, out_ch_layout,out_sample_fmt,out_sample_rate, in_ch_layout,in_sample_fmt,in_sample_rate, 0, NULL); swr_init(swrCtx); //输出的声道个数 int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout); //重采样设置参数-------------end //JNI begin------------------ //JasonPlayer jclass player_class = (*env)->GetObjectClass(env,jthiz); //AudioTrack对象 jmethodID create_audio_track_mid = (*env)->GetMethodID(env,player_class,"createAudioTrack","(II)Landroid/media/AudioTrack;"); jobject audio_track = (*env)->CallObjectMethod(env,jthiz,create_audio_track_mid,out_sample_rate,out_channel_nb); //调用AudioTrack.play方法 jclass audio_track_class = (*env)->GetObjectClass(env,audio_track); jmethodID audio_track_play_mid = (*env)->GetMethodID(env,audio_track_class,"play","()V"); (*env)->CallVoidMethod(env,audio_track,audio_track_play_mid); //AudioTrack.write jmethodID audio_track_write_mid = (*env)->GetMethodID(env,audio_track_class,"write","([BII)I"); //JNI end------------------ FILE *fp_pcm = fopen(output_cstr,"wb"); //16bit 44100 PCM 数据 uint8_t *out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRME_SIZE); int got_frame = 0,index = 0, ret; //不断读取压缩数据 while(av_read_frame(pFormatCtx,packet) >= 0){ //解码音频类型的Packet if(packet->stream_index == audio_stream_idx){ //解码 ret = avcodec_decode_audio4(codecCtx,frame,&got_frame,packet); if(ret < 0){ LOGI("%s","解码完成"); } //解码一帧成功 if(got_frame > 0){ LOGI("解码:%d",index++); swr_convert(swrCtx, &out_buffer, MAX_AUDIO_FRME_SIZE,(const uint8_t **)frame->data,frame->nb_samples); //获取sample的size int out_buffer_size = av_samples_get_buffer_size(NULL, out_channel_nb, frame->nb_samples, out_sample_fmt, 1); fwrite(out_buffer,1,out_buffer_size,fp_pcm); //out_buffer缓冲区数据,转成byte数组 jbyteArray audio_sample_array = (*env)->NewByteArray(env,out_buffer_size); jbyte* sample_bytep = (*env)->GetByteArrayElements(env,audio_sample_array,NULL); //out_buffer的数据复制到sampe_bytep memcpy(sample_bytep,out_buffer,out_buffer_size); //同步 (*env)->ReleaseByteArrayElements(env,audio_sample_array,sample_bytep,0); //AudioTrack.write PCM数据 (*env)->CallIntMethod(env,audio_track,audio_track_write_mid, audio_sample_array,0,out_buffer_size); //释放局部引用 (*env)->DeleteLocalRef(env,audio_sample_array); usleep(1000 * 16); } } av_free_packet(packet); } av_frame_free(&frame); av_free(out_buffer); swr_free(&swrCtx); avcodec_close(codecCtx); avformat_close_input(&pFormatCtx); (*env)->ReleaseStringUTFChars(env,input_jstr,input_cstr); (*env)->ReleaseStringUTFChars(env,output_jstr,output_cstr); }; #include <libavutil/opt.h> #include <libavutil/time.h> #include <libavutil/imgutils.h> /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: cameraLiveInit * Signature: (IILjava/lang/String;)V */ JNIEXPORT jint JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_cameraLiveInit (JNIEnv *env, jobject obj, jint width, jint height, jstring jurlpath){ const char *out_path = (*env)->GetStringUTFChars(env,jurlpath, 0) ; //const char *out_path = "rtmp://192.168.9.135:1935/wstv/home";//ws yuv_width = width; yuv_height = height; y_length = width * height; uv_length = width * height / 4; //FFmpeg av_log() callback av_log_set_callback(custom_log); av_register_all(); avformat_network_init();//ws add //output initialize avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path); //output encoder initialize pCodec = avcodec_find_encoder(AV_CODEC_ID_H264); if (!pCodec) { LOGE("Can not find encoder!\n"); return -1; } pCodecCtx = avcodec_alloc_context3(pCodec); if (!pCodecCtx) { LOGE("Could not allocate video codec context\n"); return -1; } pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;//PIX_FMT_YUV420P新版加 pCodecCtx->width = width; pCodecCtx->height = height; pCodecCtx->time_base.num = 1; pCodecCtx->time_base.den = 25; pCodecCtx->bit_rate = 400000; pCodecCtx->gop_size = 250; /* Some formats want stream headers to be separate. */ if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER; //H264 codec param //pCodecCtx->me_range = 16; //pCodecCtx->max_qdiff = 4; //pCodecCtx->qcompress = 0.6; pCodecCtx->qmin = 10; pCodecCtx->qmax = 51; //Optional Param pCodecCtx->max_b_frames = 0; // Set H264 preset and tune AVDictionary *param = 0; //av_dict_set(&param, "preset", "ultrafast", 0); //av_dict_set(&param, "tune", "zerolatency", 0); av_opt_set(pCodecCtx->priv_data, "preset", "ultrafast", 0); av_opt_set(pCodecCtx->priv_data, "tune", "zerolatency", 0); if (avcodec_open2(pCodecCtx, pCodec, &param) < 0) { LOGE("Failed to open encoder!\n"); return -1; } //Add a new stream to output,should be called by the user before avformat_write_header() for muxing video_st = avformat_new_stream(ofmt_ctx, pCodec);//avformat_new_stream创建流通道 if (video_st == NULL) { return -1; } video_st->time_base.num = 1; video_st->time_base.den = 30; video_st->codec = pCodecCtx; //Open output URL,set before avformat_write_header() for muxing if (avio_open(&ofmt_ctx->pb, out_path, AVIO_FLAG_READ_WRITE) < 0) { LOGE("Failed to open output file!\n"); return -1; } //Write File Header avformat_write_header(ofmt_ctx, NULL); start_time = av_gettime(); return 0; }; /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: cameraLiveStart * Signature: ([B)V */ JNIEXPORT jint JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_cameraLiveStart (JNIEnv *env, jobject obj, jbyteArray yuv){ int ret; int enc_got_frame = 0; int i = 0; pFrameYUV = av_frame_alloc();//旧版 avcodec_alloc_frame() //分配一个AVFrame结构体。 uint8_t *out_buffer = (uint8_t *) av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height)); avpicture_fill((AVPicture *) pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width,pCodecCtx->height); //安卓摄像头数据为NV21格式,此处将其转换为YUV420P格式 jbyte *in = (jbyte *) (*env)->GetByteArrayElements(env,yuv, 0); memcpy(pFrameYUV->data[0], in, y_length); for (i = 0; i < uv_length; i++) { *(pFrameYUV->data[2] + i) = *(in + y_length + i * 2); *(pFrameYUV->data[1] + i) = *(in + y_length + i * 2 + 1); } pFrameYUV->format = AV_PIX_FMT_YUV420P; pFrameYUV->width = yuv_width; pFrameYUV->height = yuv_height; enc_pkt.data = NULL; enc_pkt.size = 0; av_init_packet(&enc_pkt);//初始化 AVPacker ret = avcodec_encode_video2(pCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame); av_frame_free(&pFrameYUV); if (enc_got_frame == 1) { LOGI("Succeed to encode frame: %5d\tsize:%5d\n", framecnt, enc_pkt.size); framecnt++; enc_pkt.stream_index = video_st->index; //Write PTS AVRational time_base = ofmt_ctx->streams[0]->time_base;//{ 1, 1000 }; AVRational r_framerate1 = {60, 2};//{ 50, 2 }; AVRational time_base_q = {1, AV_TIME_BASE}; //Duration between 2 frames (us) int64_t calc_duration = (double) (AV_TIME_BASE) * (1 / av_q2d(r_framerate1)); //内部时间戳 //Parameters //enc_pkt.pts = (double)(framecnt*calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base)); enc_pkt.pts = av_rescale_q(framecnt * calc_duration, time_base_q, time_base); enc_pkt.dts = enc_pkt.pts; enc_pkt.duration = av_rescale_q(calc_duration, time_base_q,time_base); //(double)(calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base)); enc_pkt.pos = -1; //Delay int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q); int64_t now_time = av_gettime() - start_time; if (pts_time > now_time) av_usleep(pts_time - now_time); ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);//将AVPacket(存储视频压缩码流数据)写入文件。 av_free_packet(&enc_pkt); } return 0; }; /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: cameraLiveStop * Signature: ()V */ JNIEXPORT jint JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_cameraLiveStop (JNIEnv *env, jobject obj){ int ret; int got_frame; AVPacket enc_pkt; if (!(ofmt_ctx->streams[0]->codec->codec->capabilities & CODEC_CAP_DELAY)) return 0; while (1) { enc_pkt.data = NULL; enc_pkt.size = 0; av_init_packet(&enc_pkt); ret = avcodec_encode_video2(ofmt_ctx->streams[0]->codec, &enc_pkt, NULL, &got_frame); if (ret < 0) break; if (!got_frame) { ret = 0; break; } LOGI("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n", enc_pkt.size); //Write PTS AVRational time_base = ofmt_ctx->streams[0]->time_base;//{ 1, 1000 }; AVRational r_framerate1 = {60, 2}; AVRational time_base_q = {1, AV_TIME_BASE}; //Duration between 2 frames (us) int64_t calc_duration = (double) (AV_TIME_BASE) * (1 / av_q2d(r_framerate1)); //内部时间戳 //Parameters enc_pkt.pts = av_rescale_q(framecnt * calc_duration, time_base_q, time_base); enc_pkt.dts = enc_pkt.pts; enc_pkt.duration = av_rescale_q(calc_duration, time_base_q, time_base); //转换PTS/DTS(Convert PTS/DTS) enc_pkt.pos = -1; framecnt++; ofmt_ctx->duration = enc_pkt.duration * framecnt; /* mux encoded frame */ ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt); if (ret < 0) break; } //Write file trailer av_write_trailer(ofmt_ctx); return 0; }; /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: cameraLiveClose * Signature: ()V */ JNIEXPORT jint JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_cameraLiveClose (JNIEnv *env, jobject obj){ if (video_st) avcodec_close(video_st->codec); avio_close(ofmt_ctx->pb); avformat_free_context(ofmt_ctx); return 0; }; /* * Class: com_android_jni_ffmpeg_FfmpegPlayer * Method: cameraLiveJason * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_android_jni_ffmpeg_FfmpegPlayer_cameraLiveJason (JNIEnv *env, jobject obj, jstring input_jstr, jstring output_jstr){ //java string->c char* const char *input_cstr = (*env)->GetStringUTFChars(env,input_jstr, JNI_FALSE); const char *output_cstr = (*env)->GetStringUTFChars(env,output_jstr, JNI_FALSE); //变量初始化 AVFormatContext *inFmtCtx = NULL, *outFmtCtx = NULL; int ret; //注册组件 av_register_all(); //初始化网络 avformat_network_init(); //打开输入文件 if ((ret = avformat_open_input(&inFmtCtx, input_cstr, 0, 0)) < 0) { LOGE( "无法打开文件"); goto end; } //获取文件信息 if ((ret = avformat_find_stream_info(inFmtCtx, 0)) < 0) { LOGE( "无法获取文件信息"); goto end; } //输出的封装格式上下文,使用RTMP协议推送flv封装格式的流 avformat_alloc_output_context2(&outFmtCtx, NULL, "flv",output_cstr); //RTMP //avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", output_str);//UDP int i = 0; for (; i < inFmtCtx->nb_streams; i++) { //根据输入封装格式中的AVStream流,来创建输出封装格式的AVStream流 //解码器,解码器上下文都要一致 AVStream *in_stream = inFmtCtx->streams[i]; AVStream *out_stream = avformat_new_stream(outFmtCtx, in_stream->codec->codec); //复制解码器上下文 ret = avcodec_copy_context(out_stream->codec, in_stream->codec); //全局头 out_stream->codec->codec_tag = 0; if (outFmtCtx->oformat->flags == AVFMT_GLOBALHEADER){ out_stream->codec->flags = CODEC_FLAG_GLOBAL_HEADER; } } //打开输出的AVIOContext IO流上下文 AVOutputFormat *ofmt = outFmtCtx->oformat; if (!(ofmt->flags & AVFMT_NOFILE)) { ret = avio_open(&outFmtCtx->pb, output_cstr, AVIO_FLAG_WRITE); } //先写一个头 ret = avformat_write_header(outFmtCtx, NULL); if (ret < 0) { LOGE( "推流发生错误\n"); goto end; } //获取视频流的索引位置 int videoindex=-1; for(i=0; i<inFmtCtx->nb_streams; i++){ if(inFmtCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ videoindex=i; break; } } int frame_index=0; int64_t start_time=av_gettime(); AVPacket pkt; while (1) { AVStream *in_stream, *out_stream; //读取AVPacket ret = av_read_frame(inFmtCtx, &pkt); if (ret < 0) break; //没有封装格式的裸流(例如H.264裸流)是不包含PTS、DTS这些参数的。在发送这种数据的时候,需要自己计算并写入AVPacket的PTS,DTS,duration等参数 //PTS:Presentation Time Stamp。PTS主要用于度量解码后的视频帧什么时候被显示出来 //DTS:Decode Time Stamp。DTS主要是标识读入内存中的流在什么时候开始送入解码器中进行解码 if(pkt.pts==AV_NOPTS_VALUE){ //Write PTS AVRational time_base1=inFmtCtx->streams[videoindex]->time_base; //Duration between 2 frames (us) int64_t calc_duration=(double)AV_TIME_BASE/av_q2d(inFmtCtx->streams[videoindex]->r_frame_rate); //Parameters pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE); pkt.dts=pkt.pts; pkt.duration=(double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE); } if(pkt.stream_index==videoindex){ //FFmpeg处理数据速度很快,瞬间就能把所有的数据发送出去,流媒体服务器是接受不了 //这里采用av_usleep()函数休眠的方式来延迟发送,延时时间根据帧率与时间基准计算得到 AVRational time_base=inFmtCtx->streams[videoindex]->time_base; AVRational time_base_q={1,AV_TIME_BASE}; int64_t pts_time = av_rescale_q(pkt.dts, time_base, time_base_q); int64_t now_time = av_gettime() - start_time; if (pts_time > now_time){ av_usleep(pts_time - now_time); } } in_stream = inFmtCtx->streams[pkt.stream_index]; out_stream = outFmtCtx->streams[pkt.stream_index]; /* copy packet */ //Convert PTS/DTS pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX); pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; //输出进度 if(pkt.stream_index==videoindex){ LOGI("第%d帧",frame_index); frame_index++; } //推送 ret = av_interleaved_write_frame(outFmtCtx, &pkt); if (ret < 0) { LOGE( "Error muxing packet"); break; } av_free_packet(&pkt); } //输出结尾 av_write_trailer(outFmtCtx); end: //释放资源 avformat_free_context(inFmtCtx); avio_close(outFmtCtx->pb); avformat_free_context(outFmtCtx); };<file_sep>#include "include/com_android_jni_ffmpeg_FfmpegPlayer.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <android/log.h> #include <android/native_window_jni.h> #include <android/native_window.h> #define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"jason",FORMAT,##__VA_ARGS__); #define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"jason",FORMAT,##__VA_ARGS__); #include "libyuv.h" #include "queue.h" //封装格式 #include "libavformat/avformat.h" //解码 #include "libavcodec/avcodec.h" //缩放 #include "libswscale/swscale.h" //重采样 #include "libswresample/swresample.h" //nb_streams,视频文件中存在,音频流,视频流,字幕 #define MAX_STREAM 2 #define PACKET_QUEUE_SIZE 50 #define MAX_AUDIO_FRME_SIZE 48000 * 4 typedef struct _Player Player; typedef struct _DecoderData DecoderData; struct _Player{ JavaVM *javaVM; //封装格式上下文 AVFormatContext *input_format_ctx; //音频视频流索引位置 int video_stream_index; int audio_stream_index; //流的总个数 int captrue_streams_no; //解码器上下文数组 AVCodecContext *input_codec_ctx[MAX_STREAM]; //解码线程ID pthread_t decode_threads[MAX_STREAM]; ANativeWindow* nativeWindow; SwrContext *swr_ctx; //输入的采样格式 enum AVSampleFormat in_sample_fmt; //输出采样格式16bit PCM enum AVSampleFormat out_sample_fmt; //输入采样率 int in_sample_rate; //输出采样率 int out_sample_rate; //输出的声道个数 int out_channel_nb; //JNI jobject audio_track; jmethodID audio_track_write_mid; pthread_t thread_read_from_stream; //音频,视频队列数组 Queue *packets[MAX_STREAM]; }; //解码数据 struct _DecoderData{ Player *player; int stream_index; }; /** * 初始化封装格式上下文,获取音频视频流的索引位置 */ void init_input_format_ctx(Player *player,const char* input_cstr){ //注册组件 av_register_all(); //封装格式上下文 AVFormatContext *format_ctx = avformat_alloc_context(); //打开输入视频文件 if(avformat_open_input(&format_ctx,input_cstr,NULL,NULL) != 0){ LOGE("%s","打开输入视频文件失败"); return; } //获取视频信息 if(avformat_find_stream_info(format_ctx,NULL) < 0){ LOGE("%s","获取视频信息失败"); return; } player->captrue_streams_no = format_ctx->nb_streams; LOGI("captrue_streams_no:%d",player->captrue_streams_no); //视频解码,需要找到视频对应的AVStream所在format_ctx->streams的索引位置 //获取音频和视频流的索引位置 int i; for(i = 0; i < player->captrue_streams_no;i++){ if(format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){ player->video_stream_index = i; } else if(format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO){ player->audio_stream_index = i; } } player->input_format_ctx = format_ctx; } /** * 初始化解码器上下文 */ void init_codec_context(Player *player,int stream_idx){ AVFormatContext *format_ctx = player->input_format_ctx; //获取解码器 LOGI("init_codec_context begin"); AVCodecContext *codec_ctx = format_ctx->streams[stream_idx]->codec; LOGI("init_codec_context end"); AVCodec *codec = avcodec_find_decoder(codec_ctx->codec_id); if(codec == NULL){ LOGE("%s","无法解码"); return; } //打开解码器 if(avcodec_open2(codec_ctx,codec,NULL) < 0){ LOGE("%s","解码器无法打开"); return; } player->input_codec_ctx[stream_idx] = codec_ctx; } /** * 解码视频 */ void decode_video(Player *player,AVPacket *packet){ //像素数据(解码数据) AVFrame *yuv_frame = av_frame_alloc(); AVFrame *rgb_frame = av_frame_alloc(); //绘制时的缓冲区 ANativeWindow_Buffer outBuffer; AVCodecContext *codec_ctx = player->input_codec_ctx[player->video_stream_index]; int got_frame; //解码AVPacket->AVFrame avcodec_decode_video2(codec_ctx, yuv_frame, &got_frame, packet); //Zero if no frame could be decompressed //非零,正在解码 if(got_frame){ //lock //设置缓冲区的属性(宽、高、像素格式) ANativeWindow_setBuffersGeometry(player->nativeWindow, codec_ctx->width, codec_ctx->height,WINDOW_FORMAT_RGBA_8888); ANativeWindow_lock(player->nativeWindow,&outBuffer,NULL); //设置rgb_frame的属性(像素格式、宽高)和缓冲区 //rgb_frame缓冲区与outBuffer.bits是同一块内存 avpicture_fill((AVPicture *)rgb_frame, outBuffer.bits, AV_PIX_FMT_RGBA, codec_ctx->width, codec_ctx->height); //YUV->RGBA_8888 I420ToARGB(yuv_frame->data[0],yuv_frame->linesize[0], yuv_frame->data[2],yuv_frame->linesize[2], yuv_frame->data[1],yuv_frame->linesize[1], rgb_frame->data[0], rgb_frame->linesize[0], codec_ctx->width,codec_ctx->height); //unlock ANativeWindow_unlockAndPost(player->nativeWindow); usleep(1000 * 16); } av_frame_free(&yuv_frame); av_frame_free(&rgb_frame); } /** * 音频解码准备 */ void decode_audio_prepare(Player *player){ AVCodecContext *codec_ctx = player->input_codec_ctx[player->audio_stream_index]; //重采样设置参数-------------start //输入的采样格式 enum AVSampleFormat in_sample_fmt = codec_ctx->sample_fmt; //输出采样格式16bit PCM enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16; //输入采样率 int in_sample_rate = codec_ctx->sample_rate; //输出采样率 int out_sample_rate = in_sample_rate; //获取输入的声道布局 //根据声道个数获取默认的声道布局(2个声道,默认立体声stereo) //av_get_default_channel_layout(codecCtx->channels); uint64_t in_ch_layout = codec_ctx->channel_layout; //输出的声道布局(立体声) uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO; //frame->16bit 44100 PCM 统一音频采样格式与采样率 SwrContext *swr_ctx = swr_alloc(); swr_alloc_set_opts(swr_ctx, out_ch_layout,out_sample_fmt,out_sample_rate, in_ch_layout,in_sample_fmt,in_sample_rate, 0, NULL); swr_init(swr_ctx); //输出的声道个数 int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout); //重采样设置参数-------------end player->in_sample_fmt = in_sample_fmt; player->out_sample_fmt = out_sample_fmt; player->in_sample_rate = in_sample_rate; player->out_sample_rate = out_sample_rate; player->out_channel_nb = out_channel_nb; player->swr_ctx = swr_ctx; } void jni_audio_prepare(JNIEnv *env,jobject jthiz,Player *player){ //JNI begin------------------ //JasonPlayer jclass player_class = (*env)->GetObjectClass(env,jthiz); //AudioTrack对象 jmethodID create_audio_track_mid = (*env)->GetMethodID(env,player_class,"createAudioTrack","(II)Landroid/media/AudioTrack;"); jobject audio_track = (*env)->CallObjectMethod(env,jthiz,create_audio_track_mid,player->out_sample_rate,player->out_channel_nb); //调用AudioTrack.play方法 jclass audio_track_class = (*env)->GetObjectClass(env,audio_track); jmethodID audio_track_play_mid = (*env)->GetMethodID(env,audio_track_class,"play","()V"); (*env)->CallVoidMethod(env,audio_track,audio_track_play_mid); //AudioTrack.write jmethodID audio_track_write_mid = (*env)->GetMethodID(env,audio_track_class,"write","([BII)I"); //JNI end------------------ player->audio_track = (*env)->NewGlobalRef(env,audio_track); //(*env)->DeleteGlobalRef player->audio_track_write_mid = audio_track_write_mid; } /** * 音频解码 */ void decode_audio(Player *player,AVPacket *packet){ AVCodecContext *codec_ctx = player->input_codec_ctx[player->audio_stream_index]; LOGI("%s","decode_audio"); //解压缩数据 AVFrame *frame = av_frame_alloc(); int got_frame; avcodec_decode_audio4(codec_ctx,frame,&got_frame,packet); //16bit 44100 PCM 数据(重采样缓冲区) uint8_t *out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRME_SIZE); //解码一帧成功 if(got_frame > 0){ swr_convert(player->swr_ctx, &out_buffer, MAX_AUDIO_FRME_SIZE,(const uint8_t **)frame->data,frame->nb_samples); //获取sample的size int out_buffer_size = av_samples_get_buffer_size(NULL, player->out_channel_nb, frame->nb_samples, player->out_sample_fmt, 1); //关联当前线程的JNIEnv JavaVM *javaVM = player->javaVM; JNIEnv *env; (*javaVM)->AttachCurrentThread(javaVM,&env,NULL); //out_buffer缓冲区数据,转成byte数组 jbyteArray audio_sample_array = (*env)->NewByteArray(env,out_buffer_size); jbyte* sample_bytep = (*env)->GetByteArrayElements(env,audio_sample_array,NULL); //out_buffer的数据复制到sampe_bytep memcpy(sample_bytep,out_buffer,out_buffer_size); //同步 (*env)->ReleaseByteArrayElements(env,audio_sample_array,sample_bytep,0); //AudioTrack.write PCM数据 (*env)->CallIntMethod(env,player->audio_track,player->audio_track_write_mid, audio_sample_array,0,out_buffer_size); //释放局部引用 (*env)->DeleteLocalRef(env,audio_sample_array); (*javaVM)->DetachCurrentThread(javaVM); usleep(1000 * 16); } av_frame_free(&frame); } /** * 解码子线程函数(消费) */ void* decode_data(void* arg){ DecoderData *decoder_data = (DecoderData*)arg; Player *player = decoder_data->player; int stream_index = decoder_data->stream_index; //根据stream_index获取对应的AVPacket队列 Queue *queue = player->packets[stream_index]; AVFormatContext *format_ctx = player->input_format_ctx; //编码数据 //6.一阵一阵读取压缩的视频数据AVPacket int video_frame_count = 0, audio_frame_count = 0; for(;;){ //消费AVPacket AVPacket *packet = (AVPacket*)queue_pop(queue); if(stream_index == player->video_stream_index){ decode_video(player,packet); LOGI("video_frame_count:%d",video_frame_count++); }else if(stream_index == player->audio_stream_index){ decode_audio(player,packet); LOGI("audio_frame_count:%d",audio_frame_count++); } } } void decode_video_prepare(JNIEnv *env,Player *player,jobject surface){ player->nativeWindow = ANativeWindow_fromSurface(env,surface); } /** * 给AVPacket开辟空间,后面会将AVPacket栈内存数据拷贝至这里开辟的空间 */ void* player_fill_packet(){ //请参照我在vs中写的代码 AVPacket *packet = malloc(sizeof(AVPacket)); return packet; } /** * 初始化音频,视频AVPacket队列,长度50 */ void player_alloc_queues(Player *player){ int i; //这里,正常是初始化两个队列 for (i = 0; i < player->captrue_streams_no; ++i) { Queue *queue = queue_init(PACKET_QUEUE_SIZE,(queue_fill_func)player_fill_packet); player->packets[i] = queue; //打印视频音频队列地址 LOGI("stream index:%d,queue:%#x",i,queue); } } void* packet_free_func(AVPacket *packet){ av_free_packet(packet); return 0; } /** * 生产者线程:负责不断的读取视频文件中AVPacket,分别放入两个队列中 */ void* player_read_from_stream(Player* player){ int index = 0; int ret; //栈内存上保存一个AVPacket AVPacket packet, *pkt = &packet; for(;;){ ret = av_read_frame(player->input_format_ctx,pkt); //到文件结尾了 if(ret < 0){ break; } //根据AVpacket->stream_index获取对应的队列 Queue *queue = player->packets[pkt->stream_index]; //示范队列内存释放 //queue_free(queue,packet_free_func); //将AVPacket压入队列 AVPacket *packet_data = queue_push(queue); //拷贝(间接赋值,拷贝结构体数据) *packet_data = packet; LOGI("queue:%#x, packet:%#x",queue,packet); } } JNIEXPORT void JNICALL Java_com_dongnaoedu_dnffmpegplayer_JasonPlayer_play (JNIEnv *env, jobject jobj, jstring input_jstr, jobject surface){ const char* input_cstr = (*env)->GetStringUTFChars(env,input_jstr,NULL); Player *player = (Player*)malloc(sizeof(Player)); (*env)->GetJavaVM(env,&(player->javaVM)); //初始化封装格式上下文 init_input_format_ctx(player,input_cstr); int video_stream_index = player->video_stream_index; int audio_stream_index = player->audio_stream_index; //获取音视频解码器,并打开 init_codec_context(player,video_stream_index); init_codec_context(player,audio_stream_index); decode_video_prepare(env,player,surface); decode_audio_prepare(player); jni_audio_prepare(env,jobj,player); player_alloc_queues(player); //生产者线程 pthread_create(&(player->thread_read_from_stream),NULL,player_read_from_stream,(void*)player); sleep(5); //消费者线程 DecoderData data1 = {player,video_stream_index}, *decoder_data1 = &data1; pthread_create(&(player->decode_threads[video_stream_index]),NULL,decode_data,(void*)decoder_data1); DecoderData data2 = {player,audio_stream_index}, *decoder_data2 = &data2; pthread_create(&(player->decode_threads[audio_stream_index]),NULL,decode_data,(void*)decoder_data2); pthread_join(player->thread_read_from_stream,NULL); pthread_join(player->decode_threads[video_stream_index],NULL); pthread_join(player->decode_threads[audio_stream_index],NULL); /*ANativeWindow_release(nativeWindow); av_frame_free(&yuv_frame); avcodec_close(pCodeCtx); avformat_free_context(pFormatCtx); (*env)->ReleaseStringUTFChars(env,input_jstr,input_cstr); free(player);*/ }
252e8d30219ca61b3ea208c8bde7f269bdc7c98d
[ "Java", "C" ]
3
Java
Kurtash/jni_android
de7d6d2a3b0be361268d3a6c0853ed2e9ce8c332
10dba1cc3067bcfcbe8b74cc3dd3766907f3b798
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Employee } from '../employee.model'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent implements OnInit { model = new Employee("dilip","rao",true,""); lang:['English','spanish','Other']; constructor() { } ngOnInit() { } } <file_sep>export class Employee { constructor( public firstname: string, public lastname: string, public isFullTime:boolean, public paytype:string ) { } }
be7aa598c9dc0e8bb92912c9c4d0d8add65f0299
[ "TypeScript" ]
2
TypeScript
dilipteegala/Angular-Routing-Demo
66378f90197741894031bbc0fc662e05f40aa57c
d4cbd810c23fe6b61d8713da390c3ddd619d4fd4
refs/heads/master
<repo_name>andyrewlee/rubyprac<file_sep>/18_frank_users/13_users_posts_create/answer/controllers/posts_controller.rb class PostsController < ApplicationController post '/' do erb :main_layout do user = User.find(params[:user_id]) user.posts.create(content: params[:content]) redirect "/users/#{user.id}" end end end <file_sep>/18_frank_users/01_users_index/answer/controllers/users_controller.rb class UsersController < ApplicationController get '/' do @title = 'All Users' erb :main_layout do @users = User.all erb :'users/index' end end end <file_sep>/06_ruby_queue/14 - Ruby Queue/answer/queue.rb class Queue attr_accessor :data_store attr_reader :back def initialize @back = 0 @data_store = [] end def enqueue(item) @data_store[@back] = item @back += 1 end def display output = [] for i in 0...@back output << @data_store[i] end output end def dequeue output = @data_store[0] for i in 1...@back @data_store[i - 1] = @data_store[i] end @back -= 1 output end end <file_sep>/07_ruby_mathdojo/15 - Ruby Math Dojo/answer/mathdojo.rb class MathDojo attr_accessor :answer def initialize @answer = 0 end def add(arg) if arg.class == Array @answer += arg.reduce(:+) else @answer += arg end self end def subtract(arg) if arg.class == Array @answer -= arg.reduce(:+) else @answer -= arg end self end end <file_sep>/17_sinatra_projects/6 - Sinatra Projects New/answer/server.rb require 'sinatra' require 'active_record' ENV['SINATRA_ENV'] ||= "development" ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => "db/#{ENV['SINATRA_ENV']}.sqlite" ) class Project < ActiveRecord::Base end get '/' do 'Welcome to my portfolio' end get '/projects' do @projects = Project.all erb :'projects/index' end get '/projects/new' do erb :'projects/new' end <file_sep>/09_ruby_timer/1 - Ruby Timer/answer/timer.rb def timer start_time = Time.new yield end_time = Time.new end_time - start_time end <file_sep>/02_ruby_inheritance/10 - Ruby Inheritance Ninja/answer/samurai.rb class Samurai < Human def cherry_blossom @health += 1000 end end <file_sep>/16_sinatra_timedisplay/4 - Sinatra Time Display/answer/server.rb require 'sinatra' get '/' do @time = Time.new erb :time end <file_sep>/01_ruby_project/2 - Ruby Project pt. 2/answer/project.rb class Project attr_accessor :name, :description end <file_sep>/12_ruby_initialization/4 - Ruby Initialization/answer/my_create_table.rb class Table attr_accessor :table_name, :first_name, :last_name, :age end def my_create_table(name) table = Table.new table.table_name = name yield(table) return table end <file_sep>/18_frank_users/06_users_update/answer/config.ru require_relative 'frank' map('/welcomes') { run WelcomesController } map('/users') { run UsersController } <file_sep>/18_frank_users/14_users_posts_destroy/answer/controllers/posts_controller.rb class PostsController < ApplicationController post '/' do erb :main_layout do user = User.find(params[:user_id]) user.posts.create(content: params[:content]) redirect "/users/#{user.id}" end end delete '/:id' do erb :main_layout do user = User.find(params[:user_id]) post = Post.find(params[:id]) post.destroy redirect "/users/#{user.id}" end end end <file_sep>/01_ruby_project/1 - Ruby Project pt. 1/answer/project.rb class Project attr_accessor :name end <file_sep>/08_ruby_sll/16 - Ruby SLL/answer/sll.rb class SinglyLinkedList attr_accessor :head def initialize @head = Node.new('head') end def insert(new_element, element) new_node = Node.new(new_element) curr = find(element) new_node.next = curr.next curr.next = new_node end def find(element) curr = @head curr = curr.next while curr && curr.element != element curr end def display_nodes output = [] curr = @head while curr.next output << curr.next curr = curr.next end output end def display_elements display_nodes.map { |n| n.element } end def remove(element) previous_node = find_previous(element) if previous_node output = previous_node.next if previous_node.next != nil previous_node.next = previous_node.next.next end output.next = nil output else nil end end def find_previous(element) curr = @head while curr.next && curr.next.element != element curr = curr.next end if curr.next && curr.next.element == element curr else nil end end end <file_sep>/02_ruby_inheritance/10 - Ruby Inheritance Ninja/answer/samurai_spec.rb require_relative 'samurai' RSpec.describe Samurai do it 'has an ancestor chain that includes Human' do human = Samurai.ancestors.include?(Human) expect(human).to eq(true) end it 'has a cherry_blossom method that increases its health by 1000' do samurai = Samurai.new samurai.health = 0 samurai.cherry_blossom expect(samurai.health).to eq(1000) end end <file_sep>/03_ruby_fixnum/11 - Ruby Fixnum/answer/fixnum.rb class Fixnum def prev self - 1 end def skip self + 2 end def double self * 2 end end <file_sep>/11_ruby_testframework/3 - Ruby Test Framework/answer/my_expect.rb def my_expect(arg) arg == yield end <file_sep>/02_ruby_inheritance/9 - Ruby Inheritance Ninja/answer/ninja.rb class Ninja < Human def initialize super @stealth = 175 end def steal @stealth += 10 end end <file_sep>/04_ruby_string/12 - Ruby String/answer/string.rb class String def my_reverse output = [] (self.length - 1).downto(0) do |i| output << self[i] end output.join end def my_reverse! reverse = self.my_reverse.split("") for i in 0...reverse.length self[i] = reverse[i] end self end end
6a9ddaf9edc2796160e312db810e75ee16909aef
[ "Ruby" ]
19
Ruby
andyrewlee/rubyprac
a99da49327eaeebc31b16187f7e57123b036944b
6e40ad4848a967771f5afa5798b6225f0d16230b
refs/heads/master
<repo_name>hannut91/project-react-1-kwonmory<file_sep>/fixtures/interview-questions.js const depthOfQuestion = ['하', '중', '상']; const interviewQuestions = [ { id: 1, title: '인덱스(Index)란 무엇인가?', categories: ['Database'], reviews: ['리뷰', '리뷰'], depthOfQuestion: depthOfQuestion[0], relatedCompany: ['쿠팡'], }, { id: 2, title: '왜 index 를 생성하는데 b-tree 를 사용하나요?', categories: ['Database'], reviews: ['리뷰'], depthOfQuestion: depthOfQuestion[2], relatedCompany: [], }, { id: 3, title: '멀티 스레딩의 장점은 무엇인가요?', categories: ['Operation'], reviews: [], depthOfQuestion: depthOfQuestion[0], relatedCompany: [], }, { id: 4, title: 'SJF(Shortest - Job - First)의 문제점은 무엇이 있나요?', categories: ['Operation'], reviews: ['리뷰', '리뷰', '리뷰', '리뷰', '리뷰'], depthOfQuestion: depthOfQuestion[1], relatedCompany: ['우아한형제들'], }, { id: 5, title: 'Hoisting에 대해서 설명해주세요.', categories: ['Javascript'], reviews: [], depthOfQuestion: depthOfQuestion[0], relatedCompany: ['Kakao', 'Naver'], }, ]; export default interviewQuestions; <file_sep>/webpack.config.js const path = require('path'); const apiMocker = require('connect-api-mocker'); const CopyPlugin = require('copy-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: path.resolve(__dirname, 'src/index.jsx'), module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, use: 'babel-loader', }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, resolve: { extensions: ['.js', '.jsx'], }, output: { path: path.resolve(__dirname, './dist'), publicPath: process.env.BASE_URL || '/', }, plugins: [ new CopyPlugin({ patterns: [ { from: './index.html', to: './', }, ], }), new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: 'index.html', }), ], devServer: { before: (app) => { app.use(apiMocker('/api', '/mocks/api')); }, historyApiFallback: { historyApiFallback: true, }, }, }; <file_sep>/mocks/api/auth/README.md # POST api/auth 서버는 Id와 Password를 받고 access_token 발급한다. - 실제 동작 : id 와 password 요청에 따라 토큰 발급 - 목 동작 : id 와 password 관계없이 토큰 발급 <file_sep>/mocks/api/problems/README.md # GET /api/problems 문제들을 모두 가져옴 문제에 대한 댓글도 가져온다고 가정함 - 배열 형태 <file_sep>/test/header_test.js Feature('Header Area'); Scenario('헤더는 로고 클래스를 가지고 있다', (I) => { I.amOnPage('/'); I.seeElement('.logo'); }); <file_sep>/src/containers/common/HeaderContainer.test.jsx import React, { useState as useStateMock } from 'react'; import { fireEvent, render } from '@testing-library/react'; import { useDispatch, useSelector } from 'react-redux'; import { MemoryRouter } from 'react-router-dom'; import HeaderContainer from './HeaderContainer'; jest.mock('react-redux'); jest.mock('react', () => ({ ...jest.requireActual('react'), useState: jest.fn(), })); function renderHeaderContainer() { return render( <MemoryRouter> <HeaderContainer /> </MemoryRouter>, ); } describe('HeaderContainer', () => { const dispatch = jest.fn(); const dropDownMenuActive = jest.fn(); beforeEach(() => { dispatch.mockClear(); useStateMock.mockImplementation((init) => [init, dropDownMenuActive]); useDispatch.mockImplementation(() => dispatch); useSelector.mockImplementation((selector) => selector({ accessToken: given.accessToken || '', })); }); it('renders HeaderContainer', () => { const { container } = renderHeaderContainer(); expect(container.querySelector('.drop-menu-button')).not.toBeNull(); fireEvent.click(container.querySelector('.drop-menu-button')); expect(dropDownMenuActive).toBeCalled(); }); describe('accessToken', () => { context('with login', () => { given('accessToken', () => 'ACCESSTOKEN'); it('not renders "로그인" button', () => { const { queryByText } = renderHeaderContainer(); expect(queryByText(/로그인/)).toBeNull(); expect(queryByText(/회원가입/)).toBeNull(); }); }); context('without login', () => { it('renders "로그인/회원가입" button', () => { given('accessToken', () => ''); const { queryByText } = renderHeaderContainer(); expect(queryByText(/로그인/)).not.toBeNull(); expect(queryByText(/회원가입/)).not.toBeNull(); }); }); }); }); <file_sep>/mocks/api/README.md # Mock Api [connect-api-mocker](https://github.com/muratcorlu/connect-api-mocker) - 각 api는 조인(join)된 데이터 형태로 작성하려고합니다. - 각 데이터는 미확정이며, 구조는 변경됩니다. <file_sep>/src/containers/common/HeaderContainer.jsx import React, { useState } from 'react'; import { useSelector } from 'react-redux'; import Header from '../../components/common/Header'; const HeaderContainer = () => { const accessToken = useSelector((state) => state.accessToken); const [dropDownMenuActive, setDropdownMenuActive] = useState(false); const handleDropdownMenuActive = () => { setDropdownMenuActive(!dropDownMenuActive); }; return ( <Header login={accessToken} onDropdownMenuActive={handleDropdownMenuActive} dropDownMenuActive={dropDownMenuActive} /> ); }; export default HeaderContainer; <file_sep>/mocks/api/categories/README.md # GET /api/categories 문제 유형들에 대한 데이터를 반환한다. - id : 식별자 - ko : 한글용어 - en : 영어용어 <file_sep>/src/modules/reducer.test.js import reducer, { setAccessToken, setInterviewQuestions, } from './reducer'; import interviewQuestions from '../../fixtures/interview-questions'; describe('reducer', () => { const initialState = { accessToken: given.accessToken || '', interview: { questions: [], }, }; context('without state', () => { it('returns inistialState', () => { const state = reducer(undefined, { type: 'action' }); expect(state).toEqual(initialState); }); }); describe('setAccessToken', () => { it('returns accessToken', () => { const ACCESS_TOKEN = 'ACCESS_TOKEN'; const state = reducer(initialState, setAccessToken(ACCESS_TOKEN)); expect(state.accessToken).toBe(ACCESS_TOKEN); }); }); describe('setInterviewQuestions', () => { const state = reducer(initialState, setInterviewQuestions(interviewQuestions)); expect(state.interview.questions).toEqual(interviewQuestions); }); }); <file_sep>/mocks/api/users/README.md # GET /api/users/1 1번 유저에대한 데이터를 반환한다. <file_sep>/src/components/common/Header.test.jsx import React from 'react'; import { render, fireEvent } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import Header from './Header'; function renderHeader({ token, dropdownMenuActive, handleDropdownMenuActive }) { return render( <MemoryRouter> <Header login={token} dropdownMenuActive={dropdownMenuActive} onDropdownMenuActive={handleDropdownMenuActive} /> </MemoryRouter>, ); } describe('Header', () => { const handleDropdownMenuActive = jest.fn(); context('with login', () => { it('renders "로그아웃" 메뉴', () => { const { container } = renderHeader({ token: 'ACCESS_TOKEN', dropdownMenuActive: true, handleDropdownMenuActive, }); expect(container).not.toHaveTextContent('로그인'); }); }); context('without login', () => { it('renders Header', () => { const { container } = renderHeader({ token: '', dropdownMenuActive: false, handleDropdownMenuActive, }); expect(container).toHaveTextContent('서비스소개'); expect(container).toHaveTextContent('인터뷰즈'); expect(container).toHaveTextContent('인터뷰연습'); expect(container.querySelector('.logo')).not.toBeNull(); expect(container.querySelector('button')).not.toBeNull(); fireEvent.click(container.querySelector('button')); expect(handleDropdownMenuActive).toBeCalled(); }); }); }); <file_sep>/README.md # KWONMORY REACT PROJECT ## Know Answer Interview For Developer Helper 개발자 인터뷰 준비를 도와주기 위한 사이트! ## 개발 중 제한 조건 * 커밋은 의미 단위로 커밋한다. * 모든 기능은 TDD로 구현한다. * `if`는 사용할 수 있어도 `else` 사용하실 수 없다. `GuardClauses` 방법을 사용한다. * `switch`는 사용하실 수 없다. * `let`은 사용하실 수 없다. `const`만을 사용하여 문제를 해결하라. * 함수 이름과 변수 이름에 줄임말은 사용하실 수 없다. 길더라도 명확하게 써라. * indent(인덴트, 들여쓰기) depth를 1로 유지해라. 예를 들어, for문 안에 if문이 있으면 indent depth는 2입니다. depth를 줄이는 좋은 방법은 함수(또는 메소드)를 분리하면 된다. ## 설치하기 ```bash npm install ``` ## 실행하기 ```bash npm start ``` ## Lint 실행하기 ```bash npm run lint ``` ## 커버리지 출력하기 ```bash npm run coverage ``` ## 전체 테스트 ```bash npm test ``` ## 유닛 테스트 ```bash npm run test:unit ```
30596710f4ff9ec341528f7554bf459452784e86
[ "JavaScript", "Markdown" ]
13
JavaScript
hannut91/project-react-1-kwonmory
cdd0adccb73242289ceeda8b2d8335a6fa687577
7e70b0b26e65534e371eb450b7bad569deb00add
refs/heads/master
<file_sep>""" Actor-Critic using TD-error as the Advantage, Reinforcement Learning. The cart pole example. Policy is oscillated. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ Using: tensorflow 1.0 gym 0.8.0 """ import numpy as np import tensorflow as tf import os from agent.helper import * import environment.steelstockyard as ssy import environment.plate as plate np.random.seed(2) tf.set_random_seed(2) # reproducible class Actor(object): def __init__(self, sess, n_features, n_actions, feature_size, lr=0.001): self.sess = sess self.feature_size = feature_size self.s = tf.placeholder(tf.float32, [1, n_features], "state") self.s_reshaped = tf.reshape(self.s, shape=[-1, self.feature_size[0], self.feature_size[1], 1]) self.a = tf.placeholder(tf.int32, None, "act") self.td_error = tf.placeholder(tf.float32, None, "td_error") # TD_error with tf.variable_scope('Actor'): conv1 = tf.layers.conv2d( inputs=self.s_reshaped, filters=16, kernel_size=4, strides=2, padding='VALID', activation=tf.nn.relu ) conv2 = tf.layers.conv2d( inputs=conv1, filters=32, kernel_size=2, strides=1, padding='VALID', activation=tf.nn.relu ) conv2_flat = tf.layers.flatten(conv2) l1 = tf.layers.dense( inputs=conv2_flat, units=20, # number of hidden units activation=tf.nn.relu, kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l1' ) l2 = tf.layers.dense( inputs=l1, units=20, # number of hidden units activation=tf.nn.relu, kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l2' ) self.acts_prob = tf.layers.dense( inputs=l2, units=n_actions, # output units activation=tf.nn.softmax, # get action probabilities kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='acts_prob' ) with tf.variable_scope('exp_v'): log_prob = tf.log(self.acts_prob[0, self.a]) self.exp_v = tf.reduce_mean(log_prob * self.td_error) # advantage (TD_error) guided loss with tf.variable_scope('train'): self.train_op = tf.train.AdamOptimizer(lr).minimize(-self.exp_v) # minimize(-exp_v) = maximize(exp_v) def learn(self, s, a, td): s = s[np.newaxis, :] feed_dict = {self.s: s, self.a: a, self.td_error: td} _, exp_v = self.sess.run([self.train_op, self.exp_v], feed_dict) return exp_v def choose_action(self, s): s = s[np.newaxis, :] probs = self.sess.run(self.acts_prob, {self.s: s}) # get probabilities for all actions return np.random.choice(np.arange(probs.shape[1]), p=probs.ravel()) # return a int def save_model(self): if not os.path.exists('../models/a2c'): os.makedirs('../models/a2c') if not os.path.exists('../models/a2c/actor'): os.makedirs('../models/a2c/actor') if not os.path.exists('../models/a2c/actor/%d-%d' % (self.feature_size[0], self.feature_size[1])): os.makedirs('../models/a2c/actor/%d-%d' % (self.feature_size[0], self.feature_size[1])) saver = tf.train.Saver() saver.save(self.sess, '../models/a2c/actor/%d-%d' % (self.feature_size[0], self.feature_size[1])) class Critic(object): def __init__(self, sess, n_features, n_actions, feature_size, lr=0.01): self.sess = sess self.feature_size = feature_size self.s = tf.placeholder(tf.float32, [1, n_features], "state") self.s_reshaped = tf.reshape(self.s, shape=[-1, feature_size[0], feature_size[1], 1]) self.v_ = tf.placeholder(tf.float32, [1, 1], "v_next") self.r = tf.placeholder(tf.float32, None, 'r') with tf.variable_scope('Critic'): conv1 = tf.layers.conv2d( inputs=self.s_reshaped, filters=16, kernel_size=4, strides=2, padding='VALID', activation=tf.nn.relu ) conv2 = tf.layers.conv2d( inputs=conv1, filters=32, kernel_size=2, strides=1, padding='VALID', activation=tf.nn.relu ) conv2_flat = tf.layers.flatten(conv2) l1 = tf.layers.dense( inputs=conv2_flat, units=15, # number of hidden units activation=tf.nn.relu, # None # have to be linear to make sure the convergence of actor. # But linear approximator seems hardly learns the correct Q. kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l1' ) l2 = tf.layers.dense( inputs=l1, units=15, # number of hidden units activation=tf.nn.relu, # None # have to be linear to make sure the convergence of actor. # But linear approximator seems hardly learns the correct Q. kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='l2' ) self.v = tf.layers.dense( inputs=l2, units=1, # output units activation=None, kernel_initializer=tf.random_normal_initializer(0., 0.3), # weights bias_initializer=tf.constant_initializer(0.1), # biases name='V' ) with tf.variable_scope('squared_TD_error'): self.td_error = self.r + GAMMA * self.v_ - self.v self.loss = tf.square(self.td_error) # TD_error = (r+gamma*V_next) - V_eval with tf.variable_scope('train'): self.train_op = tf.train.AdamOptimizer(lr).minimize(self.loss) def learn(self, s, r, s_): s, s_ = s[np.newaxis, :], s_[np.newaxis, :] v_ = self.sess.run(self.v, {self.s: s_}) td_error, _ = self.sess.run([self.td_error, self.train_op], {self.s: s, self.v_: v_, self.r: r}) return td_error def save_model(self): if not os.path.exists('../models/a2c'): os.makedirs('../models/a2c') if not os.path.exists('../models/a2c/critic'): os.makedirs('../models/a2c/critic') if not os.path.exists('../models/a2c/critic/%d-%d' % (self.feature_size[0], self.feature_size[1])): os.makedirs('../models/a2c/critic/%d-%d' % (self.feature_size[0], self.feature_size[1])) saver = tf.train.Saver() saver.save(self.sess, '../models/a2c/critic/%d-%d' % (self.feature_size[0], self.feature_size[1])) def plot_reward(rewards): if not os.path.exists('../summary/a2c/{0}_{1}/'.format(s_shape[0], s_shape[1])): os.makedirs('../summary/a2c/{0}_{1}/'.format(s_shape[0], s_shape[1])) import csv f = open('../summary/a2c/{0}_{1}/rewards_{2}_{3}.csv'. format(s_shape[0], s_shape[1], env.action_space, env.max_stack), 'w', encoding='utf-8') wr = csv.writer(f) for i in range(1, len(rewards)+1): wr.writerow([i, rewards[i-1]]) f.close() import matplotlib.pyplot as plt plt.plot(np.arange(len(rewards)), rewards) plt.ylabel('average reward') plt.xlabel('training episode') plt.show() def run(episodes=1000): step = 0 rewards = [] avg_rewards = [] for episode in range(1, episodes+1): s = env.reset(episode) rs = [] episode_frames = [] while True: episode_frames.append(s) a = actor.choose_action(s) s_, r, done = env.step(a) rs.append(r) td_error = critic.learn(s, r, s_) # gradient = grad[r + gamma * V(s_) - V(s)] actor.learn(s, a, td_error) # true_gradient = grad[logPi(s,a) * td_error] s = s_ if done: rewards.append(sum(rs)) avg_rewards.append(sum(rewards) / len(rewards)) break step += 1 if episode % 1000 == 0: print('episode: {0} finished'.format(episode)) if not os.path.exists('../frames/a2c'): os.makedirs('../frames/a2c') if not os.path.exists('../frames/a2c/%d-%d' % s_shape): os.makedirs('../frames/a2c/%d-%d' % s_shape) save_gif(episode_frames, s_shape, episode, 'a2c') actor.save_model() critic.save_model() plot_reward(avg_rewards) # end of game print('game over') if __name__ == "__main__": # inbounds = plate.import_plates_schedule('../environment/data/plate_example1.csv') # inbounds = plate.import_plates_schedule_rev('../environment/data/SampleData.csv') inbounds = plate.import_plates_schedule_by_week('../environment/data/SampleData.csv') max_stack = 11 num_pile = 6 observe_inbounds = True if observe_inbounds: s_shape = (max_stack, num_pile + 1) else: s_shape = (max_stack, num_pile) s_size = s_shape[0] * s_shape[1] env = ssy.Locating(max_stack=max_stack, num_pile=num_pile, inbound_plates=inbounds, observe_inbounds=observe_inbounds, display_env=False) N_F = s_size N_A = env.action_space # Superparameters #OUTPUT_GRAPH = False #RENDER = True # rendering wastes time GAMMA = 0.99 # reward discount in TD error LR_A = 1e-5 # learning rate for actor LR_C = 1e-5 # learning rate for critic sess = tf.Session() actor = Actor(sess, N_F, N_A, s_shape, lr=LR_A) critic = Critic(sess, N_F, N_A, s_shape, lr=LR_C) sess.run(tf.global_variables_initializer()) run(30000)<file_sep>import pandas as pd import numpy as np import scipy.stats as stats import random from datetime import datetime random.seed = 42 def import_plates_schedule(filepath): df_schedule = pd.read_csv(filepath, encoding='euc-kr') plates = [] for i, row in df_schedule.iterrows(): plate = Plate(row['plate_id'], row['inbound_date'], row['outbound_date']) plates.append(plate) return plates def import_plates_schedule_rev(filepath, graph=False): df_schedule = pd.read_csv(filepath, encoding='euc-kr') df_schedule.dropna(subset=['자재번호', '최근입고일', '블록S/C일자'], inplace=True) df_schedule['최근입고일'] = pd.to_datetime(df_schedule['최근입고일'], format='%Y.%m.%d') df_schedule['블록S/C일자'] = pd.to_datetime(df_schedule['블록S/C일자'], format='%Y.%m.%d') df_schedule = df_schedule[df_schedule['최근입고일'] >= datetime(2019, 1, 1)] df_schedule = df_schedule[df_schedule['최근입고일'] <= df_schedule['블록S/C일자']] initial_date = df_schedule['최근입고일'].min() df_schedule['최근입고일'] = (df_schedule['최근입고일'] - initial_date).dt.days df_schedule['블록S/C일자'] = (df_schedule['블록S/C일자'] - initial_date).dt.days df_schedule.sort_values(by=['최근입고일'], inplace=True) df_schedule.reset_index(drop=True, inplace=True) if graph: inter_arrival_time = (df_schedule['최근입고일'].diff()).dropna() stock_time = (df_schedule['블록S/C일자'] - df_schedule['최근입고일'])[df_schedule['블록S/C일자'] >= df_schedule['최근입고일']] import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(2, 1, 2) ax1.set_title('Inter Arrival Time'); ax1.set_xlabel('time'); ax1.set_ylabel('normalized frequency of occurrence') ax2.set_title('Stock Time'); ax2.set_xlabel('time'); ax2.set_ylabel('normalized frequency of occurrence') ax1.hist(list(inter_arrival_time), bins=100, density=True) ax2.hist(list(stock_time), bins=100, density=True) plt.show() plates = [[]] for i, row in df_schedule.iterrows(): plate = Plate(row['자재번호'], row['최근입고일'], row['블록S/C일자']) plates[0].append(plate) return plates def generate_schedule(arrival_scale=1/0.27, stock_mean=44, stock_std=32.5, num_plate=250): df_schedule = pd.DataFrame(columns=['자재번호', '최근입고일', '블록S/C일자']) arrivals = stats.expon.rvs(scale=arrival_scale, size=num_plate) arrivals[0] = 0 #stocks = stats.expon.rvs(scale=stock_scale, size=num_plate) stocks = stats.norm.rvs(loc=stock_mean, scale=stock_std, size=num_plate) current_date = 0 plates = [[]] for i in range(num_plate): plate_id = 'plate' + str(i) inbound_date = current_date + arrivals[i] outbound_date = inbound_date + stocks[i] if inbound_date > outbound_date: outbound_date = inbound_date current_date = inbound_date plate = Plate(plate_id, inbound_date, outbound_date) plates[0].append(plate) #row = pd.Series([plate_id, inbound_date, outbound_date], index=['자재번호', '최근입고일', '블록S/C일자']) #df_schedule = df_schedule.append(row, ignore_index=True) return plates #df_schedule def import_plates_schedule_by_week(filepath): df_schedule = pd.read_csv(filepath, encoding='euc-kr') df_schedule.dropna(subset=['자재번호', '최근입고일', '블록S/C일자'], inplace=True) df_schedule['최근입고일'] = pd.to_datetime(df_schedule['최근입고일'], format='%Y.%m.%d') df_schedule['블록S/C일자'] = pd.to_datetime(df_schedule['블록S/C일자'], format='%Y.%m.%d') df_schedule = df_schedule[df_schedule['최근입고일'] >= datetime(2019, 1, 1)] df_schedule = df_schedule[df_schedule['최근입고일'] <= df_schedule['블록S/C일자']] initial_date = df_schedule['최근입고일'].min() df_schedule['최근입고일'] = (df_schedule['최근입고일'] - initial_date).dt.days df_schedule['블록S/C일자'] = (df_schedule['블록S/C일자'] - initial_date).dt.days df_schedule.sort_values(by=['블록S/C일자'], inplace=True) df_schedule.reset_index(drop=True, inplace=True) plates = [] day = df_schedule['블록S/C일자'].min() while len(df_schedule) != 0: plates_by_week = [] temp = df_schedule[df_schedule['블록S/C일자'] <= day] temp.sort_values(by=['최근입고일'], inplace=True) temp.reset_index(drop=True, inplace=True) steel_num = len(temp) if steel_num > 0: for i, row in temp.iterrows(): # plate = Plate(row['자재번호'], row['최근입고일'], row['블록S/C일자']) plate = Plate(row['자재번호'], day - 7, row['블록S/C일자']) # 주간 물량의 입고 기준일 plates_by_week.append(plate) plates.append(plates_by_week) df_schedule.drop([_ for _ in range(steel_num)], inplace=True) df_schedule.reset_index(drop=True, inplace=True) random.shuffle(plates_by_week) day += 7 return plates def import_plates_schedule_by_day(filepath): df_schedule = pd.read_excel(filepath, header=[0, 1], encoding='euc-kr') columns = map(lambda x:x[0].replace('\n','') if 'Unnamed' in x[1] else x[0]+'_'+x[1], df_schedule.columns) df_schedule.columns = columns df_schedule.dropna(subset=['자재번호'], inplace=True) df_schedule['불출요구일'] = pd.to_datetime(df_schedule['불출요구일'], format='%Y.%m.%d') initial_date = df_schedule['불출요구일'].min() df_schedule['불출요구일'] = (df_schedule['불출요구일'] - initial_date).dt.days df_schedule.reset_index(drop=True, inplace=True) plates = [] for (date, yard), group in df_schedule.groupby(['불출요구일', '적치장']): group.reset_index(drop=True, inplace=True) plates_by_day = [] priority = 1 while len(group) != 0: temp = group[group['절단장비'] == group.iloc[0]['절단장비']] steel_num = len(temp) for i, row in temp.iterrows(): plate = Plate(row['자재번호'], date, date + priority) plates_by_day.append(plate) group.drop([_ for _ in range(steel_num)], inplace=True) group.reset_index(drop=True, inplace=True) priority += 1 plates.append(plates_by_day) return plates # 강재 정보 클래스 id, 입출고일정 포함 class Plate(object): def __init__(self, plate_id=None, inbound=0, outbound=1): self.id = str(plate_id) self.inbound = inbound self.outbound = outbound if outbound == -1: # 강재 데이터가 없으면 임의로 출고일 생성 self.outbound = random.randint(1, 5) if __name__ == "__main__": inbounds = import_plates_schedule_by_day('../environment/data/강재+불출지시서.xlsx') length = [len(_) for _ in inbounds] print(np.max(length), np.argmax(length)) ''' f = open("../environment/data/plate.txt", 'w') for i in range(len(inbounds)): f.write(("-" * 50) + "\n") f.write("총 {0}개\n".format(len(inbounds[i]))) f.write("\n") for j in range(len(inbounds[i])): f.write("자재번호: {0}, 최근입고일: {1}, 블록S/C일자: {2}\n". format(inbounds[i][j].id, inbounds[i][j].inbound, inbounds[i][j].outbound)) f.close() '''
f52edf22da4a25bab69b04ffa71a14c5eeae4946
[ "Python" ]
2
Python
jjolla93/SteelStockyardReinforcement
51189aa763a86db4f225eccab572f060a76da16c
6046c41eb7fab3416108d51b46a98ed3854d4f7c
refs/heads/master
<file_sep>package account import ( "crypto/ecdsa" "encoding/hex" "github.com/paintmeyellow/gotron/pkg/common/base58" "github.com/paintmeyellow/gotron/pkg/common/crypto" "github.com/pkg/errors" ) var ErrCreatePublicKey = errors.New("cannot create public key") type Account struct { Address string PrivateKey string } func Create() (*Account, error) { privateKey, err := crypto.GenerateKey() if err != nil { return nil, err } publicKey := privateKey.Public() publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey) if !ok { return nil, ErrCreatePublicKey } addresBytes := crypto.PubkeyToAddress(*publicKeyECDSA).Bytes() tronAddress := base58.EncodeCheck(addresBytes) return &Account{ Address: tronAddress, PrivateKey: hex.EncodeToString(crypto.FromECDSA(privateKey)), }, nil } <file_sep>package base58 import ( "crypto/sha256" "errors" "github.com/shengdoushi/base58" ) var ErrDecodeCheck = errors.New("cannot decode b58 with checksum") var TronAlphabet = base58.NewAlphabet("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") func Encode(input []byte) string { return base58.Encode(input, TronAlphabet) } func EncodeCheck(input []byte) string { h1 := sha256.Sum256(input) h2 := sha256.Sum256(h1[:]) checksum := h2[:4] inputCheck := input inputCheck = append(inputCheck, checksum...) return Encode(inputCheck) } func Decode(input string) ([]byte, error) { return base58.Decode(input, TronAlphabet) } func DecodeCheck(input string) ([]byte, error) { decodeCheck, err := Decode(input) if err != nil { return nil, err } if len(decodeCheck) < 4 { return nil, ErrDecodeCheck } decodeData := decodeCheck[:len(decodeCheck)-4] h0 := sha256.Sum256(decodeData) h1 := sha256.Sum256(h0[:]) if h1[0] == decodeCheck[len(decodeData)] && h1[1] == decodeCheck[len(decodeData)+1] && h1[2] == decodeCheck[len(decodeData)+2] && h1[3] == decodeCheck[len(decodeData)+3] { return decodeData, nil } return nil, ErrDecodeCheck } <file_sep>package grpc import ( "context" "crypto/ecdsa" "github.com/paintmeyellow/gotron/pkg/common/crypto" "github.com/paintmeyellow/gotron/pkg/common/types" "github.com/paintmeyellow/gotron/pkg/proto/core" "github.com/pkg/errors" ) var ErrInvalidTransactionResult = errors.New("invalid transaction result") type SendableTransaction struct { OwnerKey ecdsa.PrivateKey ToAddress *crypto.Address Amount int64 } func (c *Client) Transfer(ctx context.Context, sendTxn SendableTransaction) (*crypto.Hash, error) { contract := core.TransferContract{ OwnerAddress: crypto.PubkeyToAddress(sendTxn.OwnerKey.PublicKey).Bytes(), ToAddress: sendTxn.ToAddress.Bytes(), Amount: sendTxn.Amount, } txn, err := c.WalletClient.CreateTransaction2(ctx, &contract) if err != nil { return nil, err } if txn == nil || txn.GetResult().GetCode() != 0 { return nil, ErrInvalidTransactionResult } txnId, err := types.SignTxn(txn.GetTransaction(), &sendTxn.OwnerKey) if err != nil { return nil, err } _, err = c.WalletClient.BroadcastTransaction(ctx, txn.GetTransaction()) if err != nil { return nil, err } var hash crypto.Hash hash.SetBytes(txnId) return &hash, nil } <file_sep>package account import ( "bytes" "crypto/ecdsa" "errors" "github.com/paintmeyellow/gotron/pkg/common/crypto" "testing" ) func TestCreate(t *testing.T) { acc, err := Create() if err != nil { t.Fatal(err) } addr, err := crypto.Base58ToAddress(acc.Address) if err != nil { t.Fatal(err) } if ok, err := isAddresForPrivateKey(addr, acc.PrivateKey); err != nil || !ok { t.Fatalf("result:%t, error:%v", ok, err) } } func isAddresForPrivateKey(addr *crypto.Address, priv string) (bool, error) { privateKey, err := crypto.HexToECDSA(priv) if err != nil { return false, err } publicKey := privateKey.Public() publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey) if !ok { return false, err } addrFromPriv := crypto.PubkeyToAddress(*publicKeyECDSA) if !bytes.Equal(addrFromPriv.Bytes(), addr.Bytes()) { return false, errors.New("invalid private key") } return true, nil } <file_sep>package rest import ( "github.com/paintmeyellow/gotron/pkg/trongrid" "net/url" ) type Client struct { WalletClient *trongrid.WalletClient } func NewClient(address url.URL) *Client { return &Client{ WalletClient: trongrid.NewWalletClient(address), } } <file_sep>package rest import ( "context" "github.com/paintmeyellow/gotron/pkg/trongrid" "golang.org/x/sync/errgroup" "sync" ) const listDepositsBatchSize = 20 type Deposit struct { Hash string Address string Amount int64 Confirmations int64 TransactionTimestamp int64 } func (c *Client) ListDeposits(ctx context.Context, minTimestamp int64, addresses []string) ([]*Deposit, error) { var ( err error wg sync.WaitGroup currentBlock *trongrid.Block list = make([]*Deposit, 0) ) errs, ctx := errgroup.WithContext(ctx) wg.Add(1) errs.Go(func() error { defer wg.Done() currentBlock, err = c.WalletClient.GetNowBlock(ctx) return err }) for _, addr := range addresses { addr := addr errs.Go(func() error { txns, err := c.WalletClient.GetAccountTransactionsList(ctx, trongrid.AccTxnsContract{ Address: addr, MinTimestamp: minTimestamp, OnlyTo: true, Limit: listDepositsBatchSize, }) if err != nil { return err } wg.Wait() for _, txn := range txns { confirmations := currentBlock.Number() - txn.BlockNumber + 1 list = append(list, &Deposit{ Hash: txn.TxID, Amount: txn.Amount(), Address: addr, Confirmations: confirmations, TransactionTimestamp: txn.Timestamp(), }) } return nil }) } return list, errs.Wait() } <file_sep>package grpc import ( "bytes" "context" "errors" "github.com/paintmeyellow/gotron/pkg/common/base58" "github.com/paintmeyellow/gotron/pkg/proto/core" ) var ErrAccountNotFound = errors.New("account not found") func (c *Client) GetAccount(ctx context.Context, addr string) (*core.Account, error) { var account core.Account var err error account.Address, err = base58.DecodeCheck(addr) if err != nil { return nil, err } acc, err := c.WalletClient.GetAccount(ctx, &account) if err != nil { return nil, err } if !bytes.Equal(acc.Address, account.Address) { return nil, ErrAccountNotFound } return acc, nil }<file_sep>package crypto import "github.com/paintmeyellow/gotron/pkg/common/hexutil" const ( // HashLength is the expected length of the hash HashLength = 32 ) // Hash represents the 32 byte Keccak256 hash of arbitrary data. type Hash [HashLength]byte // BytesToHash sets b to hash. // If b is larger than len(h), b will be cropped from the left. func BytesToHash(b []byte) *Hash { var h Hash h.SetBytes(b) return &h } // HexToHash sets byte representation of s to hash. // If b is larger than len(h), b will be cropped from the left. func HexToHash(s string) (*Hash, error) { b, err := hexutil.Decode(s) if err != nil { return nil, err } return BytesToHash(b), nil } // Bytes gets the byte representation of the underlying hash. func (h Hash) Bytes() []byte { return h[:] } // Hex converts a hash to a hex string. func (h Hash) Hex() string { return hexutil.Bytes2Hex(h[:]) } // SetBytes sets the hash to the value of b. // If b is larger than len(h), b will be cropped from the left. func (h *Hash) SetBytes(b []byte) { if len(b) > len(h) { b = b[len(b)-HashLength:] } copy(h[HashLength-len(b):], b) } <file_sep>package base58 import ( "github.com/paintmeyellow/gotron/pkg/common/hexutil" "strings" "testing" ) const ( testB58Address = "TFXEziu1kymNVHyxD5Ukb839ubSh1CZWfV" testHexAddress = "413ce79ab890eadeb5c38c15046a0e2e91846b9b65" ) func TestEncodeCheck(t *testing.T) { addrBytes, err := hexutil.Decode(testHexAddress) if err != nil { t.Fatal(err) } encode := EncodeCheck(addrBytes) if encode != testB58Address { t.Fatalf("failure: %s", encode) } } func TestDecodeCheck(t *testing.T) { decodeBytes, err := DecodeCheck(testB58Address) if err != nil { t.Fatal(err) } decode := hexutil.Encode(decodeBytes) if !strings.EqualFold(decode, testHexAddress) { t.Fatalf("failure: %s", decode) } } <file_sep>package crypto import ( "crypto/ecdsa" "github.com/ethereum/go-ethereum/crypto" ) // GenerateKey generates a new private key. func GenerateKey() (*ecdsa.PrivateKey, error) { return crypto.GenerateKey() } //FromECDSAPub gets public key bytes func FromECDSAPub(pub *ecdsa.PublicKey) []byte { return crypto.FromECDSAPub(pub) } // FromECDSA exports a private key into a binary dump. func FromECDSA(priv *ecdsa.PrivateKey) []byte { return crypto.FromECDSA(priv) } // HexToECDSA parses a secp256k1 private key. func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) { return crypto.HexToECDSA(hexkey) } func Sign(hash []byte, privateKey *ecdsa.PrivateKey) ([]byte, error) { return crypto.Sign(hash, privateKey) }<file_sep>package grpc import ( "bytes" "context" "github.com/paintmeyellow/gotron/pkg/common/crypto" "github.com/paintmeyellow/gotron/pkg/common/hexutil" "github.com/paintmeyellow/gotron/pkg/proto/api" "github.com/paintmeyellow/gotron/pkg/proto/core" "github.com/pkg/errors" "golang.org/x/sync/errgroup" "google.golang.org/protobuf/proto" "time" ) var ( ErrTransactionNotFound = errors.New("transaction not found") ErrInvalidBroadcastResult = errors.New("invalid broadcast transaction result") ErrEmptyContractList = errors.New("contract list is empty") ) type Transaction struct { Hash *crypto.Hash From *crypto.Address To *crypto.Address NetFee int64 Amount int64 } //GetTransactionInfoByID returns transaction receipt by ID func (c *Client) GetTransactionInfoByID(ctx context.Context, hash *crypto.Hash) (*core.TransactionInfo, error) { var txnID api.BytesMessage txnID.Value = hash.Bytes() txn, err := c.WalletClient.GetTransactionInfoById(ctx, &txnID) if err != nil { return nil, err } if bytes.Equal(txn.Id, txnID.Value) { return txn, nil } return nil, ErrTransactionNotFound } //GetTransactionByID returns transaction details by ID func (c *Client) GetTransactionByID(ctx context.Context, hash *crypto.Hash) (*core.Transaction, error) { var txnID api.BytesMessage txnID.Value = hash.Bytes() txn, err := c.WalletClient.GetTransactionById(ctx, &txnID) if err != nil { return nil, err } if proto.Size(txn) > 0 { return txn, nil } return nil, ErrTransactionNotFound } //GetTransactionFullInfoByID returns transaction details by ID func (c *Client) GetTransactionFullInfoByID(ctx context.Context, h *crypto.Hash, tries uint, delay time.Duration) (*Transaction, error) { var transaction Transaction errs, ctx := errgroup.WithContext(ctx) errs.Go(func() error { txn, err := c.GetTransactionByID(ctx, h) if err != nil { return err } if len(txn.GetRawData().GetContract()) == 0 { return ErrEmptyContractList } var contract core.TransferContract if err = txn.GetRawData().GetContract()[0].GetParameter().UnmarshalTo(&contract); err != nil { return err } transaction.From = crypto.HexToAddress(hexutil.Bytes2Hex(contract.OwnerAddress)) transaction.To = crypto.HexToAddress(hexutil.Bytes2Hex(contract.ToAddress)) transaction.Amount = contract.Amount return nil }) errs.Go(func() error { for tries > 0 { <-time.Tick(delay) txn, err := c.GetTransactionInfoByID(ctx, h) if errors.Is(err, ErrTransactionNotFound) { tries-- continue } if err != nil { return err } transaction.Hash = crypto.BytesToHash(txn.Id) transaction.NetFee = txn.Fee return nil } return ErrTransactionNotFound }) return &transaction, errs.Wait() } func (c *Client) Broadcast(ctx context.Context, tx *core.Transaction) (*api.Return, error) { result, err := c.WalletClient.BroadcastTransaction(ctx, tx) if err != nil { return nil, err } if !result.GetResult() || result.GetCode() != api.Return_SUCCESS { return result, errors.Wrapf(ErrInvalidBroadcastResult, "result error(%s): %s", result.GetCode(), result.GetMessage()) } return result, nil } <file_sep>package crypto import ( "crypto/ecdsa" "testing" ) const ( testPrivateKey = "001d58091ffe501203b7ff07dcd3a49d55560f93769a3eab0e7542741fe06555" testB58Address = "TFXEziu1kymNVHyxD5Ukb839ubSh1CZWfV" testHexAddress = "413ce79ab890eadeb5c38c15046a0e2e91846b9b65" ) func TestBase58ToAddress(t *testing.T) { addr, err := Base58ToAddress(testB58Address) if err != nil { t.Fatal(err) } if testB58Address != addr.String() { t.Fatal("addresses are not the same") } } func TestHexToAddress(t *testing.T) { addr := HexToAddress(testHexAddress) if testB58Address != addr.String() || testHexAddress != addr.Hex() { t.Fatal("addresses are not the same") } } func TestPubkeyToAddress(t *testing.T) { privateKey, err := HexToECDSA(testPrivateKey) if err != nil { t.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey) if !ok { t.Fatal("publicKey is not type of *ecdsa.PublicKey") } addr := PubkeyToAddress(*publicKeyECDSA) t.Log(addr.String()) if testB58Address != addr.String() { t.Fatal("addresses are not the same") } }<file_sep>package main import ( "context" "fmt" "github.com/paintmeyellow/gotron/pkg/account" "github.com/paintmeyellow/gotron/pkg/client/grpc" "github.com/paintmeyellow/gotron/pkg/client/rest" "github.com/paintmeyellow/gotron/pkg/common/crypto" "log" "net/url" "time" ) func main() { fmt.Println("----> Creating Account...") acc := createAccount() fmt.Println("<---- Done.") fmt.Println() grpcClient := grpc.NewClient("grpc.shasta.trongrid.io:50051") if err := grpcClient.Start(); err != nil { log.Fatal(err) } //Owner Public Key: <KEY> //Owner Private Key: <KEY> fmt.Println("----> Transfering Transaction...") priv := "<KEY>" transferTxn(grpcClient, priv, acc.Address, 1) fmt.Println("<---- Done.") fmt.Println() fmt.Println("----> Getting balance...") getBalance(grpcClient, "TTbfNX2MbRJ1NG1FqQmKUy4E24sV9K2yzj") fmt.Println("<---- Done.") fmt.Println() httpAddr, err := url.Parse("https://api.shasta.trongrid.io") if err != nil { log.Fatal(err) } restClient := rest.NewClient(*httpAddr) fmt.Println("----> Fetching Deposits List...") fetchDepositsList(restClient, 0, []string{ //"<KEY>", //"<KEY>", acc.Address, }) fmt.Println("<---- Done.") } func createAccount() *account.Account { acc, err := account.Create() if err != nil { log.Fatal(err) } fmt.Println("Tron Address:", acc.Address) fmt.Println("Private Key:", acc.PrivateKey) return acc } func getBalance(client *grpc.Client, addr string) { grpcAcc, err := client.GetAccount(context.Background(), addr) if err != nil { log.Fatal(err) } fmt.Println("Balance:", grpcAcc.GetBalance()) } func transferTxn(client *grpc.Client, priv string, toAddr string, amount int64) { privKeyECDSA, err := crypto.HexToECDSA(priv) if err != nil { log.Fatal(err) } addr, err := crypto.Base58ToAddress(toAddr) if err != nil { log.Fatal(err) } sendTxn := grpc.SendableTransaction{ OwnerKey: *privKeyECDSA, ToAddress: addr, Amount: amount, } hash, err := client.Transfer(context.Background(), sendTxn) if err != nil { log.Fatal(err) } fmt.Println("Transaction Hash:", hash.Hex()) fmt.Println("<---- Done.") fmt.Println() fmt.Println("----> Fetching Transaction Info...") ctx, cancel := context.WithCancel(context.Background()) go func() { time.Sleep(time.Second * 10) cancel() }() txn, err := client.GetTransactionFullInfoByID(ctx, hash, 5, time.Second) if err != nil { log.Fatal(err) } fmt.Println("Hash:", txn.Hash.Hex()) fmt.Println("From:", txn.From.String()) fmt.Println("To:", txn.To.String()) fmt.Println("Amount:", txn.Amount) fmt.Println("NetFee:", txn.NetFee) } func fetchDepositsList(client *rest.Client, minTimestamp int64, addresses []string) { deposits, err := client.ListDeposits(context.Background(), minTimestamp, addresses) if err != nil { log.Fatal(err) } for _, deposit := range deposits { fmt.Println("Address:", deposit.Address) fmt.Println("Hash:", deposit.Hash) fmt.Println("Amount:", deposit.Amount) fmt.Println("Timestamp:", deposit.TransactionTimestamp) fmt.Println("Confirmations:", deposit.Confirmations) } } <file_sep>package grpc import ( "github.com/paintmeyellow/gotron/pkg/proto/api" "google.golang.org/grpc" ) type Client struct { Address string Conn *grpc.ClientConn WalletClient api.WalletClient } func NewClient(address string) *Client { var client Client client.Address = address return &client } func (c *Client) Start() error { var err error c.Conn, err = grpc.Dial(c.Address, grpc.WithInsecure()) if err != nil { return err } c.WalletClient = api.NewWalletClient(c.Conn) return nil } <file_sep>module github.com/paintmeyellow/gotron go 1.16 require ( github.com/btcsuite/btcd v0.22.0-beta // indirect github.com/ethereum/go-ethereum v1.10.4 github.com/pkg/errors v0.9.1 github.com/shengdoushi/base58 v1.0.0 golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e // indirect golang.org/x/net v0.0.0-20210614182718-04defd469f4e // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c // indirect google.golang.org/genproto v0.0.0-20210708141623-e76da96a951f google.golang.org/grpc v1.39.0 google.golang.org/protobuf v1.27.1 ) <file_sep>protoc -I=./proto/tron -I=./proto/googleapis --go-grpc_out=paths=source_relative:./pkg/proto --go_out=paths=source_relative:./pkg/proto ./proto/tron/api/*.proto protoc -I=./proto/tron -I=./proto/googleapis --go_out=paths=source_relative:./pkg/proto ./proto/tron/core/*.proto protoc -I=./proto/tron -I=./proto/googleapis --go_out=paths=source_relative:./pkg/proto ./proto/tron/core/contract/*.proto mv pkg/proto/core/contract/* pkg/proto/core/ rm -rf pkg/proto/core/contract <file_sep>package hexutil import ( "encoding/hex" "github.com/pkg/errors" ) var ( ErrEmptyString = errors.New("empty hex string") ) // Encode encodes bytes as a hex string. func Encode(bytes []byte) string { encode := make([]byte, len(bytes)*2) hex.Encode(encode, bytes) return string(encode) } // Decode hex string as bytes func Decode(input string) ([]byte, error) { if len(input) == 0 { return nil, ErrEmptyString } return hex.DecodeString(input[:]) } // Bytes2Hex returns the hexadecimal encoding of d. func Bytes2Hex(d []byte) string { return hex.EncodeToString(d) } <file_sep>package crypto import ( "crypto/ecdsa" "github.com/ethereum/go-ethereum/crypto" "github.com/paintmeyellow/gotron/pkg/common/base58" "github.com/paintmeyellow/gotron/pkg/common/hexutil" "math/big" ) const ( // AddressLength is the expected length of the address AddressLength = 21 // TronBytePrefix is the hex prefix to address TronBytePrefix = byte(0x41) ) type Address [AddressLength]byte func (a *Address) Bytes() []byte { return a[:] } func (a *Address) Hex() string { return hexutil.Bytes2Hex(a[:]) } // String implements fmt.Stringer. func (a Address) String() string { if a[0] == 0 { return new(big.Int).SetBytes(a.Bytes()).String() } return base58.EncodeCheck(a.Bytes()) } func (a *Address) SetBytes(b []byte) { if len(b) > len(a) { b = b[len(b)-AddressLength:] } copy(a[AddressLength-len(b):], b) } func BytesToAddress(b []byte) *Address { var a Address a.SetBytes(b) return &a } // HexToAddress returns Address with byte values of s. // If s is larger than len(h), s will be cropped from the left. func HexToAddress(s string) *Address { addr, err := hexutil.Decode(s) if err != nil { return nil } return BytesToAddress(addr) } func Base58ToAddress(s string) (*Address, error) { addr, err := base58.DecodeCheck(s) if err != nil { return nil, err } return BytesToAddress(addr), nil } func PubkeyToAddress(pub ecdsa.PublicKey) *Address { address := crypto.PubkeyToAddress(pub) addressTron := make([]byte, 0) addressTron = append(addressTron, TronBytePrefix) addressTron = append(addressTron, address.Bytes()...) return BytesToAddress(addressTron) } <file_sep>package types import ( "crypto/ecdsa" "crypto/sha256" "github.com/ethereum/go-ethereum/crypto" "github.com/paintmeyellow/gotron/pkg/proto/core" "google.golang.org/protobuf/proto" "time" ) func SignTxn(txn *core.Transaction, priv *ecdsa.PrivateKey) ([]byte, error) { txn.RawData.Timestamp = time.Now().UnixNano() / 1000000 rawData, err := proto.Marshal(txn.RawData) if err != nil { return nil, err } hash := sha256.Sum256(rawData) for range txn.RawData.Contract { signature, err := crypto.Sign(hash[:], priv) if err != nil { return nil, err } txn.Signature = append(txn.Signature, signature) } return hash[:], nil } <file_sep>package trongrid import ( "context" "encoding/json" "fmt" "net/http" "net/url" "strconv" ) type WalletClient struct { Client *http.Client Address url.URL } func NewWalletClient(address url.URL) *WalletClient { return &WalletClient{ Client: http.DefaultClient, Address: address, } } type PaginatedTxns struct { Data []*Transaction `json:"data"` Meta struct { Fingerprint string `json:"fingerprint,omitempty"` } `json:"meta"` } type Transaction struct { TxID string `json:"txID"` RawData *TransactionRaw `json:"raw_data,omitempty"` BlockNumber int64 `json:"blockNumber,omitempty"` } type TransactionRaw struct { Contract []*TransactionContract `json:"contract,omitempty"` Timestamp int64 `json:"timestamp,omitempty"` } type TransactionContract struct { Parameter struct { Value struct { Amount int64 `json:"amount"` } `json:"value"` } `json:"parameter,omitempty"` } func (tx *Transaction) Amount() int64 { if len(tx.RawData.Contract) == 0 { return 0 } return tx.RawData.Contract[0].Parameter.Value.Amount } func (tx *Transaction) Timestamp() int64 { return tx.RawData.Timestamp } type Block struct { ID string `json:"blockID"` Header struct { RawData struct { Number int64 `json:"number"` Timestamp int64 `json:"timestamp"` } `json:"raw_data"` } `json:"block_header"` } func (b *Block) Number() int64 { return b.Header.RawData.Number } type AccTxnsContract struct { Address string MinTimestamp int64 OnlyTo bool Limit int64 } type PaginatedAccTxnsContract struct { Address string MinTimestamp int64 OnlyTo bool SearchInternal bool Limit int64 Fingerprint string } //GetAccountTransactionsList query the list of all normal transactions func (c *WalletClient) GetAccountTransactionsList(ctx context.Context, contr AccTxnsContract) ([]*Transaction, error) { var ( page = 1 fingerprint string list = make([]*Transaction, 0) ) for fingerprint != "" || page == 1 { batch, err := c.GetPaginatedAccountTransactions(ctx, PaginatedAccTxnsContract{ Address: contr.Address, MinTimestamp: contr.MinTimestamp, OnlyTo: contr.OnlyTo, SearchInternal: false, Limit: contr.Limit, Fingerprint: fingerprint, }) if err != nil { return nil, err } list = append(list, batch.Data...) fingerprint = batch.Meta.Fingerprint page++ } return list, nil } //GetPaginatedAccountTransactions query the paginated list of all normal transactions func (c *WalletClient) GetPaginatedAccountTransactions(ctx context.Context, contr PaginatedAccTxnsContract) (*PaginatedTxns, error) { addr := c.Address addr.Path += fmt.Sprintf("/v1/accounts/%s/transactions", contr.Address) params := url.Values{ "only_to": {strconv.FormatBool(contr.OnlyTo)}, "min_timestamp": {strconv.FormatInt(contr.MinTimestamp, 10)}, "search_internal": {strconv.FormatBool(contr.SearchInternal)}, "limit": {strconv.FormatInt(contr.Limit, 10)}, "fingerprint": {contr.Fingerprint}, } addr.RawQuery = params.Encode() req, err := http.NewRequestWithContext(ctx, http.MethodGet, addr.String(), nil) if err != nil { return nil, err } resp, err := c.Client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var txns PaginatedTxns if err = json.NewDecoder(resp.Body).Decode(&txns); err != nil { return nil, err } return &txns, nil } func (c *WalletClient) GetNowBlock(ctx context.Context) (*Block, error) { addr := c.Address addr.Path += "/wallet/getnowblock" req, err := http.NewRequestWithContext(ctx, http.MethodGet, addr.String(), nil) if err != nil { return nil, err } resp, err := c.Client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var block Block if err = json.NewDecoder(resp.Body).Decode(&block); err != nil { return nil, err } return &block, nil }
f57681d4d9d223370f6ec5e07d1215cdef43db65
[ "Go Module", "Go", "Shell" ]
20
Go
paintmeyellow/gotron
831b3c72694361b5eb80e99b15b4b50625fc1767
7a9cbc95f0614b96505c2a30f006dbafdaf6744e
refs/heads/main
<repo_name>AnnoyingOtter11/Waves<file_sep>/shaders2.c // ************** // The vertex shader for Phong lighting with Phong shading. // Mostly this copies material values, modelview position, // and modelview surface normal to the fragment shader // ************** #beginglsl vertexshader vertexShader_PhongPhong2 #version 330 core layout (location = 0) in vec3 vertPos; // Position in attribute location 0 layout (location = 1) in vec3 vertNormal; // Surface normal in attribute location 1 layout (location = 2) in vec2 vertTexCoords; // Texture coordinates in attribute location 2 layout (location = 3) in vec3 EmissiveColor; // Surface material properties layout (location = 4) in vec3 AmbientColor; layout (location = 5) in vec3 DiffuseColor; layout (location = 6) in vec3 SpecularColor; layout (location = 7) in float SpecularExponent; layout (location = 8) in float UseFresnel; // Shold be 1.0 (for Fresnel) or 0.0 (for no Fresnel) out vec3 mvPos; // Vertex position in modelview coordinates out vec3 mvNormalFront; // Normal vector to vertex in modelview coordinates out vec3 matEmissive; out vec3 matAmbient; out vec3 matDiffuse; out vec3 matSpecular; out float matSpecExponent; out vec2 theTexCoords; out float useFresnel; out vec3 vertPosNew; uniform mat4 projectionMatrix; // The projection matrix uniform mat4 modelviewMatrix; // The modelview matrix uniform float curTime; uniform int waveMode; uniform float x; uniform float z; uniform float amp; uniform float rx; uniform float rz; uniform float rxp; uniform float rzp; uniform float rebound1; uniform float rebound2; void main() { float pi = 3.1415926535; float lambda = 2.0; float freq = 0.25; vertPosNew.x = vertPos.x; vertPosNew.z = vertPos.z; if (waveMode == 1) { float d = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z - z, 2)); float d31 = sqrt(pow(vertPosNew.x - (-5 - 2*x), 2) + pow(vertPosNew.z - (-5-2*z), 2)); float d32 = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z -(-5 - 2*z), 2)); float d33 = sqrt(pow(vertPosNew.x - (10 - 2*x), 2) + pow(vertPosNew.z -(-5 - 2*z), 2)); float d21 = sqrt(pow(vertPosNew.x - (-5 - 2*x), 2) + pow(vertPosNew.z - z, 2)); float d23 = sqrt(pow(vertPosNew.x - (10-2*x), 2) + pow(vertPosNew.z - z, 2)); float d11 = sqrt(pow(vertPosNew.x - (-5 - 2*x), 2) + pow(vertPosNew.z -(10 - 2*z), 2)); float d12 = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z - (10 - 2*z), 2)); float d13 = sqrt(pow(vertPosNew.x -(10 - 2*x), 2) + pow(vertPosNew.z - (10 - 2*z), 2)); //float e = sqrt(pow(vertPosNew.x, 2) + pow(vertPosNew.z + 8, 2)); /** if ((vertPosNew.x > rxp && vertPosNew.x < rx || (-vertPosNew.x) > rxp && (vertPosNew.x) < rx) && (vertPosNew.z > rzp && vertPosNew.z < rz || (-vertPosNew.z) > rzp && (vertPosNew.z) < rz)) { vertPosNew.y = amp * cos(2 * pi*(d / lambda - freq * curTime)); } */ if (rx > sqrt(50)) { if (d < rebound1 && d > rebound2) { vertPosNew.y = amp * pow(exp(1.0), -rz) * sin(2 * pi*(d / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d21 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d12 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d23 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d32 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d11 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d13 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d31 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d33 / lambda - freq * curTime)); } if (d < rebound2) { vertPosNew.y = amp * pow(exp(1.0), -rz) * sin(2 * pi*(d / lambda - freq * curTime)); //vertPosNew.y = 0; } if (d > rebound1 && d < 2 * (sqrt(50)) - d) { vertPosNew.y = amp * pow(exp(1.0), -rz) * sin(2 * pi*(d / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d21 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d12 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d23 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d32 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d11 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d13 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d31 / lambda - freq * curTime)) + amp * pow(exp(1.0), -rz) * sin(2 * pi*(d33 / lambda - freq * curTime)); } if (d > 2 * (sqrt(50)) - d) { vertPosNew.y = 0; } } else if (d > rxp && d < rx) { vertPosNew.y = amp * pow(exp(1.0), -rz) * sin(2 * pi*(d / lambda - freq * curTime)); } else if (d < rxp) { vertPosNew.y = amp * pow(exp(1.0), -rz) * sin(2 * pi*(d / lambda - freq * curTime)); } else { vertPosNew.y = 0; } vec4 mvPos4 = modelviewMatrix * vec4(vertPosNew.x, vertPosNew.y, vertPosNew.z, 1.0); gl_Position = projectionMatrix * mvPos4; mvPos = vec3(mvPos4.x, mvPos4.y, mvPos4.z) / mvPos4.w; mvNormalFront = normalize(inverse(transpose(mat3(modelviewMatrix)))*vertNormal); // Unit normal from the surface matEmissive = EmissiveColor; matAmbient = AmbientColor; matDiffuse = DiffuseColor; matSpecular = SpecularColor; matSpecExponent = SpecularExponent; theTexCoords = vertTexCoords; useFresnel = UseFresnel; } else { vec4 mvPos4 = modelviewMatrix * vec4(vertPos.x, vertPos.y, vertPos.z, 1.0); gl_Position = projectionMatrix * mvPos4; mvPos = vec3(mvPos4.x, mvPos4.y, mvPos4.z) / mvPos4.w; mvNormalFront = normalize(inverse(transpose(mat3(modelviewMatrix)))*vertNormal); // Unit normal from the surface matEmissive = EmissiveColor; matAmbient = AmbientColor; matDiffuse = DiffuseColor; matSpecular = SpecularColor; matSpecExponent = SpecularExponent; theTexCoords = vertTexCoords; useFresnel = UseFresnel; } } #endglsl // ************** // The base code for the fragment shader for Phong lighting with Phong shading. // This does all the hard work of the Phong lighting by calling CalculatePhongLighting() // ************** #beginglsl fragmentshader fragmentShader_PhongPhong2 #version 330 core in vec3 mvPos; // Vertex position in modelview coordinates in vec3 mvNormalFront; // Normal vector to vertex (front facing) in modelview coordinates in vec3 matEmissive; in vec3 matAmbient; in vec3 matDiffuse; in vec3 matSpecular; in vec3 vertPosNew; in float matSpecExponent; in float useFresnel; layout (std140) uniform phGlobal { vec3 GlobalAmbientColor; // Global ambient light color int NumLights; // Number of lights bool LocalViewer; // true for local viewer; false for directional viewer bool EnableEmissive; // Control whether emissive colors are rendered bool EnableDiffuse; // Control whether diffuse colors are rendered bool EnableAmbient; // Control whether ambient colors are rendered bool EnableSpecular; // Control whether specular colors are rendered bool UseHalfwayVector; // Control whether halfway vector method is used }; const int MaxLights = 8; // The maximum number of lights (must match value in C++ code) struct phLight { bool IsEnabled; // True if light is turned on bool IsAttenuated; // True if attenuation is active bool IsSpotLight; // True if spotlight bool IsDirectional; // True if directional vec3 Position; vec3 AmbientColor; vec3 DiffuseColor; vec3 SpecularColor; vec3 SpotDirection; // Should be unit vector! float SpotCosCutoff; // Cosine of cutoff angle float SpotExponent; float ConstantAttenuation; float LinearAttenuation; float QuadraticAttenuation; }; layout (std140) uniform phLightArray { phLight Lights[MaxLights]; }; vec3 mvNormal; in vec2 theTexCoords; // Texture coordinates (interpolated from vertex shader) uniform sampler2D theTextureMap; uniform bool applyTexture; uniform float curTime; uniform int waveMode; uniform float amp; uniform float x; uniform float z; uniform mat4 modelviewMatrix; // The modelview matrix uniform float rx; uniform float rz; uniform float rxp; uniform float rzp; uniform float rebound1; uniform float rebound2; vec3 nonspecColor; vec3 specularColor; out vec4 fragmentColor; // Color that will be used for the fragment void CalculatePhongLighting(); // Calculates: nonspecColor and specularColor. vec4 applyTextureFunction(); void main() { float pi = 3.1415926535; float lambda = 2.0; float freq = 0.25; float dx = 0.0; float dz = 0.0; float d = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z - z, 2)); float d31 = sqrt(pow(vertPosNew.x - (-5 - 2 * x), 2) + pow(vertPosNew.z - (-5 - 2 * z), 2)); float d32 = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z - (-5 - 2 * z), 2)); float d33 = sqrt(pow(vertPosNew.x - (10 - 2 * x), 2) + pow(vertPosNew.z - (-5 - 2 * z), 2)); float d21 = sqrt(pow(vertPosNew.x - (-5 - 2 * x), 2) + pow(vertPosNew.z - z, 2)); float d23 = sqrt(pow(vertPosNew.x - (10 - 2 * x), 2) + pow(vertPosNew.z - z, 2)); float d11 = sqrt(pow(vertPosNew.x - (-5 - 2 * x), 2) + pow(vertPosNew.z - (10 - 2 * z), 2)); float d12 = sqrt(pow(vertPosNew.x - x, 2) + pow(vertPosNew.z - (10 - 2 * z), 2)); float d13 = sqrt(pow(vertPosNew.x - (10 - 2 * x), 2) + pow(vertPosNew.z - (10 - 2 * z), 2)); if (rx > sqrt(50) && waveMode == 1) { if (d < rebound1 && d > rebound2) { dx = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d21 / lambda - freq * curTime))) / (lambda*d21) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d12 / lambda - freq * curTime))) / (lambda*d12) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d23 / lambda - freq * curTime))) / (lambda*d23) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d32 / lambda - freq * curTime))) / (lambda*d32) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d11 / lambda - freq * curTime))) / (lambda*d11) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d13 / lambda - freq * curTime))) / (lambda*d13) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d31 / lambda - freq * curTime))) / (lambda*d31) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d33 / lambda - freq * curTime))) / (lambda*d33); dz = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d21 / lambda - freq * curTime))) / (lambda*d21) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d12 / lambda - freq * curTime))) / (lambda*d12) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d23 / lambda - freq * curTime))) / (lambda*d23) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d32 / lambda - freq * curTime))) / (lambda*d32) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d11 / lambda - freq * curTime))) / (lambda*d11) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d13 / lambda - freq * curTime))) / (lambda*d13) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d31 / lambda - freq * curTime))) / (lambda*d31) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d33 / lambda - freq * curTime))) / (lambda*d33); } if (d < rebound2) { dx = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); dz = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); } if (d > rebound1 && d < 2 * (sqrt(50)) - d) { dx = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d21 / lambda - freq * curTime))) / (lambda*d21) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d12 / lambda - freq * curTime))) / (lambda*d12) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d23 / lambda - freq * curTime))) / (lambda*d23) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d32 / lambda - freq * curTime))) / (lambda*d32) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d11 / lambda - freq * curTime))) / (lambda*d11) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d13 / lambda - freq * curTime))) / (lambda*d13) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d31 / lambda - freq * curTime))) / (lambda*d31) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d33 / lambda - freq * curTime))) / (lambda*d33); dz = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d21 / lambda - freq * curTime))) / (lambda*d21) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d12 / lambda - freq * curTime))) / (lambda*d12) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d23 / lambda - freq * curTime))) / (lambda*d23) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d32 / lambda - freq * curTime))) / (lambda*d32) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d11 / lambda - freq * curTime))) / (lambda*d11) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d13 / lambda - freq * curTime))) / (lambda*d13) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d31 / lambda - freq * curTime))) / (lambda*d31) + (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d33 / lambda - freq * curTime))) / (lambda*d33); } if (d > 2 * (sqrt(50)) - d) { dz = 0; dx = 0; } } else if ((d > rxp && d < rx) && waveMode == 1) { //dx = (-2*pi*amp*(vertPosNew.x) * sin(2*pi * (d/lambda - freq*curTime))) / (lambda*d); //dz = (-2*pi*amp*(vertPosNew.z) * sin(2*pi * (d/lambda - freq*curTime))) / (lambda*d); dx =(amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); dz =(amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); } else if (d < rxp && waveMode == 1) { //dx = (-2 * pi*amp/2*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); //dz = (-2 * pi*amp/2*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); dx = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.x) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); dz = (amp * pow(exp(1.0), -rz))*(-2 * pi*(vertPosNew.z) * sin(2 * pi * (d / lambda - freq * curTime))) / (lambda*d); } mvNormal.x = -dx; mvNormal.z = -dz; mvNormal.y = 1; vec3 normalVec = normalize(inverse(transpose(mat3(modelviewMatrix)))*mvNormal); if ( gl_FrontFacing ) { mvNormal = normalVec; } else { mvNormal = -normalVec; } CalculatePhongLighting(); // Calculates: nonspecColor and specularColor. fragmentColor = vec4(nonspecColor+specularColor, 1.0f); // Add alpha value of 1.0. if ( applyTexture ) { fragmentColor = applyTextureFunction(); } } #endglsl <file_sep>/WaterPlane.cpp // // WaterPlane.cpp // // Sets up and renders // - the ground plane, and // // Use the static library (so glew32.dll is not needed): #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "LinearR4.h" // Adjust path as needed. #include "WaterPlane.h" #include "WavePhongData.h" extern int meshRes; extern int modelviewMatLocation; // Defined in GlslWaves.cpp extern bool check_for_opengl_errors(); unsigned int vertPos_loc = 0; // Corresponds to "location = 0" in the verter shader definitions unsigned int vertNormal_loc = 1; // Corresponds to "location = 1" in the verter shader definitions // ************************ // General data helping with setting up VAO (Vertex Array Objects) // and Vertex Buffer Objects. // *********************** const int NumObjects = 1; const int iFloor = 0; unsigned int myVBO[NumObjects]; // a Vertex Buffer Object holds an array of data unsigned int myVAO[NumObjects]; // a Vertex Array Object - holds info about an array of vertex data; unsigned int myEBO[NumObjects]; // a Element Array Buffer Object - holds an array of elements (vertex indices) // ********************** // This sets up geometries needed for the "Initial" (the 3-D alphabet letter) // It is called only once. // ********************** void MySetupSurfaces() { // Initialize the VAO's, VBO's and EBO's for the ground plane, // No data is loaded into the VBO's or EBO's until the "Remesh" // routines are called. // For the floor: // Allocate the needed Vertex Array Objects (VAO's), // Vertex Buffer Objects (VBO's) and Element Array Buffer Objects (EBO's) glGenVertexArrays(NumObjects, &myVAO[0]); glGenBuffers(NumObjects, &myVBO[0]); glGenBuffers(NumObjects, &myEBO[0]); glBindVertexArray(myVAO[iFloor]); glBindBuffer(GL_ARRAY_BUFFER, myVBO[iFloor]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, myEBO[iFloor]); glVertexAttribPointer(vertPos_loc, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // Store vertices in the VBO glEnableVertexAttribArray(vertPos_loc); // Enable the stored vertices // No data has been loaded into the VBO yet. // This is done next by the "Remesh" routine. RemeshFloor(); check_for_opengl_errors(); // Watch the console window for error messages! } // ********************************************** // MODIFY THIS ROUTINE TO CALL YOUR OWN CODE IN // MyRemeshFloor AND MyRemeshCircularSurf // INSTEAD OF THE "DEMO" VERSIONS. // ********************************************** void MyRenderSurfaces() { RenderFloor(); check_for_opengl_errors(); // Watch the console window for error messages! } // ********************************************* // A water plane gridded as an array of rectangles (triangulated) // x and z values are in the range [-5,5]. // All points stored here with y value equal to zero. // **** Heights are changed by the vertex shader.**** // ********************************************************* void RemeshFloor() { // Floor (water plane) vertices. int numFloorVerts = (meshRes + 1)*(meshRes + 1); float* floorVerts = new float[3 * numFloorVerts]; // Floor elements (indices to vertices in a triangle strip) int numFloorElts = meshRes * 2 * (meshRes + 1); unsigned int* floorElements = new unsigned int[numFloorElts]; for (int i = 0; i <= meshRes; i++) { float z = (-5.0f*(float)(meshRes - i) + 5.0f*(float)i) / (float)meshRes; for (int j = 0; j <= meshRes; j++) { float x = (-5.0f*(float)(meshRes - j) + 5.0f*(float)j) / (float)meshRes; int vrtIdx = 3 * i * (meshRes + 1) + 3 * j; floorVerts[vrtIdx] = x; floorVerts[vrtIdx + 1] = 0.0f; floorVerts[vrtIdx + 2] = z; } } for (int i = 0; i < meshRes; i++) { for (int j = 0; j <= meshRes; j++) { int elt = 2 * i * (meshRes + 1) + 2 * j; floorElements[elt] = i * (meshRes + 1) + j; floorElements[elt + 1] = (i + 1) * (meshRes + 1) + j; } } // Load data into the VBO and EBO using glBindBuffer and glBufferData commands glBindVertexArray(myVAO[iFloor]); glBindBuffer(GL_ARRAY_BUFFER, myVBO[iFloor]); glBufferData(GL_ARRAY_BUFFER, 3 * numFloorVerts * sizeof(float), floorVerts, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, myEBO[iFloor]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, numFloorElts * sizeof(unsigned int), floorElements, GL_STATIC_DRAW); // Avoid a memory leak by deleting the arrays obtained with "new" above delete[] floorVerts; delete[] floorElements; } void RenderFloor() { glBindVertexArray(myVAO[iFloor]); // Set the uniform values (they are not stored with the VAO and thus must be set again everytime glVertexAttrib3f(vertNormal_loc, 0.0, 1.0, 0.0); // Generic vertex attribute: Normal is (0,1,0) for the floor. myMaterials[0].LoadIntoShaders(); // materials[0] defined in DemoPhongData.h glUniformMatrix4fv(modelviewMatLocation, 1, false, viewMatrix.DumpByColumns()); // Draw the the triangle strips for (int i = 0; i < meshRes; i++) { glDrawElements(GL_TRIANGLE_STRIP, 2 * (meshRes + 1), GL_UNSIGNED_INT, (void*)(i * 2* (meshRes + 1) * sizeof(unsigned int))); } } <file_sep>/README.txt Note: You will need EduPhong.glsl and shaders2.c in the same directory as the demo exe program for it to work. Arrow keys are used to control the camera, 1 2 3 4 control lights M increase mesh, while m decreases mesh E,A,D,S control the lighting options<file_sep>/GlslWaves.cpp /* * LetterProj.cpp - Version 0.3 - April 13, 2019 * * Software accompanying POSSIBLE SECOND EDITION TO the book * 3D Computer Graphics: A Mathematical Introduction with OpenGL, * by <NAME>, Cambridge University Press, 2003. * * Software is "as-is" and carries no warranty. It may be used without * restriction, but if you modify it, please change the filenames to * prevent confusion between different versions. * Bug reports: <NAME>, <EMAIL>. * Web page: http://math.ucsd.edu/~sbuss/MathCG2 */ // These libraries are needed to link the program. // First five are usually provided by the system. #pragma comment(lib,"opengl32.lib") #pragma comment(lib,"glu32.lib") #pragma comment(lib,"glfw3.lib") #pragma comment(lib,"glew32s.lib") #pragma comment(lib,"glew32.lib") // Use the static library (so glew32.dll is not needed): #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "LinearR2.h" #include "LinearR3.h" // Adjust path as needed. #include "LinearR4.h" // Adjust path as needed. #include "EduPhong.h" #include "WavePhongData.h" #include "GlGeomSphere.h" #include "GlShaderMgr.h" #include "GlslWaves.h" #include "WaterPlane.h" // Enable standard input and output via printf(), etc. // Put this include *after* the includes for glew and GLFW! #include <stdio.h> // ******************** // Animation controls and state infornation // ******************** // These variables control the view direction. // The arrow keys are used to change these values. double viewAzimuth = 0.25; // Angle of view up/down (in radians) double viewDirection = 0.0; // Rotation of view around y-axis (in radians) double deltaAngle = 0.01; // Change in view angle for each up/down/left/right arrow key press LinearMapR4 viewMatrix; // The current view matrix, based on viewAzimuth and viewDirection. // Control Phong lighting modes phGlobal globalPhongData; // These two variables control how triangles are rendered. bool wireframeMode = false; // Equals true for polygon GL_FILL mode. False for polygon GL_LINE mode. bool cullBackFaces = true; bool timer = true; bool rtime = true; bool rebound = false; float tTime = 0; // The next variable controls the resoluton of the meshes for the water plane. int meshRes=4; // Mode==0 for one wave. Mode==1 for one wave and smaller ripple. int waveMode = 0; int mouseClick = 0; //Window Size const int initWidth = 800; const int initHeight = 600; // ************************ // General data helping with setting up VAO (Vertex Array Objects) // and Vertex Buffer Objects. // *********************** unsigned int myWaveShader; // The shader program! int projMatLocation; // Location of the projectionMatrix in the currently active shader program int modelviewMatLocation; // Location of the modelviewMatrix in the currently active shader program // These two locations are not in the supplied shader code. // You will add them to your shader (GLSL) code) int timeLocation; int waveModeLocation; float amp = 0.5; float rxp, rzp = 0.0; float rebound1, rebound2 = 0.0; float rx, rz = 5.5; double xpos, ypos, newx, newz; int xloc, zloc, ampLoc, rxLoc, rzLoc, rxpLoc, rzpLoc, rebound1Loc, rebound2Loc; // The Projection matrix: Controls the "camera view/field-of-view" transformation // Geneally is the same for all objects in the scene. LinearMapR4 theProjectionMatrix; // The Projection matrix: Controls the "camera/view" transformation // A ModelView matrix controls the placement of a particular object in 3-space. // It is generally different for each object. // The array matEntries holds the matrix values as floats to be loaded into the shader program. float matEntries[16]; // Holds 16 floats (since cannot load doubles into a shader that uses floats) // ***************************** // These variables set the dimensions of the perspective region we wish to view. // They are used to help form the projection matrix and the view matrix // All rendered objects lie in the rectangular prism centered on the z-axis // equal to (-Xmax,Xmax) x (-Ymax,Ymax) x (Zmin,Zmax) // Be sure to leave some slack in these values, to allow for rotations, etc. // The model/view matrix can be used to move objects to this position // THESE VALUES MAY NEED AD-HOC ADJUSTMENT TO GET THE SCENE TO BE VISIBLE. const double Xmax = 6.0; // Control x dimensions of viewable scene const double Ymax = 4.0; // Control y dimensions of viewable scene const double Zmin = -8.0, Zmax = 8.0; // Control z dimensions of the viewable scene // zNear equals the distance from the camera to the z = Zmax plane const double zNear = 15.0; // Make this value larger or smaller to affect field of view. // ************************* // mySetupGeometries defines the scene data, especially vertex positions and colors. // - It also loads all the data into the VAO's (Vertex Array Objects) and // into the VBO's (Vertex Buffer Objects). // This routine is only called once to initialize the data. // ************************* void mySetupGeometries() { MySetupSurfaces(); mySetViewMatrix(); check_for_opengl_errors(); // Really a great idea to check for errors -- esp. good for debugging! } void mySetViewMatrix() { // Set the view matrix. Sets view distance, and view direction. // The final translation is done because the ground plane lies in the xz-plane, // YOU MAY NEED TO ADJUST THE FINAL TRANSLATION. viewMatrix.Set_glTranslate(0.0, 0.0, -(Zmax + zNear)); // Translate to be in front of the camera viewMatrix.Mult_glRotate(viewAzimuth, 1.0, 0.0, 0.0); // Rotate viewAzimuth radians around x-axis viewMatrix.Mult_glRotate(-viewDirection, 0.0, 1.0, 0.0); // Rotate -viewDirection radians around y-axis viewMatrix.Mult_glTranslate(0.0, -2.5, 0.0); // Translate the view is above the water plane } // ************************************* // Main routine for rendering the scene // myRenderScene() is called every time the scene needs to be redrawn. // mySetupGeometries() has already created the vertex and buffer objects // and the model view matrices. // The EduPhong shaders should already be setup. // ************************************* void myRenderScene() { float currentTime = (float)glfwGetTime(); if (timer) { tTime = (float)glfwGetTime(); timer = false; } //printf("currentTime: %f\n", currentTime); if (currentTime > 30.0) { waveMode = 0; } if (waveMode == 0) { amp = 0.5; rx = 2.00; rxp = 0.0; rz = 0.0; currentTime = 0.0; tTime = 0.0; timer = true; rebound = false; rebound1 = sqrt(50)+2; rebound2 = sqrt(50); } if (rx > sqrt(50)) { rebound = true; } if (currentTime - tTime > 0.01) { rx = rx + 0.0166666; rxp = rxp + 0.0166666; rz = rz + 0.005; timer = true; if (rebound) { rebound1 = rebound1 - 0.0166666; rebound2 = rebound2 - 0.0166666; //printf("rebounds: %f %f\n", rebound1, rebound2); } } // Clear the rendering window static const float black[] = { 0.0f, 0.0f, 0.0f, 0.0f }; const float clearDepth = 1.0f; glClearBufferfv(GL_COLOR, 0, black); glClearBufferfv(GL_DEPTH, 0, &clearDepth); // Must pass in a *pointer* to the depth glUseProgram(myWaveShader); // Should really check if timeLocation and waveModeLocation are -1 before calling these, // but it seems to be OK to just call them anyway. glUniform1f(timeLocation, currentTime); // Set the current time uniform variable in the shader glUniform1i(waveModeLocation, waveMode); // Set the uniform variable in the shader glUniform1f(ampLoc, amp); glUniform1f(rxLoc, rx); glUniform1f(rzLoc, rz); glUniform1f(rzpLoc, rzp); glUniform1f(rxpLoc, rxp); glUniform1f(rebound1Loc, rebound1); glUniform1f(rebound2Loc, rebound2); MyRenderSurfaces(); MyRenderSpheresForLights(); check_for_opengl_errors(); // Really a great idea to check for errors -- esp. good for debugging! } void my_setup_SceneData() { mySetupGeometries(); // **** You should add "LoadShaderSource" commands if you make more GLSL files. **** GlShaderMgr::LoadShaderSource("EduPhong.glsl"); GlShaderMgr::LoadShaderSource("shaders2.c"); unsigned int shader_vert = GlShaderMgr::CompileShader("vertexShader_PhongPhong2"); unsigned int shader_frag = GlShaderMgr::CompileShader("fragmentShader_PhongPhong2", "calcPhongLighting", "applyTextureMap"); unsigned int shaders_progs[2] = { shader_vert, shader_frag }; myWaveShader = GlShaderMgr::LinkShaderProgram(2, shaders_progs); phRegisterShaderProgram(myWaveShader); check_for_opengl_errors(); projMatLocation = glGetUniformLocation(myWaveShader, phProjMatName); modelviewMatLocation = glGetUniformLocation(myWaveShader, phModelviewMatName); // Similar commands to the next line are used to get the locations // for Uniform variables that you add to the shader programs. // glGetUniformLocation returns "-1" if the variable is not in the shader program. timeLocation = glGetUniformLocation(myWaveShader, "curTime"); waveModeLocation = glGetUniformLocation(myWaveShader, "waveMode"); xloc = glGetUniformLocation(myWaveShader, "x"); zloc = glGetUniformLocation(myWaveShader, "z"); ampLoc = glGetUniformLocation(myWaveShader, "amp"); rxLoc = glGetUniformLocation(myWaveShader, "rx"); rzLoc = glGetUniformLocation(myWaveShader, "rz"); rxpLoc = glGetUniformLocation(myWaveShader, "rxp"); rzpLoc = glGetUniformLocation(myWaveShader, "rzp"); rebound1Loc = glGetUniformLocation(myWaveShader, "rebound1"); rebound2Loc = glGetUniformLocation(myWaveShader, "rebound2"); check_for_opengl_errors(); MySetupGlobalLight(); MySetupLights(); LoadAllLights(); MySetupMaterials(); //glfwSetTime(0.0); check_for_opengl_errors(); // Really a great idea to check for errors -- esp. good for debugging! } // ******************************************************* // Process all key press events. // This routine is called each time a key is pressed or released. // ******************************************************* void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { static const double Pi = 3.1415926535f; if (action == GLFW_RELEASE) { return; // Ignore key up (key release) events } bool viewChanged = false; switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); return; case '4': case '1': case '2': case '3': { phLight& theLight = myLights[key - '1']; theLight.IsEnabled = !theLight.IsEnabled; // Toggle whether the light is enabled. LoadAllLights(); return; } case 'B': //waveMode = (waveMode + 1) % 2; return; case 'W': // Toggle wireframe mode if (wireframeMode) { wireframeMode = false; glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { wireframeMode = true; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } return; case 'C': // Toggle backface culling cullBackFaces = !cullBackFaces; // Negate truth value of cullBackFaces if (cullBackFaces) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } return; case 'M': if (mods & GLFW_MOD_SHIFT) { meshRes = meshRes < 79 ? meshRes + 1 : 80; // Uppercase 'M' } else { meshRes = meshRes > 4 ? meshRes - 1 : 3; // Lowercase 'm' } RemeshFloor(); return; case GLFW_KEY_UP: viewAzimuth = Min(viewAzimuth + 0.01, PIfourths - 0.05); viewChanged = true; break; case GLFW_KEY_DOWN: viewAzimuth = Max(viewAzimuth - 0.01, -PIfourths + 0.05); viewChanged = true; break; case GLFW_KEY_RIGHT: viewDirection += 0.01; if (viewDirection > PI) { viewDirection -= PI2; } viewChanged = true; break; case GLFW_KEY_LEFT: viewDirection -= 0.01; if (viewDirection < -PI) { viewDirection += PI2; } viewChanged = true; break; case GLFW_KEY_A: globalPhongData.EnableAmbient = !globalPhongData.EnableAmbient; break; case GLFW_KEY_E: globalPhongData.EnableEmissive = !globalPhongData.EnableEmissive; break; case GLFW_KEY_D: globalPhongData.EnableDiffuse = !globalPhongData.EnableDiffuse; break; case GLFW_KEY_S: globalPhongData.EnableSpecular = !globalPhongData.EnableSpecular; break; case GLFW_KEY_V: globalPhongData.LocalViewer = !globalPhongData.LocalViewer; break; } // Might have updated the global phong data above: upload it to the shader program. globalPhongData.LoadIntoShaders(); if (viewChanged) { mySetViewMatrix(); LoadAllLights(); // Have to call this since it affects the position of the lights! } else { // Updated the global phong data above: upload it to the shader program. globalPhongData.LoadIntoShaders(); } } // ******************************************************* // Process all mouse button events. - Mostly for debugging // ******************************************************* void mouse_button_callback(GLFWwindow* window, int button, int action, int /*mods*/) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { glfwSetTime(0.0); waveMode = (waveMode + 1) % 2; glfwGetCursorPos(window, &xpos, &ypos); printf("Mouse click at: %d, %d.\n", (int)xpos, (int)ypos); int width, height; glfwGetWindowSize(window, &width, &height); float cxpos = (xpos - width / 2) / (width / 2); float cypos = (-ypos + height/2) / (height / 2); // Solving for x,z coordinates VectorR3 xy = VectorR3(cxpos, cypos, 1); LinearMapR4 multiMat = theProjectionMatrix * viewMatrix; LinearMapR3 threeMat = LinearMapR3(multiMat.m11, multiMat.m21, multiMat.m41, multiMat.m13, multiMat.m23, multiMat.m43, multiMat.m14, multiMat.m24, multiMat.m44 ); VectorR3 xz = threeMat.Inverse() * xy; newx = xz.x / xz.z; newz = xz.y / xz.z; glUniform1f(xloc, newx); glUniform1f(zloc, newz); printf("Model position at: %f, %f.\n", newx, newz); } } // ************************************************* // This function is called with the graphics window is first created, // and again whenever it is resized. // The Projection View Matrix is typically set here. // But this program does not use any transformations or matrices. // ************************************************* void window_size_callback(GLFWwindow* window, int width, int height) { // Define the portion of the window used for OpenGL rendering. glViewport(0, 0, width, height); // Setup the projection matrix as a perspective view. // The complication is that the aspect ratio of the window may not match the // aspect ratio of the scene we want to view. double w = (width == 0) ? 1.0 : (double)width; double h = (height == 0) ? 1.0 : (double)height; double windowXmax, windowYmax; double aspectFactor = w * Ymax / (h * Xmax); // == (w/h)/(Xmax/Ymax), ratio of aspect ratios if (aspectFactor>1) { windowXmax = Xmax * aspectFactor; windowYmax = Ymax; } else { windowYmax = Ymax / aspectFactor; windowXmax = Xmax; } // Using the max & min values for x & y & z that should be visible in the window, // we set up the orthographic projection. double zFar = zNear + Zmax - Zmin; theProjectionMatrix.Set_glFrustum(-windowXmax, windowXmax, -windowYmax, windowYmax, zNear, zFar); if (glIsProgram(myWaveShader)) { glUseProgram(myWaveShader); theProjectionMatrix.DumpByColumns(matEntries); glUniformMatrix4fv(projMatLocation, 1, false, matEntries); } check_for_opengl_errors(); // Really a great idea to check for errors -- esp. good for debugging! } void my_setup_OpenGL() { glEnable(GL_DEPTH_TEST); // Enable depth buffering glDepthFunc(GL_LEQUAL); // Useful for multipass shaders // Set polygon drawing mode for front and back of each polygon glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glEnable(GL_CULL_FACE); check_for_opengl_errors(); // Really a great idea to check for errors -- esp. good for debugging! } void error_callback(int error, const char* description) { // Print error fputs(description, stderr); } void setup_callbacks(GLFWwindow* window) { // Set callback function for resizing the window glfwSetFramebufferSizeCallback(window, window_size_callback); // Set callback for key up/down/repeat events glfwSetKeyCallback(window, key_callback); // Set callbacks for mouse movement (cursor position) and mouse botton up/down events. // glfwSetCursorPosCallback(WindowID, cursor_pos_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); // Set callbacks for mouse movement (cursor position) and mouse botton up/down events. // glfwSetCursorPosCallback(window, cursor_pos_callback); // glfwSetMouseButtonCallback(window, mouse_button_callback); } int main() { glfwSetErrorCallback(error_callback); // Supposed to be called in event of errors. (doesn't work?) glfwInit(); //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_SAMPLES, 4); glEnable(GL_MULTISAMPLE); GLFWwindow* window = glfwCreateWindow(initWidth, initHeight, "Phong Demo", NULL, NULL); if (window == NULL) { printf("Failed to create GLFW window!\n"); return -1; } glfwMakeContextCurrent(window); if (GLEW_OK != glewInit()) { printf("Failed to initialize GLEW!.\n"); return -1; } // Print info of GPU and supported OpenGL version printf("Renderer: %s\n", glGetString(GL_RENDERER)); printf("OpenGL version supported %s\n", glGetString(GL_VERSION)); #ifdef GL_SHADING_LANGUAGE_VERSION printf("Supported GLSL version is %s.\n", (char *)glGetString(GL_SHADING_LANGUAGE_VERSION)); #endif printf("Using GLEW version %s.\n", glewGetString(GLEW_VERSION)); printf("------------------------------\n"); printf("Press arrow keys to adjust the view direction.\n "); printf("Press 'B' (both) to toggle whether one wave or both waves are generated.\n"); printf("Press 'w' or 'W' (wireframe) to toggle whether wireframe or fill mode.\n"); printf("Press 'M' (mesh) to increase the mesh resolution.\n"); printf("Press 'm' (mesh) to decrease the mesh resolution.\n"); printf("Press 'F'(faster) or 'f' (slower) to speed up or slow down the animation.\n"); printf("Press '1', '2', '3' to toggle the three lights.\n"); printf("Press '4' to toggle the spotlight.\n"); printf("Press ESCAPE or 'X' or 'x' to exit.\n"); printf("Press 'E' key (Emissive) to toggle rendering Emissive light.\n"); printf("Press 'A' key (Ambient) to toggle rendering Ambient light.\n"); printf("Press 'D' key (Diffuse) to toggle rendering Diffuse light.\n"); printf("Press 'S' key (Specular) to toggle rendering Specular light.\n"); printf("Press 'V' key (Viewer) to toggle using a local viewer.\n"); printf("Press ESCAPE to exit.\n"); setup_callbacks(window); // Initialize OpenGL, the scene and the shaders my_setup_OpenGL(); my_setup_SceneData(); window_size_callback(window, initWidth, initHeight); // Loop while program is not terminated. while (!glfwWindowShouldClose(window)) { myRenderScene(); // Render into the current buffer glfwSwapBuffers(window); // Displays what was just rendered (using double buffering). // Poll events (key presses, mouse events) glfwWaitEventsTimeout(1.0/60.0); // Use this to animate at 60 frames/sec (timing is NOT reliable) // glfwWaitEvents(); // Or, Use this instead if no animation. // glfwPollEvents(); // Use this version when animating as fast as possible } glfwTerminate(); return 0; } // If an error is found, it could have been caused by any command since the // previous call to check_for_opengl_errors() // To find what generated the error, you can try adding more calls to // check_for_opengl_errors(). char errNames[8][36] = { "Unknown OpenGL error", "GL_INVALID_ENUM", "GL_INVALID_VALUE", "GL_INVALID_OPERATION", "GL_INVALID_FRAMEBUFFER_OPERATION", "GL_OUT_OF_MEMORY", "GL_STACK_UNDERFLOW", "GL_STACK_OVERFLOW" }; bool check_for_opengl_errors() { int numErrors = 0; GLenum err; while ((err = glGetError()) != GL_NO_ERROR) { numErrors++; int errNum = 0; switch (err) { case GL_INVALID_ENUM: errNum = 1; break; case GL_INVALID_VALUE: errNum = 2; break; case GL_INVALID_OPERATION: errNum = 3; break; case GL_INVALID_FRAMEBUFFER_OPERATION: errNum = 4; break; case GL_OUT_OF_MEMORY: errNum = 5; break; case GL_STACK_UNDERFLOW: errNum = 6; break; case GL_STACK_OVERFLOW: errNum = 7; break; } printf("OpenGL ERROR: %s.\n", errNames[errNum]); } return (numErrors != 0); }
ade6e1083be2aa5830caff02c042dd976e0a78d3
[ "C", "Text", "C++" ]
4
C
AnnoyingOtter11/Waves
2390e030c82edda20ef8f40c64cda53592194e56
bd6b2202796405f7154e9c95f647229f6874eb75
refs/heads/master
<file_sep><?php require_once(get_template_directory().'/vendor/autoload.php'); use App\BaseDatas; use App\IncludeDatas; use App\PostFunction; use App\ThemeCustomizer; use App\util; use App\Navigation; use App\TempestRegister; new IncludeDatas(); new PostFunction(); new ThemeCustomizer(); new Navigation(); new TempestRegister(); $util = new util(); function get_header_class($option,$const) { switch($option) { case $const['background'] : return 'background-on'; break; case $const['background_none'] : return 'header-off'; break; } } function get_navigation_class($option,$const) { switch ($option) { case $const['horizontal_logo'] : return 'extend-offset-navigation'; break; case $const['horizontal_line'] : return 'extend-navigation horizontal_line'; break; case $const['horizontal_logo_none'] : return 'extend-offset-navigation logo_none'; break; case $const['vertical_logo'] : return 'extend-navigation vertical'; break; case $const['vertical_logo_none'] : return 'extend-navigation vertical logo-none'; break; case $const['none'] : return 'navigation-logo-only'; break; } } //if ( function_exists( 'register_sidebar' ) ) { // register_sidebar( array( // 'name' => 'ウィジェット1', // 'id' => 'widget01', // 'before_widget' => '<div class=”widget”>', // 'after_widget' => '</div>', // 'before_title' => '<h3>', // 'after_title' => '</h3>' // ) ); //} function get_navigation_data($navigation_name) { $locations = get_nav_menu_locations(); $menu = wp_get_nav_menu_object($locations[$navigation_name]); $menu_items = wp_get_nav_menu_items($menu->term_id); $result = []; foreach($menu_items as $key => $item) { if(array_key_exists((string)$item->menu_item_parent,$result)) { $result[$item->menu_item_parent]['children'][] = ['title'=>$item->title,'url'=>$item->url]; } else { $result[$item->ID] = ['parent'=>$item->title,'url'=>$item->url,'description'=>$item->description]; } } return $result; } <file_sep><?php namespace App; class util { public static function getConst($file) { $path = dirname(__FILE__,2).'/config/'.$file.'.php'; $config = null; if(file_exists($path)) { $config = require($path); } return $config; } }<file_sep> <section class="contents post type-list"> <?php if($tempest_post_data->have_posts()) : while($tempest_post_data->have_posts()) : $tempest_post_data->the_post(); ?> <div class="list_block"> <div class="thumbnail"> </div> <h2><?php echo get_the_title(); ?></h2> </div> <?php endwhile; else : ?> <?php endif; ?> </section><file_sep>import { hello } from "./sub"; import './css/base/standard_theme_base.scss'; // hello(); <file_sep><?php return [ 'widget' => [ [ 'name' => 'TOPコンテンツ', 'id' => 'top_contents', 'before_widget' => '<div class="top_contents_column">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', 'description' => '各テンプレート全体の左サイドバー', ], [ 'name' => '全体左カラム', 'id' => 'all_left_column', 'before_widget' => '<div class="all_left_column">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', 'description' => '各テンプレート全体の左サイドバー', ], [ 'name' => '全体右カラム', 'id' => 'all_right_column', 'before_widget' => '<div class="all_right_column">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', 'description' => '各テンプレート全体の右サイドバー', ], [ 'name' => 'セクション右カラム', 'id' => 'section_right_column', 'before_widget' => '<div class="section_right_column">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', 'description' => '各セクションの全体の右サイドバー', ], [ 'name' => 'セクション右カラム', 'id' => 'section_left_column', 'before_widget' => '<div class="section_left_column">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', 'description' => '各セクションの全体の右サイドバー', ], ], 'widget_contents' => [ 'App\Widget\PostWidget' => [ 'name' => 'サイドバー(上部)', 'id' => 'PostWidget', 'before_widget' => '<div>', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', ], ] ];<file_sep><?php namespace App; class PostFunction { public function __construct() { add_action('admin_menu',array(&$this, 'add_seo'),10,1); } public static function add_seo() { add_meta_box('seo_setting', 'SEOタイトル', function() { global $post; echo '<input type="text" name="seo_title" value="' . get_post_meta($post->ID, 'seo_title', true) . '" size="100" />'; }, 'post', 'normal'); } }<file_sep><?php namespace App\Blocks; class BaseBlock { public function __construct() { $this->extendOriginal(); $this->initActions(); } public function extendOriginal() { $categories[] = array( 'slug' => 'extend_origin', 'title' => 'extendBlock', ); return $categories; } private function initActions() { register_block_type( 'gutenberg/internallink',[]); } } <file_sep>// import { hello } from "./simpleBox"; <file_sep><?php namespace App\Widget; use App\util; use WP_Query; use WP_Widget; class PostWidget extends \WP_Widget { const N_POSTS = 30; /** * Widgetを登録する */ function __construct() { $args = array('posts_per_page' => self::N_POSTS, 'offset' => 0, 'order' => 'DESC', 'orderby' => 'date'); $post_datas = new WP_Query($args); parent::__construct( 'post_widget', // Base ID '【Tempestオリジナル】投稿一覧表示設定', // Name array( 'description' => 'ブログ表示設定', ) // Args ); } /** * 表側の Widget を出力する * * @param array $args 'register_sidebar'で設定した「before_title, after_title, before_widget, after_widget」が入る * @param array $instance Widgetの設定項目 */ public function widget( $args, $instance ) { echo $args['before_widget']; $instance = $this->getParameter($instance); $tempest_post_data = $this->getPostData($instance['post_num'],$instance['post_category']); include get_theme_file_path('sidebar-post.php'); echo $args['after_widget']; } protected function getParameter($instance) { if(empty($instance['post_num'])) { $instance['post_num'] = null; } if(empty($instance['title'])) { $instance['title'] = null; } if(empty($instance['post_category'])) { $instance['post_category'] = null; } return $instance; } protected function getPostData($req_posts,$post_category) { if(is_array($post_category)) { $post_category = ['category__in' => $post_category]; } else { $post_category = ['cat' => $post_category]; } $args = array('posts_per_page' => $req_posts, 'offset' => 0, 'order' => 'DESC', 'orderby' => 'date'); $args = array_merge($args,$post_category); return $post_datas = new WP_Query($args); } /** Widget管理画面を出力する * * @param array $instance 設定項目 * @return string|void */ public function form( $instance ) { $categories = get_categories(); $args = array('posts_per_page' => self::N_POSTS, 'offset' => 0, 'order' => 'DESC', 'orderby' => 'date'); $post_datas = new WP_Query($args); $title = ! empty( $instance['title'] ) ? $instance['title'] : __( '最大表示件数', 'text_domain' ); ?> <p> <label for="<?php echo $this->get_field_id( 'post_title' ); ?>"><?php _e( 'セクションタイトル:' ); ?></label> <input type="text" class="widefat" id="<?php echo $this->get_field_id( 'post_title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>"> </p> <p> <label for="<?php echo $this->get_field_id( 'post_num' ); ?>"><?php _e( '表示件数:' ); ?></label> <input type="number" style="width: 60px;" type="number" min="0" class="widefat" id="<?php echo $this->get_field_id( 'post_num' ); ?>" name="<?php echo $this->get_field_name( 'post_num' ); ?>"> </p> <p> <label for="<?php echo $this->get_field_id( 'post_category_1' ); ?>"><?php _e( '表示したいカテゴリ1:' ); ?></label><br /> <select size="3" id="<?php echo $this->get_field_id( 'post_category_1' ); ?>" name="<?php echo $this->get_field_name( 'post_category_1' ); ?>"> <?php foreach($categories as $key => $obj) : ?> <option value="<?php echo $obj->term_id; ?>"><?php echo $obj->name; ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'post_category_2' ); ?>"><?php _e( '表示したいカテゴリ2:' ); ?></label><br/> <select size="3" id="<?php echo $this->get_field_id( 'post_category_2' ); ?>" name="<?php echo $this->get_field_name( 'post_category_2' ); ?>"> <?php foreach($categories as $key => $obj) : ?> <option value="<?php echo $obj->term_id; ?>"><?php echo $obj->name; ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo $this->get_field_id( 'post_category_3' ); ?>"><?php _e( '表示したいカテゴリ3:' ); ?></label><br/> <select size="3" id="<?php echo $this->get_field_id( 'post_category_3' ); ?>" name="<?php echo $this->get_field_name( 'post_category_3' ); ?>"> <?php foreach($categories as $key => $obj) : ?> <option value="<?php echo $obj->term_id; ?>"><?php echo $obj->name; ?></option> <?php endforeach; ?> </select> </p> <!-- <p>--> <!-- <label for="--><?php //echo $this->get_field_id( 'post_priority' ); ?><!--">--><?php //_e( '優先表示設定:' ); ?><!--</label><br/>--> <!-- <select id="post_recent" multiple name="--><?php //echo $this->get_field_name( 'post_priority' ); ?><!--">--> <!-- --><?php // while($post_datas->have_posts()) : $post_datas->the_post(); ?> <!-- --><?php //if(!empty(get_the_title())) :?> <!-- <option value="--><?php //echo get_the_id(); ?><!--">--><?php //echo get_the_title(); ?><!--</option>--> <!-- --><?php //endif; ?> <!-- --><?php //endwhile; ?> <!-- </select>--> <!-- </p>--> <?php } /** 新しい設定データが適切なデータかどうかをチェックする。 * 必ず$instanceを返す。さもなければ設定データは保存(更新)されない。 * * @param array $new_instance form()から入力された新しい設定データ * @param array $old_instance 前回の設定データ * @return array 保存(更新)する設定データ。falseを返すと更新しない。 */ function update($new_instance, $old_instance) { filter_var($new_instance['title'],FILTER_SANITIZE_SPECIAL_CHARS); if(!filter_var($new_instance['post_category'],FILTER_VALIDATE_INT)&&!filter_var($new_instance['post_num'],FILTER_VALIDATE_INT)){ return false; } return $new_instance; } } <file_sep><?php namespace App\Blocks; use App\Blocks\BaseBlock; add_action( 'init', 'gutenberg_examples_03_load_textdomain' ); class InternalLinkBlocks extends BaseBlock { }<file_sep><?php get_header(); $const = require(get_template_directory().'/config/const.php'); ?> <section class="contet-layout-o layout-size-max"> </section> <section class="content-layout-o layout-size-max <?php if(get_option('header_type')===$const['header_type']['background']) : ?>theme_back_ground height_max <?php endif; ?>top-section"> <nav class="layout-size-o header-navigation <?php echo get_navigation_class(get_option('nav_type'),$const['nav_type']); ?>"> <div class="header_logo horizontal-logo nav-item <?php echo get_navigation_class(get_option('nav_type'),$const['nav_type']); ?>"> <img src="<?php echo esc_url(get_theme_mod('set_logo')); ?>" /> </div> <?php if(get_option('nav_type')!==$const['nav_type']['none']) : ?> <div class="navigation-wrapper <?php echo get_navigation_class(get_option('nav_type'),$const['nav_type']); ?>"> <?php foreach(get_navigation_data('tempest_header_navi') as $key => $item) : ?> <div class="nav-item on-sub-menu"> <a class="link-main" href="#"> <span class="nav-sub-title <?php echo get_header_class(get_option('header_type'),$const['header_type']); ?>"><?php echo $item['parent'] ?></span> <div class="nav-item-info <?php echo get_header_class(get_option('header_type'),$const['header_type']); ?>"><?php echo mb_substr($item['description'],0,15) ?></div> </a> <?php if(array_key_exists('children',$item)) :?> <ul class="theme-sub-menu"> <?php foreach($item['children'] as $children) : ?> <li class="sub-menu-item"><a href="#"><?php echo $children['title']; ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> </div> <?php endforeach; ?> </div> <?php endif; ?> </nav> </section> <section class="contents"> <?php dynamic_sidebar( 'top_contents' ); ?> </section> <?php dynamic_sidebar('PostWidget'); ?> <?php get_sidebar('post'); ?> <?php if ( is_active_sidebar('PostWidget') ) : ?> <?php endif; ?> <file_sep><?php namespace App; use App\util; class Navigation { public function __construct() { $navi = Util::getConst('config')['navigation']; foreach($navi as $location => $description) { register_nav_menu( $location, $description); } } }<file_sep><?php namespace App; use App\util; class IncludeDatas extends BaseDatas { public function __construct() { parent::__construct(); add_action('wp_enqueue_scripts',array(&$this, 'include_css'),10,1); do_action('wp_enqueue_scripts', $this->enqueque['css']); add_action('wp_enqueue_scripts', array(&$this, 'include_js')); do_action('wp_enqueue_scripts', $this->enqueque['js']); } public function include_css($enqueued) { if (is_array($enqueued)) { foreach($enqueued as $row) { if(!is_admin()) { wp_enqueue_style($row['name'], $row['location'],$row['deps'],$row['version']); } } } } public function include_js($enqueued) { if (is_array($enqueued)) { foreach($enqueued as $row) { if(!is_admin()) { wp_enqueue_script($row['name'], $row['location'],$row['deps'],$row['version'],$row['output']); } } } } }<file_sep><?php //var_dump(get_option('header_type')); return [ 'css' => [ [ 'name' => 'output', "location" => get_template_directory_uri().'/output.css', "deps" => [], "version" => filemtime(dirname(__FILE__,2).'/output.css'), ], [ 'name' => 'standard_base', "location" => get_template_directory_uri().'/assets/standard_base/style.css', "deps" => [], "version" => filemtime(dirname(__FILE__,2).'/assets/standard_base/style.css'), ], ], 'js' => [ [ 'name' => 'main', "location" => get_template_directory_uri().'/assets/standard_base/bundle.js', "deps" => [], "version" => filemtime(dirname(__FILE__,2).'/assets/standard_base/bundle.js'), "output" => true, ], ] ]; <file_sep><?php namespace App; use App\util; class SetData { public $Category; public $Tags; public $Posts; public function __construct() { $this->Category = $this->SetAllCategorys(); } public function SetAllCategorys() { $category = get_categories(); return $category; } }<file_sep><?php defined( 'ABSPATH' ) || die(); return[ 'navigation' => [ 'tempest_header_navi' => 'ヘッダーナビゲーション', 'tempest_footer_navi' => 'フッターナビゲーション', ] ]; /** * Post Type */ //require_once(dirname(__FILE__) . '/hooks/post-type.php'); //$post_type = new PostTypePostType1(); // //// Create Post type //add_action('init', array($post_type, 'create_post_type'), 10); // 以下略 /** * Category */ //require_once(dirname(__FILE__) . '/hooks/category.php'); //$category = new CategoryPostType1(); // //// Create Post type //add_action('init', array($category, 'create_taxonomy'), 10); // 以下略 /** * Blocks */ //require_once(dirname(__FILE__) . '/hooks/blocks.php'); //$blocks = new BlocksPostType1(); // //// Add Costom Block Category //add_filter('block_categories', array($blocks, 'add_custom_block_category'), 10, 2); // //// Allowed Block //add_filter('allowed_block_types', array($blocks, 'custom_allowed_block_types'), 10, 2); // //// Register Meta Field //add_action('init', array($blocks, 'register_meta_field'));<file_sep><?php return [ 'postEnable' => [ 'display' => '1', 'none' => '2', ], 'header_type' => [ 'background' => '1', 'background_none' => '2', ], 'nav_type' => [ 'horizontal_logo' => '1', 'horizontal_line' => '2', 'horizontal_logo_none' => '3', 'vertical_logo' => '4', 'vertical_logo_none' => '5', 'none' => '6', ], 'post_contents_type' => [ ], 'page_contents_type' => [ ], ]; <file_sep><?php namespace App; use App\util; class BaseDatas { protected $enqueque = []; protected $remove_action = []; public function __construct() { $this->enqueque = util::getConst('enqueque'); $this->remove_action = util::getConst('action')['remove']; foreach($this->remove_action as $row) { remove_action($row['action_name'],$row['remove_target'],$row['priority']); } } }<file_sep><?php return [ 'remove' => [ [ 'action_name' => 'wp_head', 'remove_target' => 'print_emoji_detection_script', 'priority' => 7, ], [ 'action_name' => 'wp_print_styles', 'remove_target' => 'print_emoji_styles', 'priority' => null, ], [ 'action_name' => 'wp_head', 'remove_target' => 'adjacent_posts_rel_link_wp_head', 'priority' => null, ], [ 'action_name' => 'wp_head', 'remove_target' => 'wp_generator', 'priority' => null, ], [ 'action_name' => 'wp_head', 'remove_target' => 'rel_canonical', 'priority' => null, ], ], 'add' => [ ['action_name' => 'wp_head'], ['action_name' => 'wp_head'] ], ];<file_sep><?php namespace App; use App\SetData; use App\util; use WP_Customize_Image_Control; class ThemeCustomizer { protected $customizer = []; public function __construct() { $this->customizer = util::getConst('theme_customizer'); add_action('customize_register',array($this,'CustomizePostDisplay')); } public function CustomizePostDisplay($wp_customize) { $WP_DATAS = new SetData(); foreach($this->customizer as $key => $record) { $group_setting = array_pop($record['group_section']); $wp_customize->add_section($record['group_name'],$record['group_section']); foreach($group_setting as $row) { for($i=0; $i < count($row['customize_setting']); $i++) { $setting_title = $row['customize_setting'][$i]['setting_name']; if(empty($row['customize_setting'][$i]['group_section'])) { $wp_customize->add_setting($setting_title); } else { $setting_contents = $row['customize_setting'][$i]['group_section']; $wp_customize->add_setting($setting_title,$setting_contents); } } for($i=0; $i < count($row['customize_control']); $i++) { //var_dump($row['customize_control']); $control_title = $row['customize_control'][$i]['setting_name']; if(!empty($row['customize_control'][$i]['object'])) { // フォームの部品を配列で指定できずにWordPressの機能を利用する場合 $control_contents = $row['customize_control'][$i]['object']; $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, $control_title, $control_contents)); } else { $control_contents = $row['customize_control'][$i]['control_section']; $wp_customize->add_control($control_title,$control_contents); } } } } } }<file_sep><?php namespace App; use App\util; class TempestRegister{ const WIDGET = 'widget'; const CONTENT = 'widget_contents'; public $theme_menus = []; public function __construct() { $this->tempest_menus = util::getConst('tempest_menus'); $this->RegisterAdminMenus(); } public function RegisterAdminMenus() { foreach($this->tempest_menus as $key=> $array) { switch($key) { case self::WIDGET : foreach($array as $widget) { register_sidebar($widget); } break; case self::CONTENT : foreach($array as $key => $widget) { add_action('widgets_init', function() use ($key,$widget) { register_widget($key); register_sidebar($widget); }); } break; } } } }
4b219b1705fecf5e154e4145f75a607abce124c9
[ "JavaScript", "PHP" ]
21
PHP
wasipo/extend
91fdc9c526dbd810abdff51179d161af0f987123
77c00d1d894bdfd736810477ffa0f04d6849f2d2
refs/heads/master
<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const graphqlHttp = require('express-graphql'); const app = express(); app.use(bodyParser.json()); const mongoose = require('mongoose'); const graphQlSchema = require('./graphql/schema') const graphQlResolvers = require('./graphql/resolvers'); const isAuth = require('./middlewares/auth.middleware'); app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type'); if(req.method === 'OPTIONS'){ res.sendStatus(200); return } next() }) app.set('view engine', 'ejs'); app.use(isAuth); app.use('/', express.static('views')) app.use('/graphql', graphqlHttp({ schema: graphQlSchema, rootValue: graphQlResolvers, graphiql: true })); mongoose.connect(`mongodb://harish_gql:<EMAIL>:39534/utilities`, { useNewUrlParser: true }) // mongoose.connect(`mongodb://localhost:27017/graphql`, { useNewUrlParser: true }) .then(() => { app.listen((process.env.PORT || 3001), () => { console.log('im listening on 3001') }); }).catch(error => { // console.log(`mongodb://${process.env.MONGO_USER}:${<EMAIL>.<EMAIL>:39534/utilities`) console.log(error) }); <file_sep>const { dateToString } = require('../../helpers/date'); const Event = require('../../models/event'); const { user } = require('./merge'); const User = require('../../models/user'); const {transformEvent} = require('./merge'); module.exports = { events: async () => { try { const events = await Event.find(); return events.map(async event => { // console.log(await transformEvent(event)) return await transformEvent(event); }); } catch (error) { throw error; } }, createEvent: async (args, req) => { try { if(!req.isAuth){ throw new Error('Unathorised'); } let createdEvent; const event = await Event.create({ title: args.eventInput.title, description: args.eventInput.description, price: +args.eventInput.price, date: new Date(), creator: req.userId }); let creator = await user.bind(this, event.creator); createdEvent = await transformEvent(event); // console.log(await user(event.creator) ) const newuser = await User.findById(req.userId); if (!newuser) { throw new Error('User not exists') } newuser.createdEvents.push(event); await newuser.save(); // console.log(createdEvent, 70) return { ...createdEvent } } catch (error) { console.log(error) throw error; } }, } <file_sep>const User = require('../../models/user'); const bcrypt = require('bcryptjs'); const { dateToString } = require('../../helpers/date'); const { user } = require('./merge'); const jwt = require('jsonwebtoken'); const transformEvent = async event => { const creator = await user(event.creator); return new Promise(async (resolve, reject) => { resolve({ ...event._doc, date: dateToString(event.date), creator: creator }) }) } module.exports = { createUser: async (args) => { try { const user = await User.findOne({ email: args.userInput.email }) if (user) { throw new Error('User exists already!') } const hashedPassword = await bcrypt.hash(args.userInput.password, 12) const newuser = await User.create({ email: args.userInput.email, password: <PASSWORD>, }) return { ...newuser._doc, password: null, _id: newuser.id }; } catch (error) { throw error } }, login: async ({ email, password }) => { try { const user = await User.findOne({ email: email }); if (!user) { throw new Error("user does not exist"); } const isEqual = await bcrypt.compare(password, user.password); if (!isEqual) { throw new Error('Password is incorrect') } const token = jwt.sign({ userId: user.id, email: user.email }, 'secretKey', { expiresIn: '1h' } ); return { userId: user.id, token: token, tokenExpiration: 1 } } catch (error) { throw error } } } <file_sep># node-graphql node-graphql This a sample POC for graphql and react
c6e9011a71407ae4e2572914d76b5e9c6e931646
[ "JavaScript", "Markdown" ]
4
JavaScript
harishkonda92/node-graphql
99f35b0bd7c29e8b5d16c4157ba0cc63fdc49698
d9e84240201d5097e50ce992a75fb6e94217153e
refs/heads/master
<file_sep> required Ssh pass https://gist.github.com/arunoda/7790979 sshpass is a utility where you can execute ssh or scp commands without password 1. install sshpass 2. export SSHPASS=<PASSWORD> 3. configure shell script <file_sep>#!/bin/bash #set -xv USERC="MYUSER" HOST_DEV="1.1.1.1" HOST_QA="2.2.2.2" HOST_PRD="3.3.3.3" HOST=$HOST_PRD PATH_LOG="/logs/myapp.log" PATH_REMOTE=$PATH_LOG echo "scp "$USERC"@"$HOST":"$PATH_REMOTE" ." mkdir logs sshpass -e scp $USERC@$HOST:$PATH_REMOTE logs/
a049e7f97360e4741da7faf2ce73af1a6fddb17c
[ "Markdown", "Shell" ]
2
Markdown
dact/shell-scripts
77e8fc4d6324729a2884148508b213fe54252daf
fc42132ea848c1e1e337f371e6fd65040cca29c9
refs/heads/master
<file_sep>package com.greenServices.services; import java.sql.SQLException; import java.text.ParseException; import java.util.List; import java.util.TreeSet; import com.greenServices.bean.AccountList; import com.greenServices.bean.CustomerList; import com.greenServices.bean.RegisterForm; import com.greenServices.contract.CustomerListContract; import com.greenServices.entities.SecAccounts; public interface CustomerService { public CustomerListContract isPresent(String userName,String password) ; public boolean isAdded(RegisterForm registerForm) throws ClassNotFoundException, SQLException, ParseException ; public List<SecAccounts> addAccountForm(int userId,AccountList accountList); public List<AccountList> searchBykey(int userId,String keyword); public List<AccountList> fetchByUserId(int userId); public List<AccountList> OrderByCompany(int userId); public List<AccountList> OrderByCountry(int userId,int countryClick); public TreeSet<AccountList> sortByTree(int userId,int companyClick); } <file_sep>package greenServices; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import com.fasterxml.jackson.databind.ObjectMapper; import com.greenServices.contract.CustomerListContract; import com.greenServices.contract.LoginFormContract; public class GreenServicesPostCliet { public static void main(String[] args) { try { HttpClient client = HttpClientBuilder.create().build(); HttpPost postRequest = new HttpPost("http://localhost:8080/greenServices/services/login/loginForm"); LoginFormContract loginFormContract=new LoginFormContract(); System.out.println("in try block main method()"); ObjectMapper mapper = new ObjectMapper(); postRequest.addHeader("Content-Type","application/json"); loginFormContract.setUsername("harsha"); loginFormContract.setPassword("<PASSWORD>"); String jsonInString = mapper.writeValueAsString(loginFormContract); System.out.println("Input Json: " + jsonInString); StringEntity entity = new StringEntity(jsonInString); postRequest.setEntity(entity); HttpResponse response = client.execute(postRequest); if (response.getStatusLine().getStatusCode() == 200) { System.out.println("Rest API call is success full"); if(response.getEntity()!=null) { InputStreamReader responseReader = new InputStreamReader(response.getEntity().getContent()); BufferedReader responseBr = new BufferedReader(responseReader); StringBuffer result = new StringBuffer(); String line = ""; while ((line = responseBr.readLine()) != null) { //System.out.println("-" + line + "-"); result.append(line); } System.out.println("Complete RestApi REsponse: \n " + result.toString()); } }else { System.out.println("Status Code : " + response.getStatusLine().getStatusCode()); throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.greenServices.resource; import org.springframework.stereotype.Service; import com.greenServices.bean.ResponseBody; import com.greenServices.bean.UserBean; /** * * 100 = Success * 101 = Success but invalid credentials * 102 = success but invalid body content * 301 = failed * 302 = failed with internal exception * 303 = Filed. Data already exists * * @author Harsha * */ @Service("userResource") public class IUserResourceImpl implements IUserResource { @Override public String printCustomName(String name) { System.out.println("In IUserResourceImpl class and printCustomName() method #############"); System.out.println("Entered Name : " + name); return "Hello " + name + "!! Welcome to Restful API...."; } @Override public UserBean getUserInfo(int userId) { System.out.println("In IUserResourceImpl class and getUserInfo() method *************$$$$$$$$"); UserBean user = new UserBean(); user.setUserId(userId); user.setFirstName("Siddharth"); user.setLastName("Mannem"); return user; } @Override public String addName(String name) { System.out.println("In IUserResourceImpl class and addName() method #############"); System.out.println("POst body String you entered: " + name); return "Hello... " + name; } @Override public ResponseBody addUser(UserBean userbean) { System.out.println("In IUserResourceImpl and addUser() *** "); System.out.println("Request body user firstnmae and Id are : " + userbean.getUserId() + " & " + userbean.getFirstName()); ResponseBody response = new ResponseBody(); if(userbean.getUserId() == 21 || userbean.getUserId() == 22 || userbean.getUserId() == 23) { response.setStatus(100); response.setStatusDesc("Success."); response.setMessage("New user added into our system..."); } else { response.setStatus(303); response.setStatusDesc("Failed!!"); response.setMessage("Failed to add. Data already exists"); } return response; } } <file_sep>package com.greenServices.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="customeraccounts") public class SecAccounts { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column private int user_id; @Column private String company_name; @Column private String country; @Column private String account_username; @Column private String password; @Column private String account_email; @Column private String company_url; @OneToOne @JoinColumn(name="addr_id") private AddressEntity addressEntity; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getCompany_name() { return company_name; } public void setCompany_name(String company_name) { this.company_name = company_name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getAccount_username() { return account_username; } public void setAccount_username(String account_username) { this.account_username = account_username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAccount_email() { return account_email; } public void setAccount_email(String account_email) { this.account_email = account_email; } public String getCompany_url() { return company_url; } public void setCompany_url(String company_url) { this.company_url = company_url; } public AddressEntity getAddressEntity() { return addressEntity; } public void setAddressEntity(AddressEntity addressEntity) { this.addressEntity = addressEntity; } /*@ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "STOCK_ID", nullable = false) private CustomerEntity customerEntity;*/ } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.technodeed.services</groupId> <artifactId>greenServices</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <jdk.version>1.8</jdk.version> <spring.version>4.1.0.RELEASE</spring.version> <servletapi.version>3.1.0</servletapi.version> <mysql.connector.version>5.1.31</mysql.connector.version> <deployFolder>/Users/rohithmannem/apache-tomcat-8.5.11/webapps</deployFolder> <cxf.version>3.1.11</cxf.version> <jackson.version>2.9.3</jackson.version> <hibernate.version>4.3.11.Final</hibernate.version> <hsqldb.version>2.3.2</hsqldb.version> <logback.version>1.1.3</logback.version> <!-- <logback.version>1.1.3</logback.version> --> </properties> <dependencies> <!-- Apache CXF --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>${cxf.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api --> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.6.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.transaction/javax.transaction-api --> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>${jackson.version}</version> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.0.RELEASE</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.1.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.0.RELEASE</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.9</version> </dependency> </dependencies> <build> <finalName>greenServices</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <url>http://localhost:8080/manager/text</url> <server>TomcatServer</server> <path>/greenServices</path> </configuration> </plugin> <!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>greenServices</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> --> <!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>1.5</version> <executions> <execution> <goals> <goal>xjc</goal>xjc/generate </goals> <configuration> <outputDirectory>${basedir}/generated/java/source</outputDirectory> <schemaDirectory>${basedir}/src/main/resources/com/apache/cxf/json/service/entities</schemaDirectory> <schemaFiles>*.xsd</schemaFiles> <schemaLanguage>XMLSCHEMA</schemaLanguage> <extension>true</extension> <args> <arg>-XtoString</arg> </args> <plugins> <plugin> <groupId>org.jvnet.jaxb2_commons</groupId> <artifactId>jaxb2-basics</artifactId> <version>0.6.4</version> </plugin> </plugins> </configuration> </execution> </executions> </plugin> --> </plugins> </build> </project><file_sep>package com.greenServices.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="address") public class AddressEntity { @Id private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getZipcode() { return zipcode; } public void setZipcode(int zipcode) { this.zipcode = zipcode; } @Column private String address; @Column private int zipcode; }
6dc790d41886f8da449ab81f29ee37358dfff7f7
[ "Java", "Maven POM" ]
6
Java
kharshavardhan18/harsha-first
6368e2e23a56dc930a899ca0bfd21daf2b57bfd8
eaee545891792cea8113225ebd30284bd39095b1
refs/heads/master
<file_sep>package Package2; public class Hello2 { //NOTE:There can be only 1 main method which is declare in another class public void Two(){ System.out.println("Package two"); } } <file_sep> /** * Write a description of class max here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class max { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a[] = new int[5]; int max=a[3]; for(int i = 0; i < a.length; i++){ System.out.println("Enter a["+i+"]:"); a[i]=sc.nextInt(); if(max < a[i]){ max = a[i]; } } System.out.println("The maximum out of all the array elements is:"+max); } } <file_sep> /** * Write a description of class max_3 here. * * @author (Ayush) * @version (3/6/20-08) */ import java.util.Scanner; public class max_3 { public static void main(String[] args){ int a,b,c; Scanner s = new Scanner(System.in); System.out.println("Enter three different numbers to find out the largest number:"); a = s.nextInt(); b = s.nextInt(); c = s.nextInt(); if(a>b && a>c){ System.out.println(a+" is the greatest number among the three numbers."); } else if(b>a && b>c){ System.out.println(b+" is the greatest number among the three numbers."); } else if(c>a && c>b){ System.out.println(c+" is the greatest number among the three numbers."); } } } <file_sep> /** * Write a description of class ascending here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class ascending { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a[] = new int[5]; int i,j,temp; System.out.println("Enter the numbers:"); for(i = 0; i <= 4; i++){ a[i]=sc.nextInt(); } for(i = 0; i <= 4; i++){ for(j = i+1; j <= 4; j++){ if(a[i]>a[j]){ temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.println("Ascending order:"); for(i = 0; i <= 4; i++){ System.out.println(a[i]); } } } <file_sep> /** * Write a description of class Methods here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class Methods { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str,str2; System.out.println("\nEnter a string in lower case to make it upper case:"); str = sc.nextLine(); System.out.println("The String in uppercase is : "+str.toUpperCase()); System.out.println("\nEnter a string in upper case to make it lower case:"); str = sc.nextLine(); System.out.println("The String in lowercase is : "+str.toLowerCase()); System.out.println("\nEnter a string to find out its length:"); str = sc.nextLine(); System.out.println("The length of the String is : "+str.length()); System.out.println("\nEnter two strings to concate them:"); str = sc.nextLine(); str2 = sc.nextLine(); System.out.println("The string concate is : "+str.concat(str2)); System.out.println("Enter a string including letter 'a' to replace all the letter 'a' with letter 'd'"); str = sc.nextLine(); System.out.println("The new word with letter 'd' on the place of letter 'a' is : "+str.replace('a','d')); System.out.println("Enter a string:"); str = sc.nextLine(); System.out.println("Enter the number of the letter(starting from 0) which you want to print:"); int i = sc.nextInt(); char result = str.charAt(i); System.out.println("The new word only with some letters is : "+result); } } <file_sep>import java.util.Scanner; public class Combined{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); Scanner sc2 = new Scanner(System.in); System.out.println("WELCOME TO TOP-SECRET LANGUAGE TRANSLATOR"); System.out.println("Enter the user name:"); String username = sc.nextLine(); if(username.equals("Sanskriti") || username.equals("Dhairya")){ System.out.println("Enter the password:"); String password = sc.nextLine(); if(password.equals("<PASSWORD>") || password.equals("<PASSWORD>")){ System.out.println("From which language to which language would you like to translate:"); System.out.println("1_____Normal to Secret"); System.out.println("2_____Secret to Normal"); System.out.println("3_____Exit"); int choice = sc2.nextInt(); switch(choice){ case 1: System.out.println("Enter a phrase:"); String str = sc.nextLine(); str = str.replace('a',' '); str = str.replace('b','!'); str = str.replace('c','-'); str = str.replace('d','('); str = str.replace('e','3'); str = str.replace('f',':'); str = str.replace('g',')'); str = str.replace('h','&'); str = str.replace('i','8'); str = str.replace('j','#'); str = str.replace('k','*'); str = str.replace('l','"'); str = str.replace('m',';'); str = str.replace('n','?'); str = str.replace('o','9'); str = str.replace('p','0'); str = str.replace('q','1'); str = str.replace('r','4'); str = str.replace('s','_'); str = str.replace('t','5'); str = str.replace('u','7'); str = str.replace('v','~'); str = str.replace('w','2'); str = str.replace('x','6'); str = str.replace('y','@'); str = str.replace('z','`'); System.out.println("The translated line is: \n"+str); break; case 2: System.out.println("Enter a phrase:"); str = sc.nextLine(); str = str.replace(' ','a'); str = str.replace('!','b'); str = str.replace('-','c'); str = str.replace('(','d'); str = str.replace('3','e'); str = str.replace(':','f'); str = str.replace(')','g'); str = str.replace('&','h'); str = str.replace('8','i'); str = str.replace('#','j'); str = str.replace('*','k'); str = str.replace('"','l'); str = str.replace(';','m'); str = str.replace('?','n'); str = str.replace('9','o'); str = str.replace('0','p'); str = str.replace('1','q'); str = str.replace('4','r'); str = str.replace('_','s'); str = str.replace('5','t'); str = str.replace('7','u'); str = str.replace('~','v'); str = str.replace('2','w'); str = str.replace('6','x'); str = str.replace('@','y'); str = str.replace('`','z'); System.out.println("The translated line is: \n"+str); break; case 3: System.exit(0); } } else{ System.out.println("INCORRECT PASSWORD!!!"); } } else{ System.out.println("INCORRECT USERNAME!!!"); } } }<file_sep> public class Threads_for_loop__3_objects extends Thread{ public void run() { for (int i = 0; i <= 10; i++) { System.out.println("Name = "+Thread.currentThread().getName()+", Value of i = "+i); /*Thread.sleep(500);*/ //If I keep it like this there will be an error. IF YOU HOVER ON THIS LINE & CLICK ON SURROUND WITH TRY AND CATCH, DELAY WILL BE PUT BY TRY AND CATCH try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { Threads_for_loop__3_objects t1 = new Threads_for_loop__3_objects(); Threads_for_loop__3_objects t2 = new Threads_for_loop__3_objects(); Threads_for_loop__3_objects t3 = new Threads_for_loop__3_objects(); t1.start(); t2.start(); t3.start(); //Random numbers will come because all Threads work together and the one executed first will run first } } <file_sep> /** * Write a description of class HelloWorld here. * * @author <NAME> * @version (2/6/20-01) */ public class HelloWorld { public static void main(String[] args){ System.out.println("Hello World!"); } } <file_sep> /** * Write a description of class matrixe_sum here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class matrices_sum { public static void main(String[] args){ int i,j; int a[][] = new int[3][3]; int b[][] = new int[3][3]; int c[][] = new int[3][3]; Scanner scan = new Scanner(System.in); System.out.println("Enter the 9 elements of first array a[i][j]:-"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ a[i][j] = scan.nextInt(); } } System.out.println("Enter the 9 elements of second array b[i][j]:-"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ b[i][j] = scan.nextInt(); } } for(i=0;i<3;i++){ for(j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; } } System.out.println(); System.out.println("a[i][j] :-"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ System.out.printf(a[i][j]+" "); } System.out.printf("\n"); } System.out.println(); System.out.println("b[i][j] :-"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ System.out.printf(b[i][j]+" "); } System.out.printf("\n"); } System.out.println(); System.out.println("c[i][j] :-"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ System.out.printf(c[i][j]+" "); } System.out.printf("\n"); } } } <file_sep> /** * Write a description of class pattern here. * * @author <NAME> * @author (Ayush) * @version (3/6/20-01) */ import java.util.Scanner; public class pattern { public static void main(String[] args){ int row,i,j; System.out.println("Enter the number of rows to make pattern:"); Scanner s = new Scanner(System.in); row = s.nextInt(); for(i=1;i<=row;i++){ for(j=1;j<=i;j++){ System.out.printf("%d",i); } System.out.printf("\n"); } } } <file_sep> /** * Write a description of class basic here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class basic { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Enter a string:"); String str; str = sc.nextLine(); System.out.println("String entered by you is : "+str); } } <file_sep> /** * Write a description of class scan here. * * @author <NAME> * @version (2/6/20-03) */ import java.util.Scanner; public class scan { public static void main(String[] args){ Scanner s1 = new Scanner(System.in); System.out.println("Enter an integer:"); int a; a = s1.nextInt(); System.out.println("The entered integer is "+a); } } <file_sep> /** * Write a description of class vowel_consonant_switchcase here. * * @author <NAME> * @version (3/6/20-01) */ import java.util.Scanner; public class vowel_consonant { public static void main(String[] args){ System.out.println("Enter a letter to check whether it is a vowel or consonant(Enter in small letters):"); Scanner s = new Scanner(System.in); char a = s.next().charAt(0); if(a=='a' || a=='e' || a=='i' || a=='o' || a=='u'){ System.out.println("The entered integer is an vowel."); } else{ System.out.println("Given character is a consonant."); } } } <file_sep> /** * Write a description of class col_sum here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class col_sum { public static void main(String[] args){ int i,j; int arr[][] = new int[3][3]; Scanner sc = new Scanner(System.in); System.out.println("Enter 9 values for finding column wise sum of ther tabular form:"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { arr[i][j] = sc.nextInt(); } } for (i = 0; i < 3; i++){ for (j = 0; j < 3;j++){ System.out.print(arr[i][j] + " "); } System.out.println(); } System.out.println(); for (i = 0; i < 3; i++) { int cSum = 0; for (j = 0; j < 3; j++) { cSum += arr[j][i]; } System.out.println("Column " + (i + 1) + " sum = " + cSum); } } } <file_sep> /** * Write a description of class positive_negative here. * * @author (Ayush) * @version (3/6/20-07) */ import java.util.Scanner; public class positive_negative { public static void main(String[] args){ int a; Scanner s = new Scanner(System.in); System.out.println("Enter a number to know whether it is +ve or -ve:"); a = s.nextInt(); if(a>0){ System.out.println("Your entered number is +ve."); } else if(a<0){ System.out.println("Your entered number is -ve."); } else{ System.out.println("Your entered number is 0."); } } } <file_sep>import java.util.Scanner; public class Arithmetic_exception { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int ans = 0; System.out.println("Enter two numbers: "); int no1 = sc.nextInt(); int no2 = sc.nextInt(); try { //It will try doing this but if there will be any arithmetic exception(error*(for eg. no2 = 0), it will go to catch block for the indication of error ans = no1 / no2; } catch(ArithmeticException e){ //e is just an object to call the error e.printStackTrace(); } System.out.println(no1+"/"+no2+"="+ans); } } <file_sep> /** * Write a description of class calculator here. * * @author (Ayush) * @version (4/6/20-12) */ import java.util.Scanner; public class calculator { public static void main(String[] args){ int a,b,c,choice; Scanner s = new Scanner(System.in); System.out.println("Enter a choice:"); System.out.println("1.Addition"); System.out.println("2.Subtraction"); System.out.println("3.Multiplication"); System.out.println("4.Division"); System.out.println("5.exit"); choice = s.nextInt(); switch(choice){ case 1: System.out.println("Enter two numbers to be added:"); a = s.nextInt(); b = s.nextInt(); c=a+b; System.out.println(a+"+"+b+"="+c); break; case 2: System.out.println("Enter two numbers to be Subtracted(first-second):"); a = s.nextInt(); b = s.nextInt(); c=a-b; System.out.println(a+"-"+b+"="+c); break; case 3: System.out.println("Enter two numbers to be multiplied:"); a = s.nextInt(); b = s.nextInt(); c=a*b; System.out.println(a+"*"+b+"="+c); break; case 4: System.out.println("Enter two numbers to be Divided(first/second):"); a = s.nextInt(); b = s.nextInt(); c=a/b; System.out.println(a+"/"+b+"="+c); break; case 5: System.exit(1); default: System.out.println("\t\t\tInvalid choice!!!"); } } } <file_sep> /** * Write a description of class sum here. * * @author (your name) * @version (a version number or a date) */ import java.util.Scanner; public class sum { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a[] = new int[5]; int sum=0; for(int i = 0; i < a.length; i++){ System.out.println("Enter a["+i+"]:"); a[i]=sc.nextInt(); sum = sum+a[i]; } System.out.println("The sum of all the Array elements is:"+sum); } }
90277313076f5106ff5b52d99ebf1681eccbe0b4
[ "Java" ]
18
Java
Ayush181005/Core-Java
85a66150e14a94f760978a352a3067f9423789f7
b7ec911f48020216b4b8c2188dd5542e5ebbaed1
refs/heads/main
<repo_name>BMidhun/aud-player-react<file_sep>/src/helper/filesAsArray.ts function filesAsArray(filesList: FileList):File[] { if (filesList) { const tracks = []; for (let index = 0; index < filesList.length; index++) { tracks.push(filesList[index]); } return tracks; } else return []; } export default filesAsArray;<file_sep>/src/helper/getRandomTrackNumber.ts function getRandomTrack (playlistLength:number):number { return Math.floor(Math.random() * playlistLength) } export default getRandomTrack;<file_sep>/src/helper/computeDuration.ts function computeDuration(duration: number): string { let time: any = new Date(); // create Date object and set to today's date and time time.setHours((duration / 3600) % 24); time.setMinutes((duration / 60) % 60); time.setSeconds(duration % 60); time = time.toTimeString().split(" ")[0]; const [hours, minutes, seconds]: string[] = time.split(":"); let res = ""; if (parseInt(hours)) { res = `${hours}:${minutes}:${seconds}`; } else res = `${minutes}:${seconds}`; return res; } export default computeDuration;
221060b2f2073be99d6a0fa6ccfba01a286ae384
[ "TypeScript" ]
3
TypeScript
BMidhun/aud-player-react
c7623cbacf3623e1ef2a467805617db4d1cb54d8
81852bcd7265d6c852d1f7768d952828948c639c
refs/heads/master
<repo_name>klopstock-dviz/heatmap_hass<file_sep>/gulpfile.js const gulp = require('gulp'); const browserSync = require('browser-sync').create(); gulp.task('sync', function() { let files = [ '*.html', 'css/*.css', 'js/*.js' ]; browserSync.init({ server: { files: files, baseDir: './', }, port: 3000 }); // watch for any change in these files then reload gulp.watch('*.html').on('change',browserSync.reload); gulp.watch('src/*.js').on('change',browserSync.reload); gulp.watch('css/style.css').on('change',browserSync.reload); }) <file_sep>/src/app.js console.log('page chargée'); /* ********************************************************************************** */ /* PARAMETRAGE GRAPHIQUE 1 (diagramme en baton) */ /* ********************************************************************************** */ let margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 760 - margin.left - margin.right, height = 600 - margin.top - margin.bottom; let x = d3.scaleBand() .range([0, width]) .padding(0.1); let y = d3.scaleLinear() .range([height, 0]); // append the svg object to the body of the page let svg = d3.select("#graphique_1") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); /* ********************************************************************************** */ /* PARAMETRAGE GRAPHIQUE 2 (courbe d'évolution) */ /* ********************************************************************************** */ // COURBE EVOLUTION // 1. Créer les dimensions du conteneur qui va accueillir le graphique let marginEv = {top: 50, right: 50, bottom: 50, left: 50} , widthEv = 500 - marginEv.left - marginEv.right // Use the window's width , heightEv = 300 - marginEv.top - marginEv.bottom; // Use the window's height // 2. Créer les axes et leur attribuer les unités let x2 = d3.scaleTime().range([0, widthEv]); let y2 = d3.scaleLinear().range([heightEv, 0]); let valueline = d3.line() .x(d => { return x2(d.key)}) .y(d => { return y2(d.value)}) // 3. Ajouter un élément svg reprenant les dimensions du contenur déclaré en 1. var svg2 = d3.select("#graphique_2").append("svg") .attr("width", widthEv + marginEv.left + marginEv.right) .attr("height", heightEv + marginEv.top + marginEv.bottom) .append("g") .attr("transform", "translate(" + marginEv.left + "," + marginEv.top + ")"); // tooltip (commun aux deux graphiques) const div = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); function mousemove() { div.style("left", (d3.event.pageX - 50) + "px") .style("top", (d3.event.pageY - 40) + "px"); }; /* ********************************************************************************** */ /* PARAMETRAGE <NAME> */ /* ********************************************************************************** */ let map = L.map("map") L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y }.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); /* ********************************************************************************** */ /* CHARGEMENT FICHIER */ /* ********************************************************************************** */ // chemin et nom du ficher let filePath = "./feuxUSA.csv"; // décompte du temps de chargement du fichier let t0 = performance.now() let temps; // chargement du fichier d3.csv(filePath) .then(data => { // décompte de chargement let t1 = performance.now(); temps = (t1 - t0)/1000; // affichage du temps nécessaire au chargement du fichier console.log("Le fichier"+filePath+" a été chargé en : "+temps+"secondes"); // 1er jeu de données pour le premier graphique : aggrégation par État pour avoir le nombre d'incendies par état let data2 = d3.nest() .key(d => { return d.STATE}) .entries(data) .sort((a, b) => { return d3.descending(a.values.length, b.values.length); }) // Centrer la carte sur les coordonnées ci-dessous latlong = data[0] map.setView([latlong.LATITUDE,latlong.LONGITUDE],2) // intégration valeurs des axes du graphique 1 x.domain(data2.map(d => {return d.key})) y.domain([0, d3.max(data2, d => {return d.values.length})]); /* ********************************************************************************** */ /* CREATION DU GRAPHIQUE 1 */ /* ********************************************************************************** */ svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).tickSize(0)) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)"); // Ajout de l'axe Y au SVG avec 6 éléments de légende en utilisant la fonction ticks (sinon D3JS en place autant qu'il peut). svg.append("g") .call(d3.axisLeft(y).ticks(6)); // Ajout des bars en utilisant les données agrégées de data2 // La largeur de la barre est déterminée par la fonction x // La hauteur par la fonction y en tenant compte de la population // La gestion des events de la souris pour le popup svg.selectAll(".bar") .data(data2) .enter().append("rect") .attr("class", "bar") .attr("x", d => { return x(d.key); }) // en x, renvoie le nom de l'état .attr("width", x.bandwidth()) .attr("y", d => { return y(d.values.length); }) /* en y, le nombre d'incendies */ .attr("height", d => { return height - y(d.values.length); }) .on("mouseover", function(d) { /* au passage de la souris .... */ div.transition() /* affiche un tooltip */ .duration(50) .style("opacity", .9); div.html( d.values.length + " feux") .style("left", (d3.event.pageX + 10) + "px") .style("top", (d3.event.pageY - 50) + "px"); }) .on("mousemove",mousemove) /* fais bouger la tooltip en suivant le mouvement de la souris */ .on("mouseout", function(d) { div.transition() .duration(500) .style("opacity", 0); }).on("click", d => { /* au click ... */ // réinitialisation de la carte (nécesssaire pour ne pas superposer à chaque changement d'état les données) map.eachLayer(function (layer) { if(layer._url == undefined) { map.removeLayer(layer); }; }); let fires = d.values; map.flyTo([fires[0].LATITUDE, fires[0].LONGITUDE],5) /* Création d'un tableau vide, qui va accueillir les latitudes et longitudes des points d'incendies */ heatMapData = []; fires.forEach(feature => { let lat = feature.LATITUDE let lon = feature.LONGITUDE heatMapData.push(L.latLng(lat,lon)) }); /* génération de la carte de chaleur */ let heatmap = L.heatLayer(heatMapData, {maxZoom: 12}) map.addLayer(heatmap) /* ********************************************************************************** */ /* CREATION DU GRAPHIQUE 2 */ /* ********************************************************************************** */ // nouveau jeu de données à utiliser /* agrégation par année uniquement sur l'état sélectionné dans le graphique 1 */ nb_year = d3.nest() .key(d => { return d.YEAR}) .rollup(d => { return d.length; }) .entries(fires) .sort((a, b) => { return d3.ascending(a.key, b.key); }) // régler les axes x2.domain(d3.extent(nb_year, d => { return d.key; })); y2.domain(d3.extent(nb_year, d => { return d.value; })); /* trace la courbe sur le graphique */ path = svg2 .append("path") .data([nb_year]) .attr("class", "line") .attr("d", valueline) .on("mouseover", function(d) { div.transition() .duration(50) .style("opacity", .9); div.html( d.value + " feux") .style("left", (d3.event.pageX + 10) + "px") .style("top", (d3.event.pageY - 50) + "px"); }) .on("mousemove",mousemove); // animation courbe d'évolution var totalLength = path.node().getTotalLength(); path .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) .transition() .duration(1000) .ease(d3.easeLinear) .attr("stroke-dashoffset", 0) // Ajoute ou redimensionne l'axe en x en fonction des données svg2.append("g") .attr("transform", "translate(0," + heightEv + ")") .call(d3.axisBottom(x2)); // Ajoute ou redimensionne l'axe en y en fonction des données svg2.append("g") .call(d3.axisLeft(y2)); }) }); /* WOOOF */
925074d54a54c28767844a2c500b008f6b7950dc
[ "JavaScript" ]
2
JavaScript
klopstock-dviz/heatmap_hass
3f67348d8eef72e2e7536cef344155a4c9c2d4d6
e1d0e5cc628e66f4a9b94bfb2035ed000eee79ed
refs/heads/master
<repo_name>jedk1/WCMN<file_sep>/src/eu/wcmn/main/Menu.java package eu.wcmn.main; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; public final class Menu extends JavaPlugin implements Listener { Plugin plugin = this; IconMenu menu_Hats; IconMenu menu_Servers; IconMenu menu_Main; IconMenu menu_Help; IconMenu menu_Rules; IconMenu menu_Other; IconMenu menu_Rewards; static String user_name; static String password; static String ip; static String port; static String database_name; boolean EchoPetEnabled; boolean BuyCraftEnabled; boolean InvMoveEnabled; boolean RewardsEnabled; private int gems = 0; private int gemsOther = 0; private static Connection connection; public static Economy economy = null; //============================================= //SQL STUFF public synchronized static void openConnection() { try{ connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":" + port + "/" + database_name, user_name, password); //System.out.printf("jdbc:mysql://" + ip + ":" + port + "/" + database_name, user_name, password); }catch(Exception e) { e.printStackTrace(); } } public synchronized static void closeConnection() { try{ connection.close(); }catch(Exception e) { e.printStackTrace(); } } public synchronized static boolean playerDataContainsPlayer(Player player){ try{ PreparedStatement sql = connection.prepareStatement("SELECT * FROM `player_data` WHERE player=?;"); sql.setString(1, player.getName()); ResultSet resultSet = sql.executeQuery(); boolean containsPlayer = resultSet.next(); sql.close(); resultSet.close(); return containsPlayer; }catch(Exception e) { e.printStackTrace(); return false; } } public ItemStack applyToStack(ItemStack stack , String name , String...lore){ ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(name); meta.setLore(Arrays.asList(lore)); stack.setItemMeta(meta); return stack; } @EventHandler public void onPlayerJoin(PlayerJoinEvent event){ final Player player = (Player) event.getPlayer(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { if(!player.getInventory().contains(Material.BOOK)) { player.getInventory().addItem(applyToStack(new ItemStack(Material.BOOK), "§6§lWCMN Menu", "Right-Click to access the menu!")); } openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); sql.close(); result.close(); }else{ PreparedStatement newPlayer = connection.prepareStatement("INSERT INTO `player_data` values(?,0);"); newPlayer.setString(1, player.getName()); newPlayer.execute(); newPlayer.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } },5L); } public void gemQuery(Player player){ openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); gems = result.getInt("player_gems"); String str0 = Integer.toString(gems); player.sendMessage("§b========================="); player.sendMessage("§3You have §6§l" + str0 + " §3gems!"); player.sendMessage("§b========================="); sql.close(); result.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } public void gemQueryOther(Player player){ openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); gems = result.getInt("player_gems"); //String str0 = Integer.toString(gems); gemsOther = gems; sql.close(); result.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } public void gemGive(Player player, int i){ openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); gems = result.getInt("player_gems"); PreparedStatement addGems = connection.prepareStatement("UPDATE `player_data` SET player_gems=? WHERE player=?;"); addGems.setInt(1, gems + i); addGems.setString(2, player.getName()); addGems.executeUpdate(); addGems.close(); sql.close(); result.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } public void gemSet(Player player, int i){ openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); PreparedStatement setGems = connection.prepareStatement("UPDATE `player_data` SET player_gems=? WHERE player=?;"); setGems.setInt(1, i); setGems.setString(2, player.getName()); setGems.executeUpdate(); setGems.close(); sql.close(); result.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } public void gemTake(Player player, int i){ openConnection(); try { if(playerDataContainsPlayer(player)) { PreparedStatement sql = connection.prepareStatement("SELECT player_gems FROM `player_data` WHERE player=?"); sql.setString(1, player.getName()); ResultSet result = sql.executeQuery(); result.next(); gems = result.getInt("player_gems"); PreparedStatement takeGems = connection.prepareStatement("UPDATE `player_data` SET player_gems=? WHERE player=?;"); if(i < gems) { takeGems.setInt(1, gems - i); takeGems.setString(2, player.getName()); takeGems.executeUpdate(); }else if(i > gems){ takeGems.setInt(1, 0); takeGems.setString(2, player.getName()); takeGems.executeUpdate(); } takeGems.close(); sql.close(); result.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ closeConnection(); } } public void setHat(Player p, Material m, String s){ p.getInventory().setHelmet(new ItemStack(m)); p.getPlayer().sendMessage("You are now wearing a " + s); } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } @Override public void onEnable(){ ConsoleCommandSender console = getServer().getConsoleSender(); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(this, this); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); this.saveDefaultConfig(); setupEconomy(); getLogger().info("Hooked into Vault!"); user_name = plugin.getConfig().getString("Username"); password = plugin.getConfig().getString("<PASSWORD>"); ip = plugin.getConfig().getString("IP"); port = plugin.getConfig().getString("Port"); database_name = plugin.getConfig().getString("Database_Name"); if(getServer().getPluginManager().isPluginEnabled("EchoPet")) { EchoPetEnabled = true; }else{ EchoPetEnabled = false; console.sendMessage("[WCMN] EchoPets isn't installed/working on this server, Pets option has been disabled in the menu!"); } if(getServer().getPluginManager().isPluginEnabled("Buycraft")) { BuyCraftEnabled = true; }else{ BuyCraftEnabled = false; console.sendMessage("[WCMN] BuyCraft isn't installed/working on this server, Ranks option has been disabled in the menu!"); } //Servers menu_Servers = new IconMenu("WCMN User Panel (Servers)", 36, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); event.getPlayer().performCommand("menu"); String server = event.getName(); Player player = event.getPlayer(); ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); out.writeUTF(ChatColor.stripColor(server)); if(event.getName() == "§lBack") { }else{ player.sendPluginMessage(plugin, "BungeeCord", out.toByteArray()); } } }, this) .setOption(10, new ItemStack(Material.WOOL, 1, (byte)5), "§a§lHub", "§eJump to the Hub Server.") .setOption(12, new ItemStack(Material.WOOL, 1, (byte)10), "§5§lWitchCraft", "§eJump to WitchCraft.") .setOption(14, new ItemStack(Material.WOOL, 1, (byte)4), "§6§lMythology", "§eJump to Mythology.") .setOption(16, new ItemStack(Material.WOOL, 1, (byte)9), "§9§lGhettoVille", "§eJump to GhettoVille.") .setOption(35, new ItemStack(Material.REDSTONE, 1), "§lBack", "§7§oBack to User Panel Home."); //Help menu_Help = new IconMenu("WCMN User Panel (Help/FAQ)", 9, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); event.getPlayer().performCommand("menu"); if(event.getName() == "§lBack") { } } }, this) .setOption(1, new ItemStack(Material.IRON_INGOT, 1), "§6Can I be staff?", "§aWhen we hire staff, we usually", "§alook at staff applications on", "§athe forums! But we don't usually", "§aaccept new staff.") .setOption(3, new ItemStack(Material.SIGN, 1), "§6§lWebsite", "§ewww.wcmn.eu") .setOption(4, new ItemStack(Material.SIGN, 1), "§6§lForums", "§ewww.wcmn.eu/forums/") .setOption(5, new ItemStack(Material.SIGN, 1), "§6§lTwitter", "§e@WCMN_Official") .setOption(6, new ItemStack(Material.SIGN, 1), "§6§lServer Host", "§ewww.vortron.co.uk") .setOption(8, new ItemStack(Material.REDSTONE, 1), "§lBack", "§7§oBack to User Panel Home."); //Hats menu_Hats = new IconMenu("WCMN User Panel (Hats)", 45, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); event.getPlayer().performCommand("menu"); if(event.getName() == "§lBack") { }else if(event.getPosition() == 0){ setHat(event.getPlayer(), Material.GRASS, event.getName()); }else if(event.getPosition() == 1){ setHat(event.getPlayer(), Material.WOOD, event.getName()); }else if(event.getPosition() == 2){ setHat(event.getPlayer(), Material.LOG, event.getName()); }else if(event.getPosition() == 3){ setHat(event.getPlayer(), Material.GLASS, event.getName()); }else if(event.getName() == "§a§lTnt Hat"){ setHat(event.getPlayer(), Material.TNT, event.getName()); }else if(event.getName() == "§a§lBookshelf Hat"){ setHat(event.getPlayer(), Material.BOOKSHELF, event.getName()); }else if(event.getName() == "§a§lDiamond Hat"){ setHat(event.getPlayer(), Material.DIAMOND_BLOCK, event.getName()); }else if(event.getName() == "§a§lIce Hat"){ setHat(event.getPlayer(), Material.ICE, event.getName()); }else if(event.getName() == "§a§lGlowstone Hat"){ setHat(event.getPlayer(), Material.GLOWSTONE, event.getName()); }else if(event.getName() == "§a§lMelon Hat"){ setHat(event.getPlayer(), Material.MELON, event.getName()); }else if(event.getName() == "§a§lHellbreak Hat"){ setHat(event.getPlayer(), Material.NETHER_BRICK, event.getName()); }else if(event.getName() == "§a§lEnd Hat"){ setHat(event.getPlayer(), Material.ENDER_STONE, event.getName()); }else if(event.getName() == "§a§lEmerald Hat"){ setHat(event.getPlayer(), Material.EMERALD_BLOCK, event.getName()); }else if(event.getName() == "§a§lQuartz Hat"){ setHat(event.getPlayer(), Material.QUARTZ_BLOCK, event.getName()); }else if(event.getName() == "§a§lHay Hat"){ setHat(event.getPlayer(), Material.HAY_BLOCK, event.getName()); } } }, this) .setOption(0, new ItemStack(Material.GRASS, 1), "§a§lGrass Hat", "§eClick to wear.") .setOption(1, new ItemStack(Material.WOOD, 1), "§a§lWood Hat", "§eClick to wear.") .setOption(2, new ItemStack(Material.LOG, 1), "§a§lLog Hat", "§eClick to wear.") .setOption(3, new ItemStack(Material.GLASS, 1), "§a§lGlass Hat", "§eClick to wear.") .setOption(4, new ItemStack(Material.TNT, 1), "§a§lTnt Hat", "§eClick to wear.") .setOption(5, new ItemStack(Material.BOOKSHELF, 1), "§a§lBookshelf Hat", "§eClick to wear.") .setOption(6, new ItemStack(Material.DIAMOND_BLOCK, 1), "§a§lDiamond Hat", "§eClick to wear.") .setOption(7, new ItemStack(Material.ICE, 1), "§a§lIce Hat", "§eClick to wear.") .setOption(8, new ItemStack(Material.GLOWSTONE, 1), "§a§lGlowstone Hat", "§eClick to wear.") .setOption(9, new ItemStack(Material.MELON_BLOCK, 1), "§a§lMelon Hat", "§eClick to wear.") .setOption(10, new ItemStack(Material.NETHER_BRICK, 1), "§a§lHellbreak Hat", "§eClick to wear.") .setOption(11, new ItemStack(Material.ENDER_STONE, 1), "§a§lEnd Hat", "§eClick to wear.") .setOption(12, new ItemStack(Material.EMERALD_BLOCK, 1), "§a§lEmerald Hat", "§eClick to wear.") .setOption(13, new ItemStack(Material.QUARTZ_BLOCK, 1, (byte)1), "§a§lQuartz Hat", "§eClick to wear.") .setOption(14, new ItemStack(Material.HAY_BLOCK, 1), "§a§lHay Hat", "§eClick to wear.") .setOption(44, new ItemStack(Material.REDSTONE, 1), "§lBack", "§7§oBack to User Panel Home"); //Rewards menu_Rewards = new IconMenu("WCMN User Panel (Rewards)", 36, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); event.getPlayer().performCommand("menu"); if(event.getName() == "§lBack") { }else if(event.getPosition() == 0){ gemQueryOther(event.getPlayer()); if(gemsOther > 4) { event.getPlayer().getInventory().addItem(new ItemStack(Material.DIAMOND, 3)); economy.depositPlayer(event.getPlayer().getName(), 3000); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§6Enjoy your reward!"); event.getPlayer().sendMessage("§63x Diamond, $3000"); event.getPlayer().sendMessage("§b========================="); gemTake(event.getPlayer(), 4); }else{ event.getPlayer().sendMessage("§6You don't have enough Gems! You have: " + gemsOther); } }else if(event.getPosition() == 1){ gemQueryOther(event.getPlayer()); if(gemsOther > 10) { event.getPlayer().getInventory().addItem(new ItemStack(Material.DIAMOND, 3)); economy.depositPlayer(event.getPlayer().getName(), 7500); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§6Enjoy your reward!"); event.getPlayer().sendMessage("§68x Diamond, $7500"); event.getPlayer().sendMessage("§b========================="); gemTake(event.getPlayer(), 10); }else{ event.getPlayer().sendMessage("§6You don't have enough Gems! You have: " + gemsOther); } }else if(event.getPosition() == 2){ gemQueryOther(event.getPlayer()); if(gemsOther > 18) { event.getPlayer().getInventory().addItem(new ItemStack(Material.DIAMOND, 3)); economy.depositPlayer(event.getPlayer().getName(), 15000); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§6Enjoy your reward!"); event.getPlayer().sendMessage("§618x Diamond, $15000"); event.getPlayer().sendMessage("§b========================="); gemTake(event.getPlayer(), 18); }else{ event.getPlayer().sendMessage("§6You don't have enough Gems! You have: " + gemsOther); } } } }, this) .setOption(0, new ItemStack(Material.EMERALD, 1), "§b§lReward Pack [1]", "§9Costs: §64 Gems", "§9Contains: §63x Diamond, $3000") .setOption(1, new ItemStack(Material.EMERALD, 1), "§b§lReward Pack [2]", "§9Costs: §610 Gems", "§9Contains: §68x Diamond, $7500") .setOption(2, new ItemStack(Material.EMERALD, 1), "§b§lReward Pack [3]", "§9Costs: §618 Gems", "§9Contains: §618x Diamond, $15000") .setOption(35, new ItemStack(Material.REDSTONE, 1), "§lBack", "§7§oBack to User Panel Home"); //Other menu_Other = new IconMenu("WCMN User Panel (Mod Servers)", 9, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); event.getPlayer().performCommand("menu"); if(event.getName() == "§lBack") { } } }, this) .setOption(3, new ItemStack(Material.JUKEBOX, 1), "§9§lPixelmon Server", "§epkmn.wcmn.eu", "§eFor install instructions, visit:", "www.wcmn.eu/pkmn") .setOption(5, new ItemStack(Material.PISTON_BASE, 1), "§c§lFTB Server", "§eftb.wcmn.eu", "§eTo play, use the Direwolf20 pack", "§efrom the FTB Launcher available at", "www.feed-the-beast.com") .setOption(8, new ItemStack(Material.REDSTONE, 1), "§lBack", "§7§oBack to User Panel Home."); //Main menu_Main = new IconMenu("WCMN User Panel (Home)", 45, new IconMenu.OptionClickEventHandler() { @Override public void onOptionClick(IconMenu.OptionClickEvent event) { event.setWillClose(false); if(event.getName() == "§6§lServers") { menu_Servers.open(event.getPlayer()); }else if(event.getName() == "§2§lHelp/FAQ") { menu_Help.open(event.getPlayer()); }else if(event.getName() == "§4§lRules") { event.setWillClose(true); event.getPlayer().sendMessage("§b=========!Rules!==========="); if(plugin.getConfig().getString("Rules") != null) { String str0 = plugin.getConfig().getString("Rules"); String str1 = str0.replaceAll(";,", "\n §c-").replaceAll("\\[", " §c- ").replaceAll(";\\]", "").replaceAll("&", "§"); event.getPlayer().sendMessage(str1); }else{ event.getPlayer().sendMessage("§3The config has no rules defined!"); } event.getPlayer().sendMessage("§b========================="); }else if(event.getName() == "§3§lRanks Shop") { if(BuyCraftEnabled == true) { event.getPlayer().chat("/buy"); }else{ event.setWillClose(true); event.getPlayer().sendMessage("§3Sorry, Ranks are disabled on the menu on this server!"); } }else if(event.getName() == "§9§lHats") { if(plugin.getConfig().getBoolean("HatsEnabled") == true) { if(event.getPlayer().hasPermission("wcmn.userpanel.hats")) { menu_Hats.open(event.getPlayer()); }else{ event.setWillClose(true); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§3Hats are a donator feature!"); event.getPlayer().sendMessage("§3Buy a rank via the menu or use §5§l/buy!"); event.getPlayer().sendMessage("§b========================="); }}else{ event.setWillClose(true); event.getPlayer().sendMessage("§3Sorry, Hats are disabled on the menu on this server!"); } }else if(event.getName() == "§5§lPets") { if(EchoPetEnabled == true) { if(event.getPlayer().hasPermission("wcmn.userpanel.pets")) { event.getPlayer().performCommand("pet select"); }else{ event.setWillClose(true); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§3Pets are a donator feature!"); event.getPlayer().sendMessage("§3Buy a rank via the menu or use §5§l/buy!"); event.getPlayer().sendMessage("§b========================="); }}else{ event.setWillClose(true); event.getPlayer().sendMessage("§3Sorry, Pets are disabled on the menu on this server!"); } }else if(event.getName() == "§6§lVote") { event.setWillClose(true); event.getPlayer().sendMessage("§b========================="); event.getPlayer().sendMessage("§3Vote at these sites to earn Gems!"); event.getPlayer().sendMessage("§b========================="); if(plugin.getConfig().getString("Links") != null) { String str0 = plugin.getConfig().getString("Links"); String str1 = str0.replaceAll(",", "§r\n§6").replaceAll("\\[", " §6").replaceAll("\\]", "").replaceAll(": ", ": §r"); event.getPlayer().sendMessage(str1); }else{ event.getPlayer().sendMessage("§3The config has no voting links!"); } event.getPlayer().sendMessage("§b========================="); }else if(event.getName() == "§a§lModded Servers") { menu_Other.open(event.getPlayer()); }else if(event.getName() == "§2§lClaim Rewards!") { menu_Rewards.open(event.getPlayer()); }else if(event.getName() == "§7§lClose Menu") { event.setWillClose(true); } } }, this) .setOption(10, new ItemStack(Material.COMPASS, 1), "§6§lServers", "§eQuick access to the servers!") .setOption(11, new ItemStack(Material.DIAMOND, 1), "§2§lHelp/FAQ", "§aSome useful info about WCMN!") .setOption(12, new ItemStack(Material.BOOK, 1), "§4§lRules", "§cRead these before playing!") .setOption(13, new ItemStack(Material.GOLD_INGOT, 1), "§3§lRanks Shop", "§bView buyable ranks for the server!") .setOption(14, new ItemStack(Material.TNT, 1), "§9§lHats", "§3Equip yourself with a hat!","§7Donator Feature") .setOption(15, new ItemStack(Material.LEASH, 1), "§5§lPets", "§cGrab yourself a furry (or not) friend!","§7Donator Feature") .setOption(16, new ItemStack(Material.EMPTY_MAP, 1), "§6§lVote", "§aVote and earn some ingame perks!") .setOption(19, new ItemStack(Material.LAVA_BUCKET, 1), "§a§lModded Servers", "§dInfo about the other servers related to", "§dthe network!") .setOption(20, new ItemStack(Material.EMERALD_BLOCK, 1), "§2§lClaim Rewards!", "§3Claim yourself some rewards from Gems!") .setOption(44, new ItemStack(Material.BEDROCK, 1), "§7§lClose Menu", "§fClose the menu and return to game!"); } @SuppressWarnings("deprecation") @EventHandler(ignoreCancelled=false) public void onInventoryClick(InventoryClickEvent event) { if(plugin.getConfig().getBoolean("InvMoveEnabled") == false) { Player player = (Player) event.getWhoClicked(); if(!player.isOp()) { if((!event.getInventory().getTitle().contains("WCMN")) || (!event.getInventory().getTitle().contains("Buy")) || (!event.getInventory().getTitle().contains("Pets")) ){ event.setCancelled(true); player.updateInventory(); } } } return; } @EventHandler(priority=EventPriority.HIGH) public void onPlayerUse(PlayerInteractEvent event){ Player p = event.getPlayer(); if(event.getAction().equals(Action.RIGHT_CLICK_AIR)){ if(p.getItemInHand().getType() == Material.BOOK){ p.performCommand("menu"); } } } //ValueCheck public static boolean isNumeric(String str) { NumberFormat formatter = NumberFormat.getInstance(); ParsePosition pos = new ParsePosition(0); formatter.parse(str, pos); return str.length() == pos.getIndex(); } //COMMANDS =================== @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (label.equalsIgnoreCase("menu")) { final Player player = ((Player) sender).getPlayer(); if (args.length == 0){ menu_Main.open(player); return true; }else if(args[0].equalsIgnoreCase("reload") && player.hasPermission("wcmn.userpanel.admin")) { this.reloadConfig(); player.sendMessage("§b========================="); player.sendMessage("§3WCMN Menu config reloaded!"); player.sendMessage("§b========================="); return true; }else if(args[0].equalsIgnoreCase("info") && player.hasPermission("wcmn.userpanel.menu")) { player.sendMessage("§b========!Menu Info!========"); player.sendMessage("§3Developed by: jedk1"); player.sendMessage("§3Website: http://wcmn.eu"); player.sendMessage("§3Exclusively for WCMN"); player.sendMessage("§b========================="); return true; }else if(args[0].equalsIgnoreCase("help") && player.hasPermission("wcmn.userpanel.menu")) { player.sendMessage("§b========!Menu Help!========"); player.sendMessage("§3Main Usage: /menu"); player.sendMessage("§3Reload: /menu reload"); player.sendMessage("§3Info: /menu info"); player.sendMessage("§3Check your gem balance: /gems"); player.sendMessage("§b========================="); //player.getInventory().addItem(applyToStack(new ItemStack(Material.BOOK), "§6§lWCMN Menu", "Right-Click to access the menu!")); return true; }else{ player.sendMessage("§e/menu " + args[0] + " §3isn't a valid command!"); player.sendMessage("§3Use '/menu help' for more info!"); return true; } } if (label.equalsIgnoreCase("gems")) { final Player player = ((Player) sender).getPlayer(); if (args.length == 0){ player.sendMessage("§bChecking gem database for: §e§o" + player.getName()); gemQuery(player); return true; }else if(args[0].equalsIgnoreCase("give") && player.hasPermission("wcmn.userpanel.admin")) { boolean playerFound = false; if(args.length > 1){ for (Player p : Bukkit.getServer().getOnlinePlayers()) { if(p.getName().equalsIgnoreCase(args[1])) { if(isNumeric(args[2])){ player.sendMessage("§bGiving " + p.getName() + " " + args[2] + " gems!"); player.sendMessage("§bUpdating gem database..."); int i = Integer.parseInt(args[2]); gemGive(p, i); gemQueryOther(p); player.sendMessage("§b" + p.getName() + " now has §6§l" + gemsOther + " §bgems!"); p.sendMessage("§bYou've received " + args[2] + " gems from " + player.getName() + "!"); }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems give <online player> <amount>"); } playerFound = true; break; } } if(playerFound == false) { player.sendMessage("§4Invalid Arguments! Usage: /gems give <online player> <amount>"); } }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems give <online player> <amount>"); } return true; }else if(args[0].equalsIgnoreCase("set") && player.hasPermission("wcmn.userpanel.admin")) { boolean playerFound = false; if(args.length > 1){ for (Player p : Bukkit.getServer().getOnlinePlayers()) { if(p.getName().equalsIgnoreCase(args[1])) { if(isNumeric(args[2])){ player.sendMessage("§bSetting " + p.getName() + " gems to " + args[2] + "!"); player.sendMessage("§bUpdating gem database..."); int i = Integer.parseInt(args[2]); gemSet(p, i); gemQueryOther(p); player.sendMessage("§b" + p.getName() + " now has §6§l" + gemsOther + " §bgems!"); }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems set <online player> <amount>"); } playerFound = true; break; } } if(playerFound == false) { player.sendMessage("§4Invalid Arguments! Usage: /gems set <online player> <amount>"); } }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems set <online player> <amount>"); } return true; }else if(args[0].equalsIgnoreCase("remove") && player.hasPermission("wcmn.userpanel.admin")) { boolean playerFound = false; if(args.length > 1){ for (Player p : Bukkit.getServer().getOnlinePlayers()) { if(p.getName().equalsIgnoreCase(args[1])) { if(isNumeric(args[2])){ player.sendMessage("§bRemoving " + args[2] + " gems from " + p.getName()); player.sendMessage("§bUpdating gem database..."); int i = Integer.parseInt(args[2]); gemTake(p, i); gemQueryOther(p); player.sendMessage("§b" + p.getName() + " now has §6§l" + gemsOther + " §bgems!"); }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems remove <online player> <amount>"); } playerFound = true; break; } } if(playerFound == false) { player.sendMessage("§4Invalid Arguments! Usage: /gems remove <online player> <amount>"); } }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems remove <online player> <amount>"); } return true; }else if(args[0].equalsIgnoreCase("bal") && player.hasPermission("wcmn.userpanel.admin")) { boolean playerFound = false; if(args.length > 1){ for (Player p : Bukkit.getServer().getOnlinePlayers()) { if(p.getName().equalsIgnoreCase(args[1])) { player.sendMessage("§bChecking gem database for: §e§o" + p.getName()); gemQueryOther(p); player.sendMessage("§b========================="); player.sendMessage("§3" + p.getName() + " has §6§l" + gemsOther + " §3gems!"); player.sendMessage("§b========================="); playerFound = true; break; } } if(playerFound == false) { player.sendMessage("§4Invalid Arguments! Usage: /gems bal <online player>"); } }else{ player.sendMessage("§4Invalid Arguments! Usage: /gems bal <online player>"); } return true; }else if(args[0].equalsIgnoreCase("help") && player.hasPermission("wcmn.userpanel.menu")) { player.sendMessage("§b========!Gems Help!========="); player.sendMessage("§3Main Usage: /gems"); player.sendMessage("§3Give Gems: /gems give <online player> <amount>"); player.sendMessage("§3Remove Gems: /gems remove <online player> <amount>"); player.sendMessage("§3Check Others Balance: /gems bal <online player>"); player.sendMessage("§b========================="); return true; }else{ player.sendMessage("§e/gems " + args[0] + " §3isn't a valid command!"); player.sendMessage("§3Use '/gems help' for more info!"); return true; } } return false; } //========================= @Override public void onDisable() { menu_Main.destroy(); menu_Servers.destroy(); menu_Help.destroy(); menu_Hats.destroy(); try { if(connection != null && connection.isClosed()) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
ef22c5227037b190beab607ec6688ad782f54da2
[ "Java" ]
1
Java
jedk1/WCMN
6d891b604b479832fcd44e31a97e85fbd93f3a6d
877733e35af53c7bb9ccef1d59d53d8cd0780442
refs/heads/master
<file_sep>package ui; public class MainUI { }
9ab6a989ffd96c3dae86d60d40b6f953430af8a0
[ "Java" ]
1
Java
LauridsA/Zuul_Project_2.0
1ea5d02ae1be5b30ea7528c7f7050b4eb2591fed
1dc1391ece79bcdb41b822271db061f99389416b
refs/heads/master
<repo_name>jearyvon/lantern<file_sep>/packages/iconfont/index.js import iconfont from './src/iconfont.vue'; export default iconfont<file_sep>/src/index.js /* * @Author: bianhao * @Date: 2017-12-21 15:32:04 * @Last Modified by: bianhao * @Last Modified time: 2018-02-07 17:18:06 */ import Message from '../packages/message/index.js'; import WaterFall from '../packages/water-fall/index.js'; import Scroll from '../packages/scroll/index.js'; import { Aside, Footer, Header, Layout, Main } from '../packages/layout/index.js'; import Select from '../packages/select/index.js'; import { Menu, MenuItem, MenuItemGroup, MenuItemSelect } from '../packages/menu/index.js'; import Pagination from '../packages/pagination/index.js' import IconFont from '../packages/iconfont/index.js' //import test from '../packages/layout/index.js'; const prefix = 'Lt'; const packages = { Message, WaterFall, Scroll, Aside, Footer, Header, Layout, Main, Menu, MenuItem, MenuItemGroup, MenuItemSelect, Select, Pagination, IconFont } const install = function(Vue) { Object.keys(packages).forEach(key => { Vue.component(prefix + key, packages[key]); }); Vue.prototype.$message = Message; } if (typeof window !== 'undefined' && window.Vue) { install(window.Vue); }; const API = { ...packages, install } module.exports.default = module.exports = API;<file_sep>/examples/document/pagination.md ## 分页 ### 实例 ::: demo demo ```html <template> <lt-Pagination bgcolor="#FFF" :count="count" :current="current" :type="'route'" :routePath="pageNo => 'pagination?pageNo=' + pageNo" @jumpUrl="jumpUrl" ></lt-Pagination> </template> <script> export default { data () { return { count: 10, current: 1 } }, methods: { jumpUrl (pageNo) { this.$router.push('pagination?pageNo=' + pageNo) } }, watch: { $route (val) { this.current = val.query.pageNo } }, mounted () { this.current = this.$route.query.pageNo || 1 } } </script> ``` ::: ### Usage |参数|说明|类型|默认值|可选| |---|---|---|---|---| |bgcolor|背景颜色|ColorHex|'#fff'|可选| |count|总页码|Number|1|必选| |current|当前页码|Number|1|必选| |type|模式(event&#124;route)|String|'event'|可选| |routePath|路由的计算func|Function|null|模式为route时必选| |jumpUrl|event模式下返回点击的页码|Emit|pageNo=>{}|必选| ### 路由模式下routePath的一个栗子 ```javascript import Vue from 'vue' Vue.component('', { methods: { routePath (pageNo) { return 'lantern.com?pageNo=' + pageNo } }, computed: { routePath () { return pageNo => 'lantern.com?pageNo=' + pageNo } } }) ``` ::::vuecode:::: <script> export default { data () { return { count: 10, current: 1 } }, methods: { jumpUrl (pageNo) { this.$router.push('pagination?pageNo=' + pageNo) } }, watch: { $route (val) { this.current = val.query.pageNo } }, mounted () { this.current = this.$route.query.pageNo || 1 } } </script><file_sep>/examples/document/iconfont.md ## iconfont ### 使用方式 ```html <lt-icon-font class="icon-left"></lt-icon-font> ``` ### 类名列表 <div class="iconlist-md-wrap"> <div v-for="item in iconlist" class="iconfont-md-content"> <lt-icon-font :class="item" class="iconfont-md-show"></lt-icon-font> <div class="iconfont-md-title">{{item[0]}}</div> <div class="iconfont-md-code">{{item[1]}}</div> </div> </div> ::::vuecode:::: <script> export default { data() { return { iconlist: [ ['icon-signout', '\\e604'], ['icon-confirm', '\\e605'], ['icon-details', '\\e606'], ['icon-cancel', '\\e607'], ['icon-dropdown', '\\e608'], ['icon-close', '\\e609'], ['icon-tickcross', '\\e60a'], ['icon-right', '\\e60b'], ['icon-left', '\\e60c'], ['icon-mylike', '\\e60d'], ['icon-mybuy', '\\e60e'], ['icon-recycle', '\\e60f'], ['icon-mydesign', '\\e610'], ['icon-mytemplate', '\\e611'] ] } } } </script> <style> .iconfont-md-content { width: 100px; height: 120px; float: left; text-align: center; margin: 10px; } .iconfont-md-show { font-size: 30px !important; width: 100%; display: block; } .iconfont-md-code { margin-top: 10px; } </style>
82424a57c745e63543b3cf0ce36923e6c7856a4d
[ "JavaScript", "Markdown" ]
4
JavaScript
jearyvon/lantern
8c1d6aa20324e474a314eeb1bd57a26757cf5e2e
54a3c379cc3018472d461891e3eb764aef94b6c2
refs/heads/master
<repo_name>himanshunegi378/Period-Tracker<file_sep>/src/views/stats/services/sortDate.ts // function to sort the array of dates without mutating it export function sortDates(dates: Date[]) { // copy array let sortedDates = dates.slice(); // sort the array sortedDates.sort(function (a, b) { return a.getTime() - b.getTime(); }); return sortedDates; } <file_sep>/src/services/storage.ts import localforage from "localforage"; localforage.setDriver([localforage.INDEXEDDB, localforage.LOCALSTORAGE]); const load = async <T>(key: string): Promise<T | null> => { return localforage.getItem(key); }; const save = (key: string, data: { [key: string]: any }) => { return localforage.setItem(key, data); }; const remove = (key: string) => { return localforage.removeItem(key); }; export const storage = { load, save, remove }; <file_sep>/src/services/same-day.ts //check if two dates are the same day export function isSameDay(date1: Date, date2: Date) { return ( date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear() ); } <file_sep>/src/services/periodManger.ts import { isSameDay } from "./same-day"; import EventEmitter from "events"; import { storage } from "./storage"; export type Period = { date: Date; remark: string; }; // A class that manages the period objects export class PeriodManager extends EventEmitter { private periods: Period[]; private id: string; constructor(managerId: string) { super(); this.periods = []; this.id = managerId; this.loadPeriodsFromStorage(this.id).then((periods) => { if (periods) { this.periods = periods; this.emitChange(); } }); } private emitChange() { this.savePeriodsToStorage(this.periods); this.emit("change", this.periods); } // load periods array from the storage and add it to periods array private loadPeriodsFromStorage(id: string) { return storage.load<Period[]>(id); } // save periods array to storage public savePeriodsToStorage(periods: Period[]): void { storage.save(this.id, periods); } // Adds a period to the manager public addPeriod(date: Date, remark: string): void { // get period for the date if present let existingPeriod = this.getPeriod(date); // if period is not present // - create a new period and add to the list otherwise update the existing period if (!existingPeriod) { let newPeriod = { date: date, remark: remark }; this.periods.push(newPeriod); this.emitChange(); } else { existingPeriod.remark = remark; this.emitChange(); } } // update the period remark public updatePeriod(date: Date, remark: string): void { let period = this.getPeriod(date); if (period) { period.remark = remark; this.emitChange(); } } // remove period from the manager if exists public removePeriod(date: Date): void { let period = this.getPeriod(date); if (period) { this.periods.splice(this.periods.indexOf(period), 1); this.emitChange(); } } // Returns the period by the date else return null public getPeriod(date: Date): Period | null { let period: Period | null = null; this.periods.forEach((p) => { if (isSameDay(p.date, date)) { period = p; } }); return period; } // Returns the periods array public getPeriods(): Period[] { return this.periods; } // create an instance of the PeriodManager public static create(id: string): PeriodManager { return new PeriodManager(id); } }
cdaad4948e0a4db74113fd9b754e03b7f3e8f912
[ "TypeScript" ]
4
TypeScript
himanshunegi378/Period-Tracker
b116e10838a8424a53f2e6fef7dae7b16184a371
97d084da419c684a4584b7277c2d8041dff608f2
refs/heads/master
<file_sep>var app = angular.module('app', ['autocomplete','ngStorage']); app.controller('MyCtrl', function($scope,$http,$localStorage){ var db=[]; var data=[]; $scope.weather_data=getCityWiseData(); /* below scope is used to show autocomple city list */ $scope.doSomething = function(typedthings){ $http({ method: 'jsonp', url: 'http://gd.geobytes.com/AutoCompleteCity', params: { callback: 'JSON_CALLBACK', q: typedthings } }).then(function (response) { if(response.data=="%s") { $scope.citys="" } else { $scope.citys= response.data; } }); } /* Below function is triggered when user click on city search list item */ $scope.doSomethingElse = function(suggestion){ $scope.result="" $http({ method: 'jsonp', url: 'http://gd.geobytes.com/GetCityDetails', params: { callback: 'JSON_CALLBACK', fqcn: suggestion } }).then(function (response) { getPrevCitydb=$localStorage.cityDB if(typeof getPrevCitydb != "undefined") { if(getPrevCitydb.length>=10) { alert("oops!!! you can view maximum 5 city at a time") return } for(i=0;i<getPrevCitydb.length;i+=2) { if(getPrevCitydb[i]==suggestion.substring(0,suggestion.indexOf(","))) { alert("You are already add this city") return } } getPrevCitydb.push(suggestion.substring(0,suggestion.indexOf(","))) getPrevCitydb.push(response.data.geobytesinternet) $localStorage.cityDB=getPrevCitydb; } else { array=[] array.push(suggestion.substring(0,suggestion.indexOf(","))) array.push(response.data.geobytesinternet) $localStorage.cityDB=array; } $scope.weather_data=getCityWiseData(); }); } /* below function is used to get weather information from openweathermap api */ function getDatafromOpnWeather(cityname,countryCode) { $http({ method: 'jsonp', url: 'http://api.openweathermap.org/data/2.5/weather', params: { callback: 'JSON_CALLBACK', q:cityname+','+countryCode, appid:'664dd0f0d8d317ea0b820767585d3b28', units:'Metric' } }).then(function (response) { db.push(response.data.name); db.push(cityname); data.push(response.data) //return response.data }); } function getCityWiseData() { getPrevCitydb=$localStorage.cityDB if(typeof getPrevCitydb != "undefined") { data=[]; db=[]; for(i=0,j=1;i<getPrevCitydb.length;i+=2,j+=2) { cityname=getPrevCitydb[i]; //db.push(cityname); countryCode=getPrevCitydb[j]; getDatafromOpnWeather(cityname,countryCode) } //console.log("initial db:"+db) return data; } } /*Below function is called when user want to delete a city*/ $scope.delCity=function(cityName) { getPrevCitydb=$localStorage.cityDB var index = db.indexOf(cityName); if (index > -1) { index2=db[index+1] //console.log("from db array:" +index2) index2 = getPrevCitydb.indexOf(index2); //console.log("DB ARRAY:"+db) //console.log("getprev ARRAY:"+getPrevCitydb) //console.log("db index:"+index) //console.log("getprev index:"+index2) getPrevCitydb.splice(index2, 2); db.splice(index,2) $localStorage.cityDB=getPrevCitydb; $scope.weather_data=getCityWiseData(); $scope.result="" } } /* Below function is used for getting wind direction */ $scope.getWindDirection = function(degree){ if (degree>337.5) return 'North'; if (degree>292.5) return 'North West'; if(degree>247.5) return 'West'; if(degree>202.5) return 'South West'; if(degree>157.5) return 'South'; if(degree>122.5) return 'South East'; if(degree>67.5) return 'East'; if(degree>22.5){return 'North East';} return 'North'; } }); /* Below directive is used for getting time for a specifie country using GOOGLE TimeZone Api */ app.directive("item", function() { return { restrict: 'E', link: function(scope, element, attrs,myCtrl) { scope.myFunc(attrs.lat,attrs.lon) }, controller: ['$scope', '$http', function($scope, $http) { $scope.myFunc=function(lat,lon) { url="https://maps.googleapis.com/maps/api/timezone/json?location="+lat+","+lon+"&timestamp="+Math.floor(Date.now() / 1000)+"&sensor=false" $http.get(url).then( function(response) { offset=response.data.rawOffset/3600 $scope.data=new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" ) }); } }], template: '<div class="day" style="text-align:center;float:none">{{data}}</div>' } }) <file_sep># Time-and-Weather-App Project Summary: The primary purpose of this project is to be able to view the local time and temperature of different cities around the world. Description: In this app, user will be able to add 5 cities or less for which he/she wants to view the local time and current temperature. The user can also remove the cities one by one from the page. Show the informations of the cities side by side. the cities they added will be saved in the browser’s Local Storage using javascript. So, next time they open browser and open the app they can see the information of the cities they added previously. Technology Used(s): HTML, CSS, Angular.js
e0aab503a58d2efe992f1ebae2523000abac5e00
[ "JavaScript", "Markdown" ]
2
JavaScript
ummoybiswas/Time-and-Weather-App
52e67c664b95d8f95e4d2e701d8f5eb007a6b72b
b047150f19431b670d546b9ea2da7f51601fd5d9
refs/heads/master
<file_sep>package com.arcreane.resources; import com.arcreane.base.JungleObject; public class Resource extends JungleObject { } <file_sep>package com.arcreane; import com.arcreane.base.Ecosystem; import com.arcreane.base.Weather; public class Jungle { public static void main(String[] args) { //Creation of ecosystem and weather variables Ecosystem ecosystem = Ecosystem.getInstance(); //Weather needs to know where the rain is gonna fall => we pass the ecosystem as a parameter Weather weather = new Weather(ecosystem); //Define an algo or a condition to stop the loop //For instance : // * There is no living creature left on the ecosystem // * No Prey => the predator will die of hunger // * No Predator => the prey will grow too much // * There is too much water on the ground it is a flood // * The is no water left // *.... while(ecosystem.getWaterSpot().m_iWaterQuantity > 0){ System.out.println("*********************** Start Cycle **********************"); ecosystem.step(); weather.step(); ecosystem.draw(); try { Thread.sleep(250); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } } System.out.println("Equilibrium has been shattered, the world is dying"); } } <file_sep>package com.arcreane.resources; import com.arcreane.base.Coords; public class Plant extends Resource{ public void grow(){ } @Override public void step() { System.out.println("Je suis une plante et je step"); } } <file_sep>package com.arcreane.base; import com.arcreane.animal.Animal; import com.arcreane.animal.Predator; import com.arcreane.animal.Prey; import com.arcreane.resources.Plant; import com.arcreane.resources.WaterSpot; public class Ecosystem { //Creation des tableaux de predateur, de proies, de plantes //et également création du plan d'eau //private Predator[] m_PredatorArray; //private Prey[] m_PreyArray; private JungleObject[] m_JungleObjectArray; public WaterSpot getWaterSpot() { return (WaterSpot)m_JungleObjectArray[0]; } private static Ecosystem s_Instance; public static Ecosystem getInstance() { if (s_Instance == null) s_Instance = new Ecosystem(); return s_Instance; } private Ecosystem() { m_JungleObjectArray = new JungleObject[301]; m_JungleObjectArray[0] = new WaterSpot(); for (int i = 1; i < m_JungleObjectArray.length - 2; i += 3) { m_JungleObjectArray[i] = new Predator(); m_JungleObjectArray[i + 1] = new Prey(); m_JungleObjectArray[i + 2] = new Plant(); } } public void step() { for (JungleObject obj : m_JungleObjectArray) { obj.step(); } } public void draw() { for (JungleObject obj : m_JungleObjectArray) { obj.draw(); } } public void raining(int rainQuantity) { System.out.println("Plouf"); } public void raining(int startTime, int EndTime) { //pour gérer le fait qu'il puisse pleuvoir pendant plusieur cycle System.out.println("Il pleut depuis des jours"); } } <file_sep>package com.arcreane.animal.senses; public class Vision { } <file_sep>package com.arcreane.animal; import com.arcreane.base.Coords; import com.arcreane.base.Ecosystem; import com.arcreane.resources.WaterSpot; public class Prey extends Animal{ private int m_iWaterToDrink; public Prey() { super(new Coords()); System.out.println("Je suis une proie"); m_iWaterToDrink = 1; } public Coords getCoords() { return m_Coords; } public void setCoords(Coords p_Coords) { m_Coords = p_Coords; } @Override public void step() { super.step(); System.out.println("Je suis une proie et je fais mon step"); } } <file_sep>package com.arcreane.resources; public class WaterSpot extends Resource { public int m_iWaterQuantity; public WaterSpot() { m_iWaterQuantity = 500; } @Override public void step() { System.out.println("Water quantity : " + m_iWaterQuantity); } }
014a89a00dbc39b408fe042c01b44d64d608498f
[ "Java" ]
7
Java
dy-dev/JungleCC_TH3
b7b86854acf472dc6e36f0165f24381fc9e5813e
aee2495f2c239f97f742b35a5c00d54b82fbbe67
refs/heads/master
<file_sep>import React, { Fragment } from "react"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import Studies from "./Containers/Studies/Studies"; import Study from "./Containers/Study/Study"; const AppRouter = () => ( <Router> <Fragment> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/study/m16-043/expected-data-and-idrp-checks"> Study / M16-043 / Expected Data & IDRP Checks </Link> </li> </ul> </nav> <Route path="/" exact component={Studies} /> <Route path="/study/" component={Study} /> </Fragment> </Router> ); export default AppRouter; <file_sep>import React, { Component } from "react"; import { Container, Divider, Grid, Header, Image } from "semantic-ui-react"; import JarvisLogo from "/logos/"; import "react-ui-css"; class Layout extends Component { state = {}; render() { return <div />; } } export default Layout; <file_sep>import React, { Component, Fragment } from "react"; import { Accordion, Icon } from "semantic-ui-react"; export default class IdrpCheck extends Component { state = { activeIndex: 1 }; handleClick = (e, titleProps) => { const { index } = titleProps; const { activeIndex } = this.state; const newIndex = activeIndex === index ? -1 : index; this.setState({ activeIndex: newIndex }); }; render() { return ( <Fragment> <Accordion fluid styled style={{ borderRadius: 0 }}> <Accordion.Title active={this.state.activeIndex === 0} index={0} //onClick={this.handleClick} style={{ backgroundColor: "#cad8f7", border: "#dddddd", color: "#000" }} > <Icon name="dropdown" /> Study </Accordion.Title> <Accordion.Content active={this.state.activeIndex === 0} /> </Accordion> </Fragment> ); } } <file_sep>import React, { Component } from "react"; import "./Study.css"; import { Accordion, Button, Confirm, Container, Divider, Form, Grid, Header, Icon, Menu, Modal, Select, Table } from "semantic-ui-react"; //import MultiSelectBox from "react-multiselect-box"; import AppliedVisits from "../../Components/ExpectedDataAndIdrpChecks/AppliedVisits/AppliedVisits"; import CriticalData from "../../Components/ExpectedDataAndIdrpChecks/CriticalData/CriticalData"; import DataTrajectory from "../../Components/ExpectedDataAndIdrpChecks/DataTrajectory/DataTrajectory"; import IdrpCheck from "../../Components/ExpectedDataAndIdrpChecks/IdrpCheck/IdrpCheck"; export default class Study extends Component { state = { activeItem: "DATA TRAJECTORY", assignSubjectsModalOpen: false }; handleAssignSubjectsOpen = () => { this.setState({ assignSubjectsModalOpen: true }); }; handleAssignSubjectsClose = () => { this.setState({ assignSubjectsModalOpen: false }); }; handleTabMenuClick = (e, { name }) => this.setState({ activeItem: name }); render() { const { activeItem } = this.state; const options = [ { key: "a", text: "A Value", value: "A Value" }, { key: "b", text: "B Value", value: "B Value" } ]; const AssignSubjects = () => ( <Modal size="small" trigger={ <button className="headerLinks" style={{ background: "none", color: "#2185d0", border: "none", padding: "0!important", font: "inherit", cursor: "pointer", fontWeight: "bold" }} > Assign Subjects </button> } > <Modal.Header>Assign Subjects</Modal.Header> <Modal.Content> <Modal.Description> {/* <Header>Assign Subjects</Header> */} </Modal.Description> <Form> <Form.TextArea label="Rule Logic Text" /> <Divider /> <Container textAlign="center" fluid> Subjects will be assigned to ARM IF: </Container> <Grid style={{ padding: "1em 0 0 0" }}> <Grid.Row> <Grid.Column width={3} verticalAlign="middle" textAlign="center" > Visit/Frequency </Grid.Column> <Grid.Column width={13}> <Form.Field control={Select} options={options} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={3} verticalAlign="middle" textAlign="center" > Form </Grid.Column> <Grid.Column width={13}> <Form.Field control={Select} options={options} /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={3} verticalAlign="middle" textAlign="center" > Field </Grid.Column> <Grid.Column width={13}> <Form.Field control={Select} options={options} /> </Grid.Column> </Grid.Row> </Grid> <Table celled style={{ margin: "2em 0 0 0" }}> <Table.Header> <Table.Row> <Table.HeaderCell textAlign="center"> DATA TRAJECTORY Name </Table.HeaderCell> <Table.HeaderCell textAlign="center">Value</Table.HeaderCell> <Table.HeaderCell textAlign="center"> Manually Assign </Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell textAlign="center">DATA TRAJECTORY 1</Table.Cell> <Table.Cell> <Form.Field control={Select} options={options} /> </Table.Cell> <Table.Cell textAlign="center"> <Icon color="blue" name="cog" size="large" /> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell textAlign="center">DATA TRAJECTORY 2</Table.Cell> <Table.Cell> <Form.Field control={Select} options={options} /> </Table.Cell> <Table.Cell textAlign="center"> <Icon color="blue" name="cog" size="large" /> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell textAlign="center">DATA TRAJECTORY 3</Table.Cell> <Table.Cell> <Form.Field control={Select} options={options} /> </Table.Cell> <Table.Cell textAlign="center"> <Icon color="blue" name="cog" size="large" /> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell textAlign="center">DATA TRAJECTORY 4</Table.Cell> <Table.Cell> <Form.Field control={Select} options={options} /> </Table.Cell> <Table.Cell textAlign="center"> <Icon color="blue" name="cog" size="large" /> </Table.Cell> </Table.Row> <Table.Row> <Table.Cell textAlign="center">DATA TRAJECTORY 5</Table.Cell> <Table.Cell> <Form.Field control={Select} options={options} /> </Table.Cell> <Table.Cell textAlign="center"> <Icon color="blue" name="cog" size="large" /> </Table.Cell> </Table.Row> </Table.Body> </Table> <Container textAlign="center" fluid style={{ margin: "3em 0 0 0" }}> <Modal.Actions> <Button primary onClick={this.handleClose}> Done </Button> <Button onClick={this.handleClose}>Cancel</Button> </Modal.Actions> </Container> {/* <Grid> <Grid.Row> <Grid.Column width={6} floated="left"> <Form.Input placeholder="Search" /> </Grid.Column> <Grid.Column width={2} /> <Grid.Column width={6} floated="right" verticalAlign="middle"> <p>Assigned Subjects</p> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={6} floated="left"> left side </Grid.Column> <Grid.Column width={2}> <Icon style={{ marginBottom: "1em" }} name="arrow alternate circle right" size="big" color="blue" /> <br /> <Icon name="arrow alternate circle left outline" size="big" color="blue" /> </Grid.Column> <Grid.Column width={6} floated="right"> right side </Grid.Column> </Grid.Row> </Grid> */} </Form> </Modal.Content> </Modal> ); let showDataOfTab = <DataTrajectory />; switch (this.state.activeItem) { case "DATA TRAJECTORY": showDataOfTab = <DataTrajectory />; break; case "IDRP CHECK": showDataOfTab = <IdrpCheck activeIndex={this.state.activeIndex} />; break; case "APPLIED VISITS": showDataOfTab = <AppliedVisits />; break; case "CRITICAL DATA": showDataOfTab = <CriticalData />; break; default: showDataOfTab = <DataTrajectory />; } // showDataOfTab = <DataTrajectory />; // } // if (this.state.activeItem === "IDRP CHECK") { // showDataOfTab = <IdrpCheck />; // } return ( <div className="Study" style={{ padding: "2em 2em 2em 2em" }}> <Container fluid> <p> Study: M16-043 <Icon name="angle down" color="blue" /> </p> <Grid> <Grid.Column floated="left" width={6} verticalAlign="bottom"> <Header as="h1">Expected Data & IDRP Checks</Header> </Grid.Column> <Grid.Column floated="right" textAlign="right" verticalAlign="bottom" width={6} > <AssignSubjects /> <a href="/#" style={{ marginLeft: "30px", fontWeight: "bold" }}> Submit for Review </a> <a href="/#" style={{ marginLeft: "30px", fontWeight: "bold" }}> Submit for Approval </a> </Grid.Column> </Grid> <Divider /> <Menu pointing secondary stackable width={8} color="blue" style={{ marginTop: "2em" }} > <Menu.Item name="IDRP CHECK" active={activeItem === "IDRP CHECK"} onClick={this.handleTabMenuClick} /> <Menu.Item name="DATA TRAJECTORY" active={activeItem === "DATA TRAJECTORY"} onClick={this.handleTabMenuClick} /> <Menu.Item name="APPLIED VISITS" active={activeItem === "APPLIED VISITS"} onClick={this.handleTabMenuClick} /> <Menu.Menu> <Menu.Item name="CRITICAL DATA" active={activeItem === "CRITICAL DATA"} onClick={this.handleTabMenuClick} /> </Menu.Menu> </Menu> <Button primary icon="plus" content="Add Expected Data" /> <Button primary icon="plus" content="Add IDRP Checks" /> <Grid> <Grid.Column floated="left" /> <Grid.Column width={2} floated="right" textAlign="right" style={{ paddingTop: "3em", color: "#2185d0" }} > Filters <Icon name="filter" size="large" color="blue" /> </Grid.Column> </Grid> {showDataOfTab} </Container> <Container textAlign="center" fluid> <Divider /> <p>&copy; 2018 AbbVie Inc</p> </Container> {/* use callback for this instead this is just for demo purpose. */} </div> ); } }
f9264c2320478363285c4f87942ccd0d0c3675d7
[ "JavaScript" ]
4
JavaScript
okeymama/cdrp-react-ui
9290d9d3f4be2354f1a6dbbccd076cd5d1099e33
c521890ecc1ba7e53aba5ed32b0dc323e36b8f79
refs/heads/master
<repo_name>kanchankotiya/listing-locator<file_sep>/app/views/listings/_listing.json.jbuilder json.extract! listing, :id, :name, :city, :state, :country, :banner_image, :longitude, :latitude, :about_palce, :created_at, :updated_at json.url listing_url(listing, format: :json) <file_sep>/app/models/touristplace_category.rb class TouristplaceCategory < ApplicationRecord has_many :images, as: :imageable has_many :tourist_places, dependent: :destroy accepts_nested_attributes_for :tourist_places, reject_if: :all_blank, allow_destroy: true end <file_sep>/db/migrate/20180228094828_change_col_name.rb class ChangeColName < ActiveRecord::Migration[5.1] def change rename_column :listings, :about_palce, :about_listing end end <file_sep>/test/system/tourist_places_test.rb require "application_system_test_case" class TouristPlacesTest < ApplicationSystemTestCase # test "visiting the index" do # visit tourist_places_url # # assert_selector "h1", text: "TouristPlace" # end end <file_sep>/app/views/listing_types/show.json.jbuilder json.partial! "listing_types/listing_type", listing_type: @listing_type <file_sep>/app/models/image.rb class Image < ApplicationRecord belongs_to :imageable, polymorphic: true mount_uploader :img_name, AvatarUploader end<file_sep>/app/admin/listings.rb ActiveAdmin.register Listing do # See permitted parameters documentation: # https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters # permit_params :name, :city, :state, :country, :banner_image, :user_id, :about_listing, :address, :phone_number, :email, :website,:zip_code, :listing_type_id, :featured # # or # # permit_params do # permitted = [:permitted, :attributes] # permitted << :other if params[:action] == 'create' && current_user.admin? # permitted # end end <file_sep>/app/controllers/tourist_places_controller.rb class TouristPlacesController < ApplicationController before_action :set_tourist_place, only: [:show, :edit, :update, :destroy] layout 'listing' # GET /tourist_places # GET /tourist_places.json def index @tourist_places = TouristPlace.all end # GET /tourist_places/1 # GET /tourist_places/1.json def show;end # GET /tourist_places/new def new @tourist_place = TouristPlace.new end # GET /tourist_places/1/edit def edit;end def tourist_place_image @tourist_places = TouristPlace.find(params[:upload_images][:tourist_place_id]) @image = @tourist_places.images.build(img_name: params[:upload][:img_name]) if @image.save! respond_to do |format| format.json{ render :json => @image } end end end def remove_tourist_place_image @image = Image.find(params[:id]) if @image .destroy render json: { message: "file delete from server"} else render json: {message: @image.errors.full_messages.join(", ") } end end # POST /tourist_places # POST /tourist_places.json def create @tourist_place = TouristPlace.new(tourist_place_params) respond_to do |format| if @tourist_place.save format.html { redirect_to @tourist_place, notice: 'Tourist place was successfully created.' } format.json { render :show, status: :created, location: @tourist_place } else format.html { render :new } format.json { render json: @tourist_place.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tourist_places/1 # PATCH/PUT /tourist_places/1.json def update respond_to do |format| if @tourist_place.update(tourist_place_params) format.html { redirect_to @tourist_place, notice: 'Tourist place was successfully updated.' } format.json { render :show, status: :ok, location: @tourist_place } else format.html { render :edit } format.json { render json: @tourist_place.errors, status: :unprocessable_entity } end end end # DELETE /tourist_places/1 # DELETE /tourist_places/1.json def destroy @tourist_place.destroy respond_to do |format| format.html { redirect_to tourist_places_url, notice: 'Tourist place was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tourist_place @tourist_place = TouristPlace.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tourist_place_params params.require(:tourist_place).permit(:name, :city, :state, :country, :banner_image,:zip_code, :longitude, :latitude, :about_place, images_attributes:[:id, :img_name, :imageable_type, :imageable_id, :_destroy ]) end end <file_sep>/app/controllers/dashboard/listings_controller.rb module Dashboard class ListingsController < ApplicationController load_and_authorize_resource before_action :set_listing, only: [:show, :edit, :update, :destroy] layout 'dashboard' # GET /listings # GET /listings.json def index @listings = current_user.listings @users = User.all end # GET /listings/1 # GET /listings/1.json def show end # GET /listings/new def new @listing = Listing.new end # GET /listings/1/edit def edit end def upload_listing_image @listings = Listing.find(params[:upload_images][:listing_id]) @image = @listings.images.build(img_name: params[:upload][:img_name]) if @image.save! respond_to do |format| format.json{ render :json => @image } end end end def remove_listing_image @image = Image.find(params[:id]) if @image .destroy render json: { message: "file delete from server"} else render json: {message: @image.errors.full_messages.join(", ") } end end # POST /listings # POST /listings.json def create @listing = Listing.new(listing_params) respond_to do |format| if @listing.save format.html { redirect_to dashboard_listings_path, notice: 'Listing was successfully created.' } format.json { render :show, status: :created, location: @listing } else format.html { render :new } format.json { render json: @listing.errors, status: :unprocessable_entity } end end end # PATCH/PUT /listings/1 # PATCH/PUT /listings/1.json def update respond_to do |format| if @listing.update_attributes(listing_params) format.html { redirect_to dashboard_listings_path, notice: 'Listing was successfully created.' } format.json { render :show, status: :ok, location: @listing } else format.html { render :edit } format.json { render json: @listing.errors, status: :unprocessable_entity } end end end # DELETE /listings/1 # DELETE /listings/1.json def destroy @listing.destroy respond_to do |format| format.html { redirect_to listings_url, notice: 'Listing was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_listing @listing = Listing.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def listing_params params.require(:listing).permit(:name, :city, :state, :country, :banner_image, :user_id, :about_listing, :address, :phone_number, :email, :website,:zip_code, :listing_type_id, images_attributes: [:id,:img_name, :imageable_id, :imageable_type, :_destroy], opening_hours_attributes: [:id, :day, :from , :to, :_destroy]) end end end<file_sep>/config/routes.rb Rails.application.routes.draw do resources :accommodations do collection do post :upload_accommodation_image end end devise_for :users devise_for :admin_users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) get '/dashboard/user' => "dashboard#user" get '/dashboard/admin' => "dashboard#admin" resources :amenities resources :listing_types do resources :listings, only: [:show, :index] end mount Ckeditor::Engine => '/ckeditor' resources :touristplace_categories resources :tourist_places do collection do post :tourist_place_image end end delete '/remove_tourist_place_image/:id' => "tourist_places#remove_tourist_place_image" delete '/remove_listing_image/:id' => "listings#remove_listing_image" delete '/remove_accommodation_image/:id' => "accommodations#remove_accommodation_image" get 'home/index' root "home#index" namespace :admins do resources :touristplace_categories resources :tourist_places end namespace :dashboard do resources :listings do collection do post :upload_listing_image end end end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>/app/models/amenity.rb class Amenity < ApplicationRecord validates :amenity_icon, :amenity_name, presence: true has_many :listing_amenities has_many :listings, through: :listing_amenities end <file_sep>/app/models/accommodation.rb class Accommodation < ApplicationRecord has_many :images, as: :imageable mount_uploader :img_name, AvatarUploader geocoded_by :address after_validation :geocode end <file_sep>/app/models/listing.rb class Listing < ApplicationRecord #validations..... validates :name, :city, :state, :country, :banner_image, :about_listing, :address, :email, :phone_number, :website, :zip_code, presence: true has_many :images, as: :imageable belongs_to :user # mount_uploader :img_name, AvatarUploader mount_uploader :banner_image, AvatarUploader belongs_to :listing_type, optional: true has_many :listing_amenities # has_many :opening_hours, dependent: :destroy has_many :opening_hours, inverse_of: :listing accepts_nested_attributes_for :opening_hours, reject_if: :all_blank, allow_destroy: true # accepts_nested_attributes_for :opening_hours, :opening_hours, allow_destroy: true has_many :amenities, through: :listing_amenities,:class_name => 'Amenity' accepts_nested_attributes_for :amenities accepts_nested_attributes_for :listing_amenities geocoded_by :address after_validation :geocode DAYS = ['Select Day','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] FROM = ['Opening Time','1AM', '2AM', '3AM', '4AM', '5AM', '6AM', '7AM', '8AM', '9AM', '10AM', '12AM', 'Closed'] TO = ['Closing Time','1PM', '2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM', '10PM', '12PM', 'Closed'] def address "#{self.city} #{self.state} #{self.zip_code}" end end <file_sep>/app/controllers/listings_controller.rb class ListingsController < ApplicationController load_and_authorize_resource before_action :set_listing, only: [:show] before_action :set_listing_type, only: [:show, :index] layout 'listing' def index @listings = @listing_type.listings end def show @image = Image.all @opening= OpeningHour.all end private # Use callbacks to share common setup or constraints between actions. def set_listing @listing = Listing.find(params[:id]) end def set_listing_type @listing_type = ListingType.find(params[:listing_type_id]) end end <file_sep>/app/controllers/amenities_controller.rb class AmenitiesController < InheritedResources::Base private def amenity_params params.require(:amenity).permit(:amenity_icon, :amenity_name) end end <file_sep>/db/migrate/20180226054230_add_amenity_ref_to_listing_amenities.rb class AddAmenityRefToListingAmenities < ActiveRecord::Migration[5.1] def change add_reference :listing_amenities, :amenity, foreign_key: true end end <file_sep>/test/controllers/listing_types_controller_test.rb require 'test_helper' class ListingTypesControllerTest < ActionDispatch::IntegrationTest setup do @listing_type = listing_types(:one) end test "should get index" do get listing_types_url assert_response :success end test "should get new" do get new_listing_type_url assert_response :success end test "should create listing_type" do assert_difference('ListingType.count') do post listing_types_url, params: { listing_type: { name: @listing_type.name } } end assert_redirected_to listing_type_url(ListingType.last) end test "should show listing_type" do get listing_type_url(@listing_type) assert_response :success end test "should get edit" do get edit_listing_type_url(@listing_type) assert_response :success end test "should update listing_type" do patch listing_type_url(@listing_type), params: { listing_type: { name: @listing_type.name } } assert_redirected_to listing_type_url(@listing_type) end test "should destroy listing_type" do assert_difference('ListingType.count', -1) do delete listing_type_url(@listing_type) end assert_redirected_to listing_types_url end end <file_sep>/db/migrate/20180220103540_add_listing_type_ref_to_listing.rb class AddListingTypeRefToListing < ActiveRecord::Migration[5.1] def change add_reference :listings, :listing_type, foreign_key: true end end <file_sep>/app/views/listing_types/_listing_type.json.jbuilder json.extract! listing_type, :id, :name, :created_at, :updated_at json.url listing_type_url(listing_type, format: :json) <file_sep>/app/views/accommodations/_accommodation.json.jbuilder json.extract! accommodation, :id, :name, :city, :state, :country, :address, :latitude, :longitude, :created_at, :updated_at json.url accommodation_url(accommodation, format: :json) <file_sep>/app/helpers/admins/tourist_places_helper.rb module Admins::TouristPlacesHelper end <file_sep>/app/views/tourist_places/show.json.jbuilder json.partial! "tourist_places/tourist_place", tourist_place: @tourist_place <file_sep>/db/migrate/20180216053435_create_tourist_places.rb class CreateTouristPlaces < ActiveRecord::Migration[5.1] def change create_table :tourist_places do |t| t.string :name t.string :city t.string :state t.string :country t.string :banner_image t.float :longitude t.float :latitude t.text :about_place t.timestamps end end end <file_sep>/app/helpers/admins/touristplace_categories_helper.rb module Admins::TouristplaceCategoriesHelper end <file_sep>/app/models/listing_amenity.rb class ListingAmenity < ApplicationRecord #validations..... validates :name, presence: true belongs_to :listing belongs_to :amenity end <file_sep>/app/controllers/home_controller.rb class HomeController < ApplicationController layout 'listing' def index @tourist_places = TouristPlace.all @listing_types = ListingType.all end end <file_sep>/app/controllers/touristplace_categories_controller.rb class TouristplaceCategoriesController < ApplicationController before_action :set_touristplace_category, only: [:show, :edit, :update, :destroy] # GET /touristplace_categories # GET /touristplace_categories.json def index @touristplace_categories = TouristplaceCategory.all end # GET /touristplace_categories/1 # GET /touristplace_categories/1.json def show end # GET /touristplace_categories/new def new @touristplace_category = TouristplaceCategory.new end # GET /touristplace_categories/1/edit def edit end # POST /touristplace_categories # POST /touristplace_categories.json def create @touristplace_category = TouristplaceCategory.new(touristplace_category_params) respond_to do |format| if @touristplace_category.save format.html { redirect_to @touristplace_category, notice: 'Touristplace category was successfully created.' } format.json { render :show, status: :created, location: @touristplace_category } else format.html { render :new } format.json { render json: @touristplace_category.errors, status: :unprocessable_entity } end end end # PATCH/PUT /touristplace_categories/1 # PATCH/PUT /touristplace_categories/1.json def update respond_to do |format| if @touristplace_category.update(touristplace_category_params) format.html { redirect_to @touristplace_category, notice: 'Touristplace category was successfully updated.' } format.json { render :show, status: :ok, location: @touristplace_category } else format.html { render :edit } format.json { render json: @touristplace_category.errors, status: :unprocessable_entity } end end end # DELETE /touristplace_categories/1 # DELETE /touristplace_categories/1.json def destroy @touristplace_category.destroy respond_to do |format| format.html { redirect_to touristplace_categories_url, notice: 'Touristplace category was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_touristplace_category @touristplace_category = TouristplaceCategory.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def touristplace_category_params params.require(:touristplace_category).permit(:name,tourist_place_attributes: [:id, :name, :city, :state, :country, :banner_image, :longitude, :latitude, :about_place]) end end <file_sep>/app/views/admins/tourist_places/index.json.jbuilder json.array! @tourist_places, partial: 'tourist_places/tourist_place', as: :tourist_place <file_sep>/test/controllers/tourist_places_controller_test.rb require 'test_helper' class TouristPlacesControllerTest < ActionDispatch::IntegrationTest setup do @tourist_place = tourist_places(:one) end test "should get index" do get tourist_places_url assert_response :success end test "should get new" do get new_tourist_place_url assert_response :success end test "should create tourist_place" do assert_difference('TouristPlace.count') do post tourist_places_url, params: { tourist_place: { about_place: @tourist_place.about_place, banner_image: @tourist_place.banner_image, city: @tourist_place.city, country: @tourist_place.country, latitude: @tourist_place.latitude, longitude: @tourist_place.longitude, name: @tourist_place.name, state: @tourist_place.state } } end assert_redirected_to tourist_place_url(TouristPlace.last) end test "should show tourist_place" do get tourist_place_url(@tourist_place) assert_response :success end test "should get edit" do get edit_tourist_place_url(@tourist_place) assert_response :success end test "should update tourist_place" do patch tourist_place_url(@tourist_place), params: { tourist_place: { about_place: @tourist_place.about_place, banner_image: @tourist_place.banner_image, city: @tourist_place.city, country: @tourist_place.country, latitude: @tourist_place.latitude, longitude: @tourist_place.longitude, name: @tourist_place.name, state: @tourist_place.state } } assert_redirected_to tourist_place_url(@tourist_place) end test "should destroy tourist_place" do assert_difference('TouristPlace.count', -1) do delete tourist_place_url(@tourist_place) end assert_redirected_to tourist_places_url end end <file_sep>/app/views/admins/tourist_places/_tourist_place.json.jbuilder json.extract! tourist_place, :id, :name, :city, :state, :country, :banner_image, :longitude, :latitude, :about_place, :created_at, :updated_at json.url tourist_place_url(tourist_place, format: :json) <file_sep>/app/views/listing_types/index.json.jbuilder json.array! @listing_types, partial: 'listing_types/listing_type', as: :listing_type <file_sep>/test/system/touristplace_categories_test.rb require "application_system_test_case" class TouristplaceCategoriesTest < ApplicationSystemTestCase # test "visiting the index" do # visit touristplace_categories_url # # assert_selector "h1", text: "TouristplaceCategory" # end end <file_sep>/app/models/listing_type.rb class ListingType < ApplicationRecord validates :name, :icon, presence: true has_many :listings, dependent: :destroy mount_uploader :icon, AvatarUploader end <file_sep>/app/views/amenities/_amenity.json.jbuilder json.extract! amenity, :id, :amenity_icon, :amenity_name, :created_at, :updated_at json.url amenity_url(amenity, format: :json) <file_sep>/app/controllers/dashboard_controller.rb class DashboardController < ApplicationController def user end def admin end end <file_sep>/app/controllers/admins/tourist_places_controller.rb class Admins::TouristPlacesController < ApplicationController before_action :set_tourist_place, only: [:show, :edit, :update, :destroy] # GET /tourist_places # GET /tourist_places.json def index @tourist_places = TouristPlace.all end # GET /tourist_places/1 # GET /tourist_places/1.json def show end # GET /tourist_places/new def new @tourist_place = TouristPlace.new end # GET /tourist_places/1/edit def edit end # POST /tourist_places # POST /tourist_places.json def create @tourist_place = TouristPlace.new(tourist_place_params) respond_to do |format| if @tourist_place.save format.html { redirect_to @tourist_place, notice: 'Tourist place was successfully created.' } format.json { render :show, status: :created, location: @tourist_place } else format.html { render :new } format.json { render json: @tourist_place.errors, status: :unprocessable_entity } end end end # PATCH/PUT /tourist_places/1 # PATCH/PUT /tourist_places/1.json def update respond_to do |format| if @tourist_place.update(tourist_place_params) format.html { redirect_to @tourist_place, notice: 'Tourist place was successfully updated.' } format.json { render :show, status: :ok, location: @tourist_place } else format.html { render :edit } format.json { render json: @tourist_place.errors, status: :unprocessable_entity } end end end # DELETE /tourist_places/1 # DELETE /tourist_places/1.json def destroy @tourist_place.destroy respond_to do |format| format.html { redirect_to tourist_places_url, notice: 'Tourist place was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_tourist_place @tourist_place = TouristPlace.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def tourist_place_params params.require(:tourist_place).permit(:name, :city, :state, :country, :banner_image, :longitude, :latitude, :about_place) end end <file_sep>/app/views/touristplace_categories/_touristplace_category.json.jbuilder json.extract! touristplace_category, :id, :name, :created_at, :updated_at json.url touristplace_category_url(touristplace_category, format: :json) <file_sep>/db/migrate/20180226132714_add_column_to_listing.rb class AddColumnToListing < ActiveRecord::Migration[5.1] def change add_column :listings, :address, :string add_column :listings, :email, :string add_column :listings, :phone_number, :string add_column :listings, :website, :string add_column :listings, :zip_code, :string end end <file_sep>/test/controllers/touristplace_categories_controller_test.rb require 'test_helper' class TouristplaceCategoriesControllerTest < ActionDispatch::IntegrationTest setup do @touristplace_category = touristplace_categories(:one) end test "should get index" do get touristplace_categories_url assert_response :success end test "should get new" do get new_touristplace_category_url assert_response :success end test "should create touristplace_category" do assert_difference('TouristplaceCategory.count') do post touristplace_categories_url, params: { touristplace_category: { name: @touristplace_category.name } } end assert_redirected_to touristplace_category_url(TouristplaceCategory.last) end test "should show touristplace_category" do get touristplace_category_url(@touristplace_category) assert_response :success end test "should get edit" do get edit_touristplace_category_url(@touristplace_category) assert_response :success end test "should update touristplace_category" do patch touristplace_category_url(@touristplace_category), params: { touristplace_category: { name: @touristplace_category.name } } assert_redirected_to touristplace_category_url(@touristplace_category) end test "should destroy touristplace_category" do assert_difference('TouristplaceCategory.count', -1) do delete touristplace_category_url(@touristplace_category) end assert_redirected_to touristplace_categories_url end end <file_sep>/app/models/tourist_place.rb class TouristPlace < ApplicationRecord validates :name, :city, :state, :country, :banner_image, :about_palce, :zip_code, presence: true mount_uploader :banner_image, AvatarUploader has_many :images, as: :imageable mount_uploader :img_name, AvatarUploader belongs_to :touristplace_category, optional: true geocoded_by :address after_validation :geocode def address "#{self.city} #{self.state} #{self.zip_code} " end end <file_sep>/app/controllers/accommodations_controller.rb class AccommodationsController < InheritedResources::Base def upload_accommodation_image @accommodations = Accommodation.find(params[:upload_images][:accommodation_id]) @image = @accommodations.images.build(img_name: params[:upload][:img_name]) if @image.save! respond_to do |format| format.json{ render :json => @image } end end end def remove_accommodation_image @image = Image.find(params[:id]) if @image .destroy render json: { message: "file delete from server"} else render json: {message: @image.errors.full_messages.join(", ") } end end private def accommodation_params params.require(:accommodation).permit(:name, :city, :state, :country, :address, :latitude, :longitude, images_attributes: [:id,:img_name, :imageable_id, :imageable_type, :_destroy]) end end
92dc1de7646801e89f96fe32cf23804acfc0bb78
[ "Ruby" ]
41
Ruby
kanchankotiya/listing-locator
a86d7665855025df704c7db2949752a8839d1d9f
07fddda6cba98ae63fb1822c8036460f5062249e
refs/heads/main
<repo_name>VikramTiwari/rust-wasm-web-nodejs-experiment<file_sep>/webwasm/index.js (function () { console.log("loading..."); fetch("./assets/web.wasm") .then((response) => response.arrayBuffer()) .then((bytes) => WebAssembly.instantiate(bytes, {})) .then((wasmContainer) => { const { add, subtract, multiply } = wasmContainer.instance.exports; console.log("4 + 2 = ", add(4, 2)); console.log("4 - 2 = ", subtract(4, 2)); console.log("4 * 2 = ", multiply(4, 2)); }) .catch((err) => console.log(err)); })(); <file_sep>/nodewasm/index.js const fs = require("fs"); const buf = fs.readFileSync("./lib/web.wasm"); async function start() { const lib = await WebAssembly.instantiate(new Uint8Array(buf)).then( (res) => res.instance.exports ); const { add, subtract, multiply } = lib; console.log("4 + 2 = ", add(4, 2)); console.log("4 - 2 = ", subtract(4, 2)); console.log("4 * 2 = ", multiply(4, 2)); } start(); <file_sep>/README.md # Rust with Node.js ## Installation - Install rust using rustup `https://www.rust-lang.org/tools/install` - Create a new project using `cargo new --lib web` - Install deps for wasm build of rust code ```sh rustup update rustup target add wasm32-unknown-unknown ``` ## Coding - Add your code in `web/src/lib.rs` ## Build WASM Use `cargo` to build rust lib to wasm - Modify `Cargo.toml` file and add the following ```toml [package] ... ... [lib] crate-type = ["cdylib"] [dependencies] ... ... ``` - Run `cargo build --target wasm32-unknown-unknown --release` - You can also compile the rust code to wasm using `rustc`: `rustc --target wasm32-unknown-unknown --crate-type=cdylib src/lib.rs -o web.big.wasm` - `web.wasm` file is in `web/target/wasm32-unknown-unknown/release/web.wasm` ## Using WASM - For web based usage, look into `webwasm` dir - For nodejs based usage, look into `nodewasm` dir Note that both projects use native `WebAssembly` modules for loading `web.wasm`. You might get better performance with `.dylib` files but I don't like to deal with `node-gyp`.
c4008ddb9cfbd60c6e7a7ddcfa8d445071795e60
[ "JavaScript", "Markdown" ]
3
JavaScript
VikramTiwari/rust-wasm-web-nodejs-experiment
0ffd07b918fe3a9077b8eebf985e53c197adf65f
e7aa49ce4d1855393afb33edc6eca7d1438cabe7
refs/heads/master
<repo_name>AllstarVirgo/zhuanli<file_sep>/temp_test.py ##_*_coding:utf-8_*_ with open('CompanyList.txt', 'r') as f: mingdan = f.read() # 将读取的中文名单放入到list_corp中 list_corp = [] for each in mingdan.split('\n'): (code, name) = each.split(',') list_corp.append((code, name)) ste_set=set() for item in list_corp: ste_set.add(item) with open("result.txt",'wb') as f: for each in ste_set: f.write(','.join(each)) f.write('\n') <file_sep>/b_test.py #_*_coding:utf-8_*_ import os import sys reload(sys) sys.setdefaultencoding('utf-8') from PIL import Image try: import pytesseract except Exception: print "Install tesseract and pytesseract first" exit() """require google tesseract-ocr""" try: import requests except Exception: print "Install requests first" import time import json import re from parse_page import * from dumpdata import * from random import randint from zl_login import zl_login import traceback import tzsetting #'''requsts and login''' ss = requests.Session() ss = zl_login(ss) time.sleep(5) #'''file related''' with open('中文公司名单.txt', 'r') as f: f.readline() mingdan = f.read() list_corp = [] for each in mingdan.split('\n'): (name, code) = each.split(',') list_corp.append((name, code)) list_corp.insert(0, ('测试公司名', '0')) if os.path.exists('data'): pass else: os.makedirs('data') with open('./data/测试公司名.csv', 'w') as f: f.write('') headlist = [{ '申请人':'申请(专利权)', '申请人地址':'申请人地址', '邮编':'邮编', '申请地':'申请(专利权)人所在国(省', '申请号':'申请号', '申请日':'申请日', '公开号':'公开(公告)', '公开日':'公开(公告)', 'IPC分类':'IPC分类', '设计分类号':'洛迦分类号', '引证':'引证', '被引':'被引', '同族':'同族', '同族1':'同族公司1', '同族2':'同族公司2', '同族3':'同族公司3', '同族4':'同族公司4'}] #'''BIG LOOP''' for each in list_corp: corp = each corp_name = corp[0] corp_code = str(int(corp[1])) if os.path.isfile('./data/'+corp_name+'.csv'): continue print corp_name tfname = "%s.csv.tmp"%(corp_name) ttname = "%s.csv"%(corp_name) fp = open('./data/'+tfname, 'w') write_data(headlist, fp, "输入公司", "公司代码") lcn = list(corp_name.decode('utf-8')) kw_pack = '' for word in lcn: seg = '[%s][ ]{0,}'%(word) kw_pack = kw_pack+seg #print kw_pack ''' ret = ss.get("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/tableSearch-showTableSearchIndex.shtml") print "get advanced search.", ret.status_code ''' tzsetting.tongzu = 0 url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/eTS_executeTableSearch-executeCommandSearch.shtml" post_data2 = {'searchCondition.searchExp':'申请(专利权)人=("%s")'%corp_name, 'searchCondition.dbId':'VDB', 'searchCondition.searchType':'Sino_foreign', "searchCondition.extendInfo['MODE']":'MODE_TABLE', "searchCondition.extendInfo['STRATEGY']":"STRATEGY_CALCULATE", "searchCondition.originalLanguage":"", "searchCondition.targetLanguage":"", "wee.bizlog.modulelevel":'0200201', "resultPagination.limit":12} while(True): try: print "Post data to search" #ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/preExecuteSearch!preExecuteSearch.do") #print ret.status_code ret = ss.post(url_bsch2, params=post_data2) print ret.status_code except Exception: traceback.print_exc() print ">>>>","Continuing..." time.sleep(randint(3,7)) continue break webcon = ret.content with open('temp.html', 'w') as f: f.write(webcon) #with open('%s.html'%corp_name, 'w') as f: # f.write(webcon) if "没有检索到相关专利" in webcon: time.sleep(randint(5,7)) os.rename('./data/'+tfname, './data/'+ttname) continue pattern = '共&nbsp;(\d+)&nbsp;页' res = re.findall(pattern, webcon) if len(res) != 0: page_num = int(res[0]) if page_num > 20000: time.sleep(randint(5,7)) os.rename('./data/'+tfname, './data/'+ttname) continue else: print "ERROR: Can't find page number" write_data(parse_page(ss, webcon), fp, corp_name, corp_code) total_account = 0 pattern = "&nbsp;(\d+)&nbsp;条数据" res = re.findall(pattern, webcon) if len(res) != 0: total_account = int(res[0]) else: print "ERROR Can't find total acount" if page_num == 1: time.sleep(randint(5,7)) f.close() os.rename('./data/'+tfname, './data/'+ttname) continue for ii in xrange(1, page_num+1): print "Page %d/%d"%(ii+1, page_num) time.sleep(5) post_data3 = [("resultPagination.limit", "12"), ("resultPagination.sumLimit", "10"), ("resultPagination.start", "%d"%(ii*12)), ("resultPagination.totalCount", "%d"%(total_account)), ("searchCondition.searchType", "Sino_foreign"), ("searchCondition.dbId", ""), ("searchCondition.extendInfo['STRATEGY']", "STRATEGY_CALCULATE"), ("searchCondition.strategy", ""), ("searchCondition.literatureSF", '申请(专利权)人=("%s")'%(corp_name)), ("searchCondition.targetLanguage", ""), ("searchCondition.originalLanguage", ""), ("searchCondition.extendInfo['MODE']", "MODE_TABLE"), ("searchCondition.searchExp", '申请(专利权)人=("%s")'%(corp_name)), ("resultPagination.sumLimit", "10,10"), ("searchCondition.executableSearchExp", "VDB:(PAVIEW='%s')"%(corp_name)), ("wee.bizlog.modulelevel", "0200201"), ('searchCondition.searchKeywords',""), ("searchCondition.searchKeywords", "%s"%kw_pack)] print "Page begin from item%d"%(ii) while(True): try: time.sleep(randint(1,5)) #ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/preExecuteSearch!preExecuteSearch.do") time.sleep(5) #print ret.status_code url_bsch3 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showSearchResult-startWa.shtml" time.sleep(randint(1,5)) ret = ss.post(url_bsch3, params=post_data3) except Exception: traceback.print_exc() print ">>>>","Continuing..." time.sleep(randint(3,7)) continue break time.sleep(5) #ret = ss.post(url_bsch3, params=post_test) #print ret.url #print ret.headers print ret.status_code write_data(parse_page(ss, webcon), fp, corp_name, corp_code) time.sleep(10) <file_sep>/a_test.py #_*_coding:utf-8_*_ import os import sys reload(sys) sys.setdefaultencoding('utf-8') from PIL import Image import pytesseract """require google tesseract-ocr""" import requests import base64 import time import json import re from parse_page import * from random import randint counter = 0 ss = requests.Session() headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} print "Access home page" url_home = "http://www.pss-system.gov.cn/sipopublicsearch/portal/uilogin-forwardLogin.shtml" ss.get(url_home, headers = headers) print "done" print "get icon" url_icon = "http://www.pss-system.gov.cn/sipopublicsearch/portal/login-showPic.shtml" ret = ss.get(url_icon, headers = headers) con = ret.content print "done" username = "Goofyconan" username_b64 = base64.b64encode(username) password = "<PASSWORD>" password_b64 = base64.b64encode(password) with open("icon.png", 'w') as f: f.write(con) str_icon = pytesseract.image_to_string(Image.open("icon.png")) post_data = { 'j_loginsuccess_url':'', 'j_validation_code':str_icon, 'j_username':'R29vZnljb25hbg==', 'j_password':'<PASSWORD>=='} print "to login" url_login_check = "http://www.pss-system.gov.cn/sipopublicsearch/wee/platform/wee_security_check" counter = counter+1 print "INT",counter time.sleep(randint(1,5)) ret = ss.post(url_login_check, params=post_data) time.sleep(5) print "done" print "Access main page" url_main = "http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml" ret = ss.get(url_main) if username in ret.content: print "login successfully!" else: print "Fail to login" print "Search string:", "中心通讯" ss_sch = "中心通讯" post_data = {"params":"searchExpFromIndex=%s@==@searchCondition_scope=@==@searchCondition_type=AI"%(ss_sch)} url_encode_param = "http://www.pss-system.gov.cn/sipopublicsearch/portal/paramRewriter-paramEncode.shtml" counter = counter+1 print "INT",counter time.sleep(randint(1,5)) ret = ss.post(url_encode_param, params=post_data) time.sleep(5) padic = eval(ret.content) print padic param_sch = padic['params'] print "done", param_sch url_bsch = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml?"+param_sch print "seach content" ss.get(url_bsch) headers = {"Accept":"*/*", "Accept-Encoding":"gzip, deflate", "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36", "X-Requested-With":"XMLHttpRequest"} print "Acess common search" url_mainsch = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml" ret = ss.get(url_mainsch) print ret.status_code ''' url_bsch1 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showSearchHistory-showSearchHistoryList.shtml" #url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/general_smartSearch-executeSmartSearch.shtml" url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/1208executeTableSearch-executeCommandSearch.shtml" post_data1 = {"searchHistory.dbCode":"VDB", "searchHistory.searchType":"Sino_foreign", "searchHistory.searchMode":"", "historyPagination.limit":"4", "historyPagination.start":"0"} post_data2 = {#'searchCondition.searchExp':'申请(专利权)人=(中兴)+AND+关键词=("Method+for+forwarding+feedback+information+by+relay+in+HARQ")', 'searchCondition.searchExp':'申请(专利权)人=(中兴通讯) AND 关键词=("HARQ")', 'searchCondition.dbId':'VDB', 'searchCondition.searchType':'Sino_foreign', "searchCondition.extendInfo['MODE']":'MODE_TABLE', "searchCondition.extendInfo['STRATEGY']":"STRATEGY_CALCULATE", "searchCondition.originalLanguage":"", "searchCondition.targetLanguage":"", "wee.bizlog.modulelevel":'0200201', "resultPagination.limit":'12'} print "Post data to search" ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/preExecuteSearch!preExecuteSearch.do") print ret.status_code #ret = ss.post(url_bsch1, data=post_data1) #print ret.status_code ret = ss.post(url_bsch2, params=post_data2) print ret.status_code parse_page(ss, ret.content) with open("res.html", 'w') as f: f.write(ret.content) print "done" ''' #time.sleep(3) for ii in xrange(0, 683, 12): post_data3 = [('resultPagination.limit',"12"), ('resultPagination.sumLimit',"10"), ('resultPagination.start',"%d"%(ii)), ('resultPagination.totalCount',"672"), ('searchCondition.searchType',"Sino_foreign"), ('searchCondition.dbId',""), ("searchCondition.extendInfo['STRATEGY']","STRATEGY_CALCULATE"), ('searchCondition.strategy',""), ('searchCondition.searchExp','申请(专利权)人=(中兴通讯) AND 关键词=("HARQ")'), ('searchCondition.targetLanguage',""), ('searchCondition.originalLanguage',""), ("searchCondition.extendInfo['MODE']","MODE_TABLE"), ('searchCondition.executablesearchExp',"VDB:((PAVIEW='中兴通讯' AND KW_CPP='HARQ'))"), ('searchCondition.literatureSF','申请(专利权)人=(中兴通讯) AND 关键词=("HARQ")'), ('wee.bizlog.modulelevel',"0200201"), ('searchCondition.searchKeywords',""), ('searchCondition.searchKeywords',"[中][ ]{0,}[兴][ ]{0,}[通][ ]{0,}[讯][ ]{0,}"), ('searchCondition.searchKeywords',"[ ]{0,}[H][ ]{0,}[A][ ]{0,}[R][ ]{0,}[Q][ ]{0,}[ ]{0,}")] post_data3 = [("resultPagination.limit", "12"), ("resultPagination.sumLimit", "10"), ("resultPagination.start", "%d"%ii), ("resultPagination.totalCount", "672"), ("searchCondition.searchType", "Sino_foreign"), ("searchCondition.dbId", ""), ("searchCondition.extendInfo['STRATEGY']", "STRATEGY_CALCULATE"), ("searchCondition.strategy", ""), ("searchCondition.literatureSF", '申请(专利权)人=(中兴通讯) AND 关键词=("HARQ")'), ("searchCondition.targetLanguage", ""), ("searchCondition.originalLanguage", ""), ("searchCondition.extendInfo['MODE']", "MODE_TABLE"), ("searchCondition.searchExp", '申请(专利权)人=(中兴通讯) AND 关键词=("HARQ")'), ("resultPagination.sumLimit", "10,10"), ("searchCondition.executableSearchExp", "VDB:((PAVIEW='中兴通讯' AND KW_CPP='HARQ'))"), ("wee.bizlog.modulelevel", "0200201"), ('searchCondition.searchKeywords',""), ("searchCondition.searchKeywords", "[中][ ]{0,}[兴][ ]{0,}[通][ ]{0,}[讯][ ]{0,}"), ("searchCondition.searchKeywords", "[ ]{0,}[H][ ]{0,}[A][ ]{0,}[R][ ]{0,}[Q][ ]{0,}[ ]{0,}")] print "Page begin from item%d"%(ii) counter = counter+1 print "INT",counter time.sleep(randint(1,5)) ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/preExecuteSearch!preExecuteSearch.do") time.sleep(5) print ret.status_code url_bsch3 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showSearchResult-startWa.shtml" counter = counter+1 print "INT",counter time.sleep(randint(1,5)) ret = ss.post(url_bsch3, params=post_data3) time.sleep(5) #ret = ss.post(url_bsch3, params=post_test) print ret.url print ret.headers print ret.status_code parse_page(ss, ret.content) with open("res%d.html"%ii, 'w') as f: f.write(ret.content) time.sleep(10) <file_sep>/temp_tongzu.html import json str="{"cognationList":[{"an":"CN94112517","anKi":null,"appDate":"1994.09.14 12:00:00","cp_num":"3","docStatus":null,"examineNum":null,"fn":"5036194","fnList":null,"invTitleNO":"Thermophilic corrosion-resistance coating preparation process","lang":"OTHER","p_num":"3","pn":"CN1040671C","pnKi":null,"prn":"CN94112517","pubCn":"CN","pubDate":"1998.11.11 12:00:00","pubSn":"1040671","ssid":null,"standardAnNum":"CN199400001251700.0001","standardPnNum":"CN999999999999000000000104067100C.0000","vid":"CN1040671C"},{"an":"CN94112517","anKi":null,"appDate":"1994.09.14 12:00:00","cp_num":"3","docStatus":null,"examineNum":null,"fn":"5036194","fnList":null,"invTitleNO":"Thermophilic corrosion-resistance coating","lang":"OTHER","p_num":"3","pn":"CN1121538A","pnKi":null,"prn":"CN94112517","pubCn":"CN","pubDate":"1996.05.01 12:00:00","pubSn":"1121538","ssid":null,"standardAnNum":"CN199400001251700.0001","standardPnNum":"CN999999999999000000000112153800A.0000","vid":"CN1121538A"}],"cognationQC":{"famn":null,"nrdAn":null,"nrdPn":null,"radioKey":"PN","radioValue":"CN1121538A"},"pagination":{"groupField":null,"groupSort":null,"limit":5,"sortColumn":null,"sortMode":null,"start":0,"sumLimit":10,"totalCount":2},"total":2}" <file_sep>/test_read.py ##_*_coding:utf-8_*_ with open('result.txt', 'r') as f: mingdan = f.read() # 将读取的中文名单放入到list_corp中 list_corp = [] for each in mingdan.split('\n'): (code, name) = each.split(',') list_corp.append((code, name))<file_sep>/tzsetting.py tongzu = 0 <file_sep>/zl_login.py #_*_encoding:utf-8_*_ import base64 from PIL import Image import pytesseract """require google tesseract-ocr""" import requests from random import randint import time def zl_login(ss): while(True): headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} print "Access home page" url_home = "http://www.pss-system.gov.cn/sipopublicsearch/portal/uilogin-forwardLogin.shtml" ss.get(url_home, headers = headers) print "done" print "get icon" url_icon = "http://www.pss-system.gov.cn/sipopublicsearch/portal/login-showPic.shtml" ret = ss.get(url_icon, headers = headers) con = ret.content print "done" username = "Goofyconan" username_b64 = base64.b64encode(username) password = "<PASSWORD>" password_b64 = base64.b64encode(password) with open("icon.png", 'w') as f: f.write(con) str_icon = pytesseract.image_to_string(Image.open("icon.png")) post_data = { 'j_loginsuccess_url':'', 'j_validation_code':str_icon, 'j_username':'R29vZnljb25hbg==', 'j_password':'<PASSWORD>=='} print "to login" url_login_check = "http://www.pss-system.gov.cn/sipopublicsearch/wee/platform/wee_security_check" time.sleep(randint(1,5)) ret = ss.post(url_login_check, params=post_data) time.sleep(3) print "done" print "Access main page to check if login?" url_main = "http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml" ret = ss.get(url_main) time.sleep(2) if username in ret.content: print "login successfully!" break else: print "Fail to login" print "Continue" return ss <file_sep>/vparse_page.py #_*_coding:utf-8_*_ import os import sys reload(sys) sys.setdefaultencoding('utf-8') import requests import re from bs4 import BeautifulSoup import json import time import tzsetting import traceback from random import randint key_clan = 'PN' level_clan = '0201901' url_clan = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showCognationInfo-showCognationList.shtml" url_clan_abs = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showAbstractInfo-viewAbstractInfo.shtml" def parse_page(session, content): '''page''' ret_page = [] bs = BeautifulSoup(content, "html5lib") lilist = bs.find_all('li', class_="patent") #print "len",len(lilist) for li in lilist: info = {"vIdHidden":'', "idHidden":'', "titleHidden":'', "nrdAnHidden":'', "nrdAdpHidden":'', "nrdpdHidden":'', "nrdPnHidden":'', "appSnHidden":'', "pnSnHidden":'', "langHidden":'', "docStatusHidden":'', "appNameHidden":'', "appAddrHidden":'', "appZipHidden":'', "appCountryHidden":'', "waiguan":'' } itemlist = li.find_all('input', {'type':'hidden'}) if len(itemlist) == 0: print "Get not attributes" # deal with <input> tags for item in itemlist: if 'name'in str(item) and item['name'] in info: info[item['name']] = re.sub("<.*?>", '', item['value']) else: pass #print item # IPC classification info['ipcClass'] = '' ptaglist = li.find_all('p', {'class':'clear'}) for ptag in ptaglist: if 'IPC分类号' in str(ptag): tmptext = ptag.get_text() tmptext = tmptext.replace('IPC分类号', '') tmptext = tmptext.replace('\t', '') tmptext = tmptext.replace('\n', '') tmptext = tmptext.replace(':', '') tmptext = tmptext.replace(' ', '') info['ipcClass'] = tmptext.strip() else: continue # application num info['appNum'] = '' ssli = str(li) # print ssli appnum_se = re.search('<b>申请号(.+?)</b>(.+?)</p>', ssli) if appnum_se: info['appNum'] = appnum_se.groups()[1] #print "申请号", info['appNum'] # deal with clans sres = re.search('同族:(\d+)', ssli) #print sres.groups() info["numClans"] = sres.groups()[0] sres = re.search('引证:(\d+)', ssli) if sres: info["numCite"] = int(sres.group(1)) sres = re.search('被引:(\d+)', ssli) if sres: info["numCiteby"] = int(sres.group(1)) sres = re.search('外观设计洛迦诺分类号 : </b>(.+?)</p>', ssli) if sres: info["waiguan"] = sres.group(1) #print info info2 = {} info2['申请人'] = '' info2['申请人'] = info['appNameHidden'].replace(',', '~') info2['申请人地址'] = '' info2['申请人地址'] = info['appAddrHidden'].replace(',', '~') info2['邮编'] = '' info2['邮编'] = info['appZipHidden'].replace(';', '') info2['申请地'] = '' info2['申请地'] = info['appCountryHidden'].replace(',', '~') info2['申请号'] = '' info2['申请号'] = info['appNum'] info2['申请日'] = '' info2['申请日'] = info['nrdAdpHidden'] info2['公开号'] = '' info2['公开号'] = info['nrdPnHidden'] info2['公开日'] = '' info2['公开日'] = info['nrdpdHidden'] info2['IPC分类'] = '' info2['IPC分类'] = info['ipcClass'] info2['设计分类号'] = '' info2['设计分类号'] = info['waiguan'] info2['引证'] = '' info2['引证'] = info['numCite'] info2['被引'] = '' info2['被引'] = info['numCiteby'] info2['同族'] = '' info2['同族'] = info['numClans'] if info2['公开号'].startswith('CN') or info2['申请号'].startswith('CN'): info2['专利国别'] = '中国' elif info2['公开号'].startswith('JP') or info2['申请号'].startswith('JP'): info2['专利国别'] = '日本' elif info2['公开号'].startswith('TW') or info2['申请号'].startswith('TW'): info2['专利国别'] = '台湾' elif info2['公开号'].startswith('MO') or info2['申请号'].startswith('MO'): info2['专利国别'] = '澳门' elif info2['公开号'].startswith('SG') or info2['申请号'].startswith('SG'): info2['专利国别'] = '新加坡' elif info2['公开号'].startswith('US') or info2['申请号'].startswith('US'): info2['专利国别'] = '美国' elif info2['公开号'].startswith('UK') or info2['申请号'].startswith('UK'): info2['专利国别'] = '英国' else: info2['专利国别'] = 'elsecountry' ret_page.append(info2) return ret_page <file_sep>/parse_page.py #_*_coding:utf-8_*_ import os import sys reload(sys) sys.setdefaultencoding('utf-8') import requests import re from bs4 import BeautifulSoup import json import time import tzsetting import traceback from random import randint key_clan = 'PN' level_clan = '0201901' url_clan = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showCognationInfo-showCognationList.shtml" url_clan_abs = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showAbstractInfo-viewAbstractInfo.shtml" def parse_page(session, content): '''page''' ret_page = [] bs = BeautifulSoup(content, "html5lib") lilist = bs.find_all('li', class_="patent") #print "len",len(lilist) for li in lilist: info = {"vIdHidden":'', "idHidden":'', "titleHidden":'', "nrdAnHidden":'', "nrdAdpHidden":'', "nrdpdHidden":'', "nrdPnHidden":'', "appSnHidden":'', "pnSnHidden":'', "langHidden":'', "docStatusHidden":'', "appNameHidden":'', "appAddrHidden":'', "appZipHidden":'', "appCountryHidden":'', "waiguan":'' } itemlist = li.find_all('input', {'type':'hidden'}) if len(itemlist) == 0: print "Get not attributes" # deal with <input> tags for item in itemlist: if 'name'in str(item) and item['name'] in info: info[item['name']] = re.sub("<.*?>", '', item['value']) else: pass #print item # IPC classification info['ipcClass'] = '' ptaglist = li.find_all('p', {'class':'clear'}) for ptag in ptaglist: if 'IPC分类号' in str(ptag): tmptext = ptag.get_text() tmptext = tmptext.replace('IPC分类号', '') tmptext = tmptext.replace('\t', '') tmptext = tmptext.replace('\n', '') tmptext = tmptext.replace(':', '') tmptext = tmptext.replace(' ', '') info['ipcClass'] = tmptext.strip() else: continue # application num info['appNum'] = '' ssli = str(li) # print ssli appnum_se = re.search('<b>申请号(.+?)</b>(.+?)</p>', ssli) if appnum_se: info['appNum'] = appnum_se.groups()[1] #print "申请号", info['appNum'] # deal with clans sres = re.search('同族:(\d+)', ssli) #print sres.groups() info["numClans"] = sres.groups()[0] info['conClans'] = [] if sres and tzsetting.tongzu < 3: print "Tong zu :",tzsetting.tongzu time.sleep(randint(13,19)) num_fail = -1 while(True): time.sleep(randint(7,13)) num_fail = num_fail + 1 try: info["numClans"] = int(sres.group(1)) info["conClans"] = [] for ii in xrange(0, info["numClans"], 5): start_clan = ii value_clan = info["nrdPnHidden"] post_data_clan = {"cognationQC.radioValue": value_clan, "cognationQC.radioKey": key_clan, "wee.bizlog.modulelevel": level_clan, "pagination.start": ii} #print "同族信息,获取列表" ret = session.post(url_clan, params=post_data_clan) time.sleep(7) #print ret.status_code jd_clan = json.loads(ret.content) for clan in jd_clan["cognationList"]: clan_openid = clan['pn'] clan_applyid = clan['an'] post_data_clan_abs = {'cid': clan_openid, 'nrdAn': clan_applyid, 'sid': clan_openid, 'wee.bizlog.modulelevel':'0201101'} #print "abstract of this" clanabs = session.post(url_clan_abs, params=post_data_clan_abs) time.sleep(13) #print ret.status_code #print clanabs.content try: jd_clan_abs = json.loads(clanabs.content) except Exception: print "Load abs exception:" print clanabs.content info["conClans"].append(info['appNameHidden']) time.sleep(randint(17,29)) continue for item in jd_clan_abs["abstractInfoDTO"]["abstractItemList"]: if item["indexCnName"] == "申请(专利权)人": if item["value"] != '' or item["value"] != None: info["conClans"].append(item["value"]) tzsetting.tongzu = tzsetting.tongzu+1 break except Exception: traceback.print_exc() print "fail times: ", num_fail if num_fail >= 2: time.sleep(randint(13,29)) break print "tongzu Exception,Continue" time.sleep(randint(13,39)) continue break # End of while sres = re.search('引证:(\d+)', ssli) if sres: info["numCite"] = int(sres.group(1)) sres = re.search('被引:(\d+)', ssli) if sres: info["numCiteby"] = int(sres.group(1)) sres = re.search('外观设计洛迦诺分类号 : </b>(.+?)</p>', ssli) if sres: info["waiguan"] = sres.group(1) #print info info2 = {} info2['申请人'] = '' info2['申请人'] = info['appNameHidden'] info2['申请人地址'] = '' info2['申请人地址'] = info['appAddrHidden'] info2['邮编'] = '' info2['邮编'] = info['appZipHidden'].replace(';', '') info2['申请地'] = '' info2['申请地'] = info['appCountryHidden'] info2['申请号'] = '' info2['申请号'] = info['appNum'] info2['申请日'] = '' info2['申请日'] = info['nrdAdpHidden'] info2['公开号'] = '' info2['公开号'] = info['nrdPnHidden'] info2['公开日'] = '' info2['公开日'] = info['nrdpdHidden'] info2['IPC分类'] = '' info2['IPC分类'] = info['ipcClass'] info2['设计分类号'] = '' info2['设计分类号'] = info['waiguan'] info2['引证'] = '' info2['引证'] = info['numCite'] info2['被引'] = '' info2['被引'] = info['numCiteby'] info2['同族'] = '' info2['同族'] = info['numClans'] info2['同族1'] = '' info2['同族2'] = '' info2['同族3'] = '' info2['同族4'] = '' if info['numClans'] > 0: for ii in xrange(min(len(info['conClans']), 4)): tpss = info['conClans'][ii] tpss = tpss.replace(';', '') tpss = tpss.replace('\n', '') tpss = tpss.replace('\t', '') tpss = tpss.replace(' ', '') info2['同族%d'%(ii+1)] = info['conClans'][ii] ret_page.append(info2) return ret_page <file_sep>/data/test/csv_test.py import csv with open('./data.csv', 'a+') as f: writer = csv.writer(f) writer.writerow(['name', 'address', 'age']) data = [ ('xiaoming ', 'china', '10'), ('jasmine', 'USA', '12')] writer.writerows(data) f.close()<file_sep>/table2.py # _*_coding:utf-8_*_ import csv import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from PIL import Image try: import pytesseract except Exception: print "Install tesseract and pytesseract first" print "sudo apt-get update" print "sudo apt-get install tesseract-ocr" print "sudo pip install pytesseract" exit() """require google tesseract-ocr""" try: import requests except Exception: print "Install requests first" print "sudo pip install requests" import time import json import re from parse_page import * from dumpdata import * from random import randint from zl_login import zl_login import traceback import tzsetting def dif_post(ss, type, params, url): if type == 0: result = ss.post(url, params) elif type == 1: result = ss.post(url, params, iheaders) else: result = ss.post(url, params, iheaders_1) return result temp_once = 0 iheaders = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Host": "www.pss-system.gov.cn", "X-Requested-With": "XMLHttpRequest", "Referer": "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml", "Origin": "http://www.pss-system.gov.cn"} iheaders_1 = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Host": "www.pss-system.gov.cn", "X-Requested-With": "XMLHttpRequest", "Referer": "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml", "Origin": "http://www.pss-system.gov.cn"} # '''requsts and login''' ss = requests.Session() ss = zl_login(ss) time.sleep(5) # '''file related''' with open('result.txt', 'r') as f: mingdan = f.read() # 将读取的中文名单放入到list_corp中 list_corp = [] for each in mingdan.split('\n'): (code, name) = each.split(',') list_corp.append((code, name)) nums = len(list_corp) if os.path.exists('data'): pass else: os.makedirs('data') headlist = [{ '申请人': '申请(专利权)', '申请人地址': '申请人地址', '邮编': '邮编', '申请地': '申请(专利权)人所在国(省', '申请号': '申请号', '申请日': '申请日', '公开号': '公开(公告)', '公开日': '公开(公告)', 'IPC分类': 'IPC分类', '设计分类号': '洛迦分类号', '引证': '引证', '被引': '被引', '同族': '同族', '同族1': '同族公司1', '同族2': '同族公司2', '同族3': '同族公司3', '同族4': '同族公司4'}] # 将待生成的同族信息csv文件写入 with open('./resultInfo.csv', 'a+') as f: writer = csv.writer(f) writer.writerow(['公司代码', '公开号', '同族数量', '同族号', '同族顺序']) f.close() # '''BIG LOOP''' ii = 0 try_totaltimes=1 for each in list_corp: corp = each corp_name = corp[1].strip() corp_code = str(int(corp[0])) print corp_name, corp_code # 以写的方式打开临时文件 # fp = open('./data/'+tfname, 'w') # write_data(headlist, fp, "输入公司", "公司代码") # 将输入公司名变成一个一个的单个字符 # lcn = list(corp_name.decode('utf-8')) # kw_pack = '' # for word in lcn: # seg = '[%s][ ]{0,}'%(word) # kw_pack = kw_pack+seg # print kw_pack tzsetting.tongzu = 0 url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/executeGeneralSearch-executeGeneralSearch.shtml" # 选择检索范围 post_data1 = {"params": "type=UNI_PN"} post_data2 = {"searchCondition.searchExp": '公开(公告)号=(%s+)' % corp_name, "search_scope": "", "searchCondition.dbId": "VDB", "resultPagination.limit": "12", "searchCondition.searchType": "Sino_foreign", "wee.bizlog.modulelevel": "0200101"} print "Post data to search" ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/portal/paramRewriter-paramEncode.shtml", params=post_data1) print ret.status_code time.sleep(randint(1, 3)) try_times=1 while(True): try: print "当前第" + str(try_times) + "次post" up_int = math.ceil(try_totaltimes / 3.0) typeInfo = up_int % 3 # 每post三次变化一次henaders ret = dif_post(ss, typeInfo, post_data2, url_bsch2) # 每次post之后暂停 time.sleep(randint(23, 39)) rpc = ret.status_code try_times += 1 try_totaltimes += 1 if rpc == 200: try_totaltimes -= 1 break rsc = ret.status_code if rsc != 200: print "Error code:", ret.status_code continue except Exception: traceback.print_exc() with open("./left.txt","a+ ") as f: f.write(corp_code) f.write(",") f.write(corp_name) f.write("\n") print ">>>>","Continuing..." time.sleep(randint(17,29)) continue break webcon = ret.content with open('temp.html', 'w') as f: f.write(webcon) if "没有检索到相关专利" in webcon: print "没有检索到相关专利" continue pattern = '共&nbsp;(\d+)&nbsp;页' res = re.findall(pattern, webcon) if len(res) != 0: page_num = int(res[0]) #write_data(parse_page(ss, webcon), fp, corp_name, corp_code) total_account = 0 pattern = "&nbsp;(\d+)&nbsp;条数据" res = re.findall(pattern, webcon) if len(res) != 0: total_account = int(res[0]) else: pattern = "(\d+)条数据" res = re.findall(pattern, webcon) if len(res) != 0: total_account = int(res[0]) else: print "ERROR Can't find total acount" print ">>>%d pages, %d items<<<<"%(page_num, total_account) for ii in xrange(1, total_account): fp=open('./resultInfo.csv', 'a+') print "Page %d/%d, Total:%d"%(ii+1, page_num, total_account) print ret.url print ret.headers print ret.status_code write_data(parse_page(ss, webcon), fp, corp_name, corp_code) time.sleep(randint(11, 15)) #end of pages fp.close() <file_sep>/dumpdata.py #_*_encoding:utf-8_*_ import os import sys reload(sys) sys.setdefaultencoding('utf-8') getlist = [u'输入公司', u'公司代码', u'申请(专利权)人', u'申请人地址', u'邮编', u'申请(专利权)人所在国(省)', u'申请号', u'申请日', u'公开(公告)号', u'公开(公告)日', u'IPC分类', u'洛迦分类号', u'引证', u'被引', u'同族', u'同族公司1', u'同族公司2', u'同族公司3', u'同族公司4'] # fp 文件流 corp_name 公司名 corp_code 公司代码 def write_data(datalists, fp, corp_name, corp_code): for datalist in datalists: writelist = [] writelist.append(corp_name) writelist.append(corp_code) writelist.append(str(datalist['申请人'])) writelist.append(str(datalist['申请人地址'])) writelist.append(str(datalist['邮编'])) writelist.append(str(datalist['申请地'])) writelist.append(str(datalist['申请号'])) writelist.append(str(datalist['申请日'])) writelist.append(str(datalist['公开号'])) writelist.append(str(datalist['公开日'])) writelist.append(str(datalist['IPC分类'])) writelist.append(str(datalist['设计分类号'])) writelist.append(str(datalist['引证'])) writelist.append(str(datalist['被引'])) writelist.append(str(datalist['同族'])) writelist.append(str(datalist['同族1'])) writelist.append(str(datalist['同族2'])) writelist.append(str(datalist['同族3'])) writelist.append(str(datalist['同族4'])) #返回一个以分隔符,连接各个元素后生成的字符串 fp.write(','.join(writelist)) fp.write('\n') def write_data2(datalists, fp, corp_name, corp_code): for datalist in datalists: writelist = [] writelist.append(corp_name) writelist.append(corp_code) writelist.append(str(datalist['申请人'])) writelist.append(str(datalist['申请人地址'])) writelist.append(str(datalist['邮编'])) writelist.append(str(datalist['申请地'])) writelist.append(str(datalist['申请号'])) writelist.append(str(datalist['申请日'])) writelist.append(str(datalist['公开号'])) writelist.append(str(datalist['公开日'])) writelist.append(str(datalist['IPC分类'])) writelist.append(str(datalist['设计分类号'])) writelist.append(str(datalist['引证'])) writelist.append(str(datalist['被引'])) writelist.append(str(datalist['专利国别'])) fp.write('%'.join(writelist)) fp.write('\n') <file_sep>/dd_test.py # _*_coding:utf-8_*_ import csv import os import sys import math reload(sys) sys.setdefaultencoding('utf-8') from PIL import Image try: import pytesseract except Exception: print "Install tesseract and pytesseract first" print "sudo apt-get update" print "sudo apt-get install tesseract-ocr" print "sudo pip install pytesseract" exit() """require google tesseract-ocr""" try: import requests except Exception: print "Install requests first" print "sudo pip install requests" import time import json import re from parse_page import * from dumpdata import * from random import randint from zl_login import zl_login import traceback import tzsetting def getTongZu(str): list = json.loads(str) tongzu = [] num = 0 if list["cognationList"] != None: num = len(list["cognationList"]) if num == 0: # 无同族信息,返回空数组 return tongzu else: i = 0 while (i < num): tongzu.append(list['cognationList'][i]['vid']) i = i + 1 return tongzu def suffiicentTongzu(code, zhuanli_num, list): seqNum = 1 numTotal = len(list) sufficientList = [] if len(list) == 0: sufficientList.append((code, zhuanli_num, 0, '无同族信息', 0)) else: for each in list: sufficientList.append((code, zhuanli_num, numTotal, each, seqNum)) seqNum += 1 return sufficientList temp_once = 0 iheaders = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Host": "www.pss-system.gov.cn", "X-Requested-With": "XMLHttpRequest", "Referer": "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml", "Origin": "http://www.pss-system.gov.cn"} iheaders_1 = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "Host": "www.pss-system.gov.cn", "X-Requested-With": "XMLHttpRequest", "Referer": "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/searchHomeIndex-searchHomeIndex.shtml", "Origin": "http://www.pss-system.gov.cn"} # '''requsts and login''' ss = requests.Session() ss = zl_login(ss) time.sleep(5) # '''file related''' with open('CompanyList.txt', 'r') as f: mingdan = f.read() # 将读取的中文名单放入到list_corp中 list_corp = [] for each in mingdan.split('\n'): (code, name) = each.split(',') list_corp.append((code, name)) nums = len(list_corp) if os.path.exists('data'): pass else: os.makedirs('data') headlist = [{ '申请人': '申请(专利权)', '申请人地址': '申请人地址', '邮编': '邮编', '申请地': '申请(专利权)人所在国(省', '申请号': '申请号', '申请日': '申请日', '公开号': '公开(公告)', '公开日': '公开(公告)', 'IPC分类': 'IPC分类', '设计分类号': '洛迦分类号', '引证': '引证', '被引': '被引', '同族': '同族', '同族1': '同族公司1', '同族2': '同族公司2', '同族3': '同族公司3', '同族4': '同族公司4'}] # 将待生成的同族信息csv文件写入 # with open('./tongzu.csv', 'a+') as f: # writer = csv.writer(f) # writer.writerow(['公司代码', '公开号', '同族数量', '同族号', '同族顺序']) # f.close() # '''BIG LOOP''' ii = 0 try_totaltimes=1 for each in list_corp: corp = each corp_name = corp[1].strip() corp_code = str(int(corp[0])) if os.path.isfile('./data/' + corp_name + '.csv'): ii = ii + 1 print "Y", ii, './data/' + corp_name + '.csv' continue time.sleep(randint(4, 8)) print corp_name, corp_code tfname = "%s.csv.tmp" % (corp_name) ttname = "%s.csv" % (corp_name) # 以写的方式打开临时文件 # fp = open('./data/'+tfname, 'w') # write_data(headlist, fp, "输入公司", "公司代码") # 将输入公司名变成一个一个的单个字符 # lcn = list(corp_name.decode('utf-8')) # kw_pack = '' # for word in lcn: # seg = '[%s][ ]{0,}'%(word) # kw_pack = kw_pack+seg # print kw_pack """ ret = ss.get("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/tableSearch-showTableSearchIndex.shtml") print "get advanced search.", ret.status_code """ tzsetting.tongzu = 0 # url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/eTS_executeTableSearch-executeCommandSearch.shtml" # url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/10379db_executeTableSearchAC!originalCode1.do" url_bsch2 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/executeGeneralSearch-executeGeneralSearch.shtml" # 选择检索范围 post_data1 = {"params": "type=UNI_PN"} post_data2 = {"searchCondition.searchExp": '公开(公告)号=(%s+)' % corp_name, "search_scope": "", "searchCondition.dbId": "VDB", "resultPagination.limit": "12", "searchCondition.searchType": "Sino_foreign", "wee.bizlog.modulelevel": "0200101"} # while(True): # try: # print "Post data to search" # # if temp_once == 0: # # pass # ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/portal/paramRewriter-paramEncode.shtml",params=post_data1) # # print ret.status_code # # temp_once = 1 # time.sleep(randint(1,3)) # #url_get = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/stmlabrbt-executeSmartSearch.shtml?searchCondition.searchExp=%s&search_scope=&searchCondition.dbId=VDB&resultPagination.limit=200&searchCondition.searchType=Sino_foreign&wee.bizlog.modulelevel=0200101"%(corp_name) # #ret = ss.get(url_get, headers = iheaders) # # ret = ss.post(url_bsch2,params=post_data2,headers=iheaders) # #每次post之后暂停 # time.sleep(randint(23, 39)) # # rsc = ret.status_code # if rsc != 200: # print "Error code:", ret.status_code # print ret.content # time.sleep(randint(23,39)) # continue # except Exception: # traceback.print_exc() # print ">>>>","Continuing..." # time.sleep(randint(17,29)) # continue # break # webcon = ret.content def dif_post(ss, type, params, url): if type == 0: result = ss.post(url, params) elif type == 1: result = ss.post(url, params, iheaders) else: result = ss.post(url, params, iheaders_1) return result # 根据公开号检索同族信息 post_data4 = {"cognationQC.radioValue": "%s" % (corp_name), "cognationQC.radioKey": "PN", "wee.bizlog.modulelevel": "0201901", "pagination.start": "0"} tongzu_url = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showCognationInfo-showCognationList.shtml"; try_atimes = 1 while True: print "当前第" + str(try_atimes) + "次post" up_int=math.ceil(try_totaltimes/3.0) typeInfo=up_int%3 #每post三次变化一次henaders ret = dif_post(ss,typeInfo,post_data4,tongzu_url) time.sleep(randint(23, 39)) rpc = ret.status_code try_atimes += 1 try_totaltimes+=1 if rpc == 200: try_totaltimes -= 1 break if rpc != 200: print ret.content time.sleep(randint(23, 39)) webcontent = ret.content if '访问受限' in webcontent: print "ERROR:IP 受限!!!!" exit() # with open('temp.html', 'w') as f: # f.write(webcon) # with open('%s.html'%corp_name, 'w') as f: # f.write(webcon) if "没有检索到相关专利" in webcontent: time.sleep(randint(5, 7)) from_file = './data/' + tfname to_file = './data/' + ttname print "From file %s to file %s." % (from_file, to_file) os.rename(from_file, to_file) continue tongZuList = getTongZu(webcontent) list = json.loads(webcontent) total = list['total'] # 计算需要提交的Post次数 post_Nums = int(math.ceil((total / 5.0))) start = 1 while (start < post_Nums): # 一个页面显示5条list,每增加一页,post中的start增加1 post_data5 = {"cognationQC.radioValue": "%s" % (corp_name), "cognationQC.radioKey": "PN", "wee.bizlog.modulelevel": "0201901", "pagination.start": "%d" % (start * 5)} try_times = 1 while True: print "当前第" + str(try_times) + "次post" up_int = math.ceil(try_totaltimes / 3.0) typeInfo = up_int % 3 # 每post三次变化一次henaders ret = dif_post(ss, typeInfo, post_data5, tongzu_url) time.sleep(randint(23, 39)) try_times += 1 try_totaltimes += 1 if ret.status_code == 200: try_totaltimes -= 1 break web_content = ret.content print web_content list_next = getTongZu(web_content) tongZuList += list_next start += 1 # 将获取的同族信息写入文件 with open('./tongzu.csv', 'a+') as f: writer = csv.writer(f) data = suffiicentTongzu(corp_code, corp_name, tongZuList) writer.writerows(data) f.close() # 以下代码注释 以先完成第一个表格 # if '访问受限' in webcon: # print "ERROR:IP 受限!!!!" # exit() # with open('temp.html', 'w') as f: # f.write(webcon) # #with open('%s.html'%corp_name, 'w') as f: # # f.write(webcon) # if "没有检索到相关专利" in webcon: # time.sleep(randint(5,7)) # from_file = './data/'+tfname # to_file = './data/'+ttname # print "From file %s to file %s."%(from_file, to_file) # os.rename(from_file, to_file) # continue # pattern = '共&nbsp;(\d+)&nbsp;页' # res = re.findall(pattern, webcon) # if len(res) != 0: # #页数 # page_num = int(res[0]) # if page_num > 10000: # time.sleep(randint(5,7)) # from_file = './data/'+tfname # to_file = './data/'+ttname # print "From file %s to file %s."%(from_file, to_file) # os.rename(from_file, to_file) # continue # else: # pass # else: # print "ERROR: Can't find page number" # #write_data(parse_page(ss, webcon), fp, corp_name, corp_code) # total_account = 0 # pattern = "&nbsp;(\d+)&nbsp;条数据" # res = re.findall(pattern, webcon) # if len(res) != 0: # total_account = int(res[0]) # else: # pattern = "(\d+)条数据" # res = re.findall(pattern, webcon) # if len(res) != 0: # total_account = int(res[0]) # else: # print "ERROR Can't find total acount" # if page_num == 1 or total_account > 99999: # time.sleep(randint(5,7)) # f.close() # from_file = './data/'+tfname # to_file = './data/'+ttname # print "From file %s to file %s."%(from_file, to_file) # os.rename(from_file, to_file) # continue # print ">>>%d pages, %d items<<<<"%(page_num, total_account) # for ii in xrange(1, page_num): # print "Page %d/%d, Total:%d"%(ii+1, page_num, total_account) # time.sleep(randint(13,29)) # post_data3 = [("resultPagination.limit", "200"), # ("resultPagination.sumLimit", "10"), # ("resultPagination.start", "%d"%(ii*200)), # ("resultPagination.totalCount", "%d"%(total_account)), # ("searchCondition.searchType", "Sino_foreign"), # ("searchCondition.dbld", ""), # ("searchCondition.strategy", ""), # ("searchCondition.literatureSF", '复合申请人与发明人=("%s")'%(corp_name)), # ("search_scope", ""), # ("searchCondition.searchExp", "%s"%(corp_name)), # ("resultPagination.sumLimit", "10"), # ("searchCondition.executableSearchExp", "VDB:(IBI='%s')"%(corp_name)), # ("wee.bizlog.modulelevel", "0200201"), # ("searchCondition.searchKeywords", "%s"%kw_pack)] # # # while(True): # try: # time.sleep(randint(13,29)) # #ret = ss.post("http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/preExecuteSearch!preExecuteSearch.do") # time.sleep(5) # #print ret.status_code # url_bsch3 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showViewList-jumpToView.shtml" # time.sleep(randint(3,5)) # ret = ss.post(url_bsch3, params=post_data3) # if ret.status_code != 200: # print ret.status_code, "Continue....." # time.sleep(randint(17,27)) # continue # else: # print ret.status_code, 'page%d done'%(ii+1) # webcon = ret.content # except Exception: # traceback.print_exc() # print ">>>>","Continuing..." # time.sleep(randint(21,33)) # continue # break # #ret = ss.post(url_bsch3, params=post_test) # #print ret.url # #print ret.headers # #print ret.status_code # #write_data(parse_page(ss, webcon), fp, corp_name, corp_code) # time.sleep(randint(11, 15)) # # #end of pages # f.close() # from_file = './data/'+tfname # to_file = './data/'+ttname # print "From file %s to file %s."%(from_file, to_file) # os.rename(from_file, to_file)
30d4306840d9aa76897a79e15c852e5f8d3d6781
[ "Python", "HTML" ]
13
Python
AllstarVirgo/zhuanli
2d8548d38fdb13a3b7b3a2c1820072656fd01c1b
83e74fb12704d4ba839f699b02d6be5dafc1cecf
refs/heads/master
<file_sep><?php $loader = require_once __DIR__.'/vendor/autoload.php'; \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists'); $shop = new \Test\Shop(); $formatNegotiator = new \Negotiation\FormatNegotiator(); $formatNegotiator->registerFormat( 'json', [ 'application/vnd.meshop+json;version=1', 'application/vnd.meshop+json;version=2', ], true ); $formatNegotiator->registerFormat( 'xml', [ 'application/vnd.meshop+xml;version=1', 'application/vnd.meshop+xml;version=2', ], true ); $shop = new \Negotiation\Stack\Negotiation($shop, $formatNegotiator, null, null, [ 'format_priorities' => [ 'application/vnd.meshop+json;version=2', 'application/vnd.meshop+xml;version=2', 'application/vnd.meshop+json;version=1', 'application/vnd.meshop+xml;version=1', 'application/hal+json', 'application/json', ], 'language_priorities' => [], ]); return $shop;<file_sep><?php namespace Api; use GuzzleHttp\Psr7\Response; class ProductTest extends TestCase { public function testListHasItems() { /** @var Response $response */ $response = $this->client->get('/', [ 'headers' => [ 'Accept' => 'application/vnd.meshop+json;version=1', ] ]); $this->assertResponseStatusCodeEquals(200, $response); $this->assertResponseHasContentType('application/vnd.meshop+json;version=1', $response); $this->assertResponseBodyMatchesJsonFile(__DIR__.'/expected/product/single-item.json', $response); /** @var Response $response */ $response = $this->client->get('/', [ 'headers' => [ 'Accept' => 'application/vnd.meshop+xml;version=1', ] ]); $this->assertResponseStatusCodeEquals(200, $response); $this->assertResponseHasContentType('application/vnd.meshop+xml;version=1', $response); } }<file_sep><?php $shop = require_once __DIR__.'/bootstrap.php'; $response = $shop->handle(\Symfony\Component\HttpFoundation\Request::createFromGlobals()); $response->send(); <file_sep><?php namespace Api; use Coduo\PHPMatcher\Factory\SimpleFactory; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Response; class TestCase extends \PHPUnit_Framework_TestCase { const BASEURL = 'http://localhost:8000/'; protected $client; protected $matcher; public function setUp() { parent::setUp(); $this->client = new Client([ 'base_uri' => self::BASEURL ]); $matcherFactory = new SimpleFactory(); $this->matcher = $matcherFactory->createMatcher(); } public function assertMatchesString($expected, $given) { $isMatched = $this->matcher->match(json_decode($given, true), json_decode($expected, true)); $this->assertTrue($isMatched, $this->matcher->getError()); } public function assertResponseBodyMatches($expected, Response $response) { $this->assertMatchesString($expected, $response->getBody()); } public function assertMatchesJsonFile($file, $given) { $expected = file_get_contents($file); $this->assertMatchesString($expected, $given); } public function assertResponseBodyMatchesJsonFile($expected, Response $response) { $this->assertMatchesJsonFile($expected, $response->getBody()); } public function assertResponseHasContentType($expected, Response $response) { $this->assertContains($expected, $response->getHeader('Content-Type')); } public function assertResponseStatusCodeEquals($expected, Response $response) { $this->assertEquals($expected, $response->getStatusCode()); } }<file_sep><?php namespace Test; class Shop implements \Symfony\Component\HttpKernel\HttpKernelInterface { public function handle(\Symfony\Component\HttpFoundation\Request $request, $type = self::MASTER_REQUEST, $catch = true) { $product = new \Test\Product('Aspirin'); $product->setVariants([ new Variant(), new Variant(), new Variant(), ]); $serializer = \Hateoas\HateoasBuilder::create() ->setDebug(true) ->build(); $mimeType = $request->attributes->get('_mime_type'); $version = (int) explode(';version=', $mimeType)[1]; $json = $serializer->serialize( $product, $request->attributes->get('_format'), \JMS\Serializer\SerializationContext::create()->setVersion($version) ); $response = \Symfony\Component\HttpFoundation\Response::create($json, 200); $response->headers->set('Content-Type', $request->attributes->get('_mime_type')); return $response; } }<file_sep><?php namespace Test; use JMS\Serializer\Annotation as Serializer; use Hateoas\Configuration\Annotation as Hateoas; /** * @Serializer\XmlRoot("variant") * @Serializer\ExclusionPolicy("all") * @Hateoas\Relation( * "self", * href = "expr('/api/products/' ~ object.getName())" * ) */ class Variant { /** * @Serializer\Expose */ private $name; /** * @Serializer\Since("1.0.x") * @Serializer\Groups({"list", "details"}) * @Serializer\Type("string") */ public function getName() { return 'Foo'; } }<file_sep><?php namespace Test; use JMS\Serializer\Annotation as Serializer; use Hateoas\Configuration\Annotation as Hateoas; /** * @Serializer\XmlRoot("product") * @Serializer\ExclusionPolicy("all") * @Hateoas\Relation( * "self", * href = "expr('/api/products/' ~ object.getName())" * ) * @Hateoas\Relation( * "variants", * href = "expr('/api/products/' ~ object.getName() ~ '/variants')", * embedded = "expr(object.getVariants())" * ) */ class Product { /** * @Serializer\Expose */ private $name = ''; /** * @Serializer\Expose * @Serializer\Since("1") * @Serializer\Groups({"list", "details"}) * @Serializer\Type("boolean") */ private $available = false; private $variants = []; /** * @Serializer\Type("boolean") */ private $yolo = false; public function __construct($name, $available = true) { $this->name = $name; $this->available = $available; } /** * @Serializer\Type("string") * @Serializer\Since("1") * @Serializer\Groups({"list", "details"}) * @return string */ public function getName() { return 'Aspirin'; } public function isAvailable() { return true; } public function isVariants() { return $this->variants; } public function getVariants() { return $this->variants; } public function setVariants($variants) { $this->variants = $variants; } public function isYolo() { return $this->yolo; } }
e0e17d79c56cc6dcac6e56255ccfc99e5165b9fa
[ "PHP" ]
7
PHP
psren/api-test
4bf5729091bb0c065e7ad5fe5ae2c1eac66e448b
a1b7078d88b4782c4950515b1b2774b75d46235f
refs/heads/master
<file_sep>example-go-slackbot =============================== [![wercker status](https://app.wercker.com/status/4956e5bb2ee4285dd24b02197e9d0975/s/master "wercker status")](https://app.wercker.com/project/byKey/4956e5bb2ee4285dd24b02197e9d0975) ## Application Environment - `SLACK_BOT_TOKEN`: required - `DOCOMO_APIKEY`: `github.com/kyokomi/go-docomo/docomo` plugin - `REDISTOGO_URL`: `redis://<id>:<password>@<host>:<port>` https://redistogo.com/ ## Wercker Environment - DockerHub push - `DOCKER_HUB_USERNAME` - `DOCKER_HUB_PASSWORD` - `DOCKER_HUB_REPOSITORY`: (example) `kyokomi/go-slackbot` - Arukas restart - `ARUKAS_JSON_API_TOKEN` - `ARUKAS_JSON_API_SECRET` - `ARUKAS_CONTAINER_ID` ## License [MIT](https://github.com/kyokomi/example-go-slackbot/blob/master/LICENSE) <file_sep>package main import ( "flag" "log" "net/http" "os" godocomo "github.com/kyokomi/go-docomo/docomo" "github.com/kyokomi/slackbot" "github.com/kyokomi/slackbot/plugins/akari" "github.com/kyokomi/slackbot/plugins/cron/v2" "github.com/kyokomi/slackbot/plugins/docomo" "github.com/kyokomi/slackbot/plugins/esa" "github.com/kyokomi/slackbot/plugins/kohaimage" "github.com/kyokomi/slackbot/plugins/lgtm" "github.com/kyokomi/slackbot/plugins/naruhodo" "github.com/kyokomi/slackbot/plugins/router" "github.com/kyokomi/slackbot/plugins/suddendeath" "github.com/kyokomi/slackbot/plugins/sysstd" ) type Config struct { redisToGoURL string slackToken string docomoAPIKey string esaTeam string esaToken string } func init() { if fl := log.Flags(); fl&log.Ltime != 0 { log.SetFlags(fl | log.Lmicroseconds) } } func setupSlackBot(cfg Config) error { // setup repository addr, password, err := parseRedisURL(cfg.redisToGoURL) if err != nil { return err } cronRepository := cron.NewRedisRepository(addr, password, 0, "") docomoRepository := slackbot.NewRedisRepository(addr, password, 0) cronCtx, err := cron.NewContext(cronRepository) if err != nil { return err } botCtx, err := slackbot.NewBotContextNotSysstd(cfg.slackToken) if err != nil { return err } cronCtx.AllRefresh(botCtx) sysPlugin := sysstd.NewPlugin(botCtx.PluginManager()) sysPlugin.SetTimezone("JST") botCtx.AddPlugin("sysstd", sysPlugin) botCtx.AddPlugin("cron", cron.NewPlugin(cronCtx)) botCtx.AddPlugin("router", router.NewPlugin(botCtx.Client, docomoRepository)) if cfg.docomoAPIKey != "" { botCtx.AddPlugin("docomo", docomo.NewPlugin(godocomo.NewClient(cfg.docomoAPIKey), docomoRepository)) } botCtx.AddPlugin("akari", akari.NewPlugin()) botCtx.AddPlugin("naruhodo", naruhodo.NewPlugin()) botCtx.AddPlugin("lgtm", lgtm.NewPlugin()) botCtx.AddPlugin("koha", kohaimage.NewPlugin(kohaimage.NewKohaAPI())) botCtx.AddPlugin("suddendeath", suddendeath.NewPlugin()) if cfg.esaTeam != "" && cfg.esaToken != "" { botCtx.AddPlugin("esa", esa.NewPlugin(cfg.esaTeam, cfg.esaToken)) } botCtx.WebSocketRTM() return nil } func main() { var serverAddr, slackToken, dApiKey, esaTeam, esaToken string flag.StringVar(&serverAddr, "addr", ":8080", "serverのaddr") flag.StringVar(&slackToken, "slackToken", os.Getenv("SLACK_BOT_TOKEN"), "SlackのBotToken") flag.StringVar(&dApiKey, "docomo", os.Getenv("DOCOMO_APIKEY"), "DocomoのAPIKEY") flag.StringVar(&esaTeam, "esa-team", os.Getenv("ESA_TEAM"), "esaのチーム名") flag.StringVar(&esaToken, "esa-token", os.Getenv("ESA_TOKEN"), "esaのToken") flag.Parse() cfg := Config{ redisToGoURL: os.Getenv("REDISTOGO_URL"), slackToken: <PASSWORD>Token, docomoAPIKey: dApiKey, esaTeam: esaTeam, esaToken: esaToken, } if err := setupSlackBot(cfg); err != nil { log.Fatalln(err) } // listen and serve for healthy http.HandleFunc("/ping", func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("PONG")) }) log.Println("Starting on", serverAddr) http.ListenAndServe(serverAddr, nil) } <file_sep>package main import ( "fmt" "net/url" ) func parseRedisURL(redisURL string) (string, string, error) { addr := fmt.Sprintf("%s:%d", "localhost", 6379) password := "" if redisURL == "" { return addr, password, nil } redisURLInfo, err := url.Parse(redisURL) if err != nil { return addr, password, err } addr = redisURLInfo.Host if redisURLInfo.User != nil { password, _ = redisURLInfo.User.Password() } return addr, password, nil }
35e7e3b2f3643ca0d756b335f51027b4cccfec56
[ "Markdown", "Go" ]
3
Markdown
kyokomi/example-go-slackbot
05ca0255665ccc53d4268ed72a5dd095da67919e
79f867fe98a1d518372f3ebbc9c9ff8d6e4d09d6
refs/heads/master
<repo_name>joshdholtz/Protocol-Android<file_sep>/src/com/joshdholtz/protocol/lib/CustomClient.java package com.joshdholtz.protocol.lib; import android.widget.Toast; import com.joshdholtz.protocol.lib.ProtocolClient.ProtocolStatusListener; import com.joshdholtz.protocol.lib.requests.JSONRequestData; import com.joshdholtz.protocol.lib.requests.ParamsRequestData; import com.joshdholtz.protocol.lib.responses.JSONResponseHandler; import com.joshdholtz.protocol.lib.responses.ProtocolResponseHandler; public class CustomClient extends ProtocolClient { private CustomClient() { super(); this.setBaseUrl("http://www.statuscodewhat.com"); } public static CustomClient getInstance() { return LazyHolder.instance; } private static class LazyHolder { private static CustomClient instance = new CustomClient(); } public static ProtocolTask get(String route, ParamsRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doGet(route, requestData, responseHandler); } public static ProtocolTask post(String route, JSONRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doPost(route, requestData, responseHandler); } public static ProtocolTask put(String route, JSONRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doPut(route, requestData, responseHandler); } public static ProtocolTask delete(String route, ParamsRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doDelete(route, requestData, responseHandler); } } <file_sep>/README.md # Protocol - Android Networking Library Protocol is a simple networking library for Android 2.1 and above. Protocol is built off of Android's AsyncTask and DefaultHttpClient. Below is an example of how to get a JSON from a request. ```` java ProtocolClient client = new ProtocolClient("http://www.statuscodewhat.com"); client.doGet("/200?body={\"name1\":\"value1\"}", null, new JSONResponseHandler() { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { if (jsonArray != null) { Toast.makeText(getApplication(), "JSON Array Size - " + jsonArray.length(), Toast.LENGTH_SHORT).show(); } else if (jsonObject != null) { Toast.makeText(getApplication(), "JSON Object Size - " + jsonObject.length(), Toast.LENGTH_SHORT).show(); } } }); ```` ## How To Get Started - Download the [Protocol JAR](https://github.com/joshdholtz/Protocol-Android/raw/master/builds/protocol-1.0.6.jar) - Place the JAR in the Android project's "libs" directory - Code ## Table of Contents * [Examples](#section_examples) * [ProtocolTask - The Core of Protocol](#section_protocol_task) * [ProtocolClient - Response Types](#section_protocol_client_response) * [ProtocolClient - Request Types](#section_protocol_client_request) * [ProtocolClient - Observe Statuses](#section_protocol_client_statuses) * [Custom ProtocolClient](#section_protocol_client_custom) * [Model Examples](#section_model_examples) * [ProtocolModel - Map response to Java object](#section_protocol_model) <a name='section_examples'></a> ## Examples <a name='section_protocol_task'></a> ### Using Protocol at the core level - ProtocolTask ProtocolTask is wrapped inside of ProtocolClient(see below). You probably won't have to call a ProtocolTask directly itself. ```` java ProtocolTask task = new ProtocolTask(HttpMethod.HTTP_GET, "http://www.statuscodewhat.com/200?body=HelloWorldddd", null, new ProtocolResponseHandler() { @Override public void handleResponse(HttpResponse response, int status, byte[] data) { String responseData = new String(data); Toast.makeText(getApplication(), "ProtocolTaskResponse - " + responseData, Toast.LENGTH_SHORT).show(); } }); task.execute(); ```` <a name='section_protocol_client_response'></a> ### Using ProtocolClient and different response types ProtocolClient wraps ProtocolTask making common patterns easier to use: - Set a base url for each request - Set headers that get sent up on each request - Set headers for individual requests - Set a timeout for each request - Set observers that get executed for individual status codes ```` java // Creates a client that can get used for one to many requests. // This client instance is setting the base url at "http://www.statuscodewhat.com" ProtocolClient client = new ProtocolClient("http://www.statuscodewhat.com"); // Sets headers that get sent up on each request client.addHeader("client_test_request_header", "client_test_request_header_value"); client.addHeader("client_test_request_header_override", "THIS SHOULDN'T SHOW"); // Header example further down explains why // Performs a get request to /200?body=HelloWorld // A null ProtocolRequestData parameter is passed (this could have been used to pass in the query param - see following doGet) // StringResponseHandler is passed in to create a String responsenation of the response data client.doGet("/200?body=HelloWorld", null, new StringResponseHandler() { @Override public void handleResponse(String stringResponse) { Toast.makeText(getApplication(), stringResponse, Toast.LENGTH_SHORT).show(); } }); // Performs a get request to /200 with ParamsRequestData to add the body parameter // JSONResponseHandler is passed in to create a JSOON responsenation of the response data // A JSONObject and JSONArray are passed in the response handler depending on what the resonse returns ParamsRequestData requestData1 = new ParamsRequestData(); requestData1.addParam("body", "{\"name1\":\"value1\",\"name2\":\"value2\",\"name3\":\"value3\"}"); client.doGet("/200", requestData1, new JSONResponseHandler() { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { if (jsonArray != null) { Toast.makeText(getApplication(), "JSON Array Size - " + jsonArray.length(), Toast.LENGTH_SHORT).show(); } else if (jsonObject != null) { Toast.makeText(getApplication(), "JSON Object Size - " + jsonObject.length(), Toast.LENGTH_SHORT).show(); } } }); // Performs a get request to /200 with ParamsRequestData to add the body parameter // JSONResponseHandler is passed in to create a JSOON responsenation of the response data // Sets headers to send up only on this request // NOTE: If a header set here will override a header set in the ProtocolClient ParamsRequestData requestData3 = new ParamsRequestData(); requestData3.addHeader("test_request_header", "test_request_header_value"); requestData3.addHeader("client_test_request_header_override", "client_test_request_header_override_value"); requestData3.addParam("body", ""); requestData3.addParam("show_headers", "true"); client.doGet("/200", requestData3, new JSONResponseHandler() { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { if (jsonObject != null) { try { JSONObject headers = jsonObject.getJSONObject("headers"); if (headers.has("test_request_header")) { Toast.makeText(getApplication(), "Found test_request_header - " + headers.getString("test_request_header"), Toast.LENGTH_SHORT).show(); } if (headers.has("client_test_request_header")) { Toast.makeText(getApplication(), "Found client_test_request_header - " + headers.getString("client_test_request_header"), Toast.LENGTH_SHORT).show(); } if (headers.has("client_test_request_header_override")) { Toast.makeText(getApplication(), "Found client_test_request_header_override - " + headers.getString("client_test_request_header_override"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); ```` <a name='section_protocol_client_request'></a> ### Using ProtocolClient and different request types ```` java // Performs a post request to /200 with ParamsRequestData to add post parameters to the request body ParamsRequestData requestData5 = new ParamsRequestData(); requestData5.addParam("first_name", "Josh"); requestData5.addParam("last_name", "Holtz"); client.doPost("/200", requestData5, new StringResponseHandler() { @Override public void handleResponse(String stringResponse) { if (this.getStatus() == 200) { Toast.makeText(getApplication(), "POST param success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplication(), "POST params failure", Toast.LENGTH_SHORT).show(); } } }); // Performs a post request to /200 with JSONRequestData to add a JSON string to the request body Map<String, String> jsonObjectData = new HashMap<String, String>(); jsonObjectData.put("first_name", "Josh"); jsonObjectData.put("last_name", "Holtz"); JSONObject jsonObject = new JSONObject(jsonObjectData); JSONRequestData requestData6 = new JSONRequestData(jsonObject); client.doPut("/200", requestData6, new StringResponseHandler() { @Override public void handleResponse(String stringResponse) { if (this.getStatus() == 200) { Toast.makeText(getApplication(), "POST json success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplication(), "POST json failure", Toast.LENGTH_SHORT).show(); } } }); // Performs a post request to /200 with FileRequestData to add post parameters and files with to the mulit-part request body Map<String, String> fileObjectData = new HashMap<String, String>(); fileObjectData.put("first_name", "Josh"); fileObjectData.put("last_name", "Holtz"); Map<String, File> filesData = new HashMap<String, File>(); filesData.put("file1", new File("../somepath..")); FileRequestData requestData7 = new FileRequestData(fileObjectData, filesData); client.doPut("/200", requestData7, new StringResponseHandler() { @Override public void handleResponse(String stringResponse) { if (this.getStatus() == 200) { Toast.makeText(getApplication(), "POST file success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplication(), "POST file failure", Toast.LENGTH_SHORT).show(); } } }); ```` <a name='section_protocol_client_statuses'></a> ### Observing HTTP statuses on a ProtocolClient ```` java // This ProtocolStatusListener gets called whenver a 401 is received in a ProtocolClient // Returning false does not allow that requests ProtocolResponseHandler (or subclass) to execute client.observeStatus(401, new ProtocolStatusListener() { @Override public boolean observedStatus(int status, ProtocolResponseHandler handler) { Toast.makeText(getApplication(), "You are not logged in; We observed a status - " + status, Toast.LENGTH_SHORT).show(); return false; } }); // This ProtocolStatusListener gets called whenver a 500 is received in a ProtocolClient // Returning true does allow that requests ProtocolResponseHandler (or subclass) to execute client.observeStatus(500, new ProtocolStatusListener() { @Override public boolean observedStatus(int status, ProtocolResponseHandler handler) { Toast.makeText(getApplication(), "We got a server error; We observed a status - " + status, Toast.LENGTH_SHORT).show(); return true; } }); client.doGet("/401", null, new JSONResponseHandler() { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { Toast.makeText(getApplication(), "The ProtocolStatusListener should catch this 401 and not show this toast", Toast.LENGTH_SHORT).show(); } }); client.doGet("/500", null, new JSONResponseHandler() { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { Toast.makeText(getApplication(), "The ProtocolStatusListener should catch this 500 and show this toast", Toast.LENGTH_SHORT).show(); } }); ```` <a name='section_protocol_client_custom'></a> ### Subclassing ProtocolClient as a singleton ```` java public class CustomClient extends ProtocolClient { private CustomClient() { super("http://www.statuscodewhat.com"); } public static CustomClient getInstance() { return LazyHolder.instance; } private static class LazyHolder { private static CustomClient instance = new CustomClient(); } /** * This wrapper of doGet is pointless but just an example of what a subclassed ProtocolClient could do */ public static ProtocolTask get(String route, ParamsRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doGet(route, requestData, responseHandler); } /** * This wrapper of doPost is pointless but just an example of what a subclassed ProtocolClient could do */ public static ProtocolTask post(String route, JSONRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doPost(route, requestData, responseHandler); } /** * This wrapper of doPut is pointless but just an example of what a subclassed ProtocolClient could do */ public static ProtocolTask put(String route, JSONRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doPut(route, requestData, responseHandler); } /** * This wrapper of doDelete is pointless but just an example of what a subclassed ProtocolClient could do */ public static ProtocolTask delete(String route, ParamsRequestData requestData, JSONResponseHandler responseHandler) { return CustomClient.getInstance().doDelete(route, requestData, responseHandler); } } ```` <a name='section_model_examples'></a> ## Using ProtocolModel and adding custom formats <a name='section_protocol_model'></a> ### ProtocolModel maps your JSON response to a Java object #### MemberModel.java ```` java public class MemberModel extends ProtocolModel { @MapConfig(key = "first_name") public String firstName; @MapConfigkey = "last_name") public String lastName; @MapConfig(key = "age") public int age; @MapConfig(key = "awesome_level") public double awesomeLevel; @MapConfig(key = "cool") public boolean cool; } ```` #### SomeActivity.java ```` java // Builds a member model off of a JSON string MemberModel member = ProtocolModel.createModel(MemberModel.class, "{\"first_name\":\"Josh\"," + "\"last_name\":\"Holtz\"," + "\"age\":4," + "\"awesome_level\":\"4.6\"," + "\"cool\":true," + "\"dob\":\"2012-10-12T22:55:20+00:00\"" + "}"); // Displays member information in a Toast Toast.makeText(getApplication(), "First Name - " + member.firstName + "\nLast Name " + member.lastName + "\nAge " + member.age + "\nAwesome level " + member.awesomeLevel + "\nCool " + member.cool + "\nBirthday " + member.birthday, Toast.LENGTH_LONG).show(); ```` <file_sep>/src/com/joshdholtz/protocol/lib/models/MemberModel.java package com.joshdholtz.protocol.lib.models; import java.util.Date; import java.util.List; import org.json.JSONObject; import com.joshdholtz.protocol.lib.ProtocolModel; import com.joshdholtz.protocol.lib.ProtocolModelFormats; import com.joshdholtz.protocol.lib.ProtocolModelFormats.MapConfig; import com.joshdholtz.protocol.lib.ProtocolModelFormats.MapModelConfig; public class MemberModel extends ProtocolModel { @MapConfig(key = "first_name", format = ProtocolModelFormats.FORMAT_STRING) public String firstName; @MapConfig(key = "last_name", format = ProtocolModelFormats.FORMAT_STRING) public String lastName; @MapConfig(key = "age", format = ProtocolModelFormats.FORMAT_INT) public int age; @MapConfig(key = "awesome_level", format = ProtocolModelFormats.FORMAT_DOUBLE) public double awesomeLevel; @MapConfig(key = "cool", format = ProtocolModelFormats.FORMAT_BOOLEAN) public boolean cool; @MapConfig(key = "dob", format = "date") public Date birthday; @MapModelConfig(key = "friend", modelClass = MemberModel.class) public MemberModel friend; @MapModelConfig(key = "friends", modelClass = MemberModel.class) public List<MemberModel> friends; } <file_sep>/src/com/joshdholtz/protocol/lib/requests/ProtocolRequestData.java package com.joshdholtz.protocol.lib.requests; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.message.BasicNameValuePair; import android.util.Log; import com.joshdholtz.protocol.lib.helpers.Base64; import com.joshdholtz.protocol.lib.helpers.ProtocolConstants; public abstract class ProtocolRequestData { private Map<String, String> headers; public abstract String getContentType(); public abstract HttpEntity getEntity(); public abstract void log(); public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public void addBasicAuthHeader(String valueToBeBase64Encoded) { addHeader("Authorization", "Basic: " + Base64.encodeToString(valueToBeBase64Encoded.getBytes(), Base64.NO_WRAP)); } public void addBearerAuthHeader(String value) { addHeader("Authorization", "Bearer " + value); } public void addHeader(String key, String value) { if (headers == null) { headers = new HashMap<String, String>(); } headers.put(key, value); } public boolean containsHeader(String key) { if (headers == null) { return false; } return headers.containsKey(key); } protected List<BasicNameValuePair> paramsToValuePairs(Map<String, Object> params) { List<BasicNameValuePair> nameValuePair = new ArrayList<BasicNameValuePair>(); List<String> keys = new ArrayList<String>(params.keySet()); for (int i = 0; i < keys.size(); ++i) { nameValuePair.add(new BasicNameValuePair(keys.get(i), params.get(keys.get(i)).toString())); } return nameValuePair; } public void logHeaders() { Log.d(ProtocolConstants.LOG_TAG, "\tHEADERS:"); if (headers != null) { for (String header : headers.keySet()) { Log.d(ProtocolConstants.LOG_TAG, "\t\t" + header + " - " + headers.get(header)); } } } } <file_sep>/src/com/joshdholtz/protocol/lib/ProtocolModel.java package com.joshdholtz.protocol.lib; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.joshdholtz.protocol.lib.ProtocolModelFormats.MapConfig; import com.joshdholtz.protocol.lib.ProtocolModelFormats.MapModelConfig; import com.joshdholtz.protocol.lib.helpers.ProtocolConstants; import android.util.Log; public abstract class ProtocolModel { private static boolean debug = false; public static void setDebug(boolean debug) { ProtocolModel.debug = debug; } public static <T extends ProtocolModel>T createModel(Class<T> clazz, String jsonData) { T instance = null; try { instance = clazz.newInstance(); instance.initFromJSONString(jsonData); } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + " from " + jsonData, e); } } return instance; } public static <T extends ProtocolModel>T createModel(Class<T> clazz, JSONObject object) { T instance = null; try { instance = clazz.newInstance(); instance.initFromJSONObject(object); } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + " from " + object, e); } } return instance; } public static <T extends ProtocolModel>List<T> createModels(Class<T> clazz, String jsonData) { List<T> instances = new ArrayList<T>(); try { JSONArray array = new JSONArray(jsonData); return ProtocolModel.createModels(clazz, array); } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + "s - " + e.getClass() + " " + e.getMessage(), e); Log.e(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + "s from " + jsonData, e); } } return instances; } public static <T extends ProtocolModel>List<T> createModels(Class<T> clazz, JSONArray array) { List<T> instances = new ArrayList<T>(); try { for (int i = 0; i < array.length(); ++i) { JSONObject object = array.getJSONObject(i); T instance = clazz.newInstance(); boolean success = instance.initFromJSONObject(object); if (success) { instances.add(instance); } else { Log.w(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + " from " + object.toString()); } } } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Could not create " + clazz.getCanonicalName() + "s - " + e.getClass() + " " + e.getMessage(), e); } } return instances; } public ProtocolModel() { } public ProtocolModel(String jsonString) { this.initFromJSONString(jsonString); } public ProtocolModel(JSONObject jsonObject) { this.initFromJSONObject(jsonObject); } public boolean initFromJSONString(String jsonString) { boolean success = true; try { JSONObject object = new JSONObject(jsonString); success = this.initFromJSONObject(object); } catch (JSONException e) { success = false; if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error parsing JSON string", e); } } return success; } public boolean initFromJSONObject(JSONObject object) { boolean success = true; for(Field field : this.getClass().getDeclaredFields()){ String name = field.getName(); Annotation[] annotations = field.getAnnotations(); if (field.isAnnotationPresent(MapModelConfig.class)) { MapModelConfig map = field.getAnnotation(MapModelConfig.class); try { if (!object.isNull(map.key())) { field.setAccessible(true); if (map.modelClass() != null && ProtocolModel.class.isAssignableFrom(map.modelClass())) { Object json = new JSONTokener(object.get(map.key()).toString()).nextValue(); if (json instanceof JSONObject) { Object val = ProtocolModel.createModel(map.modelClass(), (JSONObject) json); if (val != null) { field.set(this, val); } } else if (json instanceof JSONArray) { Object val = ProtocolModel.createModels(map.modelClass(), (JSONArray) json); if (val != null) { field.set(this, val); } } } } } catch (IllegalArgumentException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (IllegalAccessException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (JSONException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } } else if (field.isAnnotationPresent(MapConfig.class)) { MapConfig map = field.getAnnotation(MapConfig.class); try { if (!object.isNull(map.key())) { field.setAccessible(true); if (map.format().equals("default")) { field.set(this, object.get(map.key())); } else { Object val = ProtocolModelFormats.get(map.format(), object.get(map.key())); if (val != null) { field.set(this, val); } } } } catch (IllegalArgumentException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (IllegalAccessException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (JSONException e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } catch (Exception e) { if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error setting field " + name, e); } } } } JSONArray names = object.names(); for (int i = 0; i < names.length(); ++i) { try { String key = names.getString(i); if (!object.isNull(key)) { this.mapToClass(key, object.get(key)); } } catch (JSONException e) { success = false; if (debug) { Log.e(ProtocolConstants.LOG_TAG, "Error with legacy map to class"); } } } return success; } public void mapToClass(String key, Object value) { } } <file_sep>/src/com/joshdholtz/protocol/lib/ProtocolModelFormats.java package com.joshdholtz.protocol.lib; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.Map; import android.util.Log; import android.widget.Toast; import com.joshdholtz.protocol.lib.ProtocolClient.ProtocolStatusListener; import com.joshdholtz.protocol.lib.helpers.ProtocolConstants; import com.joshdholtz.protocol.lib.requests.JSONRequestData; import com.joshdholtz.protocol.lib.requests.ParamsRequestData; import com.joshdholtz.protocol.lib.responses.JSONResponseHandler; import com.joshdholtz.protocol.lib.responses.ProtocolResponseHandler; public class ProtocolModelFormats extends ProtocolClient { public final static String FORMAT_STRING = "string"; public final static String FORMAT_DOUBLE = "double"; public final static String FORMAT_INT = "int"; public final static String FORMAT_BOOLEAN = "boolean"; private Map<String, MapFormat> formats; @Retention(RetentionPolicy.RUNTIME) public @interface MapConfig { String key() default ""; String format() default "default"; } @Retention(RetentionPolicy.RUNTIME) public @interface MapModelConfig { String key() default ""; Class modelClass(); } public static abstract class MapFormat { public abstract Object format(Object value); } private ProtocolModelFormats() { super(); formats = new HashMap<String, MapFormat>(); formats.put(FORMAT_STRING, new MapFormat() { @Override public Object format(Object value) { return value.toString(); } }); formats.put(FORMAT_DOUBLE, new MapFormat() { @Override public Object format(Object value) { return Double.parseDouble(value.toString()); } }); formats.put(FORMAT_INT, new MapFormat() { @Override public Object format(Object value) { return Integer.parseInt(value.toString()); } }); formats.put(FORMAT_BOOLEAN, new MapFormat() { @Override public Object format(Object value) { return Boolean.parseBoolean(value.toString()); } }); } private static ProtocolModelFormats getInstance() { return LazyHolder.instance; } private static class LazyHolder { private static ProtocolModelFormats instance = new ProtocolModelFormats(); } public static void set(String format, MapFormat mapFormat) { ProtocolModelFormats.getInstance().formats.put(format, mapFormat); } public static Object get(String format, Object value) { return ProtocolModelFormats.getInstance().formats.get(format).format(value); } } <file_sep>/src/com/joshdholtz/protocol/lib/responses/ModelResponseHandler.java package com.joshdholtz.protocol.lib.responses; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.util.Log; import com.joshdholtz.protocol.lib.ProtocolModel; import com.joshdholtz.protocol.lib.helpers.ProtocolConstants; public abstract class ModelResponseHandler<T extends ProtocolModel> extends JSONResponseHandler { @Override public void handleResponse(JSONObject jsonObject, JSONArray jsonArray) { if (jsonObject != null) { T model = ProtocolModel.createModel(this.getModelClass(), jsonObject); handleResponse(model); } else if (jsonArray != null) { List<T> models = ProtocolModel.createModels(this.getModelClass(), jsonArray); handleResponse(models); } else { handleError(); } } public abstract void handleResponse(T model); public abstract void handleResponse(List<T> models); public abstract void handleError(); public Class<T> getModelClass() { Class<T> classType = null; Type genericType = this.getClass().getGenericSuperclass(); if(genericType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) genericType; Type[] typeArguments = type.getActualTypeArguments(); for(Type typeArgument : typeArguments) { classType = ((Class<T>)typeArgument); Log.d(ProtocolConstants.LOG_TAG, "---------------------- Class has a parameterized type of " + classType.getSimpleName()); } } return classType; } }
d173ffce5d85bc5a25011b5df4a2e464da535031
[ "Markdown", "Java" ]
7
Java
joshdholtz/Protocol-Android
0900044d375b459215ca3095e5a8fa17245179a6
3ac4ff3400bb4a9242589961144570fd753ec71b
refs/heads/master
<repo_name>SheaYang/TV-L1<file_sep>/Makefile # Makefile of research program OBJ_DIR = bin SRC_DIR = src INCLUDE_DIR = src LIB_DIR = lib PKG_CONFIG_PATH := /usr/local/lib/pkgconfig/:$(PKG_CONFIG_PATH) MAINFILE = main.c TARGET = deblur SRCS = ${MAINFILE} deblur.c #expsystem.c fourier.c OBJS := ${SRCS:.c=.o} OBJS := ${addprefix ${OBJ_DIR}/, ${OBJS}} CUDA_SRCS = deconvolve.cu CUDA_OBJS := ${CUDA_SRCS:.cu=.o} CUDA_OBJS := ${addprefix ${OBJ_DIR}/, ${CUDA_OBJS}} INCLUDE_HEADER = ${INCLUDE_DIR}/include.h #CVFLAGS = `pkg-config --cflags opencv` #CVLIBS = `pkg-config --libs opencv` CVFLAGS = `pkg-config --cflags opencv` CVLIBS = `pkg-config --libs opencv` CUDAFLAGS = -I/usr/local/cuda/include CUDALIBS = -L/usr/local/cuda/lib -lcufft NVCCFLAGS = -arch=sm_30 --use_fast_math CC = gcc NVCC = nvcc CFLAGS =-std=gnu99 \ -fopenmp \ -I${INCLUDE_DIR} DEBUG = -g -O2 CLIBFLAGS = -lm -lstdc++ ${TARGET}:${OBJS} ${CUDA_OBJS} ${CC} ${CFLAGS} -o $@ ${DEBUG} ${CLIBFLAGS} ${CVLIBS} ${CUDALIBS} \ ${OBJS} ${CUDA_OBJS} ${OBJ_DIR}/${MAINFILE:.c=.o}:${MAINFILE} ${CC} $< ${CFLAGS} -c -o $@ ${DEBUG} ${CVFLAGS} ${CUDAFLAGS} ${OBJ_DIR}/%.o:${SRC_DIR}/%.c ${INCLUDE_HEADER} ${SRC_DIR}/%.h ${CC} $< ${CFLAGS} -c -o $@ ${DEBUG} ${CVFLAGS} ${CUDAFLAGS} ${OBJ_DIR}/%.o:${SRC_DIR}/%.cu ${NVCC} $< -c -o $@ ${DEBUG} ${NVCCFLAGS} clean: rm -f ${TARGET} ${OBJS} ${CUDA_OBJS} <file_sep>/include.h #ifndef __INCLUDE_HEADER__ #define __INCLUDE_HEADER__ #define YES 1 #define NO 0 #define LOAD_DISPARITY_MAP YES #define LEFT_CAM 0 #define CENTER_CAM 1 #define RIGHT_CAM 2 #define MAX_DISPARITY 32 #define MAX_PSF_SIZE 32 #define FFT_SIZE 512 #define CUT_OFF_SIZE FFT_SIZE //切り取る大きさはFFTのと同じにしなければならない #define BLOCK_SIZE 16 //2^nのほうが都合が良い #define IMG_ELEM(img, h, w) ( ((uchar*) ((img)->imageData + (h) * (img)->widthStep))[(w)] ) #define IMG_ELEM_DOUBLE(img, h, w) ( ((double*) ((img)->imageData + (h) * (img)->widthStep))[(w)] ) #define max(a,b) (((a)<(b))?(b):(a)) #endif <file_sep>/src/deblur.c /**************************************** deblur.c ****************************************/ #include <deblur.h> #include "include.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> // cuda #include <cuda.h> #include <cuda_runtime.h> void normNabla(int N1, int N2, double *u, double h, double * nablaU){ double ex, ey; for (int i=0; i<N1*N2; i++) nablaU[i]=0; for (int i=1; i<N1-1;i++){ for (int j=1; j<N2-1; j++){ ex=(u[(i+1)*N2+j]-u[(i-1)*N2+j])/2/h; ey=(u[i*N2+j+1]-u[i*N2+j-1])/2/h; nablaU[i*N2+j]=sqrt(ex*ex+ey*ey); } } } void normMinus(int N1, int N2, double * a, double * b, double * result){ for (int i=0; i<N1*N2; i++){ result[i]=abs(a[i]-b[i]); } } double residual(int N1, int N2, double* u, double* f) { double residual_norm_sq = 0.0; for (int i = 0; i < N1 * N2; i++) { residual_norm_sq += (u[i] - f[i]) * (u[i] - f[i]); } return sqrt(residual_norm_sq); } void deblur(int N1, int N2, double *uIni, double *srcImg,int itertime, double h, double lambda, double delta, double epsilon, double * u){ double * deblurU=(double*) malloc(N1*N2*sizeof(double)); double * f=(double*) malloc(N1*N2*sizeof(double)); double * nablaU=(double*) malloc(N1*N2*sizeof(double)); double * uMinusf=(double*) malloc(N1*N2*sizeof(double)); for (int i=0;i<N1*N2;i++) {u[i]=uIni[i];} printf("Initial residule: %f\n", residual(N1,N2, uIni, srcImg)); clock_t t; t=clock(); for (int iter=0;iter<itertime;iter++){ normNabla(N1,N2, u, h,nablaU); normMinus(N1,N2, u, srcImg, uMinusf); for (int i=0; i<N1*N2; i++){ f[i]=lambda*srcImg[i]/sqrt(uMinusf[i]*uMinusf[i]+delta)*sqrt(nablaU[i]*nablaU[i]+epsilon); } for (int i=1; i<N1-1;i++){ for (int j=1; j<N2-1;j++){ deblurU[i*N2+j]=(h*h*f[i*N2+j]+u[(i-1)*N2+j]+u[i*N2+j-1]+u[(i+1)*N2+j]+u[i*N2+j+1])/(4+lambda*sqrt(nablaU[i*N2+j]*nablaU[i*N2+j]+epsilon)*h*h/sqrt(uMinusf[i*N2+j]*uMinusf[i*N2+j]+delta)); if (deblurU[i*N2+j]>255){deblurU[i*N2+j]=255;} if (deblurU[i*N2+j]<0){deblurU[i*N2+j]=0;} } } for (int i=0;i<N1*N2;i++) {u[i]=deblurU[i];} if (iter%400==0){ printf("%d %f\n", iter, residual(N1,N2, u, srcImg)); } } t=clock()-t; //printf("Final residule: %f\n", residual(N1,N2, u, srcImg)); printf("time= %f seconds\n", ((float)t)/CLOCKS_PER_SEC); free(deblurU); free(f); free(nablaU); free(uMinusf); } void deblurGPU(int N1, int N2, double *uIni, double *srcImg, int itertime, double h, double lambda, double delta, double epsilon, double * dataNow) { deconvolve(N1, N2, uIni,srcImg, itertime, h, lambda, delta, epsilon, dataNow); //printf("residule: %f\n", residual(N1,N2, dataNow, srcImg)); } <file_sep>/src/deblur.h #ifndef __DEBLUR__ #define __DEBLUR__ #include <stdio.h> #include <math.h> #include <cv.h> #include <highgui.h> void normNabla(int N1, int N2, double *u, double h, double * nablaU); void normMinus(int N1, int N2, double * a, double * b, double * result); void deblur(int N1, int N2, double *uIni, double *srcImg,int itertime, double h, double lambda, double delta, double epsilon, double * dataNow); double residual(int N1, int N2, double* u, double* f); void deblurGPU(int N1, int N2, double *uIni, double *srcImg, int itertime, double h, double lambda, double delta, double epsilon, double * dataNow); #endif <file_sep>/src/blur.h #ifndef __BLUR__ #define __BLUR__ #include <stdio.h> #include <math.h> #include <cv.h> #include <highgui.h> IplImage* blur(IplImage *img, double *psf); IplImage* blurPSF(IplImage *img, IplImage *psf); #endif <file_sep>/script.sh #!/bin/bash #SBATCH --nodes=1 #SBATCH --ntasks-per-node=1 #SBATCH --cpus-per-task=20 #SBATCH --time=30:00:00 #SBATCH --output=/scratch/sy1823/HPC/final_project/mydeblur_GPU/BH_0.5/output.txt #SBATCH --error=/scratch/sy1823/HPC/final_project/mydeblur_GPU/BH_0.5/error.txt module load slurm ./deblur -f BH_gauss.png <file_sep>/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <getopt.h> #include <cv.h> #include <highgui.h> #include "deblur.h" #include "include.h" int main( int argc, char* argv[]){ char c; char *filename; int gpuFlag=0; int itertime=10000;//100000; double h, lambda=0.3, delta=0.005, epsilon=0.005; while ((c = getopt(argc, argv, ":bgk:s:d:f:p:x:y:")) != -1) { switch(c) { case 'f': filename = optarg; printf("Processing file: %s\n", filename); break; case 'g': printf("Use GPU Kernel\n"); gpuFlag = 1; break; } } IplImage* img = cvLoadImage(filename, CV_LOAD_IMAGE_COLOR); int side=img->height; int N1=img->height+2; int N2=img->width+2; printf("Height: %d, Width: %d, N1: %d, N2: %d\n", img->height, img->width, N1,N2); IplImage* imgSplit[3]; IplImage* dblSplit[3]; IplImage* diffSplit[3]; for(int i = 0; i < 3; i++){ imgSplit[i] = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1); dblSplit[i] = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1); diffSplit[i] = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1); } cvSplit(img, imgSplit[0], imgSplit[1], imgSplit[2], NULL); for (int i=0;i<3;i++){ //for (int i=2;i<3;i++){ double* datasrc=(double*) malloc (N1*N2*sizeof(double)); double* dataIni=(double*) malloc (N1*N2*sizeof(double)); double* dataNow=(double*) malloc (N1*N2*sizeof(double)); for(int h = 0 ; h < N1; h++){ for( int w = 0; w < N2; w++){ datasrc[h*N2+w]=0; dataIni[h*N2+w]=0; dataNow[h*N2+w]=0; } } for(int h = 1 ; h < N1-1; h++){ for( int w = 1; w < N2-1; w++){ datasrc[h*N2+w]=(double) IMG_ELEM(imgSplit[i], h-1, w-1); //dataIni[h*N2+w]=(double) IMG_ELEM(imgSplit[i], h-1, w-1); } } if (!gpuFlag){ deblur(N1,N2, dataIni, datasrc, itertime, 1, lambda, delta, epsilon,dataNow); } else{ deblurGPU(N1, N2, dataIni, datasrc, itertime, 1, lambda, delta, epsilon, dataNow); } for(int h = 1 ; h < N1-1; h++){ for( int w = 1; w < N2-1; w++){ IMG_ELEM(dblSplit[i], h-1, w-1) = dataNow[h * N2 + w]; IMG_ELEM(diffSplit[i], h-1, w-1) = dataNow[h * N2 + w]-datasrc[h * N2 + w]; } } free(datasrc); free(dataIni); free(dataNow); } IplImage* dbl = cvClone(img); IplImage* diff = cvClone(img); cvMerge(imgSplit[0], imgSplit[1], imgSplit[2], NULL, img); cvMerge(dblSplit[0], dblSplit[1], dblSplit[2], NULL, dbl); cvMerge(diffSplit[0], diffSplit[1], diffSplit[2], NULL, diff); cvSaveImage("/scratch/sy1823/HPC/final_project/mydeblur_GPU/img.png", img, 0); cvSaveImage("/scratch/sy1823/HPC/final_project/mydeblur_GPU/imgSplit_blue.png", imgSplit[2], 0); cvSaveImage("/scratch/sy1823/HPC/final_project/mydeblur_GPU/deblur.png", dbl, 0); //cvSaveImage("deblur_red.png", dblSplit[0], 0); //cvSaveImage("deblur_green.png", dblSplit[1], 0); cvSaveImage("/scratch/sy1823/HPC/final_project/mydeblur_GPU/deblur_blue.png", dblSplit[2], 0); cvSaveImage("/scratch/sy1823/HPC/final_project/mydeblur_GPU/diff.png", diff, 0); cvReleaseImage(&imgSplit[0]); cvReleaseImage(&imgSplit[1]); cvReleaseImage(&imgSplit[2]); cvReleaseImage(&dblSplit[0]); cvReleaseImage(&dblSplit[1]); cvReleaseImage(&dblSplit[2]); cvReleaseImage(&diffSplit[0]); cvReleaseImage(&diffSplit[1]); cvReleaseImage(&diffSplit[2]); cvReleaseImage(&img); cvReleaseImage(&dbl); cvReleaseImage(&diff); return 0; ERROR: fprintf(stderr, "Usage: -f [/path/to/image] path to the image file\n"); return 1; }
76d3a75d58ff1c67b8d4d20084c3d413f28e5884
[ "C", "Makefile", "Shell" ]
7
Makefile
SheaYang/TV-L1
cdc91510595323f8dbedc85fd35418e66d39bf52
2cc58924d8f45268c3cbec27a95bebb954e5bf41
refs/heads/master
<file_sep>import React, { useState } from 'react'; import { StyleSheet, Text, View, TextInput, Button, ScrollView, FlatList } from 'react-native'; import GoalItem from './components/GoalItem'; import GoalInput from './components/GoalInput'; export default function App() { const [courseGoals, setCourseGoals] = useState([]); const [isAddMode,setIsAddMode] = useState(false); const addGoalInputHandler = (goalTitle) => { if(goalTitle.length === 0) return; setCourseGoals((currentGoals) => [...currentGoals, { id: Math.random().toString(), value: goalTitle }]); setIsAddMode(false); //settting two states after each other //it will batch these together //it will not re render the component twice //apply all state changes once }; const deleteGoal = (goalId) => { setCourseGoals(currentgls => { console.log(currentgls); return currentgls.filter(goal => goal.id !== goalId); }); } const cancelGoalInputHandler = () =>{ setIsAddMode(false); } return ( <View style={styles.container}> <Button title="Add New Goal" onPress={() => setIsAddMode(true)}></Button> <GoalInput visibleAddMode={isAddMode} onCancel={cancelGoalInputHandler} onAddGoal={addGoalInputHandler} /> <FlatList keyExtractor={(item, index) => item.id} data={courseGoals} renderItem={itemData => <GoalItem onDelete={deleteGoal} goalId={itemData.item.id} title={itemData.item.value} />} /> </View> ); } const styles = StyleSheet.create({ container: { padding: 50 } });
40f1cbaf1a24eda80e148cf8f325959e2717b4d3
[ "JavaScript" ]
1
JavaScript
anurag19289/React-Native-To-Do
f6aa9a2713c9e4d94e8741ce7b3c69af5455e159
b828118531282b84c2b07ee8e5717c43e0d00923
refs/heads/master
<file_sep>import React from "react"; import { Tab, Menu, Icon } from "semantic-ui-react"; import { NavLink } from "react-router-dom"; export default class TabNav extends React.Component { state = { activeItem: 'Home Page' } handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( <Menu tabular> <NavLink to="/"> <Menu.Item name='Home Page' active={activeItem === 'Home Page'} onClick={this.handleItemClick} ><Icon name='home' />Home Page</Menu.Item> </NavLink> <NavLink to="/characters"> <Menu.Item name='Characters' active={activeItem === 'Characters'} onClick={this.handleItemClick} > <Icon name='group' />Characters</Menu.Item> </NavLink> <NavLink to="/locations"> <Menu.Item name='Locations' active={activeItem === 'Locations'} onClick={this.handleItemClick} ><Icon name='map' />Locations</Menu.Item> </NavLink> <NavLink to='/episodes'> <Menu.Item name='Episodes' active={activeItem === 'Episodes'} onClick={this.handleItemClick} > <Icon name='video' />Episodes</Menu.Item> </NavLink> </Menu> ) } } <file_sep>import React from "react"; import { Card, Button, CardTitle, CardText, Row, Col } from 'reactstrap'; export default function LocationCard(props) { const {name, type, dimension, residents} = props.location; return ( <Row> <Col sm="6"> <Card body> <CardTitle>Location: {name}</CardTitle> <CardText>Planet: {type}</CardText> <CardText>{dimension}</CardText> <div className="button"> <Button>Residents:{residents.length}</Button> </div> </Card> </Col> </Row> ); }; <file_sep>import React from "react"; import { Card, Button, CardTitle, CardText, Row, Col } from 'reactstrap'; import CharacterList from "./CharacterList"; export default function EpisodeCard(props) { console.log(props.episode) const {name,air_date, episode, characters} = props.episode; return ( <Row> <Col sm="6"> <Card body> <CardTitle>Episode: {name}</CardTitle> <CardText>Air Date: {air_date}</CardText> <CardText>Episode: {episode}</CardText> <div className="button"> <Button>Characters:{characters.length}</Button> </div> </Card> </Col> </Row> ); }; <file_sep>import React, { useEffect, useState } from "react"; import EpisodeCard from './EpisodeCard'; import Loading from './Load'; import axios from "axios"; export default function EpisodesList() { const [episodes,setEpisodes] = useState([]); useEffect( () => { axios.get(`https://rickandmortyapi.com/api/episode/`) .then(response => { console.log(response.data.results) setEpisodes(response.data.results); }) .catch(err => { console.log(err) }) },[]) if(episodes.length === 0) { return ( <span className="loading"><h1> Loading Characters <Loading /></h1></span> ) } return( <div className="episodes-container"> {episodes.map( (episode, index) => { return( <EpisodeCard key={index} episode={episode} /> ) })} </div> ) } <file_sep>import React, {useState, useEffect} from "react"; import TabNav from "./components/TabNav.js"; import Header from "./components/Header.js"; import CharacterList from "./components/CharacterList"; import WelcomePage from './components/WelcomePage'; import {Route} from 'react-router-dom'; import LocationsList from "./components/LocationsList.js"; import EpisodesList from "./components/EpisodesList"; import './style.css'; export default function App() { return ( <main> <Header /> <TabNav /> <div> <Route exact path='/' render={ (props) => <WelcomePage {...props}/>} /> <Route path='/characters' render={(props) => <CharacterList {...props} /> } /> <Route path='/locations' render={(props) => <LocationsList {...props} /> } /> <Route path="/episodes" render={(props) => <EpisodesList {...props}/> } /> </div> </main> ); } <file_sep>import React, { useEffect, useState } from "react"; import LocationCard from './LocationCard'; import Loading from './Load'; import axios from "axios"; export default function LocationsList() { const [locations,setLocations] = useState([]); useEffect( () => { const getLocations = async () => { const response = await axios.get("https://rickandmortyapi.com/api/location/"); console.log(response.data.results); setLocations(response.data.results); }; getLocations(); },[]) if(locations.length === 0) { return ( <> <span className="loading"><h1> Loading Locations<Loading /></h1></span> </> ) } return( <div className="locations-container"> {locations.map( (location, index) => { return( <LocationCard key={index} location={location} /> ) })} </div> ) }
d62944888b4077b13ebb574ac96afdb1623e9501
[ "JavaScript" ]
6
JavaScript
vy3191/Sprint-Challenge-Single-Page-Apps
37c269529162b0057fb7ef0614b4560d31c0bd46
054916c5f1ed6135d98e37f943813b7408670c88
refs/heads/master
<file_sep><?php require_once '../functions.php'; include_once '../section/head.php'; session_start(); if ($_SERVER["REQUEST_METHOD"] == "POST") { $username = $_POST['username']; $password = $_POST['<PASSWORD>']; if (doLogin($username,$password)) { header('Location: ../Panel/index.php'); die; }else{ e("رمزعبور یا نام کاربری اشتباه است","alert-danger"); } } require 'Login.view.php'; <file_sep><?php include 'functions.php'; require_once 'Panel/config.php'; include 'section/head.php'; $FullName = $_POST['FullName']; $email = $_POST['email']; $username1 = $_POST['username']; $password1 = $_POST['password']; $PasswordConfirm = $_POST['ConfirmPassword']; try { if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($password1 == $PasswordConfirm) { $dbPDO = new PDO('mysql:host='.$host.';dbname='.$namedb, $username, $password); $Result = $dbPDO->prepare("INSERT INTO users(FullName, Email, Password, username) VALUES (:Fullname,:Email,:Password,:username)"); $Result->bindParam(':Fullname', $FullName); $Result->bindParam(':Email', $email); $Result->bindParam(':Password', <PASSWORD>($<PASSWORD>)); $Result->bindParam(':username', $username1); $Result->execute(); echo $dbPDO->errorInfo(); e("اطلاعات شما با موفقیت ثبت شد", "alert-success"); } else { e("رمز عبور و تکرار رمزعبور باهم برابر نمی باشد.", "alert-danger"); } } } catch (PDOException $e) { e($e, "alert-danger"); } ?> <file_sep><body> <div class="container-fluid"> <?php getpost(); ?> <file_sep><?php require_once 'functions.php'; require_once 'section/head.php'; require_once 'section/header.php'; require_once 'section/Content.php'; require_once 'section/footer.php'; ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Mar 13, 2019 at 04:30 PM -- Server version: 5.7.25-0ubuntu0.18.04.2 -- PHP Version: 7.2.12-1+ubuntu18.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `blog` -- -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `Title` varchar(20) CHARACTER SET utf8 DEFAULT 'بدون عنوان', `Description` text CHARACTER SET utf8 NOT NULL, `ID` int(6) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`Title`, `Description`, `ID`) VALUES ('amin is developer', 'amin loved programming and trad.\r\n', 1), ('dasdasd', 'dasd', 2), ('hi', 'ads', 3), ('Learn php', 'We have used print_r function to display the array\r\nWE have used FETCH_OBJ parameter get property name corresponding to column name. Same way we will try other parameters In your downloaded script ( file name : pdo-fetch.php ) the area to change the part of the code is marked. You can replace them with these lines to check the output ', 4), ('bugati', 'bugati is car.', 5); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `FullName` varchar(15) CHARACTER SET utf8 NOT NULL, `Email` text CHARACTER SET utf8 NOT NULL, `Password` varchar(30) CHARACTER SET utf8 NOT NULL, `ID` int(6) NOT NULL, `username` varchar(15) CHARACTER SET utf8 NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `posts` -- ALTER TABLE `posts` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`ID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `posts` -- ALTER TABLE `posts` MODIFY `ID` int(6) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `ID` int(6) NOT NULL AUTO_INCREMENT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php require_once 'Panel/config.php'; require_once 'section/head.php'; function e($text, $type = "alert-info") { echo "<div class=\"container\">"; echo "<div class=\"alert margin $type\">"; echo "<strong>$text</strong>"; echo "</div>"; echo "</div>"; } function getpost() { global $mypdo; $result = $mypdo->prepare("SELECT * From posts"); $result->execute(); echo "<br/><br/>"; $fetch = $result->fetchAll(); foreach ($fetch as $row) { echo "<div class=\"card margin \">"; echo "<div class=\"card-header text-white bg-info\">" . "<b>" . $row['Title'] . "</b>" . "</div>"; echo "<div class=\"card-body\">"; echo "<p class=\"text-body\">" . $row['Description'] . "</p>"; echo "</div>"; echo "</div>"; } } function getHash($str) { $saltStr = 'l0calhost'; $hash = sha1($saltStr . md5($str . $saltStr)); return $hash; } function getUser($username, $fields = '*') { global $username, $mypdo; $statement = $mypdo->prepare("SELECT $fields from users where username=?"); $statement->execute(array($username)); $Blogger = $statement->fetch(PDO::FETCH_ASSOC); if (count($Blogger) > 0) { return $Blogger; } return false; } function doLogin($username, $password) { $user = getUser($username); if ($user && $username == $user['username'] && getHash($password) == $user['Password']) { $_SESSION['login'] = $username; $_SESSION['user'] = $user['display_name']; $_SESSION['email'] = $user['email']; $_SESSION['userIP'] = $_SERVER['REMOTE_ADDR']; // $_SESSION['last_action_time'] = time(); return true; } return false; } function IsSession() { session_start(); if (!isset($_SESSION['login'])) { header('Location: ../session/Login.view.php'); die; } return 0; } ?> <file_sep><?php $host = 'localhost'; $namedb = 'blog'; $username = 'root'; $password = ''; $mypdo = new PDO("mysql:host=$host;dbname=$namedb", $username, $password); <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Panel admin</title> <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="css/simple-sidebar.css" rel="stylesheet"> </head> <body> <div class="d-flex" id="wrapper"> <!-- Sidebar --> <div class="bg-dark float-right text-white border-right" id="sidebar-wrapper"> <div class="sidebar-heading">Panel Admin</div> <div class="list-group list-group-flush"> <a href="index.php" class="list-group-item list-group-item-action text-white bg-dark">Send Post</a> </div> <div class="list-group list-group-flush"> <a href="../logout.php" class="list-group-item list-group-item-action text-white bg-dark">Send logout</a> </div> </div> <!-- /#sidebar-wrapper --> <!-- Page Content --> <div id="page-content-wrapper"> <nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto mt-2 mt-lg-0"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <NAME> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Setting</a> <a class="dropdown-item" href="../logout.php">Exit</a> </div> </li> </ul> </div> </nav> <?php $title = $_POST['title']; $description = $_POST['description']; include_once '../functions.php'; require 'config.php'; IsSession(); try { $myPDO = new PDO("mysql:host=$host;dbname=$namedb", $username, $password); $query = "SELECT COUNT(*) from posts where Title=:title and Description=:description"; $countResult = $myPDO->prepare($query); $countResult->bindParam(':title', $title); $countResult->bindParam(":description", $description); $countResult->execute(); $count = $countResult->fetch()[0]; if ($count == 0) { $result = $myPDO->prepare("INSERT INTO posts(Title, Description) VALUES (:title,:description)"); $result->bindParam(':title', $title); $result->bindParam(":description", $description); if ($result->execute()) { e("Successfuly insert data to Database $namedb", "alert-success"); } } } catch (PDOException $e) { e("Error: " . $e->getMessage(), "alert-danger"); } ?> <div class="container-fluid"> <form action="index.php" enctype="multipart/form-data" method="post"> <div class="form-group"> <label for="exampleFormControlInput1">Title :</label> <input name="title" type="Text" class="form-control" id="exampleFormControlInput1" placeholder="Hello World!"> <label for="exampleFormControlInput1">Description :</label> <textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3" required></textarea><br/> <input type="submit" class="btn btn-primary" value="Send"> </div> </form> </div> </div> </div> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> </body> </html> <file_sep><?php session_start(); session_destroy(); header('Location: session/Login.view.php'); die; ?>
9392cda85b35ad022986bd1b780a49657201a259
[ "SQL", "PHP" ]
9
PHP
aminmalekzadeh/MyBlog
54762be6a530a470b269639cb7245bf8549960de
fa75a2982d96481045a2b9c03238decf353fad37
refs/heads/master
<file_sep>const outputResult = function() { this.hasError = null; this.code = null; this.data = []; this.message = ''; this.status = 200 } outputResult.prototype.setCode = function(code){ this.hasError = false; this.code = code; return this; } outputResult.prototype.setErrorCode = function(code){ this.hasError = true; this.code = code; this.status = code == 403? code: 400 return this; } outputResult.prototype.setData = function(data){ this.data = data; return this; } outputResult.prototype.setMessage = function(message){ this.message = message; return this; } outputResult.prototype.validateResultForOutput = function(){ if(this.code == -1){ this.message = 'Internal Server Error' } return this; } module.exports = outputResult; <file_sep># backEndBase Base Code for Back-End node.js <file_sep>function outputResult(code, hasError, data, message) { return { code, hasError, data, message, } } function validateResult(input) { return ((input && input.hasError) == true) } module.exports = { outputResult, validateResult, } <file_sep>const finalize = function(result, res) { result.validateResultForOutput() res.status(result.status) res.send(result) } module.exports = finalize <file_sep>module.exports ={ isArrayFull(obj) { return obj && Array.isArray(obj) && obj.length }, }
0226408b93cb8248b6f92f32ccac3999ae72c57e
[ "JavaScript", "Markdown" ]
5
JavaScript
mayyamak/backEndBase
6b65ca5b0c9b058a4eb12143cdfcaa2f032b58ec
a079336f317b51afc3e939e5e202bc468555fb1d
refs/heads/develop
<file_sep># -*- coding: utf-8 -*- """ static_file Static File :copyright: (c) 2013-2015 by Openlabs Technologies & Consulting (P) Limited :license: BSD, see LICENSE for more details. """ from trytond.model import fields from trytond.pyson import Eval, Bool from boto.s3 import connection from boto.s3 import key from trytond.pool import PoolMeta __all__ = ['NereidStaticFolder', 'NereidStaticFile'] __metaclass__ = PoolMeta class NereidStaticFolder: __name__ = "nereid.static.folder" _rec_name = "folder_name" s3_use_bucket = fields.Boolean("Use S3 Bucket?") s3_access_key = fields.Char( "S3 Access Key", states={'required': Bool(Eval('s3_use_bucket'))} ) s3_secret_key = fields.Char( "S3 Secret Key", states={'required': Bool(Eval('s3_use_bucket'))} ) s3_bucket_name = fields.Char( "S3 Bucket Name", states={'required': Bool(Eval('s3_use_bucket'))} ) s3_cloudfront_cname = fields.Char( "S3 Cloudfront CNAME", states={'required': Bool(Eval('s3_use_bucket'))} ) s3_object_prefix = fields.Char("S3 Object Prefix") @classmethod def __setup__(cls): super(NereidStaticFolder, cls).__setup__() cls._error_messages.update({ "invalid_cname": "Cloudfront CNAME with '/' at the end is not " + "allowed", }) @classmethod def validate(cls, records): """ Checks if cloudfront cname ends with '/' :param records: List of active records """ super(NereidStaticFolder, cls).validate(records) for record in records: record.check_cloudfront_cname() def get_bucket(self): ''' Return an S3 bucket for the static file ''' s3_conn = connection.S3Connection( self.s3_access_key, self.s3_secret_key ) return s3_conn.get_bucket(self.s3_bucket_name) @staticmethod def default_s3_cloudfront_cname(): """ Sets default for Cloudfront CNAME """ return "http://your-domain.cloudfront.net" def check_cloudfront_cname(self): """ Checks for '/' at the end of Cloudfront CNAME """ if self.s3_cloudfront_cname.endswith('/'): return self.raise_user_error('invalid_cname') class NereidStaticFile: __name__ = "nereid.static.file" is_s3_bucket = fields.Function( fields.Boolean("S3 Bucket?"), 'get_is_s3_bucket' ) s3_key = fields.Function(fields.Char("S3 key"), "get_s3_key") def get_s3_key(self, name): """ Returns s3 key for static file """ if self.folder.s3_object_prefix: return '/'.join([self.folder.s3_object_prefix, self.name]) else: return self.name def get_url(self, name): """ Return the URL for the given static file :param name: Field name """ if self.type == 's3': return '/'.join( [self.folder.s3_cloudfront_cname, self.s3_key] ) return super(NereidStaticFile, self).get_url(name) def _set_file_binary(self, value): """ Stores the file to amazon s3 :param static_file: Browse record of the static file :param value: The value to set """ if not value: return if self.type == "s3": bucket = self.folder.get_bucket() s3key = key.Key(bucket) s3key.key = self.s3_key return s3key.set_contents_from_string(value[:]) return super(NereidStaticFile, self)._set_file_binary(value) def get_file_binary(self, name): ''' Getter for the binary_file field. This fetches the file from the Amazon s3 :param name: Field name :return: File buffer ''' if self.type == "s3": bucket = self.folder.get_bucket() s3key = key.Key(bucket) s3key.key = self.s3_key return buffer(s3key.get_contents_as_string()) return super(NereidStaticFile, self).get_file_binary(name) def get_file_path(self, name): """ Returns path for given static file :param static_file: Browse record of the static file """ if self.type == "s3": return '/'.join( [self.folder.s3_cloudfront_cname, self.s3_key] ) return super(NereidStaticFile, self).get_file_path(name) @fields.depends('type') def on_change_type(self): """ Changes the value of functional field when type is changed :return: Updated value of functional field """ return { 'is_s3_bucket': self.type == 's3' } def get_is_s3_bucket(self, name): """ Gets value of s3_use_bucket of folder :param name: Field name :return: value of field """ return bool(self.folder.s3_use_bucket) def check_use_s3_bucket(self): """ Checks if type is S3 then folder must have use_s3_bucket """ if self.type == "s3" and not self.folder.s3_use_bucket: return self.raise_user_error('s3_bucket_required') @classmethod def validate(cls, records): """ Checks if use_s3_bucket is True for static file with type s3 :param records: List of active records """ super(NereidStaticFile, cls).validate(records) for record in records: record.check_use_s3_bucket() @classmethod def __setup__(cls): super(NereidStaticFile, cls).__setup__() s3 = ('s3', 'S3') if s3 not in cls.type.selection: cls.type.selection.append(s3) cls.folder.domain = [('s3_use_bucket', '=', Eval('is_s3_bucket'))] cls.folder.depends.append('is_s3_bucket') cls._error_messages.update({ "s3_bucket_required": "Folder must have s3 bucket if type is 'S3'", })
fdbaeb9fee5af1fbf724bc5c493f284d2f3127f6
[ "Python" ]
1
Python
PritishC/trytond-nereid-s3
d5d30099857113594858cef0b6973c7e0c157da3
24b33bcf0ebd9f9659583638a10ae3caa191ee0c
refs/heads/master
<file_sep>#include <ctime> #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include <string> static bool value_in_v( const std::vector<std::string>& rv_s_check, const std::string& rs_value) { bool res = (std::find(std::begin(rv_s_check), std::end(rv_s_check), rs_value) != std::end(rv_s_check)); return res; } int main(int ac, char** av) { if( ac != 4 && ac != 2 ) { std::cerr << "-------------" << "\n" << "USAGE: \n\n./work (start | [end] [Category] [Item])\n" << "\n" << "-------------" << std::endl; return 1; } char ca_dt[50]; std::time_t result = std::time(nullptr); std::strftime(ca_dt, sizeof(ca_dt), "%d.%m.%Y %H:%M:%S", std::localtime(&result)); std::ofstream dataTable; dataTable.open("./tables/Time", std::ios_base::app | std::ios_base::in ); std::vector<std::string> v_options (av, av+ac); if(value_in_v(v_options, "start")) { dataTable << ca_dt << "\t"; } else if(value_in_v(v_options, "end")) { dataTable << ca_dt << "\tSS17\t" << av[ac-2] << "\t" << av[ac-1] << "\n"; } dataTable.close(); return 0; } <file_sep>* Script reads data from google spreadsheets and local data tables ( cols separated by `\t` ) and creates different plots to visualize the read-in data. * Pdf file in this repo showed plots for _random, uniformly_ distributed data. In order to get _real_ plots connect your google (spreadsheet) account and adjust the `R` script. This repo currently contains my personal data. ---- * _Todo_: Currently, I do not have enough data to apply a monthly rolling average, thus ASAP as I do have enough data, set `width=31` in `rollapply(.., width,...)`. * _Todo/Idea_: Add GUI (_Qt_?) to read in data (?) ---- Mainly based on [Finance Spending](https://github.com/daniel-wells/spending-habits/blob/master/Finance.Rmd) Install instruction for `R` on `Ubuntu Xenail Xerus 16.04` [here](https://www.r-bloggers.com/how-to-install-r-on-linux-ubuntu-16-04-xenial-xerus/) <file_sep>#include <ctime> #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include <string> int main(int ac, char** av) { if( ac != 4 && ac != 1 ) { std::cerr << "-------------" << "\n" << "USAGE: \n\n./sleep [TimeStart] [TimeWakeUp] [Rating]\n" << "\n" << "-------------" << std::endl; return 1; } char ca_dt[50]; std::time_t result = std::time(nullptr); std::strftime(ca_dt, sizeof(ca_dt), "%d.%m.%Y", std::localtime(&result)); std::ofstream dataTable; dataTable.open( "./tables/Sleep", std::ios_base::app | std::ios_base::in ); if( ac == 1 ) { using namespace std; std::string input; cout << "TimeStart[%H:%M]: "; cin >> input; dataTable << ca_dt << " " << input << ":00"; cout << "TimeWakeup[%H:%M]: "; cin >> input; dataTable << "\t" << ca_dt << " " << input << ":00"; dataTable << "\tSS17"; cout << "Rating: "; cin >> input; dataTable << "\t" << input << "\n"; } else { dataTable << ca_dt << " " << av[ac-3] << ":00" << "\t" << ca_dt << " " << av[ac-2] << ":00" << "\tSS17" << "\t" << av[ac-1] << "\n"; } dataTable.close(); return 0; } <file_sep>#include <ctime> #include <fstream> #include <iostream> #include <vector> #include <algorithm> #include <string> int main(int ac, char** av) { if( ac != 6 && ac != 1 ) { std::cerr << "-------------" << "\n" << "USAGE: \n\n./finance [Time] [Category] [Price] [Item] [Vendor]\n" << "\n" << "-------------" << std::endl; return 1; } char ca_dt[50]; std::time_t result = std::time(nullptr); std::strftime(ca_dt, sizeof(ca_dt), "%d.%m.%Y", std::localtime(&result)); std::ofstream dataTable; dataTable.open( "./tables/Finance", std::ios_base::app | std::ios_base::in ); if( ac == 1 ) { using namespace std; std::string input; cout << "Time[%H:%M]: "; cin >> input; dataTable << ca_dt << " " << input << ":00"; cout << "Category: "; cin >> input; dataTable << "\t" << input; cout << "Price: "; cin >> input; dataTable << "\t" << input; cout << "Item: "; cin >> input; dataTable << "\t" << input; cout << "Vendor: "; cin >> input; dataTable << "\t" << input; dataTable << "\tSS17\n"; } else { dataTable << ca_dt << " " << av[ac-5] << "\t" << av[ac-4] << "\t" << av[ac-3] << "\t" << av[ac-2] << "\t" << av[ac-1] << "\tSS17\n"; } dataTable.close(); return 0; } <file_sep> 1. Working hours and leisure time summed per week 1. Histograms about sleeping time start and end plotted in ggplot 1. facetial bar ggplots about total hours done per lecture and term 1. leisure time categories plotted <file_sep>library(knitr) library(zoo) opts_chunk$set(echo=FALSE, fig.width=10, fig.asp=1/1.5, fig.retina=2, message=FALSE, warning=FALSE) library(data.table, quietly = TRUE) library(ggplot2, quietly=TRUE) library(scales, quietly=TRUE) library(lubridate, quietly=TRUE) library(dplyr, quietly=TRUE) library(scales, quietly=TRUE) library(ggTimeSeries, quietly=TRUE) library(googlesheets, quietly=TRUE) library(chron, quietly=TRUE) # Colours have been chosen according to this table http://sape.inf.usi.ch/quick-reference/ggplot2/colour # Get google spreadsheet # data_gs <- gs_title("TrackingPersonalData") # # # save gs workspaces # data_work <- gs_read(data_gs, ws = "Time") # data_sleep <- gs_read(data_gs, ws = "Sleep") # data_finance <- gs_read(data_gs, ws = "Finance") data_work <- list() data_sleep <- list() data_finance <- list() # Save as data tables WorkDat <- as.data.table(data_work) SleepDat <- as.data.table(data_sleep) FinDat <- as.data.table(data_finance) # read local spreadsheets WorkDat <- rbindlist(list(as.data.table(read.table("tables/Time", sep="\t", header=TRUE)), WorkDat), use.name=TRUE) FinDat <- rbindlist(list(as.data.table(read.table("tables/Finance", sep="\t", header=TRUE)), FinDat), use.name=TRUE) SleepDat <- rbindlist(list(as.data.table(read.table("tables/Sleep", sep="\t", header=TRUE)), SleepDat), use.name=TRUE) # Sample data for test purposes only # dtData = data.table( Date = seq(as.Date("1/01/2014", "%d/%m/%Y"), # as.Date("31/12/2015", "%d/%m/%Y"), # "days" # ), # Term = as.factor(c("SS2017")), # Duration = runif(730, min=0, max=16 ), # Category = as.factor(c("ML", "MVG", "Robotics", "Cognitiv Systems", "Vision", "Work")) # ) # dtData_2 = data.table( Date = seq(as.Date("1/01/2014", "%d/%m/%Y"), # as.Date("31/12/2015", "%d/%m/%Y"), # "days" # ), # Term = as.factor(c("SS2017")), # Duration = runif(730, min=4, max=12 ) # ) # Preprocess downloaded data tables Data = list(SleepDat=SleepDat, WorkDat=WorkDat) Data <- lapply(Data, function(df) { # preprocessing data and times df_s <- as.data.table(strsplit(as.character(df[, StartDate]), ' ') ) df_e <- as.data.table(strsplit(as.character(df[, EndDate]), ' ') ) times_e <- as.POSIXct(substr(as.character(df_e[2, ]), 0, 7), format='%H:%M:%S') times_s <- as.POSIXct(substr(as.character(df_s[2, ]), 0, 7), format='%H:%M:%S') # duration of the activity { res <- times_e - times_s ; res <- as.numeric(res) } # get duration right for dates / durations over two days ( -> sleep) for( i in seq(from=1, to=length(res), by=1)) { if( res[i] < 0 ) { res[i] <- 24 - abs(res[i]) } } # start date of the activity always "day of wake-up" dates <- dmy(df_e[1, ]) # reformat the columns of the data table invisible(df[, Term := as.factor(Term)]) invisible(df[, Duration := res ]) invisible(df[, Date := dmy(df_s[1,]) ]) # Category is contained in the Time Workspace if("Category" %in% df ) { invisible(df[, Category := as.factor(Category)]) } }) # Prep finance Data df <- as.data.table(strsplit(as.character(FinDat[, Date]), ' ') ) invisible(FinDat[, Price := as.numeric(FinDat[,Price])]) invisible(FinDat[, Date := dmy(df[1, ]) ]) invisible(FinDat[, Percentage := Price / sum(Price, na.rm = TRUE)]) invisible(FinDat[, Category := as.factor(Category)]) FinDat_2 <- FinDat # Test data sets # WorkDur_Day <- dtData # SleepDur_Day <- dtData_2 # WorkDur_Summed <- WorkDat # Real Data WorkDur_Day <- WorkDat SleepDur_Day <- SleepDat WorkDur_Summed <- WorkDat ################################################ WORK ################################################ ################ HEATMAP ################ # plot Heatmap of working duration 0-16h # rescale input duration to produce a fitting scale WorkDur_Day <- WorkDur_Day[, .(Duration = sum(Duration, na.rm=TRUE)), by=Date] WorkDur_Day_2 <- WorkDur_Day[, .(Duration = sum(Duration, na.rm=TRUE)), by=Date] WorkDur_Day <- WorkDur_Day[, Duration := rescale_mid(Duration, to=c(0,10), from=c(0,14), mid=8) ] plot_work <- ggplot_calendar_heatmap(WorkDur_Day[!is.na(Date)], 'Date', 'Duration') + scale_fill_gradient2(low="red", mid="green", high="red", midpoint=5, name="Work Duration ", breaks = seq(from=0, to=10, length=5), limits=c(0,10), labels=c("\n0[h]\n", "\n4[h]\n", "\n8[h]\n", "\n12[h]\n", "\n16[h]\n")) + theme(legend.position = "bottom", legend.key.width = unit(4, "cm"), legend.key.height= unit(1, "cm"), legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(hjust=+0, size=30, face="bold"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25), strip.text.x = element_text(size=20)) + labs(title="\nWork Heatmap\n", x="\nMonth\n", y="\nDoW\n") facet_wrap(~Year, ncol = 1) ################ BAR PLOT ################ targeted_max<- 8 avg_work_done <- sum(WorkDur_Day_2[, Duration]) / length(WorkDur_Day_2[, Duration]) avg_work_done_plotable <- sum(WorkDur_Day[, Duration]) / length(WorkDur_Day[, Duration]) latest_work <- WorkDur_Day_2[length(WorkDur_Day_2[, Duration]), Duration] latest_work_plotable <- WorkDur_Day[length(WorkDur_Day[, Duration]), Duration] sub_title <- paste("Overall mean: ", avg_work_done, " Hours\n", "Latest value: ", latest_work, " Hours\n", sep="") plot_work_bar <- ggplot(WorkDur_Day, aes(x = Date, y = Duration)) + geom_bar(aes(fill=Duration), stat="identity", colour="black") + geom_point(aes(x=Date, y=Duration), colour="red", size=3) + geom_smooth(aes(x=Date, y=Duration), colour="red", span= 0.35) + geom_hline(aes(colour="Latest Value", yintercept=latest_work_plotable), size=2, show.legend=TRUE) + geom_hline(aes(colour="Overall Mean", yintercept=avg_work_done_plotable), size=2.5, show.legend=TRUE, linetype="dashed") + scale_color_manual(values=c("red4", "black"), name="") + scale_fill_gradient2(low="red", mid="green", high="red", midpoint=5, name="Work Duration\n", breaks = seq(from=0, to=10, length=5), limits=c(0,10), labels=c("0[h]", "4[h]", "8[h]", "12[h]", "16[h]")) + scale_y_continuous(breaks = seq(from=0, to=10, length=5), labels=c("0[h]", "4[h]", "8[h]", "12[h]", "16[h]")) + theme(legend.position = "right", legend.key.width = unit(1, "cm"), legend.key.height= unit(2, "cm"), legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(subtitle= sub_title, title="\nWork per Day Overview\n", x="\nDate\n", y="\nHours\n") ################ WORK POINT PLOT CATEGORICAL ################ # plot worked hours per day seperately for each category WorkDur_Summed <- WorkDur_Summed [ , .(Duration = sum(Duration, na.rm=TRUE)), by=.(Category, Term, Date)] plot_work_summed <- ggplot(WorkDur_Summed, aes(shape=Term, x = Date, y = Duration, color=Category)) + geom_point(size=8) + geom_smooth(span=0.35) + theme(plot.title=element_text(size=30, face="bold"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25), legend.text=element_text(size=20), legend.title=element_text(size=20), legend.position="bottom", legend.direction="horizontal", strip.text.x = element_text(size=20)) + scale_y_continuous(labels = dollar_format(suffix = "[h]", prefix="")) + scale_color_discrete(name="Lecture") + labs(title="\nAggregation of Time Spent\n", x = "\nDate\n" , y = "\nDuration\n") + facet_wrap(~Category, ncol=2) ################################################ SLEEP ################################################ ################ HEATMAP ################ # plot Heatmap of sleeping duration 0-16h # rescale input duration to produce a fitting scale SleepDur_Day <- SleepDur_Day[, .(Duration = sum(Duration, na.rm=TRUE), Rating), by=Date] SleepDur_Day_2 <- SleepDur_Day[, .(Duration = sum(Duration, na.rm=TRUE), Rating), by=Date] SleepDur_Day <- SleepDur_Day [,Duration := rescale_mid(Duration, to=c(0,10), from=c(0,14), mid=8) ] SleepDur_Day <- SleepDur_Day [,Rating := rescale_mid(Rating, to=c(0,8), from=c(0,10), mid=4) ] plot_sleep <- ggplot_calendar_heatmap(SleepDur_Day [!is.na(Date)], 'Date', 'Duration') + theme(legend.position = "top", legend.key.width = unit(4, "cm")) + scale_fill_gradient2(low="red", mid="blue", high="red", midpoint=5, name="Sleep Duration ", breaks = seq(from=0, to=10, length=5), limits=c(1,9), labels=c("\n0[h]\n", "\n4[h]\n", "\n8[h]\n", "\n12[h]\n", "\n16[h]\n")) + theme(legend.position = "bottom", legend.key.width = unit(4, "cm"), legend.key.height= unit(1, "cm"), legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(hjust=+0, size=30, face="bold"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25), strip.text.x = element_text(size=20)) + labs(title="\nSleep Heatmap\n", x="\nMonth\n", y="\nDoW\n") facet_wrap(~Year, ncol = 1) ################ BAR PLOT ################ latest_sleep <- SleepDur_Day_2[length(SleepDur_Day_2[, Duration]), Duration] latest_sleep_plotable <- SleepDur_Day[length(SleepDur_Day[, Duration]), Duration] sub_title <- paste("Latest value: ", latest_sleep, " Hours\n", sep="") plot_sleep_bar <- ggplot(SleepDur_Day, aes(x = Date, y = Duration)) + geom_bar(aes(fill=Duration), stat="identity", colour="black") + geom_point(aes(x= Date, y= Rating), colour="red", size=3) + geom_smooth(aes(x= Date, y= Rating), colour="red", size=1, span=0.35) + geom_hline(aes(colour="Latest Value", yintercept=latest_sleep_plotable), size=2, show.legend=TRUE) + scale_fill_gradient2(low="red", mid="blue", high="red", midpoint=5, name="Sleep Duration\n", breaks = seq(from=0, to=10, length=5), limits=c(1,9), labels=c("0[h]", "4[h]", "8[h]", "12[h]", "16[h]")) + scale_color_manual(values=c("black"), name="") + scale_y_continuous(breaks = seq(from=0, to=10, length=5), labels=c("0[h]", "4[h]", "8[h]", "12[h]", "16[h]")) + theme(legend.position = "right", legend.key.width = unit(1, "cm"), legend.key.height= unit(2, "cm"), legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(subtitle = sub_title, title="\nSleep per Day Overview\n", x="\nDate\n", y="\nHours\n") ################################################ FINANCE ################################################ ################ BAR PLOT ################ FinDat <- FinDat[, .(Price = sum(Price, na.rm=TRUE)), by=Date] targeted_max <- 550 / 31 # equals 550€ per 31 days avg_money_spend <- sum(FinDat[, Price]) / length(FinDat[, Price]) currency <- c(" Euro\n") sub_title <- paste("Average: ", avg_money_spend, currency, "Targeted Maximum: ", targeted_max, currency, sep="") label_title <- c("\nMoney Spent per Day\n") plot_finance_bar <- ggplot(FinDat, aes(x = Date, y = Price)) + geom_bar(aes(fill=Price), stat="identity") + geom_hline(aes(colour="Target Max.", yintercept=550/31), size=2, show.legend=TRUE, linetype="dashed") + geom_hline(aes(colour="Overall Mean", yintercept=avg_money_spend), size=2, show.legend=TRUE, linetype="dashed") + scale_fill_gradient(name="Money [Euro]\n", low="gold", high="black") + scale_y_continuous(labels = dollar_format(prefix = "Euro "), limits=c(0, max(FinDat[, Price]))) + scale_color_manual(values=c("red","gray51"), name="") + theme(legend.position = "right", legend.key.width = unit(1, "cm"), legend.key.height= unit(2, "cm"), legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(title=label_title, subtitle=sub_title, x="\nDate\n", y="\nMoney\n") ################ FINANCE BY DAY ROLLING ################ setkey(FinDat, Date) FinDat_Padded <- FinDat[J(seq(min(Date, na.rm =TRUE), max(Date, na.rm =TRUE),by=1))] FinDat_Padded[is.na(Price),Price:=0] # the width in rollapply specifies how many days in the past should be considered to build an average value # the avareage value is then applied "rolling" # AIM for one month FinanceByDayRolling <- FinDat_Padded[,.(Date, Daily_Spend=rollapply(Price, 1, mean, align="right", fill=NA))] plot_finance_rolling <- ggplot(FinanceByDayRolling[!is.na(Daily_Spend)], aes(Date, Daily_Spend)) + geom_line(size=2.5, colour="gold") + geom_hline(aes(colour="Target Maximum", yintercept=550/31), size=2, show.legend=TRUE, linetype="dashed") + geom_hline(aes(colour="Overall Mean", yintercept=avg_money_spend), size=2, show.legend=TRUE, linetype="dashed") + geom_point(size=8, colour="goldenrod") + scale_y_continuous(labels = dollar_format(prefix = "Euro "), limits=c(0, max(FinDat[, Price]))) + scale_color_manual(values=c("red","gray51"), name="") + theme(legend.position = "top", legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(x="\nDate\n", y="\nDaily Spent\n") + labs(title="\nMoney Spent per Day (7 Day Rolling Average)\n", subtitle=sub_title) ################ PERCENTAGE PER CATEGORY ################# FinanceByCategory <- FinDat_2[,.(Spend = sum(Percentage, na.rm = T)), by = Category] invisible(FinanceByCategory[, Category := factor(Category, levels=FinanceByCategory[order(Spend)]$Category)]) plot_finance_category <- ggplot(FinanceByCategory, aes(Category, Spend)) + geom_col(fill="lightsteelblue3", stat="identity") + coord_flip() + scale_y_continuous(labels = scales::percent)+ theme(legend.position = "top", legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(title="\nPercentage Spent per Category\n", x="\nCategory\n", y="\nTotal Spend Per Category\n") ################ PERCENTAGE PER VENDOR ###################### FinanceByVendor <- FinDat_2[!is.na(Vendor)][,.(Spend = sum(Percentage, na.rm = TRUE)), by = Vendor] invisible(FinanceByVendor[,Vendor := factor(Vendor, levels=FinanceByVendor[order(Spend)]$Vendor)]) plot_finance_vendor <- ggplot(FinanceByVendor[order(-Spend)][1:8], aes(Vendor,Spend)) + geom_col(fill="lightsteelblue3", stat="identity") + coord_flip() + scale_y_continuous(labels = scales::percent) + theme(legend.position = "top", legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(title="\nPercantage per Vendor\n", x="", y="\nTotal Spend Per Vendor\n") ################ PERCENTAGE BY ITEM ###################### FinanceByItem <- FinDat_2[,.(Spend = sum(Price, na.rm=T),.N), by = Item][order(-N)] invisible(FinanceByItem[,Item := factor(Item, levels=FinanceByItem[order(N)]$Item)]) # Histogram Number of items plot_finance_item <- ggplot(FinanceByItem[order(-N)][1:20], aes(Item,N)) + geom_col(fill="lightsteelblue3", stat="identity") + coord_flip() + theme(legend.position = "top", legend.text=element_text(size=20), legend.title=element_text(size=20), plot.title=element_text(size=30, face="bold"), plot.subtitle=element_text(size=20, colour="gray45"), axis.text.x=element_text(size=20), axis.text.y=element_text(size=20), axis.title.x=element_text(size=25), axis.title.y=element_text(size=25)) + labs(title="\nNumb. of Purchase per Item\n", x="", y="\nTotal Number of Purchases\n") # save in pdf pdf(file="plots/plots.pdf", width = 20, height=10) print(plot_work) print(plot_work_bar) print(plot_sleep) print(plot_sleep_bar) print(plot_finance_rolling) print(plot_finance_bar) print(plot_finance_category) print(plot_finance_item) print(plot_finance_vendor) print(plot_work_summed) dev.off() <file_sep>CXX = g++ CXXFLAGS = --std=c++17 -Wextra -Wall SOURCES = $(wildcard ./src/*.cpp) OBJECTS = $(patsubst %.cpp, %.o, $(SOURCES)) all: build tools build: @mkdir -p bin tools: $(OBJECTS) $(CXX) $(CXXFLAGS) -o $(word 1,$(patsubst %.o, bin/%, $(^F))) $(word 1, $^) $(CXX) $(CXXFLAGS) -o $(word 2,$(patsubst %.o, bin/%, $(^F))) $(word 2, $^) $(CXX) $(CXXFLAGS) -o $(word 3,$(patsubst %.o, bin/%, $(^F))) $(word 3, $^) .%.o : $(SOURCES) $(CXX) $(CXXFLAGS) -c $< -o ./src/$@ .PHONY:plots plots: @Rscript Tracking.R 2>&1 >/dev/null && evince plots/plots.pdf clean: rm -rf $(OBJECTS) bin
7afde0fa7d6be5075d6eb7b7238d8da6b7a1c671
[ "Markdown", "R", "C++", "Makefile" ]
7
C++
SebNag/PersonalDataTracking
ae66507914f7fabc6ee9f4a79dde95dbc8d2db3f
f16f9ae0c331c5c661f4c6e91f64a02014b3219d
refs/heads/master
<repo_name>xiaobaicxy/numpy-least-sqaure-method<file_sep>/main.py # -*- coding: utf-8 -*- """ Created on Tue May 19 09:47:11 2020 numpy实现最小二乘法 @author: 86186 """ import numpy as np import matplotlib.pyplot as plt def loss(w, b, x, y): total_loss = 0.0 differ = w*x + b - y for i in range(len(x)): total_loss += differ[i] ** 2 return total_loss/len(x) #根据公式计算参数w和b def compute_parameters(x, y): numerator = 0.0 #分子 denominator = 0.0 #分母 x_mean = np.mean(x) y_mean = np.mean(y) for i in range(len(x)): numerator += (x[i] - x_mean) * (y[i] - y_mean) denominator += (x[i] - x_mean) ** 2 w = numerator / denominator b = y_mean - w * x_mean return w, b x = np.linspace(1,100,200) #在[1,100]区间里生成均匀分布的200个数字 noise = np.random.normal(loc=0.0, scale=20, size=200)#生成均值为0,标准差为20的正态分布数据(200个) y = 0.8 * x + noise w, b = compute_parameters(x, y) plt.figure() plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #plt处理中文,字体为微软雅黑 y_pred = w * x + b plt.scatter(x, y, c='r') #画散点图 plt.title("x与y的拟合函数") plt.plot(x, y_pred, c='b') #画直线图 plt.xlabel('x') plt.ylabel('y') plt.show() #矩阵求解法 #计算公式params = (X.T dot X)^-1 dot X.T dot Y x = np.array(x) y = np.array(y) x_features = [] for i in range(len(x)): x_features.append(np.array([x[i], 1]).T) #将输入特征加上偏置向并转置成列向量 x_features = np.array(x_features) #[200, 2] xTx = np.dot(x_features.T, x_features) #[2, 2] xTx_inv = np.linalg.inv(xTx) #[2, 2] xTx_inv_xT = np.dot(xTx_inv, x_features.T) params = np.dot(xTx_inv_xT, y) w,b = params[0], params[1] plt.figure() plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #plt处理中文,字体为微软雅黑 y_pred = w * x + b plt.scatter(x, y, c='r') #画散点图 plt.title("x与y的拟合函数") plt.plot(x, y_pred, c='b') #画直线图 plt.xlabel('x') plt.ylabel('y') plt.show()
268a473d3710ea6a5182a5fd27a0aacf2fd00949
[ "Python" ]
1
Python
xiaobaicxy/numpy-least-sqaure-method
7136e1d801d384377527bea59daedbd22c3e88a7
c8692f29d1b7d55957e89efc6521afcc2a3ef123
refs/heads/master
<file_sep>Title: Intuitive Linear Algebra Date: 2016-06-22 Author: <NAME> Rawr[^1]. [^1]: Here is the footnote. <file_sep>Title: Implementing Batch Normalization in Tensorflow Date: 2016-03-29 Author: <NAME> Status: published Summary: Batch normalization is deep learning technique introduced in 2015 that enables the use of higher learning rates, acts as a regularizer and can speed up training by 14 times. In this post, I show how to implement batch normalization in Tensorflow. Batch normalization, as described in the March 2015 [paper](http://arxiv.org/pdf/1502.03167v3.pdf) (the BN2015 paper) by <NAME> and <NAME>, is a simple and effective way to improve the performance of a neural network. In the BN2015 paper, Ioffe and Szegedy show that batch normalization enables the use of higher learning rates, acts as a regularizer and can speed up training by 14 times. In this post, I show how to implement batch normalization in Tensorflow. ### The Problem Batch normalization is intended to solve the following problem: Changes in model parameters during learning change the distributions of the outputs of each hidden layer. This means that later layers need to adapt to these (often noisy) changes during training. ### Batch Normalization in Brief To solve this problem, the BN2015 paper proposes the _batch normalization_ of the input to the activation function of each neuron (e.g., the sigmoid or ReLU function) during training, so that the input across each training batch has a mean of 0 and a variance of 1. For example, applying batch normalization to the activation $\sigma(Wx + b)$ would result in $\sigma(BN(Wx + b))$ where $BN$ is the _batch normalizing transform_. ### The Batch Normalizing Transform To normalize a value across a batch (i.e., to batch normalize the value), we subtract the batch mean, $\mu_B$, and divide the result by the batch standard deviation, $\sqrt{\sigma^2_B + \epsilon}$. Note that a small constant $\epsilon$ is added to the variance in order to avoid dividing by zero. Thus, the initial batch normalizing transform of a given value, $x_i$, is: $$BN_{initial} (x_i) = \frac{x_i - \mu_B}{\sqrt{\sigma^2_B + \epsilon}}$$ Because the batch normalizing transform given above restricts the inputs to the activation function to a prescribed normal distribution, this can limit the representational power of the layer. Therefore, we allow the network to undo the batch normalizing transform by multiplying by a new scale parameter $\gamma$ and adding a new shift parameter $\beta$. $\gamma$ and $\beta$ are learnable parameters. Adding in $\gamma$ and $\beta$ producing the following final batch normalizing transform: $$BN(x_i) = \gamma(\frac{x_i - \mu_B}{\sqrt{\sigma^2_B + \epsilon}}) + \beta$$ ### Implementing Batch Normalization in Tensorflow We will add batch normalization to a basic fully-connected neural network that has three hidden layers of 100 neurons each and show a similar result to Figure 1 (b) and (c) of the BN2015 paper. ```python import numpy as np import tensorflow as tf import load_mnist #Google's MNIST loader, available: https://goo.gl/tjmpXP import matplotlib.pyplot as plt %matplotlib inline mnist = load_mnist.read_data_sets('MNIST_data', one_hot=True) sess = tf.InteractiveSession() ``` ```python #Using randomly predetermined weights so the networks are similarly initialized w1_initial = np.random.normal(size=(784,100)).astype(np.float32) w2_initial = np.random.normal(size=(100,100)).astype(np.float32) w3_initial = np.random.normal(size=(100,100)).astype(np.float32) w4_initial = np.random.normal(size=(100,10)).astype(np.float32) ``` ```python x = tf.placeholder("float", shape=[None, 784]) y_ = tf.placeholder("float", shape=[None, 10]) ``` ```python epsilon = 1e-3 ``` ```python # layer 1 without BN w1 = tf.Variable(w1_initial) b1 = tf.Variable(tf.zeros([100])) z1 = tf.matmul(x,w1)+b1 l1 = tf.nn.sigmoid(z1) ``` Here is the same layer 1 with batch normalization: ```python # layer 1 with BN w1_BN = tf.Variable(w1_initial) # note that pre-batch normalization bias is ommitted. The effect of this bias would be # eliminated when subtracting the batch mean. Instead, the role of teh bias is performed # by the new beta variable. See Section 3.2 of the BN2015 paper. z1_BN = tf.matmul(x,w1_BN) # calculate batch mean and variance batch_mean1, batch_var1 = tf.nn.moments(z1_BN,[0]) # apply the initial batch normalizing transform z1_hat = (z1_BN - batch_mean1) / tf.sqrt(batch_var1 + epsilon) # create two new parameters, scale and beta (shift) scale1 = tf.Variable(tf.ones([100])) beta1 = tf.Variable(tf.zeros([100])) # scale and shift to obtain the final output of the batch normalization # this value is fed into the activation function (here a sigmoid) BN1 = scale1 * z1_hat + beta1 l1_BN = tf.nn.sigmoid(BN1) ``` ```python # layer 2 without BN w2 = tf.Variable(w2_initial) b2 = tf.Variable(tf.zeros([100])) z2 = tf.matmul(l1,w2)+b2 l2 = tf.nn.sigmoid(z2) ``` Note that tensorflow provides a `tf.nn.batch_normalization`, which I apply to layer 2 below. This code does the same thing as the code for layer 1 above. See the documentation [here](https://www.tensorflow.org/versions/master/api_docs/python/nn.html#batch_normalization) and the code [here](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn.py#L639). ```python # layer 2 with BN, using Tensorflows built-in BN function w2_BN = tf.Variable(w2_initial) z2_BN = tf.matmul(l1_BN,w2_BN) batch_mean2, batch_var2 = tf.nn.moments(z2_BN,[0]) scale2 = tf.Variable(tf.ones([100])) beta2 = tf.Variable(tf.zeros([100])) BN2 = tf.nn.batch_normalization(z2_BN,batch_mean2,batch_var2,beta2,scale2,epsilon) l2_BN = tf.nn.sigmoid(BN2) ``` ```python # layer 3 without BN w3 = tf.Variable(w3_initial) b3 = tf.Variable(tf.zeros([100])) z3 = tf.matmul(l2,w3)+b3 l3 = tf.nn.sigmoid(z3) ``` ```python # layer 2 with BN w3_BN = tf.Variable(w3_initial) z3_BN = tf.matmul(l2_BN,w3_BN) batch_mean3, batch_var3 = tf.nn.moments(z3_BN,[0]) z3_hat = (z3_BN - batch_mean3) / tf.sqrt(batch_var3 + epsilon) scale3 = tf.Variable(tf.ones([100])) beta3 = tf.Variable(tf.zeros([100])) BN3 = scale3 * z3_hat + beta3 l3_BN = tf.nn.sigmoid(BN3) ``` ```python w4 = tf.Variable(w4_initial) b4 = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(l3,w4)+b4) w4_BN = tf.Variable(w4_initial) b4_BN = tf.Variable(tf.zeros([10])) y_BN = tf.nn.softmax(tf.matmul(l3_BN,w4_BN)+b4_BN) ``` ```python sess.run(tf.initialize_all_variables()) ``` ```python cross_entropy = -tf.reduce_sum(y_*tf.log(y)) cross_entropy_BN = -tf.reduce_sum(y_*tf.log(y_BN)) ``` ```python train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) train_step_BN = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy_BN) ``` ```python correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) correct_prediction_BN = tf.equal(tf.arg_max(y_BN,1),tf.arg_max(y_,1)) accuracy_BN = tf.reduce_mean(tf.cast(correct_prediction_BN,tf.float32)) ``` ```python zs, BNs, acc, acc_BN = [], [], [], [] for i in range(10000): batch = mnist.train.next_batch(60) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) train_step_BN.run(feed_dict={x: batch[0], y_: batch[1]}) if i % 50 is 0: res = sess.run([accuracy,accuracy_BN,z2,BN2],feed_dict={x: mnist.test.images, y_: mnist.test.labels}) acc.append(res[0]) acc_BN.append(res[1]) zs.append(np.mean(res[2],axis=0)) # record the mean value of z2 over the entire test set BNs.append(np.mean(res[3],axis=0)) # record the mean value of BN2 over the entire test set zs, BNs, acc, acc_BN = np.array(zs), np.array(BNs), np.array(acc), np.array(acc_BN) ``` ### Accuracy/Speed Improvement As seen below, there is a noticeable improvement in the accuracy and speed of training. As shown in figure 2 of the BN2015 paper, this difference can be very significant for certain other network architectures. ```python fig, ax = plt.subplots() ax.plot(range(0,len(acc)*50,50),acc, label='Without BN') ax.plot(range(0,len(acc)*50,50),acc_BN, label='With BN') ax.set_xlabel('Training steps') ax.set_ylabel('Accuracy') ax.set_title('Batch Normalization Accuracy') ax.legend(loc=4) plt.show() ``` ![Effect of batch normalization on training]({filename}/static/images/BN_output_25_0.png) ### Illustration of input to activation functions over time Below is the distribution over time of the inputs to the sigmoid activation function of the first five neurons in the network's second layer. Batch normalization has a visible and significant effect of removing variance/noise in these inputs. As described by Ioffe and Szegedy, this allows the third layer to learn faster and is responsible for the increase in accuracy and learning speed. See Figure 1 and Section 4.1 of the BN2015 paper. ```python fig, axes = plt.subplots(5, 2, figsize=(6,12)) fig.tight_layout() for i, ax in enumerate(axes): ax[0].set_title("Without BN") ax[1].set_title("With BN") ax[0].plot(zs[:,i]) ax[1].plot(BNs[:,i]) ``` ![Effect of batch normalization on inputs to activation functions]({filename}/static/images/BN_output_27_0.png) ### Making predictions with the model As a final note: when putting a batch normalized model into practice, make sure to replace the batch mean and batch variance in each batch normalization step with the mean and variance of the entire training set or population. In this particular model, I did not do this because the entire test set was predicted at once and the test set is large enough such that the mean and variance of the test set are good estimates of the mean and variance of the population. See Section 3.1 of the BN2015 paper. <file_sep>This is my ML/AI blog, which used to be in Hakyll, redone in Pelican. <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = '<NAME>' SITENAME = 'R2RT' SITEURL = 'http://localhost:8000' THEME = "./theme" PATH = 'content' TIMEZONE = 'US/Eastern' DEFAULT_LANG = 'en' #Random settings GITHUB_URL = 'https://github.com/spitis' TYPEKIT_URL = 'https://use.typekit.net/wat7zgx.js' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None #PLUGINS PLUGIN_PATHS = ['pelican-plugins'] PLUGINS = ['pandoc_reader'] PANDOC_ARGS = [ '--mathjax', '--smart', '-t', 'html5', '-s' ] STATIC_PATHS = ['static'] # Blogroll #LINKS = (('Pelican', 'http://getpelican.com/'), # ('Python.org', 'http://python.org/'), # ('Jinja2', 'http://jinja.pocoo.org/'), # ('You can modify those links in your config file', '#'),) # Social widget #SOCIAL = (('You can add links in your config file', '#'), # ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True
394b5cb2a813cdfb57f4d793d2f621fa9487e272
[ "Markdown", "Python" ]
4
Markdown
spitis/r2rt-pelican
676954c6609f77f14411df2cd30f280daee389ba
f10d821dbfc54a8a94875fae3871e7fd9ccbb875
refs/heads/master
<repo_name>gao-li-gong/gao-li-gong-cms<file_sep>/src/components/RichTextEditor/index.js import React from 'react'; import 'braft-editor/dist/index.css'; import BraftEditor from 'braft-editor'; import debounce from 'lodash/debounce'; import styles from './index.less'; import { ContentUtils } from 'braft-utils'; import { Upload, Button, Icon } from 'antd'; class ReachTextEditor extends React.Component { handleChange = debounce(editorState => { const { onChange } = this.props; onChange(editorState.toHTML()); }, 200); constructor(props) { super(props); this.state = { editorState: BraftEditor.createEditorState(null), prevValue: props.value, }; } componentDidMount() { const { value = null } = this.props; const editorState = BraftEditor.createEditorState(value); this.setState({ editorState }); } static getDerivedStateFromProps(props, state) { if (props.value !== state.prevValue) { return { prevValue: props.value, editorState: BraftEditor.createEditorState(props.value), }; } return null; } handleEditorChange = editorState => { this.setState({ editorState }); this.handleChange(editorState); }; beforeUpload = ({ file, fileList }) => { //判断图片是否上传成功 const host = window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1' ? '' : 'http://admin.wildgaoligong.com'; if (file.status === 'uploading') { } //上传成功后的回调 if (file.status === 'done') { this.setState({ editorState: ContentUtils.insertMedias(this.state.editorState, [ { type: 'IMAGE', url: host + file.response, }, ]), }); } }; render() { const { editorState } = this.state; //隐藏原来的上传 // const excludeControls = ['media']; const uploadUrl = '/api/upload/image'; // 添加需要展示的扩展控件 const extendControls = [ { key: 'antd-uploader', type: 'component', component: ( <Upload accept="image/*" action={uploadUrl} showUploadList={false} onChange={this.beforeUpload} headers={{ token: localStorage.getItem('token') }} > <Button className="control-item button upload-button" data-title="插入图片"> <Icon type="picture" theme="filled" /> </Button> </Upload> ), }, ]; return ( <section className={styles.richText}> <BraftEditor value={editorState} onChange={this.handleEditorChange} q extendControls={extendControls} /> </section> ); } } export default ReachTextEditor; <file_sep>/src/pages/Home/Partner.js import React, { PureComponent } from 'react'; import router from 'umi/router'; import { Card, List, Button, Icon, Popconfirm, Avatar } from 'antd'; import { connect } from 'dva'; import styles from './Slider.less'; import Ellipsis from '@/components/Ellipsis'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; const tabList = [ { key: 'partner', tab: '支持单位', }, { key: 'sponsor', tab: '主办方', } ]; @connect(({ partner, loading }) => ({ list: partner, loading: loading.models.list, })) class Partner extends PureComponent { componentDidMount() { const { dispatch } = this.props; dispatch({ type: 'partner/fetch', }); } delete = (id, type) => { const { dispatch } = this.props; dispatch({ type: 'partner/delete', payload: { id: id, type: type }, }); }; toEditPage = param => { if (typeof param === 'object') { router.push(`/home/partner/partner-add`); return; } router.push(`/home/partner/partner-edit/id/${param}`); }; state = { activeTabKey: tabList[0].key, // searchVal: null, // newTag: { // name: '', // type: '物种分类', // backgroundColor: '#000', // }, }; handleTabChange = activeTabKey => { const { dispatch } = this.props; this.setState({ activeTabKey, // searchVal: null, }); switch (activeTabKey) { case 'partner': dispatch({ type: 'partner/fetch', }); break; case 'sponsor': dispatch({ type: 'partner/fetchSponsorList', }); break; default: break; } }; render() { const { list: { list }, loading, } = this.props; const { activeTabKey, searchVal } = this.state; const partners = list.sort((a, b) => b.id - a.id); return ( <PageHeaderWrapper tabList={tabList} tabActiveKey={activeTabKey} onTabChange={this.handleTabChange} > <div className={styles.cardList} tabActiveKey={activeTabKey} onTabChange={this.handleTabChange}> <List rowKey="id" loading={loading} grid={{ gutter: 24, lg: 3, md: 2, sm: 1, xs: 1 }} dataSource={['', ...partners]} renderItem={item => item ? ( <List.Item key={item.id}> <Card hoverable className={styles.card} actions={[ <a onClick={() => this.toEditPage(item.id)}>编辑</a>, <Popconfirm title="确定要删除吗?" onConfirm={() => this.delete(item.id, item.type)}> <a href="javascript:;">删除</a> </Popconfirm>, ]} > <Card.Meta avatar={ <Avatar size="large" shape="circle" src={item.imgUrl ? `${item.imgUrl}` : ''} /> } title={item.description} /> </Card> </List.Item> ) : ( <List.Item> <Card hoverable className={styles.card}> <Button type="dashed" className={styles.partnerButton} onClick={this.toEditPage} > <Icon type="plus" /> 新建伙伴 </Button> </Card> </List.Item> ) } /> </div> </PageHeaderWrapper> ); } } export default Partner; <file_sep>/src/components/RichTextEditor/index copy.js import React from 'react'; import 'braft-editor/dist/index.css'; import BraftEditor from 'braft-editor'; import debounce from 'lodash/debounce'; import styles from './index.less'; import { ContentUtils } from 'braft-utils'; import { Upload, Icon } from 'antd'; class ReachTextEditor extends React.Component { handleChange = debounce(editorState => { const { onChange } = this.props; onChange(editorState.toHTML()); }, 200); constructor(props) { super(props); this.state = { editorState: BraftEditor.createEditorState(null), prevValue: props.value, }; } componentDidMount() { const { value = null } = this.props; const editorState = BraftEditor.createEditorState(value); this.setState({ editorState }); } static getDerivedStateFromProps(props, state) { if (props.value !== state.prevValue) { return { prevValue: props.value, editorState: BraftEditor.createEditorState(props.value), }; } return null; } handleEditorChange = editorState => { this.setState({ editorState }); this.handleChange(editorState); }; beforeUpload = ({ file, fileList }) => { //判断图片是否上传成功 const host = window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1' ? '' : 'http://static.wildgaoligong.com'; if (file.status === 'uploading') { } //上传成功后的回调 if (file.status === 'done') { this.setState({ editorState: ContentUtils.insertMedias(this.state.editorState, [ { type: 'IMAGE', url: host + file.response, }, ]), }); } }; render() { const { editorState } = this.state; //隐藏原来的上传 // const excludeControls = ['media']; const controls = [ 'undo', 'redo', 'separator', 'font-size', 'line-height', 'letter-spacing', 'separator', 'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator', 'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator', 'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator', 'link', 'separator', 'hr', 'separator', 'separator', 'clear', ]; const uploadUrl = '/api/upload/image'; // 添加需要展示的扩展控件 const extendControls = [ { key: 'antd-uploader', type: 'component', component: ( <Upload accept="image/*" action={uploadUrl} showUploadList={false} onChange={this.beforeUpload} > {/* 这里的按钮最好加上type="button",以避免在表单容器中触发表单提交,用Antd的Button组件则无需如此 */} <button type="button" className="control-item button upload-button" data-title="插入图片" > <Icon type="picture" theme="filled" /> </button> </Upload> ), }, ]; return ( <section className={styles.richText}> <BraftEditor value={editorState} onChange={this.handleEditorChange} controls={controls} extendControls={extendControls} /> </section> ); } } export default ReachTextEditor; <file_sep>/src/pages/About-us/index.js import React from 'react'; import { Form, Button, Input, Icon, Tooltip, Card, Spin, message } from 'antd'; import { connect } from 'dva'; import debounce from 'lodash/debounce'; import ImgUPload from '@/components/ImgUpload'; import RichTextEditor from '@/components/RichTextEditor'; const { TextArea } = Input; const FormItem = Form.Item; @Form.create() @connect(({ aboutUs, loading }) => ({ aboutUs, loading, })) export default class AboutUs extends React.Component { state = { imgLeft: '', imgRight: '' }; componentDidMount() { const { dispatch, form } = this.props; dispatch({ type: 'aboutUs/fetch', payload: {}, callback: ({ nameLeft, nameRight, contentLeft, contentRight, logoLeft, logoRight}) => { this.setState({ imgLeft: [logoLeft], imgRight: [logoRight] }); form.setFieldsValue({ nameLeft, nameRight, contentLeft, contentRight, }); } }); } handleChange = (value, key) => { const { dispatch, aboutUs: { aboutUs } } = this.props; dispatch({ type: 'aboutUs/save', payload: { ...aboutUs, [key]: value } }) } handleUploadChange = (file, type) => { switch (type) { case 'left': this.setState({ imgLeft: file }) this.handleChange(file[0], 'logoLeft') break; case 'right': this.setState({ imgRight: file }) this.handleChange(file[0], 'logoRight') break; default: void 0; } } beforeUpload = (file) => { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; } prompt = debounce(e => { const { dispatch, form, aboutUs: { aboutUs }, history } = this.props; const { imgLeft, imgRight } = this.state; // e.preventDefault(); e.persist() form.validateFieldsAndScroll((err, values) => { if(!err) { dispatch({ type: 'aboutUs/update', payload: { ...aboutUs, }, callback: () => { // history.push('/about-us') message.success('保存成功'); window.scrollTo(0, 0); } }); } }) }, 500); getBase64 = (img, callback) => { const reader = new FileReader(); reader.addEventListener('load', () => callback(reader.result)); reader.readAsDataURL(img); } render() { const { aboutUs: { aboutUs }, loading: { global }, form } = this.props; const {imgLeft, imgRight} = this.state; const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 5 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 15 }, md: { span: 15 }, }, }; return ( <Spin spinning={global} delay={500}> <Card title="关于我们"> <Form onSubmit={this.prompt}> <FormItem {...formItemLayout} label={"左标题"}> {form.getFieldDecorator('nameLeft', { rules: [ { required: true, message: '左标题不能为空!', }, ], })(<Input onChange={e => this.handleChange(e.target.value, 'nameLeft')} placeholder="请输入左标题" />) } </FormItem> <FormItem {...formItemLayout} label={"左内容"}> {form.getFieldDecorator('contentLeft', { rules: [ { required: true, message: '左内容不能为空!', }, ], })(<TextArea rows={4} onChange={e => this.handleChange(e.target.value, 'contentLeft')} placeholder="请输入左内容" />) } </FormItem> <FormItem {...formItemLayout} label={"右标题"}> {form.getFieldDecorator('nameRight', { rules: [ { required: true, message: '右标题不能为空!', }, ], })(<Input onChange={e => this.handleChange(e.target.value, 'nameRight')} placeholder="请输入右标题" />) } </FormItem> <FormItem {...formItemLayout} label={"右内容"}> { form.getFieldDecorator('contentRight', { rules: [ { required: true, message: '右内容不能为空!', }, ], })(<TextArea rows={4} onChange={e => this.handleChange(e.target.value, 'contentRight')} placeholder="请输入右内容" />) } </FormItem> <FormItem {...formItemLayout} label={ <span> logoLeft&nbsp; <Tooltip title={`只能上传1张图片`}> <Icon type="question-circle-o" /> </Tooltip> </span> }> {imgLeft && ( <ImgUPload fileList={imgLeft} limit={1} onChange={imgUrl => this.handleUploadChange(imgUrl, 'left')} /> )} </FormItem> <FormItem {...formItemLayout} label={ <span> logoRight&nbsp; <Tooltip title={`只能上传1张图片`}> <Icon type="question-circle-o" /> </Tooltip> </span> }> {imgRight && ( <ImgUPload fileList={imgRight} limit={1} onChange={imgUrl => this.handleUploadChange(imgUrl, 'right')} /> )} </FormItem> <FormItem {...formItemLayout} colon={false} label={<></>}> <Button style={{ marginTop: 16 }} type={'primary'} htmlType="button" onClick={this.prompt}>保存</Button> </FormItem> </Form> </Card> </Spin> ); } }
6da3981fd5f9477d3bd4c552f3132df3d6b42da7
[ "JavaScript" ]
4
JavaScript
gao-li-gong/gao-li-gong-cms
3f163fd58a38412b0adf4ce752d9eecbdc25f7d7
6880e45d7ac0e1b0dc85e6d2f017c4703d9e9efc
refs/heads/main
<repo_name>danieljaeim/LiquidHacks2020<file_sep>/src/components/Box.js // REGULAR IMPORTS import React, { Children } from 'react'; // STYLESHEETS import '../css/Champion.css'; class Box extends React.Component { constructor(props) { super(props) } render() { const {className, children} = this.props; return( <div className={className + ' box'}> {children} </div> ) } } export default Box;<file_sep>/src/containers/Champion.js // REGULAR IMPORTS import React from 'react'; // STYLESHEETS import '../css/Champion.css'; class Champion extends React.Component { constructor(props) { super(props) } render() { const { children } = this.props; return( <div className="champion-container"> <div className="champ-header"> <img className="champ-portrait" src={this.props.icon}></img> <span className="champ-name"> {this.props.name} </span> </div> {children} </div> ) } } export default Champion;<file_sep>/src/containers/Runes.js // REGULAR IMPORTS import React from 'react'; // STYLESHEETS import '../css/Runes.css'; class Runes extends React.Component { constructor(props) { super(props) } render() { return(<></>) } } export default Runes;<file_sep>/src/containers/Searchbar.js import React from 'react'; import '../css/Searchbar.css'; import { Dropdown } from 'semantic-ui-react'; class Searchbar extends React.Component { state = { championOptions: null } componentDidMount = () => { this.setState({ championOptions: this.generateListOfChampNames() }) } searchTextOnChange = e => { this.setState({ searchText: e.target.value }) } returnListOfIcons = () => { const { champdata } = this.props; let retArr = []; for (let key of Object.keys(champdata)) { let obj = { key, icon: champdata[key].icon } retArr.push(obj); } return retArr; } /* RETURNS A LIST OF CHAMPION NAMES FOR THE SEARCHBAR */ generateListOfChampNames = () => { let { champdata } = this.props; let arr = Object.keys(champdata).map(key => { return { key: key, value: key, image: {src: champdata[key].icon}, text: key } }) return arr; } handleDropdownChange = (event, data) => { this.props.addChampionToList(data.value) } render() { const { addChampionToList, generateListOfChampNames } = this.props; const { championOptions } = this.state; return ( <> {/* change this for a working searchbar later */} <div className="champions-modal"> <Dropdown placeholder='Select Champion' onChange={this.handleDropdownChange} fluid search selection options={championOptions} /> </div> </> ); } } export default Searchbar; <file_sep>/src/containers/Items.js // REGULAR IMPORTS import React from 'react'; import { Dropdown } from 'semantic-ui-react'; // STYLESHEETS import '../css/Items.css'; class Items extends React.Component { state = { totalCost: 0 } handleDropdownChange = (event, data) => { this.props.addItemToChampion(this.props.name, data.value) } generateListOfItemNames = () => { let { itemdata } = this.props; let arr = Object.keys(itemdata).map(key => { return { key: key, value: key, image: { src: itemdata[key].icon }, text: itemdata[key].name } }) return arr; } render() { const { items, name } = this.props; const itemOptions = this.generateListOfItemNames(); return ( <> <div className='dropdown-items'> <Dropdown placeholder='Select Items' onChange={this.handleDropdownChange} fluid search selection options={itemOptions} /> </div> {items.map((i, ind) => { return ( <span key={ind} className="itemslot" onClick={_ => console.log('adding item')}> <span className="add-item-option"> {i ? <div className="item-active"> <img className="item-icon" src={i.icon}/> </div> : <div className="item-deactive"> ITEM HERE </div> } </span> </span> ) })} </> ) } } export default Items;<file_sep>/src/containers/Stats.js // REGULAR IMPORTS import React, { useEffect } from 'react'; import { Dropdown, Transition } from 'semantic-ui-react'; import { round } from 'mathjs'; // STYLESHEETS import '../css/Stats.css'; class Stats extends React.Component { state = { levelOptions: null, currentLevel: 1 } images = ["https://i.imgur.com/phYfxhw.png", "https://i.imgur.com/VwNC3Gx.png", "https://i.imgur.com/jbm413s.png" , "https://i.imgur.com/1a2gqd6.png", "https://i.imgur.com/HpHBuzr.png", "https://i.imgur.com/YGLWVBm.png", "https://i.imgur.com/O6G2qo5.png", "https://i.imgur.com/rC7N7BE.png", "https://i.imgur.com/BICPlMn.png", "https://i.imgur.com/4unvtif.png", "https://i.imgur.com/ZHaYb8o.png", "https://i.imgur.com/ZHaYb8o.png", "https://i.imgur.com/xIygZzN.png"]; componentDidMount = () => { this.setState({ levelOptions: this.levels() }) } levels = () => { var arr = [] for (var level = 1; level <= 18; level++) { arr.push({ key: level, value: level, text: "Level: " + level }) } return arr; } handleDropdownChange = (event, data) => { this.props.addChampionToList(this.props.name, data.value) this.setState({ currentLevel: data.value }) } getRoles() { var roles = this.props.roles.join(" ").toLowerCase().split(" "); var newroles = []; for (var role in roles) { newroles.push((roles[role].charAt(0).toUpperCase() + roles[role].slice(1))) } return newroles.join(" "); } render() { const { levelOptions } = this.state; return ( <> <div className="role"> Roles: {this.getRoles()} </div> <div className="level-stat" > <Dropdown placeholder='Level 1' onChange={this.handleDropdownChange} fluid search selection options={levelOptions} /> </div> {Object.keys(this.props.currentStats).map((stat, index) => { if (stat === 'level') return; return ( <div key={stat + this.props.id} className={`${stat} stat`} > <img src={this.images[index]} width="15px" height="15px" style={{ textDecoration: 'capitalize' }} /> {stat}: {round(this.props.currentStats[stat], 2)} </div> ) })} </> ) } } export default Stats;
8b4a60a1226445af55a8d4d7f5ef92bac4d0a432
[ "JavaScript" ]
6
JavaScript
danieljaeim/LiquidHacks2020
971751694c05329b4a1895fec6e44bf6db8fb2b8
3f76e33c67a18336e75cee5c832e0f0be8fea788
refs/heads/master
<repo_name>Mathilda11/BOS-LOG<file_sep>/bos-parent/.svn/pristine/16/16f8fc21fec520e5058a8bd6ec62811d5635ad02.svn-base #Generated by Maven #Fri Apr 20 15:13:12 CST 2018 version=0.0.1-SNAPSHOT groupId=com.itheima artifactId=bos-web <file_sep>/README.md ### BOS物流项目 <file_sep>/bos-parent/bos-dao/src/main/java/com/itheima/bos/dao/IRoleDao.java package com.itheima.bos.dao; import java.util.List; import com.itheima.bos.dao.base.IBaseDao; import com.itheima.bos.domain.Function; import com.itheima.bos.domain.Role; public interface IRoleDao extends IBaseDao<Role> { List<Function> findFunctionByRole(String id); } <file_sep>/bos-parent/bos-web/src/main/java/com/itheima/bos/web/action/RoleAction.java package com.itheima.bos.web.action; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.itheima.bos.domain.Function; import com.itheima.bos.domain.Role; import com.itheima.bos.service.IRoleService; import com.itheima.bos.web.action.base.BaseAction; @Controller @Scope("prototype") public class RoleAction extends BaseAction<Role> { //属性驱动 接受权限的Id private String functionIds; @Autowired private IRoleService service; public void setFunctionIds(String functionIds) { this.functionIds = functionIds; } /** * 添加角色 */ public String add(){ service.save(model,functionIds); return LIST; } /** * 分页查询 * @return */ public String pageQuery(){ service.pageQuery(pageBean); this.java2Json(pageBean, new String[]{"functions","users"}); return NONE; } /** * 查询所有的角色数据 */ public String listajax(){ List<Role> list = service.findAll(); this.java2Json(list, new String[]{"functions","roles"}); return NONE; } /** * 根据id查询对应的角色 */ public String findRole(){ String id = model.getId(); Role role = service.findRoleById(id); this.java2Json(role, new String[]{"users","roles","functions"}); return NONE; } public String edit(){ service.edit(model,functionIds); return LIST; } public String findFunctionByRole(){ List<Function> list = service.findFunctionByRole(model.getId()); this.java2Json(list, new String[]{"roles","children"}); return NONE; } }
428d8f3b2e4193a88fd2e90b3a7a5306524b29ce
[ "Markdown", "Java", "Java Properties" ]
4
Java Properties
Mathilda11/BOS-LOG
9dd19707d7545aaee45bb00018a3950ac02c1d71
f6e99ae83461644ebc3562df1003434db4137431
refs/heads/master
<file_sep># Corporate Princess Carnage ----------------------------- # APIs Used - https://github.com/speps/XInputDotNet <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using XInputDotNetPure; public class MovementController : MonoBehaviour { /** * Player index ID, don't change after the object has started. From 0-3 (0=player 1, 3=player 4) */ public int PlayerID=-1; bool playerIndexSet = false; public bool IsPlayerPlaying; PlayerIndex playerIndex; public float runSpeed; public float jumpForce; GamePadState state; GamePadState prevState; public bool isDead = false; bool leftPressed = false; bool rightPressed = false; bool jumpPressed = false; Rigidbody2D rb; // Use this for initialization void Start () { rb = gameObject.GetComponent<Rigidbody2D>(); rb.freezeRotation = true; if (PlayerID == -1) { Debug.LogAssertion("ERROR: did you forget to assign a character a player (controller) ID?"); } } // Update is called once per frame void Update () { rb.freezeRotation = true; // Find a PlayerIndex, for a single player game // Will find the first controller that is connected ans use it if (!playerIndexSet || !prevState.IsConnected) { for (int i = 0; i < 4; ++i) { PlayerIndex testPlayerIndex = (PlayerIndex)PlayerID; GamePadState testState = GamePad.GetState(testPlayerIndex); if (testState.IsConnected) { //Debug.Log(string.Format("GamePad found {0}", testPlayerIndex)); playerIndex = testPlayerIndex; playerIndexSet = true; } } } prevState = state; state = GamePad.GetState(playerIndex); // Detect if left button was pressed this frame if (prevState.DPad.Left == ButtonState.Released && state.DPad.Left == ButtonState.Pressed) { Debug.Log("Left pressed"); leftPressed = true; //GetComponent<Renderer>().material.color = new Color(Random.value, Random.value, Random.value, 1.0f); } // Detect if left button was released this frame if (prevState.DPad.Left == ButtonState.Pressed && state.DPad.Left == ButtonState.Released) { leftPressed = false; Debug.Log("Left released"); //GetComponent<Renderer>().material.color = new Color(1.0f, 1.0f, 1.0f, 1.0f); } // Detect if left button was pressed this frame if (prevState.DPad.Right == ButtonState.Released && state.DPad.Right == ButtonState.Pressed) { Debug.Log("Right pressed"); rightPressed = true; //GetComponent<Renderer>().material.color = new Color(Random.value, Random.value, Random.value, 1.0f); } // Detect if left button was released this frame if (prevState.DPad.Right == ButtonState.Pressed && state.DPad.Right == ButtonState.Released) { Debug.Log("Right released"); rightPressed = false; //GetComponent<Renderer>().material.color = new Color(1.0f, 1.0f, 1.0f, 1.0f); } //////////////////////////Left and right movement //left: if (!isDead) { if (leftPressed) { rb.AddForce(Vector2.left * runSpeed, ForceMode2D.Impulse); } if (rightPressed) { rb.AddForce(Vector2.right * runSpeed, ForceMode2D.Impulse); } } } }
e93a62a90b3056b68aab7be6a973f1144b14adef
[ "Markdown", "C#" ]
2
Markdown
SCBionicle/GameDevProject
8255479a180ca97008534fd9dbe9929c2177a5c9
61b4130ca83b93d7b7440c217a66d30eb988ca5b
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.crisposs</groupId> <name>ABS API Documentation</name> <artifactId>abs-api-docs</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <url>https://github.com/CrispOSS/abs-api-parent/tree/master/abs-api-docs</url> <parent> <groupId>com.github.crisposs</groupId> <artifactId>abs-api-parent</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.docs.directory>${project.build.directory}/docs</project.docs.directory> <version.asciidoctor>1.5.2</version.asciidoctor> </properties> <build> <resources> <resource> <directory>${project.docs.directory}</directory> </resource> </resources> <plugins> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>${version.asciidoctor}</version> <executions> <execution> <id>output-html</id> <phase>generate-resources</phase> <goals> <goal>process-asciidoc</goal> </goals> <configuration> <sourceDirectory>${basedir}/src/main/docs/asciidoc</sourceDirectory> <outputDirectory>${project.docs.directory}/reference</outputDirectory> <doctype>book</doctype> <backend>html5</backend> <sourceHighlighter>highlightjs</sourceHighlighter> <attributes> <docVersion>${project.version}</docVersion> <doctype>book</doctype> <icons>font</icons> <toc2>true</toc2> <toc-position>right</toc-position> <setanchors>true</setanchors> <numbered>true</numbered> <idprefix>-</idprefix> <idseparator>-</idseparator> </attributes> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> </dependencies> </project> <file_sep>package abs.api.remote.sample; import java.util.Properties; import java.util.function.BiConsumer; import abs.api.Actor; import abs.api.Configuration; import abs.api.Context; import abs.api.Reference; import abs.api.remote.ActorServer; import abs.api.remote.MessageConverter; /** * @author <NAME> */ public class Main2 { public static void main(String[] args) throws Exception { System.setProperty(Configuration.PROPERTY_DEBUG, "true"); System.setProperty(Configuration.PROPERTY_THREAD_MANAGEMENT, "false"); Properties props2 = new Properties(); props2.put("host", "localhost"); props2.put("port", "8888"); Echo e2 = new Echo(2); BiConsumer<Echo, String> messageHandler = (e, s) -> { e2.echo(s); }; ActorServer server2 = new ActorServer(props2); server2.registerParamConverter(Echo.class, MessageConverter.TO_STRING); server2.registerMessageConsumer(Echo.class, messageHandler); Context context = server2.context; Actor a2 = context.newActor("echo-2", e2); e2.send(Reference.from("abs://echo-1@http://localhost:7777"), "a msg from echo-2"); } } <file_sep>package abs.api.remote; import java.io.InputStream; import java.util.function.BiConsumer; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import abs.api.Actor; import abs.api.Context; import abs.api.Envelope; import abs.api.Reference; import abs.api.SimpleEnvelope; /** * @author <NAME> */ @Provider public class ActorResource { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Context context; private final Actor actor; private final Object actorObject; private final MessageConverter converter; private final BiConsumer consumer; public ActorResource(Context context, Actor actor, MessageConverter converter, BiConsumer consumer, Object actorObject) { this.context = context; this.actor = actor; this.converter = converter; this.consumer = consumer; this.actorObject = actorObject; } @Consumes(MediaType.APPLICATION_OCTET_STREAM) @Produces(MediaType.TEXT_PLAIN) @Path("{from}") @PUT public Response send(@PathParam("from") String from, InputStream msg) { try { Reference sender = Reference.decode(from); Object messageParam = convertMessage(msg, converter); logger.debug("Received a message parameter from {} to {}: {}", sender, this.actor, messageParam); abs.api.Response<Object> response = consumeMessage(sender, this.actor, this.actorObject, this.consumer, messageParam, this.context); logger.debug("Remote envelope sent to {} from {}: {}", this.actor.toString(), sender.toString(), response); return Response.ok(response.get(), MediaType.TEXT_PLAIN).build(); } catch (Throwable e) { return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN) .entity(e.toString()).build(); } } protected abs.api.Response<Object> consumeMessage(Reference sender, Actor receiver, Object actorObject, BiConsumer consumer, Object messageParam, Context context) { if (consumer == null) { Envelope e = new SimpleEnvelope(sender, receiver, messageParam); context.router().route(e); return e.response(); } else { Actor senderActor = new Actor() { @Override public Reference self() { return sender; } }; Runnable message = () -> consumer.accept(actorObject, messageParam); abs.api.Response<Object> response = senderActor.send(receiver, message); return response; } } protected Object convertMessage(InputStream in, MessageConverter converter) { if (converter == null) { return MessageConverter.readObject(in); } return converter.apply(in); } } <file_sep>package abs.api; import java.time.Duration; import java.time.Instant; /** * An abstraction for time measurement for an active object such * as {@link Context}. */ public interface Timed { /** * The start of this context. * * @return an instant of time for the start of the context */ default Instant startTime() { return ContextClock.T0; } /** * Now. * * @return the current time */ default Instant now() { return ContextClock.CLOCK.instant(); } /** * The uptime of this timed instance. * * @return a duration between {@link #startTime()} and now. */ default Duration upTime() { return ContextClock.uptime(); } } <file_sep>= ABS Remote API ABS API provides an extension modules to enable using actors in a distributed setting. In a distributed setting, each JVM instance contains a set of actors. The following properties holds when using the remote API: 1. **Location Reference Transparency**: Actors are blind to the location of the reference that they use to communicate with other actors. Either in a local or remote setting, an actor may use an instance of `Reference` to refer to another actor. The referred actor may be local or remote and this is transparent for the calling actor. 2. **Communication Transparency**: Actors send and receive messages. The transport of each message and how it is transferred to the receiver of the message is transparent to the sender of the message. The extension of ABS API provides a transparent way to provide a container of actors that can be accessed through HTTP. The communication of the messages through HTTP is handled by the Remote API implementation and abstracted from the user of the API. In the following, we provide a simple actor `Echo`: [source,java] .Echo.java ---- public class Echo implements Actor, Behavior { private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(getClass()); private final Integer index; public Echo(Integer i) { this.index = i; } @Override public Object respond(Object message) { logger.error("echo#{} --- message: {} --- from: {}", index, message, sender()); send(sender(), "an echo from " + index); return null; } } ---- To demonstrate how this actor can be used with ABS Remote API, we create two separate actor servers: [source,java] .Main1.java ---- public class Main1 { public static void main(String[] args) throws UnknownHostException { Properties props1 = new Properties(); props1.put("host", "localhost"); props1.put("port", "7777"); ActorServer server1 = new ActorServer(props1); Echo e1 = new Echo(1); Actor a1 = server1.context.newActor("echo-1", e1); System.out.println(" === actor: " + a1.name()); } } ---- and also the second actor which is similar: [source,java] .Main2.java ---- public class Main2 { public static void main(String[] args) throws UnknownHostException { Properties props2 = new Properties(); props2.put("host", "localhost"); props2.put("port", "8888"); ActorServer server2 = new ActorServer(props2); Echo e2 = new Echo(2); Actor a2 = server2.context.newActor("echo-2", e2); a2.send(Reference.from("abs://echo-1@http://localhost:7777"), "a msg from echo-2"); } } ---- As the result of running the program, you can follow a trace of remote message. Note that the API for the actors do not change and its part of transparent implementation in the server. A complete source of this example is available at: https://github.com/CrispOSS/abs-api-remote-sample <file_sep># abs-api ABS Actor API in Java 8 is an implementation of [ABS actor modeling][1] language using Java 8 features. This implementation is part of [Envisage][2] project. You can find the latest API documentation at https://envisage.ifi.uio.no:8080/jenkins/job/abs-api/javadoc/ and the latest reference manual at https://envisage.ifi.uio.no:8080/jenkins/job/abs-api-docs/Reference_Manual/ # License and Copyright ``` Copyright 2014 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. ``` [1]: http://abs-models.org/ [2]: http://envisage-project.eu/ <file_sep>package abs.api; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * A router that unifies routing over a collection of routers. */ public class RouterCollection implements Router, Iterable<Router> { private final List<Router> routers; /** * Ctor * * @param routers the routers */ public RouterCollection(Collection<Router> routers) { this.routers = new ArrayList<>(routers); } /** * Ctor * * @param routers the routers */ public RouterCollection(Router... routers) { this.routers = Arrays.asList(routers); } @Override public void route(Envelope envelope) { for (Router router : this.routers) { router.route(envelope); } } @Override public void bind(Context context) { for (Router router : this.routers) { router.bind(context); } } @Override public Iterator<Router> iterator() { return this.routers.iterator(); } } <file_sep>package abs.api.remote; import java.net.URI; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.HttpUrlConnectorProvider; import abs.api.Context; import abs.api.Envelope; import abs.api.Router; /** * @author <NAME> * @since 1.0 */ public class RemoteRouter implements Router { private final ConcurrentMap<URI, WebTarget> targets = new ConcurrentHashMap<>(4096); private final URI uri; private Context context; public RemoteRouter(URI uri) { this.uri = uri; } @Override public void route(Envelope envelope) { URI uri = getRemoteURI(envelope); WebTarget target = getWebTargetClient(envelope, uri); RemoteEnvelope renv = new RemoteEnvelope(envelope, target); renv.send(); } @Override public void bind(Context context) { this.context = context; } protected WebTarget getWebTargetClient(Envelope envelope, URI uri) { WebTarget target = targets.get(uri); if (target != null) { return target; } System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); Integer timeout = Long.valueOf(TimeUnit.MINUTES.toMillis(10)).intValue(); ClientConfig cc = new ClientConfig().property(ClientProperties.READ_TIMEOUT, timeout) .property(ClientProperties.CONNECT_TIMEOUT, timeout) .connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); Client client = ClientBuilder.newClient(cc); target = client.target(uri); targets.put(uri, target); return target; } protected URI getRemoteURI(Envelope envelope) { String name = envelope.to().name().toASCIIString(); int index = name.indexOf('@'); if (index == -1) { return null; } try { return URI.create(name.substring(index + 1)); } catch (Exception e) { throw new RuntimeException(e); } } } <file_sep>package abs.api; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; /** * A sequencer is a thread-safe unique {@link java.lang.Long} * generator. * * @author <NAME> * @since 1.0 */ @FunctionalInterface public interface Sequencer extends Supplier<Long> { /** * Creates a sequencer with starting from a specific value. * * @param start * the starting point for the sequencer * @return an instance of {@link abs.api.Sequencer} */ static Sequencer of(Long start) { return new AtomicSequencer(start); } /** * A sequencer using {@link AtomicLong} as its thread-safe * concurrent storage. */ static class AtomicSequencer implements Sequencer { private final AtomicLong sequence; public AtomicSequencer(long start) { sequence = new AtomicLong(start); } @Override public Long get() { return sequence.incrementAndGet(); } } } <file_sep>package abs.api; /** * A life cycle supports phases of execution in the run time of the * environment. This is a general high-level interface to allow * different abstractions support the same behavior from top-down * design approach. * * @author <NAME> * @since 1.0 */ public interface Lifecycle { /** * Initializes the implementing life cycle. * * @throws Exception * if the implementation decides to interrupt or * escalate the initialization error */ default void initialize() throws Exception { } /** * Starting a life cycle ensures that the implementation is ready * to be used after the completion of this method. * * @throws Exception * if the implementation decides to interrupt or * escalate the problem */ default void start() throws Exception { } /** * After a life cycle is stopped, the implementing object cannot * be used. * * @throws Exception * if stopping has problem and needs to be escalated */ default void stop() throws Exception { } } <file_sep>package abs.api; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** * A dispatch inbox maintains an in-memory mapping of separate inboxes * for each recipient. It delegates posting of an envelope to the proper * inbox and creates them on-the-fly. * * @author <NAME> * @since 1.0 */ public class DispatchInbox extends AbstractInbox { private final ConcurrentMap<Reference, Inbox> inboxes; private final ExecutorService executor; /** * <p> * Constructor for DispatchInbox. * </p> * * @param executor * a {@link java.util.concurrent.ExecutorService} object. */ public DispatchInbox(ExecutorService executor) { this.executor = executor; this.inboxes = new ConcurrentHashMap<>(8192); } @Override public <V> Future<V> post(Envelope envelope, Object receiver) { Inbox inbox = getInbox(envelope.to()); inbox.post(envelope, receiver); return envelope.response(); } /** * <p> * getInbox. * </p> * * @param owner * a {@link abs.api.Reference} object. * @return a {@link abs.api.Inbox} object. */ protected Inbox getInbox(Reference owner) { Inbox inbox = inboxes.get(owner); if (inbox != null) { return inbox; } inbox = new QueueInbox(getExecutor()); inbox.bind(context); inboxes.put(owner, inbox); return inbox; } /** * <p> * Getter for the field <code>executor</code>. * </p> * * @return a {@link java.util.concurrent.ExecutorService} object. */ protected ExecutorService getExecutor() { return executor; } } <file_sep>package abs.api; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; /** * An implementation of {@link Inbox} that uses a dedicated * thread to await on the next message for <i>any</i> object and * then completes its execution and move on to the next. * * @author <NAME> */ class ThreadInbox extends AbstractInbox { private static class TargettedEnvelope { private final Envelope envelope; private final Object target; TargettedEnvelope(Envelope envelope, Object target) { this.envelope = envelope; this.target = target; } } class SelectorThread extends Thread { public SelectorThread() { super("message-queue"); } @Override public void run() { while (true) { try { TargettedEnvelope te = messages.take(); final Envelope envelope = te.envelope; final Object target = te.target; doOpen(envelope, target); final Future<?> f = envelope.response(); f.get(); } catch (ExecutionException e) { // The future already has failed and the caller will // get the exception. Proceed to the next. } catch (InterruptedException e) { // We need to know "who" is the interrupter! try { context.stop(); return; } catch (Exception stoppingException) { // We cannot do anything at this moment. return; } } } } } private final BlockingQueue<TargettedEnvelope> messages; private final ExecutorService executor; /** * Ctor * * @param executor the executor service for the messages */ public ThreadInbox(ExecutorService executor) { this.executor = executor; this.messages = new LinkedBlockingQueue<>(); } @Override protected void open(Opener opener, Envelope envelope, Object receiver) { messages.offer(new TargettedEnvelope(envelope, receiver)); } protected void doOpen(final Envelope envelope, final Object target) { final Opener opener = opener(envelope, target); executor.submit(() -> opener.open(envelope, target)); } } <file_sep>package abs.api; import java.util.concurrent.ExecutorService; import java.util.concurrent.PriorityBlockingQueue; /** * The queue inbox implements the concept of concurrent object (COG) * group messages queue from ABS. Every envelope is sent to the queue * and is processed based on the ordering that is implemented by the * queue executor. * * @see QueueOpener * @author <NAME> * @since 1.0 */ public class QueueInbox extends AbstractInbox { private final QueueOpener opener; /** * <p> * Constructor for QueueInbox. * </p> * * @param executor * a {@link java.util.concurrent.ExecutorService} object. */ public QueueInbox(ExecutorService executor) { this.opener = new QueueOpener(new PriorityBlockingQueue<>(8192), executor); } /** {@inheritDoc} */ @Override protected Opener opener(final Envelope envelope, final Object receiver) { return opener; } } <file_sep>= Getting Started == Development Environment To use ABS API you need to prepare an environment that supports Java features. 1. Install a version of Java 8 from 'OpenJDK releases' <<Java8>>. 2. If you develop on Eclipse, install a milestone version of next eclipse 'Luna' <<EclipseLuna>>. 3. To support Java 8 syntax on eclipse Luna, you need to install a beta version of 'JDK8 support' <<EclipseLunaJava8>>. == Build from source To use the API, you can either download the 'latest build' <<APILastBuild>> or build it from source. To build from source, assuming that Git is available, checkout the source: [source,bash] ---- git clone https://github.com/CrispOSS/abs-api ---- And then, make a build using Maven 3+: [source,bash] ---- mvn clean install ---- == A first example The first example demonstrates how to implement the ``ping-pong'' example using ABS API. Let `IPing` and `IPong` be interfaces that define the interfaces. [source,java] .IPing and IPong interfaces ---- interface IPing { void ping(); } interface IPong { String pong(String msg); } ---- An implementation of either interface can turn into an actor given that it `implements` the interface `abs.api.Actor`: [source,java] .Ping implementation as an actor ---- class Ping implements IPing, abs.api.Actor { public void ping() { // implementation details } } ---- and the same goes for the other: [source,java] .Pong implementation as an actor ---- class Pong implements IPong, abs.api.Actor { public String pong(String msg) { // implementation details } } ---- In a context that an instance of `Ping` can be created using an instance of `Pong`, then the ping actor can send a message to pong an wait for the result: [source,java] .Send a message to an actor and wait for the result ---- // somewhere inside `ping` method of Ping Future<String> result = invoke(pong, "pong", pingMessage); // continues to use String pongMessage = result.get(); ---- The above message is a direct request to call a specific method of interface `IPing` with the provided arguments. A message can also be an *executable* object: [source,java] .Send a message using a lambda expression ---- Future<String> result = send(pong, () -> { return pingMessage; }); String pongMessage = result.get(); ---- An actor may refer to the sender of a message that it has received during an invocation of one of its methods: [source,java] .The notion of the `sender` of a message ---- // inside a method send(sender(), aNewMessage); ---- <file_sep>package abs.api.remote; import java.io.InputStream; import java.io.ObjectInputStream; import java.nio.charset.Charset; import java.util.function.Function; /** * A {@link FunctionalInterface} to sit between the transport * layer of actors and the actors themselves, to translate the * receiving messages to proper types and instances of objects. * * @param <T> the type of the target type to translate to */ @FunctionalInterface public interface MessageConverter<T> extends Function<InputStream, T> { /** * A {@link MessageConverter} from {@link InputStream} to * {@link String} */ MessageConverter<String> TO_STRING = in -> new String(IOUtils.toByteArray(in), Charset.forName("UTF-8")); /** * A {@link MessageConverter} from {@link InputStream} to * {@link Boolean} */ MessageConverter<Boolean> TO_BOOLEAN = in -> Boolean.parseBoolean(TO_STRING.convert(in)); /** * A {@link MessageConverter} from {@link InputStream} to * {@link Long}. */ MessageConverter<Long> TO_LONG = in -> Long.parseLong(TO_STRING.convert(in)); /** * Uses {@link ObjectInputStream} to read the * {@link InputStream} and try to cast the result to type * <code>C</code>. * * @param in the input stream from remote message * @param <C> the expected type of created object * @return an instance of <code>C</code> */ static <C> C readObject(final InputStream in) { MessageConverter<C> mc = is -> IOUtils.readObject(is); return mc.convert(in); } /** * Convert a remote message input stream to target type. * * @param remoteMessage the remote message as an * {@link InputStream} * @return the created instance of type <code>T</code> */ T convert(InputStream remoteMessage); @Override default T apply(InputStream t) { return convert(t); } } <file_sep>package abs.api; import java.util.Objects; /** * An abstraction to represent a message composing of a sender * reference, a recipient reference, the message, the eventual * result of the message as a future value and a unique * sequence. * * @author <NAME> */ public interface Envelope { /** * Provides the sender of the envelope. * * @return the reference who sent the envelope */ Reference from(); /** * Provides the recipient of the envelope. * * @return the reference who should receive the envelope. */ Reference to(); /** * The message that is carried by the envelope. See * {@link abs.api.Actor} about the types of message that can * be sent. * * @return the message of this envelope */ Object message(); /** * Provides the response of the envelope as a future value. * * @return the response of the envelope as a future value. * @param <V> a T object. */ <V> Response<V> response(); /** * Provides a unique sequence that is assigned to this * envelope. * * @return the unique sequence of this envelope */ long sequence(); /** * Checks if this is a message from an actor to itself. * * @return <code>true</code> if {@link #to()} and * {@link #from()} at the same; otherwise * <code>false</code>. */ default boolean isSelfEnvelope() { return Objects.equals(from(), to()); } } <file_sep>/** * An implementation of ABS API using event-based approaches. * * @author <NAME> * @since 1.0 */ package abs.api.event;<file_sep>package abs.api; import java.util.concurrent.Future; /** * An envelope opener should allow a recipient object process an * incoming message from another object and finalize the result of the * message. The message should be opened in a {@link abs.api.Context} * where the object may possibly need to access other information such * as the sender of the message. * * @see Context * @see Inbox * @see Actor#sender() * @author <NAME> * @since 1.0 */ @FunctionalInterface public interface Opener { /** * Opens the envelope, runs a process inside the context of the * target object to prepare the result of the envelope that is * captured at the time the messages was sent. It is highly * recommended that the implementation does not throw an exception * and instead capture an fault into the future result of the * envelope. * * @param envelope * the envelope to be opened * @param target * the recipient object that binds to the reference by * {@link abs.api.Envelope#to()} * @return the eventual result of the message which is already * captured by another actor reference and should complete * or fail the future of the {@link abs.api.Envelope}. * Note that the returned here may not actually be used as * it is already used by using * {@link java.util.concurrent.Future#get()}. * @param <V> * a V object. */ <V> Future<V> open(Envelope envelope, Object target); } <file_sep>package abs.api.remote; import java.net.InetAddress; import java.net.URI; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import javax.ws.rs.core.UriBuilder; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.Jetty; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import abs.api.Actor; import abs.api.Context; import abs.api.Lifecycle; /** * @author <NAME> */ public class ActorServer implements Lifecycle { static { LoggingConfiguration.configure(); } private final Logger logger = LoggerFactory.getLogger(getClass()); private final ConcurrentMap<Class, MessageConverter> paramConverters = new ConcurrentHashMap<>(); private final ConcurrentMap<Class, BiConsumer> messageConsumers = new ConcurrentHashMap<>(); private final String host; private final Integer port; private final URI uri; private final ContextApplication application; private final Server server; public final Context context; public ActorServer(Properties properties) throws Exception { host = properties.getProperty("host", InetAddress.getLocalHost().getCanonicalHostName()); port = Integer.valueOf(properties.getProperty("port", "7777")); uri = UriBuilder.fromUri("http://" + host).port(port).build(); application = new ContextApplication(uri, paramConverters, messageConsumers); ResourceConfig resourceConfig = ResourceConfig.forApplication(application); server = createServer(resourceConfig, uri); context = application.context; logger.info("ABS Actor Context started on: {}", uri); } @Override public void start() throws Exception {} @Override public void stop() throws Exception { new Thread(new Runnable() { @Override public void run() { try { server.stop(); } catch (Exception e) { logger.error("Failed to stop server on {}: {}", uri, e); } } }).start(); } @Override public void initialize() throws Exception {} /** * @param resourceConfig * @param uri * @return * @throws Exception */ protected Server createServer(ResourceConfig resourceConfig, URI uri) throws Exception { logger.debug("Using {}", Jetty.VERSION); ThreadPool pool = new QueuedThreadPool(1024, 16); Server server = new Server(pool); HttpConfiguration http = new HttpConfiguration(); ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(http)); connector.setPort(uri.getPort()); server.setConnectors(new Connector[] {connector}); ServletContextHandler sch = new ServletContextHandler(); ServletContainer sc = new ServletContainer(resourceConfig); sch.setContextPath("/"); sch.addServlet(new ServletHolder(sc), "/*"); server.setHandler(sch); server.start(); return server; } public <A extends Actor, P> void registerParamConverter(Class<A> actorClass, MessageConverter<P> converter) { paramConverters.putIfAbsent(actorClass, converter); } public <A extends Actor, P> void registerMessageConsumer(Class<A> actorClass, BiConsumer<A, P> messageHandler) { messageConsumers.putIfAbsent(actorClass, messageHandler); } public static void main(String[] args) throws Exception { new ActorServer(System.getProperties()); } } <file_sep>package abs.api; /** * A simple implementation of {@link Envelope}. * * @author <NAME> * @since 1.0 */ public class SimpleEnvelope implements Envelope { private static final Sequencer SEQUENCER = Sequencer.of(0L); private final Reference sender; private final Reference receiver; private final Object message; private final Response<Object> future; private final long sequence; /** * <p> * Constructor for SimpleEnvelope. * </p> * * @param sender * a {@link abs.api.Reference} object. * @param receiver * a {@link abs.api.Reference} object. * @param message * a {@link java.lang.Object} object. */ public SimpleEnvelope(Reference sender, Reference receiver, Object message) { this.sender = sender; this.receiver = receiver; this.message = message; this.future = createResponse(); this.sequence = SEQUENCER.get(); } /** {@inheritDoc} */ @Override public final Reference from() { return sender; } /** {@inheritDoc} */ @Override public final Reference to() { return receiver; } /** {@inheritDoc} */ @Override public final Object message() { return message; } /** {@inheritDoc} */ @Override public <V> Response<V> response() { return (Response<V>) future; } /** {@inheritDoc} */ @Override public long sequence() { return sequence; } /** {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder("Envelope("); sb.append("id: ").append(sequence).append(", "); sb.append("from: ").append(sender).append(", "); sb.append("to: ").append(receiver).append(", "); sb.append("message: ").append(messageString(message)).append(", "); sb.append("future: ").append(future); return sb.append(")").toString(); } protected <V> Response<V> createResponse() { return new ContextResponse<V>(); } protected String messageString(Object message) { String simpleName = message.getClass().getSimpleName(); if (simpleName.contains("Lambda")) { return simpleName; } return simpleName + "@" + Integer.toHexString(message.hashCode()); } } <file_sep># ABS API Documentation The latest rendered documentation is available at: https://envisage.ifi.uio.no:8080/jenkins/job/abs-api-docs/Reference_Manual/ <file_sep>package abs.api; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import abs.api.ContextInbox.InboxSweeperThread; import abs.api.LoggingRouter.LoggingThread; import net.openhft.affinity.Affinity; /** * A specialized {@link Thread} for {@link Context} that * {@link #yield()}s if an exception occurs during the run. * * @author <NAME> */ public final class ContextThread extends Thread { private static final Set<Class<? extends Thread>> INTERRUPTIBLE_THREADS = new HashSet<>(Arrays.asList(ContextThread.class, LoggingThread.class, InboxSweeperThread.class, ThreadInterruptWatchdog.class, ForkJoinWorkerThread.class)); /** * Tries to {@link #interrupt()} all the live threads in the * runtime. */ static void shutdown() { final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread t : threads) { try { if (INTERRUPTIBLE_THREADS.contains(t.getClass())) { // Interrupt only the thread types that we know we are // allowed. t.interrupt(); } } catch (Throwable x) { // Ignore } } } private static final int CPUS = Runtime.getRuntime().availableProcessors(); private static final AtomicLong COUNTER = new AtomicLong(1); private static final AtomicInteger CPU_AFFINITY = new AtomicInteger(1); /** * Ctor * * @param target the {@link Runnable} instance * @param isThreadManagementEnabled */ public ContextThread(Runnable target, boolean isThreadManagementEnabled) { super(target, createThreadName()); if (isThreadManagementEnabled) { int cpu = CPU_AFFINITY.get(); Affinity.setAffinity(cpu); CPU_AFFINITY.getAndSet((cpu + 1) % CPUS); } setDaemon(false); } /** * {@inheritDoc} */ @Override public void run() { try { super.run(); } finally { yield(); } } private static String createThreadName() { return "jabs-" + COUNTER.incrementAndGet(); } } <file_sep>package abs.api; import java.util.concurrent.Executor; import java.util.function.Supplier; /** * A context provides a set of interfaces that allows regulating * messages among actor references. The ingredient parts of a * context are: * <ul> * <li>an {@link Router} responsible to route the messages to * their recipients. Routing of a message starts from a method * such as {@link Actor#send(Object, Object)} that delegates to * its bound context. * <li>a {@link Notary} that acts as a registry of actor * references and object in the concurrent system. * <li>possibly a set of {@link Inbox} instances each of which * (or mutually) maintain a place holder to send the messages to * the owning recipients. * <li>at least one {@link Opener} that eventually is expected * to open the sent message and allow the future result to be * used. * </ul> * * <p> * <b>Note</b> that the above ingredients are not expected to be * existent at all times as different implementations of a * context may decide to bypass them. * * @see Router * @see Notary * @see Inbox * @see Opener * * @author <NAME> * @since 1.0 */ public interface Context extends Lifecycle, Executor, Timed { /** * Creates an instance of {@link Actor} with the provided name * and the object that the reference binds to. It is left to * the implementation if to throw an exception on duplicate * situations or not. * * @param name the name of the new actor reference * @param object the binding object for the actor reference * @return the newly created actor reference or possibly an * unchecked exception */ Actor newActor(String name, Object object); /** * Provides the context's router instance. * * @return the router instance that is used by the context */ Router router(); /** * Provides the context's notary instance. * * @return the notary instance that is used by the context */ Notary notary(); /** * Identifies the inbox "related" to the provided reference. * * @param reference the reference for whom the inbox is needed * @return an instance of inbox that is related/assigned to * the reference or {@code null} if there is no such * inbox */ Inbox inbox(Reference reference); /** * Identifies the opener with which the messages for the * recipient reference can be opened. * * @param reference the reference for whom the openener is * needed * @return an instance of envelope opener that can open * messages for the reference. If {@code null} is * returned, it is not known how messages will be * opened for the reference in question. */ Opener opener(Reference reference); /** * Identifies a reference with which a target binding object * is registered in this context. It is a typical * implementation to use {@link Notary} for this purpose but * it can be overriden. * * @param object the target binding object in question * @return a reference instance that is registered for the * object; otherwise, {@code null} if no reference can * be found. */ default Reference reference(Object object) { return notary().get(object); } /** * Resolves an object by a given reference. * * @param <T> the type of the object that is expected to be * registered with the reference * @param reference the reference of the object * @return the object resolved in the context or {@code null} * if not registered. This may also lead to an * exception of {@link ClassCastException} if the * wrong is expected. */ default <T> T object(Reference reference) { return (T) notary().get(reference); } /** * A facility method that allows to send a message to an actor * without being in a context or an actor. The sender of the * message will be {@link Actor#NOBODY} which means that if * the recipient actor uses {@link Actor#sender()}, it leads * an exception because the sender is not known. * * @see Actor#send(Object, Object) * * @param to the recipient actor object * @param message the message * @param <V> the parameter type that defines the result type * of the message * @return the result of the message as a future */ default <V> Response<V> send(Object to, Object message) { return Actor.NOBODY.send(to, message); } /** * Sends a message to a reference with an additional property * that the sender of the message awaits on the response. The * usage of this method when necessary ensures that, for an * object, the object might be awaiting on an arbitrary number * of envelopes. However, it is ensure that only one message * at a time is processed inside the receiver object. * * @see Actor#await(Object, Object) * * @param <V> the type of the future value of the response of * the message * @param to the receiver of the message * @param message the message itself * @return the future value to capture the result of the * message */ default <V> Response<V> await(Object to, Object message) { return Actor.NOBODY.await(to, message); } /** * Sends an await statement using {@link Actor#NOBODY} to the * recipient. * * @see Actor#await(Object, Supplier) * @param to * @param condition * @return */ default Response<Boolean> await(Object to, Supplier<Boolean> condition) { return Actor.NOBODY.await(to, condition); } } <file_sep>package abs.api; /** * A router determines the dispatching of messages to an appropriate * {@link abs.api.Inbox}. A router is a functional interface. * * @see LocalRouter * @see Inbox * @author <NAME> * @since 1.0 */ public interface Router extends Contextual { /** * Ensures that the provided message enveloped is received by an * object that knows how to open it. The object here can be an inbox * or an opener of the envelope and is left to the implementation. * * @param envelope * the envelope that should be routed */ void route(Envelope envelope); } <file_sep>package abs.api.event; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import org.junit.gen5.api.Test; import reactor.core.Environment; import reactor.core.Reactor; import reactor.core.spec.Reactors; import reactor.event.Event; import reactor.event.selector.Selectors; import reactor.function.Consumer; /** * @author <NAME> */ public class ReactorEventSequenceTest { static final int SIZE = 100000; static final Supplier<Long> SEQUENCER = new Supplier<Long>() { private final AtomicLong counter = new AtomicLong(0L); @Override public Long get() { return counter.incrementAndGet(); } }; static class Data { final long id = SEQUENCER.get(); final String data = UUID.randomUUID().toString(); } final LinkedBlockingQueue<Data> actualSequence = new LinkedBlockingQueue<>(); class DataConsumer implements Consumer<Event<Data>> { @Override public void accept(Event<Data> t) { actualSequence.offer(t.getData()); } } @Test public void testSequence() throws Exception { DataConsumer consumer = new DataConsumer(); Environment env = new Environment(); Reactor reactor = Reactors.reactor(env, Environment.RING_BUFFER); reactor.on(Selectors.$("data"), consumer); // Build data final BlockingDeque<Data> dq = new LinkedBlockingDeque<>(); for (int i = 0; i < SIZE; ++i) { Data d = new Data(); if (!dq.isEmpty() && d.id <= dq.peek().id) { throw new IllegalArgumentException("Sequence generation invalid."); } dq.offer(d); } // Dispatch events (agree, this can be improved using another // event consumer/executor service) for (int i = 0; i < 10; ++i) { new Thread(() -> { for (int j = 0; j < SIZE / 10; ++j) { if (!dq.isEmpty()) { reactor.notify("data", Event.wrap(dq.poll())); } } }).start(); } while (actualSequence.size() < SIZE) { // forcibly wait until all data is consumed! } assertTrue(actualSequence.size() == SIZE); List<Data> list = new ArrayList<>(actualSequence); for (int i = 0; i < SIZE; ++i) { if (i < SIZE - 1) { long currentId = list.get(i).id; long nextId = list.get(i + 1).id; if (currentId >= nextId) { fail("Actual processed sequence failed: " + currentId + " >= " + nextId); } } } } } <file_sep># CHANGELOG ## v0.8.8 * [#18](https://github.com/CrispOSS/abs-api-parent/issues/18) Deliver the Maven artifacts compatible with OSGi bundles ## v0.8.7 * [#14](https://github.com/CrispOSS/abs-api-parent/issues/14) Introduce `await` (Boolean await support) * [#16](https://github.com/CrispOSS/abs-api-parent/issues/16) Implement ABS functional layer in ABS API ## v0.8.6 * [#12](https://github.com/CrispOSS/abs-api-parent/issues/12) Ensure graceful shutdown of threads in the context * [#13](https://github.com/CrispOSS/abs-api-parent/issues/13) Provide a way to log of messages among actors in the runtime * [#14](https://github.com/CrispOSS/abs-api-parent/issues/14) Introduce `await` * [#15](https://github.com/CrispOSS/abs-api-parent/issues/15) Introduce an abstraction over plain `Future` <file_sep># ABS API Remote Sample In this sample, there are two main entry points `abs.api.remote.sample.Main1` and `abs.api.remote.sample.Main2`. Both use the class `Echo` as an actor. The sample demonstrates how two instances of the same actor communicate with one another through remote API. <file_sep>package abs.api.remote; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import abs.api.Envelope; import abs.api.Reference; import abs.api.SimpleEnvelope; /** * An implementation of {@link Envelope} to encapsulate * communication with a remote actor. */ class RemoteEnvelope extends SimpleEnvelope implements Envelope { private final Envelope envelope; private final WebTarget target; private Future<Response> response; public RemoteEnvelope(Envelope envelope, WebTarget target) { super(envelope.from(), envelope.to(), envelope.message()); this.envelope = envelope; this.target = target; } @Override public <V> abs.api.Response<V> response() { final abs.api.Response<V> cf = envelope.response(); try { final Response result = this.response.get(30, TimeUnit.SECONDS); Status status = Status.fromStatusCode(result.getStatus()); switch (status) { case OK: return envelope.response(); case BAD_REQUEST: cf.completeExceptionally( new IllegalArgumentException("Invalid message: " + result.readEntity(String.class))); case NOT_FOUND: cf.completeExceptionally(new IllegalArgumentException( "Remote actor not found: " + result.readEntity(String.class))); default: cf.completeExceptionally(new IllegalStateException( "Unknown error: " + status + " : " + result.readEntity(String.class))); } result.close(); } catch (InterruptedException e) { cf.completeExceptionally(e); } catch (ExecutionException e) { cf.completeExceptionally(e); } catch (TimeoutException e) { cf.completeExceptionally(e); } catch (ProcessingException e) { // ignore for closing result response } return envelope.response(); } @Override public long sequence() { return envelope.sequence(); } protected void send() { try { Object msg = envelope.message(); Entity<InputStream> message = Entity.entity( new ByteArrayInputStream(IOUtils.toByteArray(msg)), MediaType.APPLICATION_OCTET_STREAM); String from = Reference.encode(envelope.from()); String to = Reference.encode(envelope.to()); WebTarget path = target.path("actors").path(to).path(from); this.response = path.request().accept(MediaType.TEXT_PLAIN).async().put(message, Response.class); } catch (Throwable e) { ((CompletableFuture<?>) envelope.response()).completeExceptionally(e); } } } <file_sep>package abs.api; /** * An extension of {@link SimpleEnvelope} to present a message * for which the sender object is awaiting for the response * before proceeding its execution. An object might be awaiting * an arbitrary number of envelopes at a given time. An await * envelope does not change any behavior and it is mostly a * marker extension. */ class AwaitEnvelope extends SimpleEnvelope { /** * Ctor * * @param sender the sender {@link Reference} * @param receiver the receiver {@link Reference} * @param message the message to the receiver */ public AwaitEnvelope(Reference sender, Reference receiver, Object message) { super(sender, receiver, message); } @Override protected <V> ContextResponse<V> createResponse() { return new ContextResponse<V>(true); } } <file_sep>package abs.api.docs; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; /** * @author <NAME> * @since 1.0 */ public final class Docs { private Docs() { } public static String getVersion() { try { InputStream in = Docs.class.getClassLoader().getResourceAsStream( "/META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(in); String version = manifest.getMainAttributes().getValue("Implementation-Version"); if (version == null || version.isEmpty()) { return "N/A"; } return version; } catch (IOException e) { } return "N/A"; } } <file_sep>package abs.api; import static com.google.common.truth.Truth.assertThat; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import org.junit.gen5.api.Test; import com.google.common.collect.Lists; import abs.api.Functional.Match; public class FunctionalTest { @Test public void matchInteger() throws Exception { Match<Integer, Boolean> match = Match.of((Integer i) -> i > 0, i -> true) .or(i -> i < 0, i -> false).or(i -> i == 0, i -> null); Optional<Boolean> o0 = match.apply(0); assertThat(o0).isNotNull(); assertThat(o0.isPresent()).isFalse(); Optional<Boolean> o1 = match.apply(1); assertThat(o1).isNotNull(); assertThat(o1.isPresent()).isTrue(); assertThat(o1.get()).isTrue(); Optional<Boolean> o2 = match.apply(-1); assertThat(o2).isNotNull(); assertThat(o2.isPresent()).isTrue(); assertThat(o2.get()).isFalse(); } @Test public void setFromList() throws Exception { List<Long> list = null; Set<Long> result = Functional.set(list); assertThat(result).isNotNull(); assertThat(result).isEmpty(); list = new ArrayList<>(); result = Functional.set(list); assertThat(result).isNotNull(); assertThat(result).isEmpty(); list = Lists.newArrayList(1L, 2L, 3L); result = Functional.set(list); assertThat(result).isNotNull(); assertThat(result).isNotEmpty(); assertThat(result).hasSize(3); assertThat(result).containsAllIn(list); list = Lists.newArrayList(3L, 1L, 2L, 3L); result = Functional.set(list); assertThat(result).isNotNull(); assertThat(result).isNotEmpty(); assertThat(result).hasSize(3); assertThat(result).containsAnyIn(list); } } <file_sep>package abs.api; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.AbstractMap; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * ABS Functional layer as Java 8 API. */ public final class Functional { private static final String ANSI_RESET = "\u001B[0m"; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_RED = "\u001B[31m"; private static final Random RANDOM = new Random(Clock.systemUTC().millis()); /** * A pattern matching abstraction in Java 8. * * @param <X> * @param <Y> */ public static interface Match<X, Y> extends Function<X, Optional<Y>> { static <X, Y> Function<X, Optional<Y>> F(Predicate<X> cond, Function<X, Y> what) { Function<X, Optional<Y>> f = (x) -> cond.test(x) ? Optional.ofNullable(what.apply(x)) : Optional.empty(); return f; } static <X, Y> Match<X, Y> of(Predicate<X> cond, Function<X, Y> what) { Match<X, Y> m = input -> F(cond, what).apply(input); return m; } static <X, Y> Match<X, Y> of(Y origin) { Predicate<X> cond = ignored -> true; Function<X, Y> what = x -> origin; return of(cond, what); } static <X, Y> Match<X, Y> ofNull(Function<X, Y> what) { return of(x -> x == null, what); } static <X, Y> Match<X, Y> equals(X x, Y y) { Predicate<X> cond = input -> Objects.equals(x, input); Function<X, Y> what = ignored -> y; return of(cond, what); } default Match<X, Y> orDefault(Function<X, Y> what) { return or(ignored -> true, what); } default Match<X, Y> orEquals(X x, Y y) { Predicate<X> cond = input -> Objects.equals(x, input); Function<X, Y> what = ignored -> y; return or(cond, what); } default Match<X, Y> or(Predicate<X> cond, Function<X, Y> what) { Match<X, Y> orM = input -> { Optional<Y> thisMatch = apply(input); return thisMatch.isPresent() ? thisMatch : of(cond, what).apply(input); }; return orM; } } /** * An extension over {@link Map.Entry} * * @param <X> * @param <Y> */ public static interface Pair<X, Y> extends Map.Entry<X, Y> { /** * An implementation of {@link Pair} using * {@link SimpleEntry}. * * @param <X> * @param <Y> */ static class SimplePair<X, Y> extends AbstractMap.SimpleEntry<X, Y> implements Pair<X, Y> { private static final long serialVersionUID = 1L; /** * Ctor. * * @param key the first element * @param value the second element */ public SimplePair(X key, Y value) { super(key, value); } } public static <A, B> Pair<A, B> newPair(A a, B b) { return new SimplePair<A, B>(a, b); } default X getFirst() { return getKey(); } default Y getSecond() { return getValue(); } default void setSecond(Y second) { setValue(second); } } // -- Pair Constructor // --- Arithmetic public static <X> X max(X x, X y) { if (x instanceof Comparable == false) { return Objects.equals(x, y) ? x : null; } Comparable<X> cx = (Comparable<X>) x; final int c = cx.compareTo(y); return c >= 0 ? x : y; } public static <X> X min(X x, X y) { X max = max(x, y); return max == null ? null : max == x ? y : x; } public static int random(int bound) { return RANDOM.nextInt(bound); } // --- Logical public static boolean and(final boolean a, final boolean b) { return a && b; } public static boolean not(final boolean a) { return !a; } public static boolean or(final boolean a, final boolean b) { return a || b; } // --- List /** * Same as {@link #emptyList()}. * * @return a new empty {@link List}. * @deprecated Use {@link #emptyList()}. */ public static <E> List<E> EmptyList() { return emptyList(); } public static <E> List<E> Nil() { return emptyList(); } public static <E> List<E> emptyList() { return new LinkedList<>(); } public static <E> List<E> insert(E e, List<E> list) { if (list == null) { list = emptyList(); } return (List<E>) insertCollection(e, list); } /** * Same as {@link #insert(Object, List)} * * @param list the list * @param e the element * @return the updated list * @deprecated Use {@link #insert(Object, List)} */ public static <E> List<E> insertElement(List<E> list, E e) { return (List<E>) insertCollection(e, list); } public static <E> List<E> remove(List<E> list, E e) { return (List<E>) removeCollection(e, list); } public static <E> List<E> list(Set<E> set) { final List<E> list = emptyList(); if (set == null) { return list; } list.addAll(set); return list; } public static <E> List<E> list(E... args) { if (args == null || args.length == 0) { return emptyList(); } List<E> asList = Arrays.asList(args); List<E> result = emptyList(); result.addAll(asList); return result; } public static <E> boolean contains(List<E> list, E e) { return containsCollection(e, list); } public static <E> int size(List<E> list) { return sizeCollection(list); } public static <E> int length(List<E> list) { return size(list); } public static <E> boolean isEmpty(List<E> list) { return isEmptyCollection(list); } /** * Same as {@link #isEmpty(List)} * * @param list the list * @return <code>true</code> if the list is empty; otherwise * <code>false</code> * @deprecated Use {@link #isEmpty(List)} */ public static <E> boolean emptyList(List<E> list) { return isEmptyCollection(list); } public static <E> E get(List<E> list, int index) { if (index >= size(list)) { throw new IllegalArgumentException("Index out of bound: " + index); } return list.get(index); } public static <E> List<E> without(List<E> list, E e) { return remove(list, e); } public static <E> List<E> concatenate(List<E> list1, List<E> list2) { final List<E> result = emptyList(); result.addAll(list1); result.addAll(list2); return result; } public static <E> List<E> appendRight(List<E> list, E e) { return (List<E>) insertCollection(e, list); } public static <E> List<E> reverse(List<E> list) { Collections.reverse(list); return list; } public static <E> List<E> copy(final E value, final int n) { return IntStream.range(0, n).mapToObj(i -> value).collect(Collectors.toList()); } public static <E> List<E> tail(List<E> list) { if (list == null || list.isEmpty()) { return null; } return list.subList(1, list.size()); } public static <E> E head(List<E> list) { if (list == null || list.isEmpty()) { return null; } return list.get(0); } /** * Same as {@link #insert(Object, List)}. * * @param e the element * @param list the list * @return the updated list * @deprecated Please {@link #insert(Object, List)}. */ public static <E> List<E> Cons(E e, List<E> list) { return insert(e, list); } // --- Set /** * Same as {@link #emptySet()}. * * @return a new empty {@link Set} * @deprecated Use {@link #EmptySet()}. */ public static <E> Set<E> EmptySet() { return emptySet(); } public static <E> Set<E> emptySet() { return new HashSet<>(); } public static <E> Set<E> insert(E e, Set<E> set) { if (set == null) { set = emptySet(); } return (Set<E>) insertCollection(e, set); } /** * Same as {@link #insert(Object, Set)} * * @param set the set * @param e the element * @return the updated set * @deprecated Use {@link #insert(Object, Set)} */ public static <E> Set<E> insertElement(Set<E> set, E e) { return (Set<E>) insertCollection(e, set); } public static <E> Set<E> remove(Set<E> set, E e) { return (Set<E>) removeCollection(e, set); } public static <E> Set<E> set(List<E> list) { return set_java(list); } public static <E> boolean contains(E e, Set<E> set) { return containsCollection(e, set); } public static <E> int size(Set<E> set) { return sizeCollection(set); } public static <E> int length(Set<E> set) { return size(set); } public static <E> boolean isEmpty(Set<E> set) { return isEmptyCollection(set); } /** * Same as {@link #isEmpty(Set)} * * @param set the set * @return <code>true</code> if the set is empty; otherwise * <code>false</code> * @deprecated Use {@link #isEmpty(Set)} */ public static <E> boolean emptySet(Set<E> set) { return isEmptyCollection(set); } public static <E> E take(Set<E> set) { return next(set); } public static <E> boolean hasNext(Set<E> set) { return hastNext(set); } public static <E> Set<E> union(Set<E> set1, Set<E> set2) { final Set<E> union = emptySet(); union.addAll(set1); union.addAll(set2); return union; } public static <E> Set<E> intersection(Set<E> set1, Set<E> set2) { final Set<E> inter = emptySet(); inter.addAll(set1); inter.retainAll(set2); return inter; } public static <E> Set<E> difference(Set<E> set1, Set<E> set2) { final Set<E> diff = emptySet(); diff.addAll(set1); diff.removeAll(set2); return diff; } // --- Map /** * Same as {@link #emptyMap()} * * @return a new empty {@link Map} * @deprecated Use {@link #emptyMap()}. */ public static <K, V> Map<K, V> EmptyMap() { return emptyMap(); } public static <K, V> Map<K, V> emptyMap() { return new ConcurrentHashMap<>(); } public static <K, V> Map<K, V> insert(Map<K, V> map, K key, V value) { if (map == null) { map = emptyMap(); } map.put(key, value); return map; } public static <K, V> Map<K, V> insert(Map<K, V> map, Pair<K, V> pair) { return insert(pair, map); } public static <K, V> Map<K, V> insert(Entry<K, V> pair, Map<K, V> map) { return insert(map, pair.getKey(), pair.getValue()); } public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) { return insert(map, key, value); } /** * Creates a new {@link Pair}. * * @param key the first element * @param value the second element * @return an instance of {@link Pair} * @deprecated Try to use {@link #pair(Object, Object)} which * uses standard Java's {@link Entry}. */ public static <K, V> Pair<K, V> Pair(K key, V value) { return Pair.newPair(key, value); } /** * Returns the first element in a {@link Pair}. * * @param pair the pair instance * @return the first element * @deprecated Usage is not recommended. */ public static <K, V> K fst(Entry<K, V> pair) { return pair.getKey(); } /** * Retrieves the second element in a {@link Pair}. * * @param pair the pair instance * @return the second element * @deprecated Usage is not recommended. */ public static <K, V> V snd(Entry<K, V> pair) { return pair.getValue(); } public static <K, V> Map.Entry<K, V> pair(K key, V value) { return new AbstractMap.SimpleEntry<K, V>(key, value); } public static <K, V> Map<K, V> map(List<K> keys, List<V> values) { if (keys == null || values == null || keys.size() != values.size()) { throw new IllegalArgumentException( "Keys and values do not match for map construction: " + keys + " -> " + values); } ConcurrentMap<K, V> map = IntStream.range(0, keys.size()).boxed() .collect(Collectors.toConcurrentMap(index -> keys.get(index), index -> values.get(index))); return map; } public static <K, V> Map<K, V> map(Collection<Entry<K, V>> entries) { return new ArrayList<>(entries).stream().collect( Collectors.toConcurrentMap((Entry<K, V> e) -> e.getKey(), (Entry<K, V> e) -> e.getValue())); } public static <K, V> Map<K, V> removeKey(Map<K, V> map, K key) { map.remove(key); return map; } public static <K, V, C extends Collection<K>> C keys(Map<K, V> map) { return (C) map.keySet(); } public static <K, V> Collection<V> values(Map<K, V> map) { return map.values(); } public static <K, V> Optional<V> lookup(Map<K, V> map, K key) { return Optional.ofNullable(map.get(key)); } public static <K, V> V lookupDefault(Map<K, V> map, K key, V defaultValue) { return lookup(map, key).orElse(defaultValue); } public static <K, V> V lookupUnsafe(Map<K, V> map, K key) { return lookup(map, key).orElse(null); } public static <V> V fromJust(Optional<V> value) { return value.orElse(null); } // --- Strings public static String substr(String s, int beginIndex, int length) { return s.substring(beginIndex, beginIndex + length); } public static int strlen(String s) { return s.length(); } public static String toString(Object o) { return Objects.toString(o, "null"); } public static String concatenate(String s1, String s2) { return new StringBuilder().append(s1).append(s2).toString(); } // --- I/O public static void println(String format, Object... args) { System.out.println(String.format(format, args)); } public static void println(Object o) { System.out.println(o); } public static void print(Object o) { System.out.print(o); } /** * Print a boolean with ANSI color support. This is a specific * method with <code>GREEN</code> and <code>RED</code> color * support on ANSI terminal. Use with caution. * * @param bool the value */ public static void println(final boolean bool) { if (bool) { println("%sTRUE%s", ANSI_GREEN, ANSI_RESET); } else { println("%sFALSE%s", ANSI_RED, ANSI_RESET); } } public static String readln() { return System.console().readLine(); } // --- Time public static Duration duration(long duration, TimeUnit unit) { return Duration.ofMillis(unit.toMillis(duration)); } public static Duration duration(long millis) { return Duration.ofMillis(millis); } public static boolean durationLessThan(Duration d1, Duration d2) { return d1.compareTo(d2) < 0; } public static Duration subtractFromDuration(Duration d, long v) { if (isDurationInfinite(d)) { return d; } Duration d2 = d.minusMillis(v); return d2.isNegative() || d2.isZero() ? d : d2; } public static Duration infinity() { return ChronoUnit.FOREVER.getDuration(); } public static boolean isDurationInfinite(Duration d) { return d == null || infinity().equals(d); } public static long currentms() { return ContextClock.CLOCK.millis(); } public static Instant now() { return ContextClock.CLOCK.instant(); } public static long timeDifference(Instant t1, Instant t2) { return Duration.between(t1, t2).abs().toMillis(); } public static Instant addDuration(Instant t, Duration d) { return t.plus(d); } public static Instant subtractDuration(Instant t, Duration d) { return t.minus(d); } public static Duration lowlevelDeadline(Long millis) { return millis == null || millis <= 0 ? infinity() : duration(millis); } public static Duration deadline(Duration d) { return d; } public static Duration deadline(Long millis) { return lowlevelDeadline(millis); } // --- Internal protected static <E> Collection<E> insertCollection(E e, Collection<E> col) { col.add(e); return col; } protected static <E> Collection<E> removeCollection(E e, Collection<E> col) { col.remove(e); return col; } protected static <E> boolean containsCollection(E e, Collection<E> col) { return col.contains(e); } protected static <E> int sizeCollection(Collection<E> col) { return col == null ? 0 : col.size(); } protected static <E> boolean isEmptyCollection(Collection<E> col) { return col.isEmpty(); } protected static <E> E next(Iterable<E> it) { return it == null || !it.iterator().hasNext() ? null : it.iterator().next(); } protected static <E> boolean hastNext(Iterable<E> it) { return it == null ? false : it.iterator().hasNext(); } protected static <E> Set<E> set_java(List<E> list) { Set<E> set = emptySet(); if (list == null) { return set; } set.addAll(list); return set; } protected static <E> Set<E> set_func(List<E> list) { Match<List<E>, Set<E>> m = Match.ofNull((List<E> ignored) -> (Set<E>) emptySet()) .or(l -> l.isEmpty(), ignored -> emptySet()) .orDefault((List<E> l) -> insert(l.get(0), set_func(l.subList(1, l.size())))); return m.apply(list).get(); } } <file_sep>package abs.api; import java.util.concurrent.Future; /** * An inbox allows a message to be posted to it for its recipient. The * implementation of {@link #post(Envelope, Object)} can vary from * directly opening the envelope or delegating to an instance * {@link abs.api.Opener}. * * @see Opener * @author <NAME> * @since 1.0 */ public interface Inbox extends Contextual { /** * Posts an envelope to the inbox for the receiver object and * captures a future value as the result. Note that the result of * this method may or may not use * {@link abs.api.Envelope#response()}. Moreover, note that it is * highly recommended that this method does not throw an exception * and instead capture any execution problem into the future result. * * @param envelope * the envelope to be posted * @param receiver * the recipient of the envelope * @return a future value capturing the result of eventually opening * the envelop by the receiver * @param <V> * a V object. */ <V> Future<V> post(Envelope envelope, Object receiver); } <file_sep>package abs.api.event.sample; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import abs.api.Actor; import abs.api.Behavior; /** * @author <NAME> */ public class Echo implements Actor, Behavior { private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(getClass()); private final Integer index; public Echo(Integer i) { this.index = i; } @Override public Object respond(Object message) { logger.error("echo#{} --- message: {} --- from: {}", index, message, sender()); send(sender(), "an echo from " + index); return null; } } <file_sep>package abs.api; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; /** * A logging {@link Router} implementation that creates a log of * actor messages in the format * * <pre> * TIME,FROM,TO,MESSAGE_ID * </pre> * * in which <code>MESSAGE_ID</code> is the object hash code of * the message passed. * <p> * The logging can be enabled by system property * {@link #JABS_LOGGING_ENABLED} and the path of the log file * can be configured via {@link #JABS_LOGGING_PATH}. By the * default, if enabled and no path is provided, a log file is * created in the Java Temp directory. */ public class LoggingRouter implements Router { /** * System property to determine if logging is enabled or not. */ public static final String JABS_LOGGING_ENABLED = "jabs.logging.enabled"; /** * The full path to the logging file for jabs */ public static final String JABS_LOGGING_PATH = "jabs.log.path"; static final String DEFAULT_LOG_PATH = System.getProperty("java.io.tmpdir") + "/jabs-log-" + System.currentTimeMillis() + ".log"; /** * When the system started. */ static final Instant TIME_ORIGIN = Instant.now(); static final class LoggingEvent { private final long time; private final String from; private final String to; private final String message; private final String toString; LoggingEvent(String from, String to, String message) { final Instant now = Instant.now(); this.time = now.toEpochMilli(); this.from = from; this.to = to; this.message = message; final long relativeTime = Duration.between(TIME_ORIGIN, now).toMillis(); this.toString = String.join(";", Long.toString(time), Long.toString(relativeTime), this.from, this.to, this.message); } @Override public String toString() { return toString; } } static final class LoggingThread extends Thread { private static final int BUFFER_FLUSH_SIZE = 8 * 1024; private static final long PERIOD = Duration.ofMillis(100).toMillis(); private final AtomicBoolean running = new AtomicBoolean(false); private final BlockingQueue<LoggingEvent> events; private final Path logPath; LoggingThread(BlockingQueue<LoggingEvent> events, Path logPath) { super("jabs-logging"); this.events = events; this.logPath = logPath; } @Override public void run() { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("Cannot run while running is not enabled"); } while (running.get()) { try { Thread.sleep(PERIOD); } catch (InterruptedException e) { // Ignored } flush(); } flush(); } @Override public void interrupt() { running.getAndSet(false); } private void flush() { List<LoggingEvent> buffer = new ArrayList<>(); fillBuffer(buffer, events); if (buffer.isEmpty()) { return; } writeBuffer(buffer, logPath); } private void writeBuffer(List<LoggingEvent> buffer, Path path) { try (BufferedWriter w = Files.newBufferedWriter(path, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { List<String> lines = buffer.stream().map(e -> e.toString()).collect(Collectors.toList()); lines.forEach(line -> { try { w.write(line); w.newLine(); } catch (Exception ignored) { // Ignored } }); } catch (IOException e) { // Ignored } } private void fillBuffer(List<LoggingEvent> buffer, BlockingQueue<LoggingEvent> events) { if (events.size() <= BUFFER_FLUSH_SIZE) { buffer.addAll(events); events.clear(); } else { for (int i = 0; i < BUFFER_FLUSH_SIZE; ++i) { LoggingEvent e = events.poll(); if (e == null) { break; } buffer.add(e); } } } } private final BlockingQueue<LoggingEvent> events = new LinkedBlockingQueue<>(); private final boolean enabled; /** * Ctor. * * @see #LoggingRouter(boolean, String) */ public LoggingRouter() { this(Boolean.getBoolean(JABS_LOGGING_ENABLED), System.getProperty(JABS_LOGGING_PATH, DEFAULT_LOG_PATH)); } /** * Ctor * * @param enabled if the logging is enabled */ LoggingRouter(final boolean enabled) { this(enabled, DEFAULT_LOG_PATH); } /** * Ctor * * @param enabled if the logging is enabled * @param logFilePath the full path to the log file */ public LoggingRouter(final boolean enabled, String logFilePath) { this.enabled = enabled; if (!enabled) { return; } try { LoggingThread lt = new LoggingThread(events, Paths.get(logFilePath)); lt.start(); } catch (Exception e) { // Ignore } } @Override public void route(Envelope envelope) { if (!this.enabled) { return; } LoggingEvent event = create(envelope); events.offer(event); } private LoggingEvent create(Envelope e) { String from = e.from() == null ? "NOBODY" : e.from().simpleName(); String to = e.to().simpleName(); String message = toString(e.message()); return new LoggingEvent(from, to, message); } @Override public void bind(Context context) {} protected String toString(Object o) { if (o == null) { return "null"; } final String hashCode = "@" + Integer.toHexString(o.hashCode()); if (o.toString().contains("Lambda")) { return "Msg" + hashCode; } if (o instanceof Runnable || o instanceof Callable) { return o.getClass().getSimpleName() + hashCode; } return "Msg" + hashCode; } } <file_sep>package abs.api; /** * @author <NAME> * @since 1.0 */ public interface ReferenceFactory { /** * The name space of references. */ String NS = Actor.NS; /** * The default {@link ReferenceFactory}. */ ReferenceFactory DEFAULT = new ReferenceFactory() { @Override public Reference create(String name) { final String uri = name.startsWith(NS) ? name : NS + name; return Reference.from(uri); } }; /** * The factory method. * * @param name * the name with which the reference should be created * @return the created reference */ Reference create(String name); } <file_sep>package abs.api; /** * An envelope context provides a snapshot view of a {@link Context} * based on a single bound {@link Envelope} instance. The main purpose * is to create a design pattern that facilitates provisioning of a * sender actor reference in the period an envelope is being opened by * its recipient. An envelope context is always bound to one instance of * envelope and one instance of context. * * @author <NAME> * @since 1.0 */ public interface EnvelopeContext extends Context { /** * The envelope of this context. * * @return the envelope bound to this context */ Envelope envelope(); /** * The sender of an envelope context naturally is the sender of the * bound envelope. * * @return the sender of the envelope of this context */ default Reference sender() { return envelope().from(); } /** * Creates an instance of {@link EnvelopeContext} with the envelope * and context provided. * * @param envelope * the envelope of the new context * @param context * the bound context * @return an instance of {@link EnvelopeContext} */ static EnvelopeContext of(Envelope envelope, Context context) { return new SimpleEnvelopeContext(envelope, context); } /** * An implementation of {@link EnvelopeContext} that delegates its * behavior to the provided {@link Context} instance. */ static class SimpleEnvelopeContext implements EnvelopeContext { private final Envelope envelope; private final Context context; public SimpleEnvelopeContext(Envelope envelope, Context context) { this.envelope = envelope; this.context = context; } @Override public Envelope envelope() { return envelope; } public Actor newActor(String name, Object object) { return context.newActor(name, object); } public Router router() { return context.router(); } public Notary notary() { return context.notary(); } public Inbox inbox(Reference reference) { return context.inbox(reference); } public Opener opener(Reference reference) { return context.opener(reference); } @Override public void execute(Runnable command) { context.execute(command); } } } <file_sep># ABS Remote API ABS Remote API depends on ABS API and provides access to ABS actors implemented in ABS API in a remote setting. A demo on how to use the remote API is located at: https://github.com/CrispOSS/abs-api-remote-sample <file_sep>package abs.api; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; /** * An implementation of opener that is used by {@link QueueInbox}. * This implementation requires an instance of {@link ExecutorService} * that dispatches the envelopes to be executed when their turn is * resolved. * * @author <NAME> * @since 1.0 */ class QueueOpener extends DefaultOpener { private final BlockingQueue<Runnable> tasks; private final EnvelopeTaskExecutor taskExecutor; private final Runnable onEnvelopeTaskComplete; /** * <p> * Constructor for QueueOpener. * </p> * * @param tasks * a {@link java.util.concurrent.BlockingQueue} object. * @param executor * a {@link java.util.concurrent.ExecutorService} * object. */ public QueueOpener(BlockingQueue<Runnable> tasks, ExecutorService executor) { this.tasks = tasks; this.taskExecutor = new EnvelopeTaskExecutor(tasks, executor); this.onEnvelopeTaskComplete = () -> { taskExecutor.tryExecuteNext(); }; } /** {@inheritDoc} */ @Override protected void executeEnvelopeTask(final Runnable task) { tasks.offer(task); executeNext(); } /** {@inheritDoc} */ @Override protected Runnable createEnvelopeTask(Envelope envelope, Object target) { final Runnable task = super.createEnvelopeTask(envelope, target); final Callable<Object> command = () -> { super.executeEnvelopeTask(task); getOnEnvelopeTaskComplete().run(); return null; }; return new EnvelopeFutureTask(envelope, command); } /** * <p> * executeNext. * </p> */ protected void executeNext() { this.taskExecutor.executeNext(); } /** * <p> * Getter for the field <code>onEnvelopeTaskComplete</code>. * </p> * * @return a {@link java.lang.Runnable} object. */ protected Runnable getOnEnvelopeTaskComplete() { return onEnvelopeTaskComplete; } static class EnvelopeTaskExecutor { private final BlockingQueue<Runnable> tasks; private final ExecutorService executor; private final AtomicBoolean busy = new AtomicBoolean(false); public EnvelopeTaskExecutor(BlockingQueue<Runnable> tasks, ExecutorService executor) { this.tasks = tasks; this.executor = executor; } protected synchronized void tryExecuteNext() { completeCurrent(); executeNext(); } protected synchronized void completeCurrent() { if (!busy.compareAndSet(true, false)) { throw new IllegalStateException("Should have been busy!"); } } protected synchronized void executeNext() { if (!busy.compareAndSet(false, true)) { return; } Runnable task = tasks.poll(); if (task == null) { busy.compareAndSet(true, false); return; } executor.submit(task); } } } <file_sep> [![Build Status](https://img.shields.io/travis/CrispOSS/abs-api-parent.svg?style=flat-square)](https://travis-ci.org/CrispOSS/abs-api-parent) [![Coverage](https://img.shields.io/coveralls/CrispOSS/abs-api-parent.svg?style=flat-square)](https://img.shields.io/coveralls/CrispOSS/abs-api-parent.svg?style=flat-square) [![Maven Central](https://img.shields.io/maven-central/v/com.github.crisposs/abs-api-parent.svg?style=flat-square)](http://search.maven.org/#browse%7C-1892944679) [![Tag](https://img.shields.io/github/tag/CrispOSS/abs-api-parent.svg?style=flat-square)](https://github.com/CrispOSS/abs-api-parent/tags) # ABS API <file_sep>= References The following is a list of references and citations in the manual. [bibliography] - [[[EclipseLuna]]] http://www.eclipse.org/downloads/index-developer.php - [[[EclipseLunaJava8]]] https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_(BETA) - [[[Java8]]] https://jdk8.java.net/download.html - [[[APILastBuild]]] https://envisage.ifi.uio.no:8080/jenkins/job/abs-api/lastSuccessfulBuild/ <file_sep>= ABS API in Java 8 <NAME> <<EMAIL>> {docVersion} include::01.introduction.asciidoc[] include::02.gettingstarted.asciidoc[] include::03.remote.asciidoc[] include::references.asciidoc[] <file_sep>package abs.api.event; import reactor.core.Environment; import reactor.core.Reactor; import reactor.core.spec.Reactors; import reactor.event.Event; import reactor.event.selector.Selector; import reactor.event.selector.Selectors; import reactor.function.Consumer; import abs.api.DefaultOpener; import abs.api.Opener; /** * An {@link Opener} that executes asynchronous messages using an * instance of {@link Reactor}. * * @see Opener * @see Reactor * @see Event * @see Selector * @see Consumer * * @author <NAME> * @since 1.0 */ public class EventOpener extends DefaultOpener { private static final String KEY = "abs-message"; private static final Selector SELECTOR = Selectors.object(KEY); private static final Consumer<Event<Runnable>> CONSUMER = e -> e.getData().run(); private final Reactor reactor; private final Environment env; public EventOpener() { env = new Environment(); reactor = Reactors.reactor(env, Environment.RING_BUFFER); reactor.on(SELECTOR, CONSUMER); } @Override protected void executeEnvelopeTask(Runnable task) { reactor.notify(KEY, Event.wrap(task)); } } <file_sep># abs-api-event An event-driven implementation of ABS API using [reactor][1] and [LMAX Disruptor][2]. [1]: https://github.com/reactor/reactor [2]: https://github.com/LMAX-Exchange/disruptor <file_sep>package abs.api; import static org.junit.gen5.api.Assertions.assertEquals; import static org.junit.gen5.api.Assertions.assertNotNull; import static org.junit.gen5.api.Assertions.assertNull; import static org.junit.gen5.api.Assertions.assertTrue; import static org.junit.gen5.api.Assertions.expectThrows; import java.net.URI; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.gen5.api.BeforeEach; import org.junit.gen5.api.Test; /** * * @author <NAME> * @since 1.0 */ public class DefaultEnvelopeOpenerTest { private Context context; @BeforeEach public void setUp() { this.context = new LocalContext(); } @Test public void testExecuteMethodReference() throws Exception { final Object object = new Object(); final Integer result = object.hashCode(); Reference from = context.newActor("a", new Object()); Reference to = context.newActor("b", object); MethodReference message = MethodReference.of(to, "hashCode"); Envelope e = new SimpleEnvelope(from, to, message); DefaultOpener p = new DefaultOpener(); Future<?> f = p.open(e, object); assertNotNull(f); assertEquals(e.response(), f); assertTrue(f.isDone()); assertEquals(result, f.get()); } @Test public void testExecuteRunnable() throws Exception { Reference from = context.newActor("a", new Object()); Reference to = context.newActor("b", new Object()); Runnable message = to::name; Envelope e = new SimpleEnvelope(from, to, message); Opener p = new DefaultOpener(); Future<?> f = p.open(e, to); assertNotNull(f); assertEquals(f, e.response()); assertTrue(f.isDone()); assertNull(f.get()); } @Test public void testExecuteCallable() throws Exception { Reference from = context.newActor("a", new Object()); Reference to = context.newActor("b", new Object()); Callable<?> message = to::name; Envelope e = new SimpleEnvelope(from, to, message); Opener p = new DefaultOpener(); Future<?> f = p.open(e, to); assertNotNull(f); assertEquals(f, e.response()); assertTrue(f.isDone()); assertEquals(to.name(), f.get()); } @Test public void testExecuteBehavior() throws Exception { Reference from = context.newActor("a", new Object()); Actor to = context.newActor("b", new Object()); BehaviorActor toActor = new BehaviorActor(to); String message = UUID.randomUUID().toString(); Envelope e = new SimpleEnvelope(from, toActor, message); Opener p = new DefaultOpener(); Future<?> f = p.open(e, toActor); assertNotNull(f); assertEquals(f, e.response()); assertTrue(f.isDone()); assertEquals(message, f.get()); } @Test public void testExecuteWithException() throws Exception { Reference from = context.newActor("a", new Object()); Reference to = context.newActor("b", new Object()); final RuntimeException x = new RuntimeException("x"); Runnable message = () -> { throw x; }; Envelope e = new SimpleEnvelope(from, to, message); Opener p = new DefaultOpener(); Future<?> f = p.open(e, to); assertNotNull(f); assertEquals(f, e.response()); assertTrue(f.isDone()); expectThrows(ExecutionException.class, () -> f.get()); } private class BehaviorActor implements Behavior, Actor { private static final long serialVersionUID = 1L; private final Actor ref; public BehaviorActor(Actor ref) { this.ref = ref; } @Override public Object respond(Object message) { return message; } @Override public URI name() { return ref.name(); } @Override public Context context() { return context; } } } <file_sep>package abs.api; import java.net.URI; import java.time.Duration; import java.util.concurrent.Callable; import java.util.function.Predicate; import java.util.function.Supplier; /** * An actor is a reference that exposes a set of methods to send * messages to another actor. There are a number of ways that a message * would have meaning as an executable entity in this implementation. * * <p> * Every actor is registered with an instance of {@link Context}. A * gathers different layers of the actor system to be used by any actor * such as routing or executing messages. * * <p> * This interface in this version exposes methods as {@code ask} which * allows to capture the result of the message into a future value. * However, to have the model of {@code tell} in actor (fire and * forget), simply the result of the message can be ignored. * * @see Reference * @see MethodReference * * @author <NAME> * @since 1.0 */ public interface Actor extends Reference, Comparable<Reference> { /** * The prefix for all actors created in a context. */ String NS = "abs://"; /** * NOBODY refers to any recipient that is not recognized by its * {@link #name()} in the system. */ Actor NOBODY = new Actor() { private static final long serialVersionUID = 6203481166223651274L; private static final String NAME = "NOBODY"; private final URI name = URI.create(NS + NAME); @Override public URI name() { return name; } @Override public String simpleName() { return NAME; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj instanceof Reference == false) { return false; } return name.equals(((Reference) obj).name()); }; @Override public String toString() { return name.toASCIIString(); } @Override public Context context() { return SystemContext.context(); } @Override public Reference self() { Reference ref = reference(this); if (ref == null) { context().newActor(NAME, this); } return reference(this); } }; /** * A default implementation of {@link Reference#name()} that uses * {@link #NOBODY}. * * @implSpec the default implementation returns {@link NOBODY}'s * name * @return the name of this actor */ @Override default URI name() { return NOBODY.name(); } /** * A default implementation of {@link Reference#simpleName()} * that uses {@link #NOBODY}. * * @return the simple name of this actor */ @Override default String simpleName() { return NOBODY.simpleName(); } /** * Provides the context of this actor. By default, it uses the * context from {@link SystemContext} which is expected to be * initialized in the beginning of an application using this API. * * @see SystemContext * @return the context to which this actor is registered with. */ default Context context() { return SystemContext.context(); } /** * Sends a message to a reference. * * @param <V> the type of the future value of the response of * the message * @param to the receiver of the message that can be either * the {@link Reference} to the receiver or the object * itself * @param message the message itself * @return the future value to capture the result of the * message */ default <V> Response<V> send(Object to, Object message) { final Reference from = self(); final Reference toRef = reference(to); final Envelope envelope = new SimpleEnvelope(from, toRef, message); context().execute(() -> context().router().route(envelope)); return envelope.response(); } /** * Sends a message to a reference with an additional property * that the sender of the message awaits on the response. The * usage of this method when necessary ensures that, for an * object, the object might be awaiting on an arbitrary number * of envelopes. However, it is ensured that only one message * at a time is processed inside the receiver object. * * @see #await(Object, Object, Duration) * * @param <V> the type of the future value of the response of * the message * @param to the receiver of the message * @param message the message itself * @return the future value to capture the result of the * message */ default <V> Response<V> await(Object to, Object message) { return await(to, message, null); } /** * Semantics hold similar to that of * {@link #await(Object, Object)}. Additionally, await should * complete within the time boundaries specified by provided * deadline. If await fails with a timeout, then * {@link Response#getException()} holds the timeout * exception. * * @param <V> the type of the future value of the response * @param to the receiver of the message * @param message the message itself * @param deadline the duration within which the response * should complete * @return the response of the message */ default <V> Response<V> await(Object to, Object message, Duration deadline) { final Reference from = self(); final Reference toRef = reference(to); final Envelope envelope = new AwaitEnvelope(from, toRef, message); context().execute(() -> context().router().route(envelope)); envelope.response().await(deadline); return envelope.response(); } /** * Similar to {@link #await(Object, Object)} and different in * the sense that the await property holds on a "boolean" * expression encapsulated as an instance of {@link Supplier}. * Awaits continues until the supplier provides a * <code>true</code> value. * * @param to the receiver of the message * @param condition the supplier of a boolean condition * @return the response of this await over a {@link Boolean} * value */ default Response<Boolean> await(Object to, Supplier<Boolean> condition) { final Predicate<Supplier<Boolean>> predicate = supplier -> { Boolean currentValue = supplier.get(); if (currentValue != null && currentValue) { return true; } return await(to, condition).getValue(); }; final Callable<Boolean> message = () -> predicate.test(condition); final Reference from = self(); final Reference toRef = reference(to); final Envelope envelope = new AwaitEnvelope(from, toRef, message); context().execute(() -> context().router().route(envelope)); context().execute(() -> envelope.response().await(null)); return envelope.response(); } /** * Replies to the {@link #sender()} of this message with * another message. * * @param message the reply message * @param <V> The expected type of the response * @return the response of the reply message */ default <V> Response<V> reply(Object message) { Response<V> response = send(sender(), message); return response; } /** * Provides access to the reference registered for this actor * object. * * @return the reference of this object */ default Reference self() { if (this instanceof ContextActor) { return this; } return reference(this); } /** * Provides the sender of the <i>current</i> message that is being * invoked/processed by the receiver object. * * @see Context * @see ContextActor * @see EnvelopeContext * * @return the sender of the current message or {@link #NOBODY} if * there is no sender for this message */ default Reference senderReference() { try { final Reference ref = self(); if (ref instanceof ContextActor) { ContextActor caref = (ContextActor) ref; Context context = caref.context(); if (context != null || context instanceof EnvelopeContext) { return ((EnvelopeContext) context).sender(); } } if (!NOBODY.equals(this)) { Context context = context(); if (context != null && context instanceof EnvelopeContext) { return ((EnvelopeContext) context).sender(); } } } catch (Exception e) { // Ignore } return NOBODY; } /** * Provides access to the sender object of the current * message. * * @see #senderReference() * @param <T> The expected type of the sender object * @return the sender object of the current processes message * with expected type <code>T</code> */ default <T> T sender() { return object(senderReference()); } /** * Delegates to {@link Context#object(Reference)}. * * @see Context#object(Reference) * * @param <T> * the expected type of the object * @param reference * the reference of the object * @return See {@link Context#object(Reference)} */ default <T> T object(Reference reference) { return context().object(reference); } /** * Delegates to {@link Context#reference(Object)}. * * @see Context#reference(Object) * * @param object * the object to find the reference for * @return the reference of the object or {@code null} */ default Reference reference(Object object) { return context().reference(object); } /** * The implementation is not different from * {@link Reference#compareTo(Reference)}. * * @param o * the reference to compare to * @return the default semantics specified by {@link Comparable} */ @Override default int compareTo(Reference o) { return name().compareTo(o.name()); } } <file_sep># abs-api-event-sample An example on how to use [ABS API Event][1]. [1]: https://github.com/CrispOSS/abs-api-event <file_sep>package abs.api; /** * Awaits until it receives an {@link #interrupt()} through * {@link InterruptedException} or {@link #isInterrupted()}, * then shut downs {@link Context} through * {@link ContextThread#shutdown()}. * * @author <NAME> */ public final class ThreadInterruptWatchdog extends Thread { private final Runnable interruptCallback; /** * Ctor * * @param interruptCallback is executed upon the first receipt * of {@link InterruptedException} or * {@link #isInterrupted()} being {@code false} */ public ThreadInterruptWatchdog(Runnable interruptCallback) { super("interrupt-watchdog-thread"); this.interruptCallback = interruptCallback; start(); } @Override public void run() { while (true) { if (isInterrupted()) { executeInteruptCallback(); yield(); return; } else { try { sleep(32); } catch (InterruptedException e) { executeInteruptCallback(); yield(); return; } } } } protected void executeInteruptCallback() { this.interruptCallback.run(); } } <file_sep>= Introduction ABS Async API is an implementation of ABS models asynchronous message passing using the features available in Java 8. The design and implementation is driven by certain requirements and principles from the scope of ABS models and platform. ABS Async API introduces an independent Java library that can be freely used in any Java 8 compatible code base. The API implementation provides certain interfaces that allows Java objects to interact to one another through a message passing mechanism and process messages in an asynchronous and event-driven approach. The implementation separates *invocation* of messages from *execution* of messages. An invocation of a message to an object assures the delivery of the message to the receiver while execution of a message is the specifics of the message is processed. Such separation increases the extensibility and pluggability of the implementation in each layer. Morever, it evidently influences the performance of message processing and utilization of resources such as underlying Java threads. ABS Async API is designed in such way that is it ready to be used for ABS model code generations. An ABS model can transformed into an implementation language such as Java. As an ABS model may take advantage of asynchronous message passing, the generated code is expected to expose the same semantics. The ABS Async API allows code generators to generate code lines using the API library to implement the asynchronous message passing at the level of Java 8. ABS Async API realizes a one-to-one mapping from ABS asynchronous message passing to a Java 8 implementation. Such mapping provides a base ground to be able to formally reason about and verify the code generated from ABS models on top of such API implementation. <file_sep>package abs.api.remote; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.Collection; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import abs.api.Actor; import abs.api.Context; import abs.api.FactoryLoader; import abs.api.Reference; /** * @author <NAME> * @since 1.0 */ @Provider @Path("actors") public class ContextResource { private final Logger logger = LoggerFactory.getLogger(getClass()); private final Context context; private final URI uri; private final FactoryLoader factoryLoader = new FactoryLoader(); private final Integer maxLocalActors; private final ConcurrentMap<Class, MessageConverter> paramConverters; private final ConcurrentMap<Class, BiConsumer> messageConsumers; public ContextResource(Context context, URI uri, Integer maxLocalActors, ConcurrentMap<Class, MessageConverter> paramConverters, ConcurrentMap<Class, BiConsumer> messageConsumers) { this.context = context; this.uri = uri; this.maxLocalActors = maxLocalActors; this.paramConverters = paramConverters; this.messageConsumers = messageConsumers; } @GET public Response get() { return Response.status(Status.OK).entity(context.notary().size()).build(); } @Path("{to}") public ActorResource to(@PathParam("to") String to) { try { Reference target = Reference.decode(to); Actor actor = (Actor) context.notary().identify(target); Object actorObject = context.notary().get(actor); MessageConverter converter = getParamConverter(actorObject, paramConverters); BiConsumer consumer = getMessageConsumer(actorObject, messageConsumers); return new ActorResource(context, actor, converter, consumer, actorObject); } catch (UnsupportedEncodingException e) { logger.error("No actor found: {}", to); throw new RuntimeException(e); } } protected BiConsumer getMessageConsumer(Object actorObject, ConcurrentMap<Class, BiConsumer> messageConsumers) { BiConsumer consumer = messageConsumers.get(actorObject.getClass()); return consumer; } protected MessageConverter getParamConverter(Object actorObject, ConcurrentMap<Class, MessageConverter> paramConverters) { MessageConverter converter = paramConverters.get(actorObject.getClass()); return converter; } @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @PUT @Path("{name}") public Response create(@PathParam("name") String name, @QueryParam("class") String fqcn, Collection<String> params) { if (context.notary().size() >= maxLocalActors) { return Response.status(Status.NOT_ACCEPTABLE).entity("Maximum local actors reached.").build(); } try { final Object object = factoryLoader.create(fqcn, params.toArray(new String[] {})); final Actor actor = context.newActor(name, object); return Response.status(Status.CREATED).entity(actor.name().toString()).build(); } catch (Exception e) { return Response.status(Status.BAD_REQUEST) .entity(e.getMessage() + (e.getCause() != null ? e.getCause().getMessage() : "")).build(); } } } <file_sep>package abs.api; import java.util.concurrent.Future; /** * An abstract implementation of inbox that uses an instance of * {@link Context} to resolve a proper {@link Opener} for each envelope * and use the opener to open the envelope. * * @see Inbox * @see DispatchInbox * @see AsyncInbox * @see QueueInbox * * @author <NAME> * @since 1.0 */ public class AbstractInbox implements Inbox { protected Context context; /** * <p> * Constructor for AbstractInbox. * </p> */ public AbstractInbox() { } /** {@inheritDoc} */ @Override public <V> Future<V> post(final Envelope envelope, final Object receiver) { final Opener opener = opener(envelope, receiver); onOpen(envelope, opener, receiver); open(opener, envelope, receiver); return envelope.response(); } /** {@inheritDoc} */ @Override public void bind(Context context) { this.context = context; } /** * <p> * onOpen. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param opener * a {@link abs.api.Opener} object. * @param receiver * a {@link java.lang.Object} object. */ protected void onOpen(Envelope envelope, Opener opener, Object receiver) { synchronized (envelope) { Actor ref = (Actor) envelope.to(); if (ref instanceof ContextActor) { ContextActor cref = (ContextActor) ref; cref.bind(EnvelopeContext.of(envelope, context)); } } } /** * <p> * open. * </p> * * @param opener * a {@link abs.api.Opener} object. * @param envelope * a {@link abs.api.Envelope} object. * @param receiver * a {@link java.lang.Object} object. */ protected void open(final Opener opener, final Envelope envelope, final Object receiver) { opener.open(envelope, receiver); } /** * <p> * opener. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param receiver * a {@link java.lang.Object} object. * @return a {@link abs.api.Opener} object. */ protected Opener opener(Envelope envelope, Object receiver) { return context.opener(envelope.to()); } } <file_sep>package abs.api; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Future; /** * An implementation of opener that resolves the message in the * following order * <ul> * <li>if the message is an instance of {@link java.lang.Runnable} * <li>if the message is an instance of * {@link java.util.concurrent.Callable} * <li>if the message is a method invocation encapsulated by an * instance of {@link abs.api.MethodReference} * <li>if the recipient of the message is an instance of * {@link abs.api.Behavior} then opens the envelope by running the * messages inside the recipient object. * </ul> * * @see QueueOpener * * @author <NAME> * @since 1.0 */ public class DefaultOpener implements Opener { private final ConcurrentMap<MethodReference, Method> methodCache = new ConcurrentSkipListMap<>( MethodReference.COMPARATOR); private final Map<Method, MethodHandle> methodHandleCache = new LinkedHashMap<>(1024, 0.75f, true); /** {@inheritDoc} */ @Override public <V> Future<V> open(final Envelope envelope, final Object target) { return execute(envelope, target); } /** * <p> * execute. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param target * a {@link java.lang.Object} object. * @param <V> * a V object. * @return a {@link java.util.concurrent.Future} object. */ protected <V> Response<V> execute(final Envelope envelope, final Object target) { final Response<V> response = envelope.response(); Runnable task = createEnvelopeTask(envelope, target); if (task == null) { response.completeExceptionally(new IllegalArgumentException("Invalid message: " + envelope.message())); } else { try { executeEnvelopeTask(task); } catch (Throwable e) { response.completeExceptionally(e); } } return response; } /** * <p> * executeEnvelopeTask. * </p> * * @param task * a {@link java.lang.Runnable} object. */ protected void executeEnvelopeTask(Runnable task) { task.run(); } /** * <p> * createEnvelopeTask. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param target * a {@link java.lang.Object} object. * @return a {@link java.lang.Runnable} object. */ protected Runnable createEnvelopeTask(final Envelope envelope, final Object target) { final Object msg = envelope.message(); if (msg instanceof Runnable) { return createEnvelopeRunner(envelope); } else if (msg instanceof Callable) { return createEnvelopeRunner(envelope); } else if (target instanceof Behavior) { return fromActorEnvelope(envelope, (Behavior) target); } else if (msg instanceof MethodReference) { return fromMethodReferenceEnvelope(envelope, target); } return null; } /** * <p> * fromCallableEnvelope. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @return a {@link java.lang.Runnable} object. */ protected Runnable createEnvelopeRunner(final Envelope envelope) { return new EnveloperRunner(envelope); } /** * <p> * fromMethodReferenceEnvelope. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param target * a {@link java.lang.Object} object. * @return a {@link java.lang.Runnable} object. */ protected Runnable fromMethodReferenceEnvelope(final Envelope envelope, final Object target) { return () -> { final Response<Object> future = envelope.response(); try { MethodReference method = (MethodReference) envelope.message(); if (target == null) { // A method reference should be executed up a // non-null object reference. future.completeExceptionally(new RuntimeException( "No object can be found with reference: " + method.owner())); return; } MethodHandle handle = createMethodHandle(method, target); handle = handle.bindTo(target); Object result = handle.invokeWithArguments(method.args()); future.complete(result); } catch (Throwable e) { future.completeExceptionally(e); } }; } /** * <p> * fromActorEnvelope. * </p> * * @param envelope * a {@link abs.api.Envelope} object. * @param target * a {@link abs.api.Behavior} object. * @return a {@link java.lang.Runnable} object. */ protected Runnable fromActorEnvelope(final Envelope envelope, final Behavior target) { return () -> { final Response<Object> future = envelope.response(); try { Object result = target.respond(envelope.message()); future.complete(result); } catch (Exception e) { future.completeExceptionally(e); } }; } /** * <p> * createReflectionMethod. * </p> * * @param msg * a {@link abs.api.MethodReference} object. * @param target * a {@link java.lang.Object} object. * @return a {@link java.lang.reflect.Method} object. * @throws java.lang.NoSuchMethodException * if any. */ protected Method createReflectionMethod(final MethodReference msg, final Object target) throws NoSuchMethodException { final Object[] args = msg.args(); final Class<?>[] types; if (args != null) { types = new Class<?>[args.length]; for (int i = 0; i < types.length; ++i) { types[i] = args[i].getClass(); } } else { types = null; } final Class<?> targetClass = target.getClass(); final Method reflectionMethod = targetClass.getMethod(msg.name().toString(), types); return reflectionMethod; } /** * <p> * createMethodHandle. * </p> * * @param msg * a {@link abs.api.MethodReference} object. * @param target * a {@link java.lang.Object} object. * @return a {@link java.lang.invoke.MethodHandle} object. * @throws java.lang.NoSuchMethodException * if any. * @throws java.lang.IllegalAccessException * if any. */ protected MethodHandle createMethodHandle(final MethodReference msg, final Object target) throws NoSuchMethodException, IllegalAccessException { Method method = methodCache.get(msg); if (method == null) { method = createReflectionMethod(msg, target); methodCache.putIfAbsent(msg, method); } MethodHandle methodHandle = methodHandleCache.get(method); if (methodHandle == null) { methodHandle = MethodHandles.lookup().unreflect(method); methodHandleCache.putIfAbsent(method, methodHandle); } return methodHandle; } } <file_sep>/** * High-level abstractions to use ABS API in a remote setting. * * @author <NAME> * @since 1.0 */ package abs.api.remote;
039591435da603a1843dbc020062b0e0e21340fd
[ "Markdown", "Java", "Maven POM", "AsciiDoc" ]
53
Maven POM
nobeh/abs-api-parent
c461a99f33502d1ec726e6995ae67264c9511169
d8991928f0e812c087dd790f557fcd8b46d1a1bf
refs/heads/master
<repo_name>RubenSV117/TapShot<file_sep>/Assets/Scripts/ProjectileManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProjectileManager : MonoBehaviour { // Use this for initialization void Start () { StartCoroutine(wait2Secs()); } // Update is called once per frame void Update () { } public IEnumerator wait2Secs() { yield return new WaitForSeconds(2); Destroy(gameObject); } public void OnCollisionEnter2D(Collision2D other) { if(other.gameObject.name == "Tower") { other.gameObject.GetComponent<TowerManager>().reduceHealth(); } } } <file_sep>/Assets/Scripts/ProjectileEnemyManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProjectileEnemyManager : BasicEnemy { /*Inherited public int health; public float speed; public float attackCooldown; public bool grounded; public SpriteRenderer spriteRend; public bool BeginMindControl; public bool isMindControlled; public GameObject nearestEnemyToAttack; private float _attackCooldownTimer; private GameObject _tower; private Rigidbody2D _rigidB; private SoundEffectsManager _sound; */ public GameObject projectile; private bool _withinRange; // Use this for initialization new void Start () { _tower = GameObject.Find("Tower"); _rigidB = GetComponent<Rigidbody2D>(); _attackCooldownTimer = attackCooldown; _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); isMindControlled = false; BeginMindControl = false; _withinRange = true; } // Update is called once per frame void Update () { if (health <= 0) { _sound.playDeathImpact(); Destroy(gameObject); } if (grounded && !isMindControlled) { _rigidB.velocity = new Vector2(-speed, _rigidB.velocity.y); } //begin mind control, start coroutine to reset isMindControlled if (BeginMindControl) { BeginMindControl = false; isMindControlled = true; mindControl(); } if (isMindControlled) { if (nearestEnemyToAttack != null) _rigidB.velocity = (Vector2)(Vector3.Normalize(nearestEnemyToAttack.transform.position - transform.position) * (speed * 1.5f)); } //if this mindControlled enemy managed to kill the nearest enemy, move on to the next one if (isMindControlled && nearestEnemyToAttack == null) { mindControl(); } _attackCooldownTimer -= Time.deltaTime; if (_attackCooldownTimer <= 0) { _attackCooldownTimer = attackCooldown; shootProjectile(); } } public void shootProjectile() { if (_tower != null && _withinRange) { if(Mathf.Abs(_tower.transform.position.x - transform.position.x) < 15) { GameObject projectileInstance = Instantiate(projectile, transform.position, projectile.transform.rotation); Vector2 shootVector = ((Vector2)(_tower.transform.position - transform.position)); shootVector = new Vector2(shootVector.x, shootVector.y + 3); projectileInstance.GetComponent<Rigidbody2D>().velocity = shootVector; } } } public void OnBecameInvisible() { _withinRange = false; } public void OnBecameVisible() { _withinRange = true; } } <file_sep>/Assets/Scripts/CrossbowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CrossbowManager : MonoBehaviour { public GameObject basicArrow; public GameObject arrowRainArrow; public GameObject tripleShotArrow; public GameObject knockBackArrow; public GameObject poisonArrow; public GameObject mindControlArrow; public float shootSpeed; public static Transform trans; public static string powerShot; public static Vector2 shootVector; public static int tripleShotCount; public static int poisonCount; private SoundEffectsManager _sound; private GameObject _arrow; // Use this for initialization void Start() { trans = GetComponent<Transform>(); _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); powerShot = ""; tripleShotCount = 4; poisonCount = 3; } // Update is called once per frame void Update() { if (powerShot == "TripleShot") { _arrow = tripleShotArrow; } //once the triple bursts have run out if (powerShot == "TripleShot" && tripleShotCount <= 0) { powerShot = ""; } if (powerShot == "Poison" && poisonCount <= 0) powerShot = ""; else if (powerShot == "ArrowRain") _arrow = arrowRainArrow; else if (powerShot == "KnockBack") _arrow = knockBackArrow; else if (powerShot == "Poison") _arrow = poisonArrow; else if (powerShot == "MindControl") _arrow = mindControlArrow; else _arrow = basicArrow; if (Input.GetMouseButtonDown(0)) { shootVector = GetMousePosition() - (Vector2)transform.position; shootVector = shootVector.normalized * shootSpeed; //shoot burst if (powerShot == "TripleShot" && tripleShotCount > 0) { StartCoroutine(TripleShot()); } //else shoot arrows that activate on impact else if (powerShot == "ArrowRain" || powerShot == "KnockBack" || powerShot == "Poison" || powerShot == "MindControl" || powerShot == "") { GameObject arrowInstance = Instantiate(_arrow, transform.position, transform.rotation); arrowInstance.GetComponent<Rigidbody2D>().velocity = shootVector; _sound.playNormalArrowShot(); } } } public IEnumerator TripleShot() { for (int i = 0; i < 3; i++) { _arrow = tripleShotArrow; GameObject bulletInstance = Instantiate(_arrow, transform.position, transform.rotation); Vector2 newShootVector = new Vector2(shootVector.x, shootVector.y + i); bulletInstance.GetComponent<Rigidbody2D>().velocity = newShootVector; _sound.PlayTripleShot(); yield return new WaitForSeconds(.13f); } tripleShotCount--; } public Vector2 GetMousePosition() { //coordinates of object are in world coordinates (0,0) at center. Mouse position returns Screen coordinates with (0,0) at bottom left, //in order for the mouse and object coordinates to match, must convert mouse coordinates from screen to world Vector3 mouseWorldPos3D = Camera.main.ScreenToWorldPoint(Input.mousePosition); //getting x and y from something, dont need new Vector2 mouseWorldPos2D = new Vector2(mouseWorldPos3D.x, mouseWorldPos3D.y); //raycastHit2D needs a vector2, giving x and y, needs new return mouseWorldPos2D; } public void activateTripleShot() { powerShot = "TripleShot"; tripleShotCount = 4; } public void activateArrowRain() { powerShot = "ArrowRain"; } public void activateKnockback() { powerShot = "KnockBack"; KnockBackArrowManager.isFirstShot = true; } public void activatePoison() { powerShot = "Poison"; poisonCount = 3; } public void activateMindControl() { powerShot = "MindControl"; } public void deactivatePowerShot() { powerShot = ""; } public void ArrowRain(Vector3 impactPosition) { _sound.PlayMainArrowRainImpact(); if (CrossbowManager.powerShot == "ArrowRain") { CrossbowManager.powerShot = ""; Vector3 shootVector = (impactPosition - new Vector3(-6, 6, 0)) * 1.5f; ; for (int i = 0; i < 6; i++) { GameObject arrowInstance = Instantiate(_arrow, new Vector3(-6, 6, 0), transform.rotation); arrowInstance.GetComponent<RainArrowManager>().isFirstShot = false; arrowInstance.GetComponent<Rigidbody2D>().velocity = new Vector3(shootVector.x, (shootVector.y + i + 5), 0); } shootVector = (impactPosition - new Vector3(6, 6, 0)) * 1.5f; ; for (int i = 0; i < 6; i++) { GameObject arrowInstance = Instantiate(_arrow, new Vector3(6, 6, 0), transform.rotation); arrowInstance.GetComponent<RainArrowManager>().isFirstShot = false; arrowInstance.GetComponent<Rigidbody2D>().velocity = new Vector3(shootVector.x, (shootVector.y + i + 5), 0); } } } public void KnockBack() { StartCoroutine(KnockBackCo()); } public IEnumerator KnockBackCo() { _sound.PlayKnockBackImpact(); Time.timeScale = .5f; //returns all object within radius that have a collider2D Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, 20); for (int i = 0; i < objects.Length; i++) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(100, 200)); objects[i].gameObject.GetComponent<Rigidbody2D>().gravityScale = .1f; objects[i].gameObject.GetComponent<Rigidbody2D>().angularVelocity = Random.Range(-1f, 1f) * 80; } } yield return new WaitForSecondsRealtime(3f); Time.timeScale = 1; for (int i = 0; i < objects.Length; i++) { if (objects[i] != null) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().gravityScale = 1f; } } } powerShot = ""; } } <file_sep>/Assets/Scripts/MindControlOrbManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MindControlOrbManager : MonoBehaviour { public GameObject targetEnemy; public Rigidbody2D rigidB; public SoundEffectsManager _sound; // Use this for initialization void Start () { _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); } // Update is called once per frame void Update () { if (targetEnemy != null) { rigidB.velocity = (targetEnemy.transform.position - transform.position).normalized * 5; } } void OnTriggerEnter2D(Collider2D other) { if(other.tag == "Enemy") { _sound.PlayMindControlOrbImpact(); other.GetComponent<BasicEnemy>().isMindControlled = true; Destroy(gameObject); } } } <file_sep>/Assets/Scripts/PowerBallSpawnManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerBallSpawnManager : MonoBehaviour { public GameObject powerball; public float spawnDelay; private float _timer; private GameObject _powerballInstance; // Use this for initialization void Start () { _timer = spawnDelay; } // Update is called once per frame void Update () { if (_powerballInstance == null) _timer -= Time.deltaTime; if(_timer <= 0 && _powerballInstance == null) { _timer = spawnDelay; Vector3 randomPosition = new Vector3(transform.position.x + Random.Range(-8, 9), transform.position.y + Random.Range(-4, 5), transform.position.z); _powerballInstance = Instantiate(powerball, randomPosition, powerball.transform.rotation); } } } <file_sep>/Assets/Scripts/KnockBackArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class KnockBackArrowManager : BasicArrowManager { /* -Inherited- public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; */ public ParticleSystem knockBackImpactParticle; public GameObject knockBackShotParticle; public static bool isFirstShot; // Use this for initialization void Start () { if (isFirstShot) _sound.PlayKnockBackShot(); else { _sound.playNormalArrowShot(); knockBackShotParticle.transform.localScale = new Vector3(.5f, .5f, knockBackShotParticle.transform.localScale.z); rigidB.velocity = CrossbowManager.shootVector.normalized * 35; } } // Update is called once per frame void Update () { if (rigidB != null) { transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } } public new void OnTriggerEnter2D(Collider2D other) { if (isFirstShot) { isFirstShot = false; Destroy(GetComponent<SpriteRenderer>()); Destroy(trailrenderer); Destroy(GetComponent<BoxCollider2D>()); Destroy(knockBackShotParticle); _crossbow.KnockBack(); Instantiate(knockBackImpactParticle, transform.position, knockBackImpactParticle.transform.rotation); //insantiate particle on every enemy GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); for (int i = 0; i < enemies.Length; i++) { Vector3 particlePosition = new Vector3(enemies[i].transform.position.x, -4.7f, enemies[i].transform.position.z - 1); Instantiate(knockBackImpactParticle, particlePosition, knockBackImpactParticle.transform.rotation); } } else { GetComponent<BasicArrowManager>().OnTriggerEnter2D(other); } } } <file_sep>/Assets/Scripts/MindControlArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MindControlArrowManager : BasicArrowManager { /* -Inherited- public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; */ public GameObject mindControlOrb; public ParticleSystem mindControlImpactParticle; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } new void OnTriggerEnter2D(Collider2D other) { _sound.PlayMindControlArrowImpact(); Instantiate(mindControlImpactParticle, transform.position, mindControlImpactParticle.transform.rotation); GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); GameObject nearestEnemy = null; if(enemies.Length > 0) { //set nearestEnemy to the first enemy on the list nearestEnemy = enemies[0]; for(int i = 0; i < enemies.Length; i++) { //if there is an enemy that is closer than the current nearestEnemy, set nearestEnemy to that if ((Mathf.Abs(enemies[i].transform.position.x - transform.position.x)) < (Mathf.Abs(nearestEnemy.transform.position.x - transform.position.x))) nearestEnemy = enemies[i]; } } if(nearestEnemy != null) { MindControlOrbManager orb = Instantiate(mindControlOrb, transform.position, mindControlOrb.transform.rotation).GetComponent<MindControlOrbManager>(); orb.targetEnemy = nearestEnemy; } GetComponent<BasicArrowManager>().OnTriggerEnter2D(other); _crossbow.deactivatePowerShot(); } } <file_sep>/Assets/Scripts/ArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ArrowManager : MonoBehaviour { public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject arrow; public GameObject arrowRainParticle; public ParticleSystem arrowRainImpact; public GameObject tripleShotParticle; public GameObject tripleShotImpact; public GameObject knockBackParticle; public GameObject knockBackParticleImpact; public bool isRainArrow; public bool isKnockBackArrow; public GameObject trailrenderer; //after shooting the 3 arrows, CrossbowManager decrements tripleShotCount, so this boolean makes it independant after being shot private bool _tripleShoot; public static bool alreadyKnockedBack; private SoundEffectsManager _sound; // Use this for initialization void Start () { _tripleShoot = false; _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); //ArrowRain if (CrossbowManager.powerShot == "ArrowRain") { arrowRainParticle.SetActive(true); _sound.PlayArrowRainShot(); } //Triple Fire Shot if (CrossbowManager.tripleShotCount > 0 && CrossbowManager.powerShot == "TripleShot") { tripleShotParticle.SetActive(true); _tripleShoot = true; } if(CrossbowManager.powerShot == "KnockBack" && !alreadyKnockedBack) { isKnockBackArrow = true; _sound.PlayKnockBackShot(); knockBackParticle.SetActive(true); } //transform.eulerAngles = new Vector3(0, 0, rigidB.velocity.y * 7); } // Update is called once per frame void Update () { if(rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); if (CrossbowManager.powerShot == "KnockBack") { if (GetComponent<Rigidbody2D>() != null) { GetComponent<Rigidbody2D>().velocity = GetComponent<Rigidbody2D>().velocity.normalized * 25 ; } } } void OnTriggerEnter2D(Collider2D other) { //if AOE powerShot activated, then simulate blast radius and do more damage if (isRainArrow || _tripleShoot) { //returns all object within radius that have a collider2D Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, 1.3f); for (int i = 0; i < objects.Length; i++) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(700, 50)); objects[i].gameObject.GetComponent<BasicEnemy>().reduceHealth(2); } } } //for slo-mo levitating powerUp if(isKnockBackArrow && !alreadyKnockedBack) { alreadyKnockedBack = true; Instantiate(knockBackParticleImpact, transform.position, knockBackParticleImpact.transform.rotation); //insantiate particle on every enemy GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy"); for(int i = 0; i < enemies.Length; i++) { Vector3 particlePosition = new Vector3(enemies[i].transform.position.x, enemies[i].transform.position.y, enemies[i].transform.position.z - 1); Instantiate(knockBackParticleImpact, particlePosition, knockBackParticleImpact.transform.rotation); } StartCoroutine(KnockBack()); } //Hitting the ground, with or without powerShots activated if (other.name == "Ground") { //ArrowRain if (CrossbowManager.powerShot == "ArrowRain") { //prevent arrows from triggering rainArrow that were shot before shooting the powerBall; //only the ones shot after getting the power ball will have the particleSystem active if(arrowRainParticle.activeInHierarchy) { ArrowRain(); Instantiate(arrowRainImpact, transform.position, arrowRainImpact.transform.rotation); } } //wave arrows that were spawned after the first lightning arrow lands else if (isRainArrow) { Instantiate(arrowRainImpact, transform.position, arrowRainImpact.transform.rotation); _sound.PlayArrowRainImpact(); } //TripleShot else if (_tripleShoot) { Instantiate(tripleShotImpact, transform.position, tripleShotImpact.transform.rotation); _sound.PlayTripleShotImpact(); _tripleShoot = false; ; } //hits the ground with no powerShot Active else _sound.PlayGroundImpact(); } //Hitting the enemy with or without powerShots selected else if (other.tag == "Enemy") { //ArrowRain if (CrossbowManager.powerShot == "ArrowRain") { if (arrowRainParticle.activeInHierarchy) { ArrowRain(); Instantiate(arrowRainImpact, transform.position, arrowRainImpact.transform.rotation); } } //these are the arrows instantiated after the first arrow activates ArrowRain() else if (isRainArrow) { Instantiate(arrowRainImpact, transform.position, arrowRainImpact.transform.rotation); _sound.PlayArrowRainImpact(); } //hits enemy with triple shoot activated else if (_tripleShoot) { Instantiate(tripleShotImpact, transform.position, tripleShotImpact.transform.rotation); _sound.PlayTripleShotImpact(); _tripleShoot = false; } //death shot sound if (other.GetComponent<BasicEnemy>().health == 1) _sound.playDeathImpact(); //normal impact shots else _sound.playArrowImpact(); //set splatter particle to either normal shot or death shot GameObject splatter; if (other.GetComponent<BasicEnemy>().health <= 1) splatter = deathParticle.gameObject; else splatter = impactParticle.gameObject; //insantiate blood particle effect Instantiate(splatter, new Vector3(other.transform.position.x + .1f, transform.position.y - .2f, other.transform.position.z + 1), impactParticle.transform.rotation); //set rotation of blood according to direction of arrow if(rigidB != null) splatter.GetComponent<Transform>().eulerAngles = new Vector3(-rigidB.velocity.y * 7, 90, 0); //normal shot if (!isRainArrow && !_tripleShoot) { //reduce health other.GetComponent<BasicEnemy>().reduceHealth(damage); //push enemy back if(other.GetComponent<BasicEnemy>().grounded) other.GetComponent<Rigidbody2D>().AddForce(new Vector2(400, 0)); else other.GetComponent<Rigidbody2D>().AddForce(new Vector2(50, 0)); } } if(CrossbowManager.powerShot == "KnockBack") { StartCoroutine(WaitToDestroy5()); } //prevent arrow from being destroyed immediately so KnockBack coroutine can execute fully (theres a 3 second wait in it) //do not interact with player, tower, or other arrows else if ((other.tag == "Enemy" || other.tag == "PowerBall" ) && CrossbowManager.powerShot != "KnockBack") { Destroy(gameObject); } else { StartCoroutine(WaitToDestroy()); Destroy(GetComponent<BoxCollider2D>()); Destroy(trailrenderer); } } public IEnumerator KnockBack() { _sound.PlayKnockBackImpact(); Time.timeScale = .5f; //returns all object within radius that have a collider2D Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, 12); for (int i = 0; i < objects.Length; i++) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(100, 200)); objects[i].gameObject.GetComponent<Rigidbody2D>().gravityScale = .1f; objects[i].gameObject.GetComponent<Rigidbody2D>().angularVelocity = Random.Range(-1f, 1f) * 50; } } yield return new WaitForSecondsRealtime(3f); Time.timeScale = 1; for (int i = 0; i < objects.Length; i++) { if (objects[i] != null) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().gravityScale = 1f; } } } CrossbowManager.powerShot = ""; } public IEnumerator WaitToDestroy() { Destroy(rigidB); yield return new WaitForSeconds(1); Destroy(gameObject); } public IEnumerator WaitToDestroy5() { Destroy(rigidB); Destroy(trailrenderer); transform.position = new Vector3(10, 10, 0); yield return new WaitForSeconds(5); Destroy(gameObject); } public void ArrowRain() { _sound.PlayMainArrowRainImpact(); if (CrossbowManager.powerShot == "ArrowRain") { CrossbowManager.powerShot = ""; Vector3 shootVector = (transform.position - new Vector3(-6, 6, 0)) * 1.5f; ; for (int i = 0; i < 6; i++) { GameObject bulletInstance = Instantiate(arrow, new Vector3(-6, 6, 0), transform.rotation); bulletInstance.GetComponent<ArrowManager>().isRainArrow = true; bulletInstance.GetComponent<Rigidbody2D>().velocity = new Vector3(shootVector.x, (shootVector.y + i + 3), 0); } shootVector = (transform.position - new Vector3(6, 6, 0)) * 1.5f; ; for (int i = 0; i < 6; i++) { GameObject bulletInstance = Instantiate(arrow, new Vector3(6, 6, 0), transform.rotation); bulletInstance.GetComponent<ArrowManager>().isRainArrow = true; bulletInstance.GetComponent<Rigidbody2D>().velocity = new Vector3(shootVector.x, (shootVector.y + i + 3), 0); } } } } <file_sep>/Assets/Scripts/PowerBallManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerBallManager : MonoBehaviour { public float maxForce; public float minForce; public float directionChangeTimer; public ParticleSystem burstParticle; public float lifeTimer; public ParticleSystem spawnParticle; private string _powershotType; private float _directionTimer; private Rigidbody2D _rigidB; private float _forceStrength; private float _xDirection; private float _yDirection; private Vector2 _pushVector; private SoundEffectsManager _sound; private CrossbowManager _crossbow; // Use this for initialization void Start () { _crossbow = GameObject.Find("CrossbowManager").GetComponent<CrossbowManager>(); Instantiate(spawnParticle, transform.position, spawnParticle.transform.rotation); _rigidB = GetComponent<Rigidbody2D>(); _directionTimer = directionChangeTimer; PlayerPrefs.SetInt("PowerBall", ((PlayerPrefs.GetInt("PowerBall", 0) + 1) % 5)); _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); StartCoroutine(wait2Secs()); } // Update is called once per frame void Update() { _directionTimer -= Time.deltaTime; if (_directionTimer <= 0) { _directionTimer = directionChangeTimer; Push(); } lifeTimer -= Time.deltaTime; if(lifeTimer <= 0) { Destroy(gameObject); } } public IEnumerator wait2Secs() { yield return new WaitForSeconds(2); Push(); } public void Push() { //magnitude _forceStrength = Random.Range(minForce, maxForce); //direction components _xDirection = Random.Range(-1f, 1f); _yDirection = Random.Range(-1f, 1f); _pushVector = _forceStrength * new Vector2(_xDirection, _yDirection); _rigidB.AddForce(_pushVector); } public void OnBecameInvisible() { transform.position = new Vector3(-transform.position.x, -transform.position.y, transform.position.z); _directionTimer += 1; } public void OnTriggerEnter2D(Collider2D other) { if(other.tag == "Arrow") { _sound.PlayPowerballPop(); Instantiate(burstParticle, transform.position, burstParticle.transform.rotation); if (PlayerPrefs.GetInt("PowerBall", 0) == 0) _crossbow.activateTripleShot(); else if (PlayerPrefs.GetInt("PowerBall", 0) == 1) _crossbow.activateArrowRain(); else if (PlayerPrefs.GetInt("PowerBall", 0) == 2) { _crossbow.activateKnockback(); } else if (PlayerPrefs.GetInt("PowerBall", 0) == 3) { _crossbow.activatePoison(); } else if (PlayerPrefs.GetInt("PowerBall", 0) == 4) { _crossbow.activateMindControl(); } print(CrossbowManager.powerShot); Destroy(gameObject); } } } <file_sep>/Assets/Scripts/BasicArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasicArrowManager : MonoBehaviour { public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; protected static SoundEffectsManager _sound; protected static CrossbowManager _crossbow; // Use this for initialization void Start () { _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); _crossbow = GameObject.Find("CrossbowManager").GetComponent<CrossbowManager>(); } // Update is called once per frame void Update () { if (rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } public void OnTriggerEnter2D(Collider2D other) { //Hitting the ground if (other.name == "Ground") { _sound.PlayGroundImpact(); StartCoroutine(WaitToDestroy()); } //Hitting an enemy else if(other.tag == "Enemy") { //if it's the killing shot plays the juicier sound if (other.GetComponent<BasicEnemy>().health == 1) _sound.playDeathImpact(); //normal impact shots else _sound.playArrowImpact(); //set splatter particle to either normal shot or death shot GameObject splatter; //the killing shot has a bigger splatter if (other.GetComponent<BasicEnemy>().health <= 1) splatter = deathParticle.gameObject; //non killing shot has a smaller splatter else splatter = impactParticle.gameObject; //insantiate blood particle effect Instantiate(splatter, new Vector3(other.transform.position.x + .1f, transform.position.y - .2f, other.transform.position.z + 1), impactParticle.transform.rotation); //set rotation of blood according to direction of arrow, //particleSystem coordinates seem to have axes rotated (the z coordinates of the arrow rotation are needed in the x-component rotation of the particle for desired effect) if (rigidB != null) splatter.GetComponent<Transform>().eulerAngles = new Vector3(-rigidB.velocity.y * 7, 90, 0); //reduce health other.GetComponent<BasicEnemy>().reduceHealth(damage); //push enemy back //if enemy grounded, push back if (other.GetComponent<BasicEnemy>().grounded) other.GetComponent<Rigidbody2D>().AddForce(new Vector2(500, 0)); //if enemy is airborne, reduce the force else other.GetComponent<Rigidbody2D>().AddForce(new Vector2(50, 0)); //if hit enemy or powerBall, destroy on impact if (other.tag == "Enemy" || other.tag == "PowerBall") { Destroy(gameObject); } //else wait to destroy to keep arrow buried in the ground, destroy collider and trail else { StartCoroutine(WaitToDestroy()); Destroy(GetComponent<BoxCollider2D>()); Destroy(trailrenderer); } } } public IEnumerator WaitToDestroy() { Destroy(rigidB); Destroy(trailrenderer); Destroy(GetComponent<BoxCollider2D>()); yield return new WaitForSeconds(4); Destroy(gameObject); } } <file_sep>/Assets/Scripts/BlastRadiusManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BlastRadiusManager : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.tag == "Enemy") { other.gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(600, 50)); other.gameObject.GetComponent<BasicEnemy>().reduceHealth(1); print("Enter"); } } public void OnCollisionStay2D(Collision2D other) { if (other.gameObject.tag == "Enemy") { other.gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(600, 50)); other.gameObject.GetComponent<BasicEnemy>().reduceHealth(1); print("Stay"); } } } <file_sep>/Assets/Scripts/TripleShotArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TripleShotArrowManager : BasicArrowManager { /* -Inherited- public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; */ public GameObject explosionParticle; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } public new void OnTriggerEnter2D(Collider2D other) { //returns all object within radius that have a collider2D Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, 1.3f); //simulate blast radius for (int i = 0; i < objects.Length; i++) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(700, 50)); objects[i].gameObject.GetComponent<BasicEnemy>().reduceHealth(1); } } //instantiate explosion particle Instantiate(explosionParticle, transform.position, explosionParticle.transform.rotation); //play explosion sounds _sound.PlayTripleShotImpact(); } } <file_sep>/Assets/Scripts/PoisonArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PoisonArrowManager : BasicArrowManager { /* -Inherited- public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; */ public GameObject poisonCloud; public GameObject poisonImpact; // Use this for initialization void Start() { //decrement crossBow managers poisonCount CrossbowManager.poisonCount--; print(CrossbowManager.poisonCount); _sound.PlayTripleShot(); } // Update is called once per frame void Update() { if (rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } public new void OnTriggerEnter2D(Collider2D other) { if (other.tag != "PoisonCloud") { Instantiate(poisonImpact, transform.position, poisonCloud.transform.rotation); _sound.PlayPoisonImpact(); _sound.PlayTripleShotImpact(); Instantiate(poisonCloud, new Vector3(transform.position.x, -4, transform.position.z), poisonCloud.transform.rotation); Destroy(gameObject); } } } <file_sep>/Assets/Scripts/SoundEffectsManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundEffectsManager : MonoBehaviour { public AudioSource normalArrowShot; public AudioSource[] arrowImpact; public AudioSource deathImpact; public AudioSource groundImpact; public AudioSource arrowRainShot; public AudioSource mainArrowRainImpact; public AudioSource[] arrowRainImpact; public AudioSource tripleShot; public AudioSource[] tripleShotImpact; public AudioSource powerballPop; public AudioSource knockBackShot; public AudioSource knockBackImpact; public AudioSource poisonImpact; public AudioSource mindControlArrowImpact; public AudioSource mindControlOrbImpact; private AudioSource audioSource; // Use this for initialization void Start() { audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { } public void playNormalArrowShot() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) normalArrowShot.Play(); } public void playArrowImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) arrowImpact[Random.Range(0, arrowImpact.Length)].Play(); } public void playDeathImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) deathImpact.Play(); } public void PlayGroundImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) groundImpact.Play(); } public void PlayTripleShot() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) tripleShot.Play(); } public void PlayTripleShotImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) { tripleShotImpact[Random.Range(0, tripleShotImpact.Length)].Play(); } } //first lightning arrow public void PlayArrowRainShot() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) arrowRainShot.Play(); } //when the first lighting arrow lands public void PlayMainArrowRainImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) mainArrowRainImpact.Play(); } //sounds for rain arrows public void PlayArrowRainImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) arrowRainImpact[Random.Range(0, arrowRainImpact.Length)].Play(); } public void PlayPowerballPop() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) powerballPop.Play(); } public void PlayKnockBackImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) knockBackImpact.Play(); } public void PlayKnockBackShot() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) knockBackShot.Play(); } public void PlayPoisonImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) poisonImpact.Play(); } public void PlayMindControlArrowImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) mindControlArrowImpact.Play(); } public void PlayMindControlOrbImpact() { if (PlayerPrefs.GetInt("PlaySound", 1) == 1) mindControlOrbImpact.Play(); } } <file_sep>/Assets/Scripts/BasicEnemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasicEnemy : MonoBehaviour { public int health; public float speed; public float attackCooldown; public bool grounded; public SpriteRenderer spriteRend; public bool BeginMindControl; public bool isMindControlled; public GameObject nearestEnemyToAttack; protected float _attackCooldownTimer; protected GameObject _tower; protected Rigidbody2D _rigidB; protected SoundEffectsManager _sound; // Use this for initialization protected void Start () { _tower = GameObject.Find("Tower"); _rigidB = GetComponent<Rigidbody2D>(); _attackCooldownTimer = attackCooldown; _sound = GameObject.Find("SoundEffects").GetComponent<SoundEffectsManager>(); isMindControlled = false; BeginMindControl = false; } // Update is called once per frame void Update () { if(health <= 0) { _sound.playDeathImpact(); Destroy(gameObject); } if(grounded && !isMindControlled) { _rigidB.velocity = new Vector2(-speed, _rigidB.velocity.y); } //begin mind control, start coroutine to reset isMindControlled if(BeginMindControl) { BeginMindControl = false; isMindControlled = true; mindControl(); } if(isMindControlled) { if(nearestEnemyToAttack != null) _rigidB.velocity = (Vector2)(Vector3.Normalize(nearestEnemyToAttack.transform.position - transform.position) * (speed * 1.5f)); } //if this mindControlled enemy managed to kill the nearest enemy, move on to the next one if (isMindControlled && nearestEnemyToAttack == null) { mindControl(); } _attackCooldownTimer -= Time.deltaTime; } public IEnumerator wait5secs() { yield return new WaitForSeconds(5); isMindControlled = false; spriteRend.color = new Color(1, 0, 0); transform.gameObject.layer = 11; } public void mindControl() { transform.gameObject.layer = 12; StartCoroutine(wait5secs()); spriteRend.color = new Color(0, 1, 0); GameObject[] fellowEnemies = GameObject.FindGameObjectsWithTag("Enemy"); //greater than 2 because it includes THIS enemy automatically if(fellowEnemies.Length > 2) { //get first enemy on the list that isnt this for(int i = 0; i < fellowEnemies.Length; i++) { if(fellowEnemies[i] != this.gameObject) { nearestEnemyToAttack = fellowEnemies[i]; break; } } //get nearest fellowEnemy to attack for (int i = 0; i < fellowEnemies.Length; i++) { if ((((fellowEnemies[i].transform.position - transform.position).magnitude) < ((nearestEnemyToAttack.transform.position - transform.position).magnitude)) && fellowEnemies[i] != this.gameObject) nearestEnemyToAttack = fellowEnemies[i]; } } } public void reduceHealth(int damage) { health -= damage; } public void OnCollisionEnter2D(Collision2D other) { if(other.gameObject.name == "Tower") { other.gameObject.GetComponent<TowerManager>().reduceHealth(); _attackCooldownTimer = attackCooldown; print("attacked"); } if (other.gameObject.tag == "Enemy" && isMindControlled) { other.gameObject.GetComponent<BasicEnemy>().reduceHealth(3); _attackCooldownTimer = attackCooldown; } if (other.gameObject.tag == "Ground") { grounded = true; transform.rotation = new Quaternion(0, 0, 0, 0); } } public void OnCollisionStay2D(Collision2D other) { if (other.gameObject.name == "Tower" && _attackCooldownTimer <= 0) { _attackCooldownTimer = attackCooldown; other.gameObject.GetComponent<TowerManager>().reduceHealth(); print("attackedAgain"); } if (other.gameObject.tag == "Enemy" && isMindControlled && _attackCooldownTimer <= 0) { _attackCooldownTimer = attackCooldown; other.gameObject.GetComponent<BasicEnemy>().reduceHealth(3); _attackCooldownTimer = attackCooldown; } if (other.gameObject.tag == "Ground") { grounded = true; } } public void OnCollisionExit2D(Collision2D other) { if (other.gameObject.tag == "Ground") { grounded = false; } } } <file_sep>/Assets/Scripts/TowerManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TowerManager : MonoBehaviour { public int health; public Text towerHealth; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(health <= 0) { Destroy(gameObject); } towerHealth.text = "Tower HP: " + health; } public void reduceHealth() { health--; } } <file_sep>/Assets/Scripts/RainArrowManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class RainArrowManager : BasicArrowManager { /* -Inherited- public Rigidbody2D rigidB; public int damage; public ParticleSystem impactParticle; public ParticleSystem deathParticle; public GameObject trailrenderer; */ public bool isFirstShot = true; public ParticleSystem lightningParticle; // Use this for initialization void Start () { _sound.PlayArrowRainShot(); } // Update is called once per frame void Update () { if (rigidB != null) transform.eulerAngles = new Vector3(0, 0, (Mathf.Atan(rigidB.velocity.y / rigidB.velocity.x) * Mathf.Rad2Deg)); } public new void OnTriggerEnter2D(Collider2D other) { //returns all object within radius that have a collider2D Collider2D[] objects = Physics2D.OverlapCircleAll(transform.position, 1.3f); for (int i = 0; i < objects.Length; i++) { if (objects[i].gameObject.tag == "Enemy") { objects[i].gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(700, 50)); objects[i].gameObject.GetComponent<BasicEnemy>().reduceHealth(2); } } _sound.PlayArrowRainImpact(); Instantiate(lightningParticle, transform.position, lightningParticle.transform.rotation); if (isFirstShot) { _crossbow.ArrowRain(transform.position); GetComponent<BasicArrowManager>().OnTriggerEnter2D(other); } } } <file_sep>/Assets/Scripts/PoisonCloudManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PoisonCloudManager : MonoBehaviour { public int damage; public float damageCooldown; public float lifeTimer; private float _cooldownTimer; private List<GameObject> _enemies = new List<GameObject>(); // Use this for initialization void Start () { _cooldownTimer = damageCooldown; } // Update is called once per frame void Update () { _cooldownTimer -= Time.deltaTime; if(_cooldownTimer <= 0) { _cooldownTimer = damageCooldown; DamageEnemies(); } lifeTimer -= Time.deltaTime; if(lifeTimer <= 0) { Destroy(gameObject); } } public void OnTriggerEnter2D(Collider2D other) { if(other.tag == "Enemy") { _enemies.Add(other.gameObject); } } public void OnTriggerExit2D(Collider2D other) { if (other.tag == "Enemy") { _enemies.Remove(other.gameObject); } } public void DamageEnemies() { if (_enemies.Count > 0) { for (int i = 0; i < _enemies.Count; i++) { if(_enemies[i].GetComponent<BasicEnemy>() != null) _enemies[i].GetComponent<BasicEnemy>().reduceHealth(damage); } } } }
ce7e05330eb0abedfbb8e1c5a6dfd225d95e0740
[ "C#" ]
18
C#
RubenSV117/TapShot
04712af0128f2a8a9e8b8514ed647eda5ff3ffc5
597e28ade38965fcb9596627beb253e07bb5826d
refs/heads/master
<file_sep>using CustomerManagement.Domain.Models.CustomerAggregate; using Infrastructure.Core.Repositories; using Infrastructure.Domain.Repositories; namespace CustomerManagement.Domain.Models.CustomerAggregate.Repository { public interface ICustomerRepository : IRepository<Customer> { } }
c8ae3ceafdfdf3d349904677e87388b263defe5f
[ "C#" ]
1
C#
duytuit/Ecommerce
2545d03dd5b9c21a480549c801c5fa011eab0b2d
db41c48569d60f9ccff855e2233803ea5f301a1c
refs/heads/master
<repo_name>eduwarick/python<file_sep>/stringManip.py #String Manip #get single char text = "Hello" print(text[1]) #get substring print(text[2:4]) #remove any space from beggining and end text = " <NAME> " print(text) print(text.strip()) #get length of string print(len(text)) #Lower and Upper case string print(text.lower()) print(text.upper()) #replace string print(text.replace("d", "I")) #Split string if it finds the separator text = "a, b, c, d, e" print(text.split(",")) <file_sep>/helloworld.py #First program in Python. print("Hello, world.")<file_sep>/variables.py #Testing variables x = 5 print(x) x = "Hello" print(x) y = ", World!" print(x + y) #Type test ##Integer x = 5 print (x) print(type(x)) ##Float x = 5.1 print (x) print(type(x)) x = 5e3 print (x) print(type(x)) ##Complex x = 5+1j print (x) print(type(x)) #Casting test x = float(1) print (x) <file_sep>/README.md # python ### List of things learned (will change to a Jupyter Notebook): 1. Hello World 2. Variable testing 3. String Manipulation 4. ## Leetcode challenges ### Easy ### Medium ### Hard
8b31ce5862cca9ae90c040607b06fb2080a66c24
[ "Markdown", "Python" ]
4
Python
eduwarick/python
a5ffeadec18057f2155b808a49e841f24ba6bb8c
00a7dc55a83aedb392feca4bd322b0f2c3c42d5c
refs/heads/main
<file_sep>import requests from bs4 import BeautifulSoup LIMIT = 50 URL = f'https://kr.indeed.com/%EC%B7%A8%EC%97%85?q=python&limit={LIMIT}&start=99999' def extract_pages(): result = requests.get(URL) soup = BeautifulSoup(result.text, 'html.parser') pagination = soup.find('div', {'class':'pagination'}) max_page = int(pagination.find('b').text) return max_page def extract_job(html): title = html.find('h2', {'class':'jobTitle'}).text company = html.find('span', {'class':'companyName'}) if company is None: company = '' else: company = company.text location = html.find('div', {'class':'companyLocation'}).text job_id = html['data-jk'] return { 'title':title, 'company':company, 'location':location, 'link': f"https://kr.indeed.com/%EC%B7%A8%EC%97%85?q=python&limit=50&vjk={job_id}" } def extract_jobs(last_page): jobs=[] for page in range(last_page): print(f'Scrapping INDEED page {page+1}') result = requests.get(f'{URL[:-5]}{page*LIMIT}') soup = BeautifulSoup(result.text, 'html.parser') results = soup.find_all('a', {'class':'tapItem'}) for result in results: job = extract_job(result) jobs.append(job) return jobs def get_jobs(): max_pages = extract_pages() jobs = extract_jobs(max_pages + 1) return jobs<file_sep># Webscraper Scraping recruit information from indeed and stackoverflow
b2053ad6a4e745e16338dab88bc34f270804bb81
[ "Markdown", "Python" ]
2
Python
lgkrwnsdll/Webscraper
3812bf95cc4390482dd4ebd3b10a6d994d0a62a8
4b4e05d95bcc859ce00c570c47d20324a67806df
refs/heads/master
<repo_name>meemknight/cubeMarching<file_sep>/cubeMarching/worldControll.h #pragma once #include <glm/vec3.hpp> #include <functional> auto circleFunctionCreator(float r, float cx =0, float cy=0, float cz=0) { return[r, cx, cy, cz](int x, int y, int z) -> bool { float x2 = x - cx; float y2 = y - cy; float z2 = z - cz; return sqrtf(x2*x2 + y2 * y2 + z2 * z2) < r; }; } auto thorus(float innerR, float outerR, float cx=0, float cy=0, float cz = 0) { return[innerR, outerR, cx, cy, cz](int x, int y, int z) -> bool { x = x - cx; y = y - cy; z = z - cz; float r = sqrt(x*x + z*z); return(r > innerR && r < outerR); }; } struct World3d { struct Vec3 { int x, y, z; }size = { 0 }; float scale = 1; bool *world = nullptr; void popultate(std::function<bool(int, int, int)> func); bool get(int x, int y, int z); void set(int x, int y, int z, bool val); void create(); void create(int x, int y, int z) { size = { x,y,z }; create(); }; void cleanup(); void calculateGpuData(); unsigned int gpuBufferId = 0; int getTrueCount() { return trueCount; } void bind(); private: int trueCount = 0; };<file_sep>/cubeMarching/ShaderProgram.h #pragma once ///////////////////////////////////////////// //Shader.h //Copyright(c) 2019 <NAME> //https://github.com/meemknight/OpenGLEngine ///////////////////////////////////////////// #include<GL/glew.h> #include <cstdio> #include <iostream> #include <unordered_map> #include <cstring> class ShaderProgram; template <GLenum shaderType> struct Shader { Shader() {}; Shader(const char* name) { compile(name); } // static using shaderType = shaderType; unsigned int id = 0; void deleteShader(); void compile(const char* name) { size_t size; FILE *input; input = fopen(name, "rb"); if (input == nullptr) { std::cout << "couldn't open the shader file: " << name; } fseek(input, 0, SEEK_END); size = ftell(input); fseek(input, 0, SEEK_SET); char *data = new char[size + 1]; fread(data, size, 1, input); data[size] = 0; // id = glCreateShader(shaderType); glShaderSource(id, 1, &data, 0); glCompileShader(id); int result; glGetShaderiv(id, GL_COMPILE_STATUS, &result); if (!result) { char* message; int length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); message = new char[length]; glGetShaderInfoLog(id, length, &length, message); std::cout << "Error compiling shader:" << name; std::cout << message; delete[] message; } delete[] data; } friend ShaderProgram; }; using VertexShader = Shader<GL_VERTEX_SHADER>; using FragmentShader = Shader<GL_FRAGMENT_SHADER>; using GeometryShader = Shader<GL_GEOMETRY_SHADER>; struct cmp_str //for compairing the strings literals { bool operator()(const char *a, const char *b)const { return !std::strcmp(a, b); } }; ///bref this class is used for compiling shaders and also using their data class ShaderProgram { void compileProgram(); void compileProgramWithGeometryShader(); std::unordered_map<const char*, int> locations; std::unordered_map<const char*, unsigned int> subRoutines; public: ShaderProgram(); ShaderProgram(const VertexShader &vs, const FragmentShader &fs); ShaderProgram(const VertexShader &vs, const GeometryShader &gs, const FragmentShader &fs); unsigned int id = 0; void bind(); void unBind(); void deleteProgram(); int getUniformLocation(const char* name); unsigned int getSoubRutineLocation(const char* name); void uniform(const char* name, float a); void uniform(const char* name, float a, float b, float c); void uniform(const char* name, float a, float b, float c, float d); void uniform(const char* name, int count, float *a); void uniformi(const char * name, int a); VertexShader vs; FragmentShader fs; GeometryShader gs; }; template<GLenum shaderType> inline void Shader<shaderType>::deleteShader() { glDeleteShader(id); } /* #include<GL/glew.h> #include<fstream> #include<vector> #include<iostream> template<GLenum S> struct Shader { Shader(const char *file) { std::vector<char> shaderData(1000); std::ifstream f(file); if(!f.is_open()) { std::cout << "file error\n"; } std::copy(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>(), std::back_inserter(shaderData)); shaderData.push_back(0); id = glCreateShader(S); int length = shaderData.size(); auto data = &shaderData[0]; glShaderSource(id, 1, &data, 0); glCompileShader(id); int result; glGetShaderiv(id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { char* message; int length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); message = new char[length]; glGetShaderInfoLog(id, length, &length, message); std::cout << file << "\n" << message << "\n\n"; delete[] message; } } GLint id; }; using VertexShader = Shader<GL_VERTEX_SHADER>; using FragmentShader = Shader<GL_FRAGMENT_SHADER>; class ShaderProgram { public: ShaderProgram(VertexShader vs, FragmentShader fs) { id = glCreateProgram(); glAttachShader(id, vs.id); glAttachShader(id, fs.id); glLinkProgram(id); glValidateProgram(id); char message[1000] = { 0 }; glGetProgramInfoLog(id,1000,0, message); std::cout << message; bind(); } void bind() { glUseProgram(id); } GLint id; }; */<file_sep>/cubeMarching/worldControll.cpp #include "worldControll.h" #include <cmath> #include <GL/glew.h> #include <cstring> void World3d::popultate(std::function<bool(int, int, int)> func) { int tempCount = 0; for(int x=0; x<size.x; x++) { for(int y=0; y<size.y; y++) { for(int z=0; z<size.z; z++) { bool b = func(x, y, z); set(x, y, z, b); if (b) { tempCount++; } } } } trueCount = tempCount; } bool World3d::get(int x, int y, int z) { return world[x + (size.x * y) + ((size.x * size.y) * z)]; } void World3d::set(int x, int y, int z, bool val) { if(world[x + (size.x * y) + ((size.x * size.y) * z)]) { if (val == false) trueCount--; }else { if (val == true) trueCount++; } world[x + (size.x * y) + ((size.x * size.y) * z)] = val; } void World3d::create() { world = new bool[size.x * size.y * size.z]; memset(world, 0, size.x * size.y * size.z * sizeof(bool)); } void World3d::cleanup() { if(world) delete[] world; if(gpuBufferId) { glDeleteBuffers(1, &gpuBufferId); } } void World3d::calculateGpuData() { if(!gpuBufferId) { glGenBuffers(1, &gpuBufferId); } glBindBuffer(GL_ARRAY_BUFFER, gpuBufferId); float *data = new float[3 * sizeof(float) * trueCount]; int i = 0; for (int x = 0; x < size.x; x++) { for (int y = 0; y < size.y; y++) { for (int z = 0; z < size.z; z++) { if(get(x,y,z)) { data[i] = x * scale; data[i+1] = y * scale; data[i+2] = z * scale; i += 3; } } } } glBufferData(GL_ARRAY_BUFFER, 3 * sizeof(float) * trueCount, data, GL_STATIC_DRAW); delete[] data; } void World3d::bind() { glBindBuffer(GL_ARRAY_BUFFER, gpuBufferId); glVertexAttribPointer(0, 3, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(0); } <file_sep>/cubeMarching/README.md "# cubeMarching" <file_sep>/cubeMarching/main.cpp #include <iostream> #include <Windows.h> #define GLFW_EXPOSE_NATIVE_WGL #define GLFW_EXPOSE_NATIVE_WIN32 #include <gl/glew.h> #include <GLFW/glfw3.h> #include <GLFW/glfw3native.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "ShaderProgram.h" #include "Camera.h" #include "worldControll.h" int main() { if(glfwInit() == false) { std::cout << "glfwerror"; Sleep(1000); } float width = 640; float heigth = 480; GLFWwindow* window = glfwCreateWindow(width, heigth, "My Title", NULL, NULL); if (!window) { std::cout << "glfwerror window"; Sleep(1000); } glfwMakeContextCurrent(window); glewInit(); glEnable(GL_PROGRAM_POINT_SIZE); ShaderProgram program{"vert.vert", "geometry.geom","frag.frag"}; World3d world; world.scale = 1; world.create(150, 150, 150); world.popultate(thorus(4,10, 70, 70, 70)); world.calculateGpuData(); world.bind(); //glVertexAttribPointer(1, 3, GL_FLOAT, 0, 0, (void*)3); //glEnableVertexAttribArray(1); auto windowNative = (HWND)glfwGetWin32Window(window); Camera camera(windowNative, 85.f, &width, &heigth, 0.1f, 100); camera.rSpeed = 0.2; camera.position = { 0,0, 10 }; float deltaTime = 0; float lastTime = GetTickCount(); float cameraSpeed = 0.5f; while (!glfwWindowShouldClose(window)) { deltaTime = GetTickCount() - lastTime; lastTime = GetTickCount(); POINT cursorPos; GetCursorPos(&cursorPos); RECT windowRect; GetWindowRect(windowNative, &windowRect); if(GetAsyncKeyState('W')) { camera.moveFront(cameraSpeed * deltaTime); } if (GetAsyncKeyState('S')) { camera.moveBack(cameraSpeed * deltaTime); } if (GetAsyncKeyState('A')) { camera.moveLeft(cameraSpeed * deltaTime); } if (GetAsyncKeyState('D')) { camera.moveRight(cameraSpeed * deltaTime); } if (GetAsyncKeyState('R')) { camera.moveUp(cameraSpeed * deltaTime); } if (GetAsyncKeyState('F')) { camera.moveDown(cameraSpeed * deltaTime); } camera.mouseUpdate({ cursorPos.x - windowRect.top, cursorPos.y - windowRect.left}); world.bind(); program.bind(); auto uniformId = program.getUniformLocation("modelToWorldToview"); glUniformMatrix4fv(uniformId, 1, false, &camera.getProjectionViewMatrix()[0][0]); program.uniform("u_color", 0, 0.5, 0.2, 1); glDrawArrays(GL_POINTS, 0, world.getTrueCount()); glfwPollEvents(); glfwSwapBuffers(window); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); { int w = 0, h = 0; glfwGetWindowSize(window, &w, &h); glViewport(0, 0, w, h); } } glfwTerminate(); return 0; } /* #include <gl/glew.h> #include <GLFW/glfw3.h> #include <stdlib.h> #include <stdio.h> #include <glm/glm.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/transform.hpp> static const struct { float x, y; float r, g, b; } vertices[3] = { { -0.6f, -0.4f, 1.f, 0.f, 0.f }, { 0.6f, -0.4f, 0.f, 1.f, 0.f }, { 0.f, 0.6f, 0.f, 0.f, 1.f } }; static const char* vertex_shader_text = "#version 110\n" "uniform mat4 MVP;\n" "attribute vec3 vCol;\n" "attribute vec2 vPos;\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n" " color = vCol;\n" "}\n"; static const char* fragment_shader_text = "#version 110\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_FragColor = vec4(color, 1.0);\n" "}\n"; static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); } int main(void) { GLFWwindow* window; GLuint vertex_buffer, vertex_shader, fragment_shader, program; GLint mvp_location, vpos_location, vcol_location; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glewInit(); glfwSwapInterval(1); // NOTE: OpenGL error checks have been omitted for brevity glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); vcol_location = glGetAttribLocation(program, "vCol"); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*)0); glEnableVertexAttribArray(vcol_location); glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void*)(sizeof(float) * 2)); while (!glfwWindowShouldClose(window)) { float ratio; int width, height; glm::mat4 m, p, mvp; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float)height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); m = glm::mat4(1.0f); m = glm::rotate(m, (float)glfwGetTime(), {0.3,0.2,0.1}); p = glm::ortho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f); mvp = p * m; glUseProgram(program); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*)&mvp[0][0]); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } */
ca6e48090b84f1c798632109e8589b3e5c5f3bf5
[ "Markdown", "C++" ]
5
C++
meemknight/cubeMarching
62469188eb70d14ffecfdaf01e9a4e46e28d61bf
8b6dfe422f95c07f5af4ae23c4a3a5250e5c4fc6
refs/heads/master
<file_sep>package com.codecool.library.views; import com.codecool.library.utils.InputGetter; public class RootView extends AbstractView { public void displayMenu() { clearConsole(); System.out.println("\nWhat do you want to do?\n" + " 1. Add new book\n" + " 2. Edit book\n" + " 3. Delete book\n" + " 4. Search for book\n" + " 5. Show all books sorted by name ascending\n" + " 6. Show all books by given author\n" + " 7. Show authors and their books quantity\n" + " 8. Show all books written in the last 10 years\n" + " 9. Show most expensive book\n" + " 10. Show author full name and age\n" + " 0. Exit"); } public void displayWrongInputMessage() { System.out.println("Wrong input!"); } public String getUserInput() { return InputGetter.getStringInputFromConsole("Choose option: "); } } <file_sep>package com.codecool.library.services; import com.codecool.library.dao.AuthorDAO; import com.codecool.library.models.Author; import com.codecool.library.views.AuthorView; import java.util.ArrayList; import java.util.List; public class AuthorService { private AuthorDAO authorDAO; private AuthorView authorView; public AuthorService(AuthorDAO authorDAO, AuthorView authorView) { this.authorDAO = authorDAO; this.authorView = authorView; } public Author getAuthor() { authorView.displayEntriesNoInput(new ArrayList<>(authorDAO.getAll())); int id; do { id = authorView.getAuthorIdInput(); } while (authorDAO.getById(id) == null); return authorDAO.getById(id); } public List<Author> getAllAuthors() { return authorDAO.getAll(); } public void displayAuthorFullNameAndAge(Author author) { authorView.displayFullNameAndAge(author); } } <file_sep>package com.codecool.library.dao; import com.codecool.library.data.DbHelper; import com.codecool.library.data.PreparedStatementCreator; import com.codecool.library.data.contracts.BookEntry; import com.codecool.library.data.statements.BookStatement; import com.codecool.library.models.Author; import com.codecool.library.models.Book; import com.codecool.library.utils.QueryLogger; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class DbBookDAO extends DbHelper implements BookDAO { private BookStatement bookStatement = new BookStatement(); private PreparedStatementCreator psc = new PreparedStatementCreator(); private AuthorDAO authorDAO; private PublisherDAO publisherDAO; private BookTypeDAO bookTypeDAO; public DbBookDAO(AuthorDAO authorDAO, PublisherDAO publisherDAO, BookTypeDAO bookTypeDAO) { this.authorDAO = authorDAO; this.publisherDAO = publisherDAO; this.bookTypeDAO = bookTypeDAO; } @Override public boolean add(Book book) { String sqlStatement = bookStatement.insertBookStatement(); List params = Arrays.asList(book.getISBN(), book.getAuthor().getId(), book.getTitle(), book.getPublisher().getPublisherId(), book.getPublicationYear(), book.getPrice(), book.getType().getTypeId()); PreparedStatement statement = psc.getPreparedStatementBy(params, sqlStatement); return update(statement); } @Override public boolean delete(Book book) { String sqlStatement = bookStatement.deleteBookStatement(); List params = Collections.singletonList(book.getISBN()); PreparedStatement statement = psc.getPreparedStatementBy(params, sqlStatement); return update(statement); } @Override public boolean update(Book book) { String sqlStatement = bookStatement.updateBookStatement(); List params = Arrays.asList(book.getAuthor().getId(), book.getTitle(), book.getPublisher().getPublisherId(), book.getPublicationYear(), book.getPrice(), book.getType().getTypeId(), book.getISBN()); PreparedStatement statement = psc.getPreparedStatementBy(params, sqlStatement); return update(statement); } @Override public Book getByISBN(long ISBN) { String sqlStatement = bookStatement.selectBookByISBN(); Book book = null; try { PreparedStatement statement = getPreparedStatement(sqlStatement); statement.setDouble(1, ISBN); ResultSet resultSet = query(statement); while (resultSet.next()) book = new Book( resultSet.getLong(BookEntry.ISBN.toString()), authorDAO.getById(resultSet.getInt(BookEntry.author.toString())), resultSet.getString(BookEntry.title.toString()), publisherDAO.getById(resultSet.getString(BookEntry.publisher.toString())), resultSet.getInt(BookEntry.publication_year.toString()), resultSet.getDouble(BookEntry.price.toString()), bookTypeDAO.getById(resultSet.getInt(BookEntry.type.toString())) ); resultSet.close(); statement.close(); } catch (SQLException e) { QueryLogger.logInfo(e.getClass().getName() + ": " + e.getMessage(), "logs/errors.log"); System.err.println(e.getClass().getName() + ": " + e.getMessage()); } finally { closeConnection(); } return book; } @Override public List<Book> getAll() { String sqlStatement = bookStatement.selectAllBooks(); PreparedStatement statement = psc.getPreparedStatementBy(new ArrayList<>(),sqlStatement); return getBooks(statement); } @Override public List<Book> getByAuthor(Author author) { String sqlStatement = bookStatement.selectBooksByAuthor(); List params = Collections.singletonList(author.getId()); PreparedStatement statement = psc.getPreparedStatementBy(params, sqlStatement); return getBooks(statement); } @Override public List<Book> getBySearchPhrase(String searchPhrase) { String sqlStatement = bookStatement.selectBooksBySearchPhrase(); List params = new ArrayList<>(Collections.nCopies(5, "%" + searchPhrase + "%")); PreparedStatement statement = psc.getPreparedStatementBy(params, sqlStatement); return getBooks(statement); } private List<Book> getBooks(PreparedStatement statement) { List<Book> books = new ArrayList<>(); try { ResultSet resultSet = query(statement); while (resultSet.next()) books.add(new Book( resultSet.getLong(BookEntry.ISBN.toString()), authorDAO.getById(resultSet.getInt(BookEntry.author.toString())), resultSet.getString(BookEntry.title.toString()), publisherDAO.getById(resultSet.getString(BookEntry.publisher.toString())), resultSet.getInt(BookEntry.publication_year.toString()), resultSet.getDouble(BookEntry.price.toString()), bookTypeDAO.getById(resultSet.getInt(BookEntry.type.toString())) )); resultSet.close(); statement.close(); } catch (SQLException e) { QueryLogger.logInfo(e.getClass().getName() + ": " + e.getMessage(), "logs/errors.log"); System.err.println(e.getClass().getName() + ": " + e.getMessage()); } finally { closeConnection(); } return books; } } <file_sep>package com.codecool.library.services; import com.codecool.library.dao.BookTypeDAO; import com.codecool.library.models.BookType; import com.codecool.library.views.BookTypeView; import java.util.ArrayList; public class BookTypeService { private BookTypeDAO bookTypeDAO; private BookTypeView bookTypeView; public BookTypeService(BookTypeDAO bookTypeDAO, BookTypeView bookTypeView) { this.bookTypeDAO = bookTypeDAO; this.bookTypeView = bookTypeView; } public BookType getBookType() { bookTypeView.displayEntriesNoInput(new ArrayList<>(bookTypeDAO.getAll())); int id; do { id = bookTypeView.getBookTypeIdInput(); } while (bookTypeDAO.getById(id) == null); return bookTypeDAO.getById(id); } } <file_sep># Book management system Simple book management console system with SQLite database, written using Java JDBC. ### User stories * As User I would like to add new book to my book collection * As User I would like to edit given book's data. * As User I would like to delete book from collection * As User I would like to search for a books by one of theirs parameters (by ISBN number, title, author, publication year, publisher's name) * As User I would like to see all books available in library sorted ascending by name of books * As User I would like to see all books written by given author ### Expected output * Program is simple console application * Program will print simple menu with all available options based on user story * Program is foolproof. * Program is sql-injection-proof ### Additional user stories * As User I would like to see how many books authors created. * As User I would like to see all books written in the last 10 years. * As User I would like to see which of the books is the most expensive one. * As User I would like to display full name of the author and his/her age. ## Technical details ### Code architecture * You must implement program within MVC structure. * Use DAO pattern for data access. * Divide code into proper packages ### Database architecture * During tables creation use proper data type. ![c1](https://raw.github.com/lpelczar/Book-Management-System-SQLite/master/diagram.png) ![c2](https://raw.github.com/lpelczar/Book-Management-System-SQLite/master/bookstore.png) ### OOP * Use inheritance within your project structure. * Use polimorphysm for the sake of flexibility and data hiding * Use encapsulation. * Remember about abstraction! ### Clean code * Do not forget about basic principles (DRY etc), follow java code guidelines ### More info * Written for [Codecool](https://codecool.com/) programming course <file_sep>package com.codecool.library.data.statements; import com.codecool.library.data.contracts.AuthorEntry; import com.codecool.library.data.contracts.BookTypeEntry; public class BookTypeStatement { public String selectBookTypeById() { return "SELECT * FROM " + BookTypeEntry.TABLE_NAME + " WHERE " + BookTypeEntry.type_id + " = ?;" ; } public String selectAllBookTypes() { return "SELECT * FROM " + BookTypeEntry.TABLE_NAME + ";" ; } } <file_sep>CREATE TEMP TABLE booksTEMP ( ISBN, author, title, publisher, publication_year, price, type ); CREATE TEMP TABLE authorsTEMP ( author_id, name, surname, birth_year, city, country ); CREATE TEMP TABLE publishersTEMP ( publisher_id, name, city, country ); CREATE TEMP TABLE type_booksTEMP ( type_id, type ); .mode csv .import Books.csv booksTEMP .import Authors.csv authorsTEMP .import Publishers.csv publishersTEMP .import TypeBooks.csv type_booksTEMP INSERT INTO books ( ISBN, author, title, publisher, publication_year, price, type ) SELECT * FROM booksTEMP WHERE ROWID != 1; INSERT INTO authors ( author_id, name, surname, birth_year, city, country ) SELECT * FROM authorsTEMP WHERE ROWID != 1; INSERT INTO publishers ( publisher_id, name, city, country ) SELECT * FROM publishersTEMP WHERE ROWID != 1; INSERT INTO type_books ( type_id, type ) SELECT * FROM type_booksTEMP WHERE ROWID != 1;<file_sep>package com.codecool.library.utils; import java.util.Scanner; import static com.codecool.library.utils.NumberUtil.isDouble; import static com.codecool.library.utils.NumberUtil.isInteger; import static com.codecool.library.utils.NumberUtil.isLong; public class InputGetter { public static String getStringInputFromConsole(String message) { String input = null; boolean isCorrectInput = false; while(!isCorrectInput) { System.out.print(message); input = getStringInput(); if (input.trim().length() > 0) { isCorrectInput = true; } } return input; } public static int getIntInputFromConsole(String message) { String input = null; boolean isCorrectInput = false; while(!isCorrectInput) { System.out.print(message); input = getStringInput(); if (input.trim().length() > 0 && isInteger(input)) { isCorrectInput = true; } } return Integer.parseInt(input); } public static double getDoubleInputFromConsole(String message) { String input = null; boolean isCorrectInput = false; while(!isCorrectInput) { System.out.print(message); input = getStringInput(); if (input.trim().length() > 0 && isDouble(input)) { isCorrectInput = true; } } return Double.parseDouble(input); } public static long getLongInputFromConsole(String message) { String input = null; boolean isCorrectInput = false; while(!isCorrectInput) { System.out.print(message); input = getStringInput(); if (input.trim().length() > 0 && isLong(input)) { isCorrectInput = true; } } return Long.parseLong(input); } private static String getStringInput() { Scanner scanner = new Scanner(System.in); return scanner.nextLine(); } } <file_sep>package com.codecool.library.views; import com.codecool.library.utils.InputGetter; public class PublisherView extends AbstractView { public String getPublisherIdInput() { return InputGetter.getStringInputFromConsole("Enter publisher ID: "); } } <file_sep>CREATE TABLE publishers ( publisher_id TEXT PRIMARY KEY , name TEXT, city TEXT, country TEXT ); CREATE TABLE authors ( author_id INTEGER PRIMARY KEY , name TEXT, surname TEXT, birth_year INTEGER, city TEXT, country TEXT ); CREATE TABLE type_books ( type_id INTEGER PRIMARY KEY , type TEXT ); CREATE TABLE books ( ISBN INTEGER PRIMARY KEY, author INTEGER, title TEXT, publisher TEXT, publication_year INTEGER, price REAL, type INTEGER, FOREIGN KEY (publisher) REFERENCES publishers(publisher_id) ON DELETE CASCADE, FOREIGN KEY (author) REFERENCES authors(author_id) ON DELETE CASCADE, FOREIGN KEY (type) REFERENCES type_books(type_id) ON DELETE CASCADE );<file_sep>package com.codecool.library.dao; import com.codecool.library.models.Author; import com.codecool.library.models.Book; import java.util.List; public interface BookDAO { boolean add(Book book); boolean delete(Book book); boolean update(Book book); List<Book> getAll(); List<Book> getByAuthor(Author author); List<Book> getBySearchPhrase(String searchPhrase); Book getByISBN(long ISBN); } <file_sep>package com.codecool.library.dao; import com.codecool.library.models.BookType; import java.util.List; public interface BookTypeDAO { BookType getById(int id); List<BookType> getAll(); }
3af5796015343d1ec178f62de4ae299751d2a97d
[ "Markdown", "Java", "SQL" ]
12
Java
lpelczar/Book-Management-System-SQLite
e33502bf79af2d65856131aed2f75192e3caa666
e28e88a75a27eb0a8ea7a699c841d3a5a64ea979
refs/heads/master
<file_sep>package tests; import iterator.Iterator; import iterator.NestedLoopsJoinsIndexScan; import iterator.QueryPlanExecutor; import iterator.SortMerge; import heap.*; import global.*; import index.*; import java.io.*; import java.util.*; import java.lang.*; import java.nio.file.NoSuchFileException; import diskmgr.*; import bufmgr.*; import btree.*; import catalog.*; class GetInput { GetInput() {} /* * Gets validated integer choice from System.in */ public static int getChoice (int min, int max) { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); int choice = -1; boolean validChoice = false; while(!validChoice) { try { choice = Integer.parseInt(in.readLine()); } catch (NumberFormatException e) { return -1; } catch (IOException e) { return -1; } if( choice >= min && choice <= max) { break; } else { System.out.println("Invalid choice. Please enter again: "); } } return choice; } /* * Gets validated String from System.in */ public static String getString () { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); String input = ""; boolean validChoice = false; while(!validChoice) { try { input = in.readLine(); } catch (IOException e) { return ""; } if(input.length() != 0) { break; } else { System.out.println("Invalid choice. Please enter again: "); } } return input; } /* * Gets Gets return value of System.in */ public static void getReturn () { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); try { String ret = in.readLine(); } catch (IOException e) {} } } /* * Pattern Tree Driver: * - Inputs an XML path, parses the file and adds the contents into the database. * - Inputs and runs a Choice driven simple parse tree or complex parse tree. */ class PTDriver implements GlobalConst { private boolean OK = true; private boolean FAIL = false; private Heapfile heap; private SystemDefs sysdef; public PCounter pcounter = PCounter.getSingletonInstance(); public static final String INDEXNAME = "BTreeIndexForNLJ"; public SystemDefs getSysdef() { return sysdef; } public void setSysdef(SystemDefs sysdef) { this.sysdef = sysdef; } /* * Parse input XML file and add contents into a new heap file. */ public PTDriver(String path, final String heapFileName) { pcounter.resetAllCount(); String dbpath = "/tmp/"+System.getProperty("user.name")+".minibase.jointestdb"; String logpath = "/tmp/"+System.getProperty("user.name")+".joinlog"; String remove_cmd = "/bin/rm -rf "; String remove_logcmd = remove_cmd + logpath; String remove_dbcmd = remove_cmd + dbpath; String remove_joincmd = remove_cmd + dbpath; boolean status; try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); Runtime.getRuntime().exec(remove_joincmd); } catch (IOException e) { System.err.println (""+e); } this.sysdef = new SystemDefs( dbpath, 100000, NUMBUF, "Clock" ); this.heap = null; try { this.heap = new Heapfile(heapFileName); } catch (Exception e) { System.err.println("*** error in Heapfile constructor ***"); status = FAIL; e.printStackTrace(); } List<NodeTuple> nodes = null; try { nodes = global.ParseXML.parse(path); } catch (FileNotFoundException e) { System.out.println("Error: Invalid file path in xml input file"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { status = this.heap.insertRecordfromXML(nodes); } catch (InvalidSlotNumberException | InvalidTupleSizeException | SpaceNotAvailableException | HFException | HFBufMgrException | HFDiskMgrException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } pcounter.printThenResetCounters(); System.out.println("Exporting done!"); System.out.println("Creating index."); createIndex(); System.out.println("Index creation done."); pcounter.printThenResetCounters(); } public void createIndex() { // Creating Index on heapfile AttrType[] Stypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString) }; short[] Ssizes = new short[1]; Ssizes[0] = 10; // _______________________________________________________________ // *******************create an scan on the heapfile************** // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // create a tuple of appropriate size Tuple tt = new Tuple(); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } int sizett = tt.size(); tt = new Tuple(sizett); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } Scan scan = null; try { scan = new Scan(heap); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } // create the index file BTreeFile btf = null; try { btf = new BTreeFile(INDEXNAME, AttrType.attrString, 8, 1); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } RID rid = new RID(); String key = null; Tuple temp = null; try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } while (temp != null) { tt.tupleCopy(temp); try { key = tt.getStrFld(3); } catch (Exception e) { e.printStackTrace(); } try { btf.insert(new StringKey(key.trim()), rid); } catch (Exception e) { e.printStackTrace(); } try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } } // close the file scan scan.closescan(); } private void menuPatternTreeIp() { System.out.println("\n1. Run simple pattern tree"); System.out.println("2. Run complex pattern tree"); System.out.println("3. Exit"); System.out.println("Enter your choice: "); } private void menuQueryPlans() { System.out.println("\n1. Run Query 1 of pattern tree"); System.out.println("2. Run Query 2 of pattern tree"); System.out.println("3. Run Query 3 of pattern tree"); System.out.println("4. Input Another Pattern Tree"); System.out.println("5. Exit"); System.out.println("Enter your choice: "); } /* * Runs choice driven tests for running multiple simple parse trees * or multiple complex parse trees using selection of various query plansion in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration Syntax error, insert ";" to complete LocalVariableDeclarationStatement Sys cannot be resolved at tests.PTDriver.createIndex(PatternTreeTest.java:196) at tests.PTDriver.<init>(PatternTreeTest.java:171) at tests.PatternTreeTest.main(PatternTreeTest.java:407) * * TODO: Create an only argument based running of tests. */ public void runTests (Boolean noArgs, String [] args, SystemDefs sysdefs, String HEAPFILENAME) { QueryPlanExecutor query = new QueryPlanExecutor(); while(true) { menuPatternTreeIp(); int flag = 0; int choice = GetInput.getChoice(1,3); switch(choice) { // Running simple pattern tree case 1: System.out.println("Enter simple pattern tree file path: "); String ptPath = GetInput.getString(); SimplePatternTreeParser spt = new SimplePatternTreeParser(ptPath); if (spt.getConditions() == null) { break; } while(true) { menuQueryPlans(); int choice2 = GetInput.getChoice(1,5); if (choice2 == 4) { break; } // Running query plans 1, 2 or 3 Iterator it = null; NestedLoopsJoinsIndexScan nlj = null; switch(choice2) { case 1: System.out.println("Running query plan 1"); it = (NestedLoopsJoinsIndexScan)it; it = query.QueryPlanExecutor1_iterative(spt.getMap(), spt.getConditions(), spt.getInl(),0,HEAPFILENAME,-1,spt.getDynamic()); break; case 2: System.out.println("Running query plan 2"); it = (SortMerge)it; it=query.QueryPlanExecutor2_iterative(spt.getMap(), spt.getConditions(), spt.getInl(),0,HEAPFILENAME,-1,spt.getDynamic()); // QueryPlans.query2(spt.getConditions()); break; case 3: System.out.println("Running query plan 3"); it = (SortMerge)it; it=query.QueryPlanExecutor3(spt.getMap(), spt.getConditions(), spt.getInl(),0,HEAPFILENAME,-1,spt.getDynamic()); // QueryPlans.query3(spt.getConditions()); break; case 5: System.exit(0); break; default: it = (NestedLoopsJoinsIndexScan)it; it = query.QueryPlanExecutor1_iterative(spt.getMap(), spt.getConditions(), spt.getInl(),0,HEAPFILENAME,-1,spt.getDynamic()); nlj = (NestedLoopsJoinsIndexScan)it; } int sizeofTuple = it.getFinalTupleSize(); AttrType [] outputtype = new AttrType[sizeofTuple]; for(int i=0;i< sizeofTuple;i=i+3) { outputtype[i]= new AttrType(AttrType.attrInterval); outputtype[i+1]=new AttrType(AttrType.attrInteger); outputtype[i+2]=new AttrType(AttrType.attrString); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(outputtype); } } catch (Exception e) { System.err.println (""+e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println ("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } pcounter.printThenResetCounters(); } break; // Running complex pattern tree case 2: System.out.println("Enter complex pattern tree file path: "); String complexPtPath = GetInput.getString(); ComplexPatternTreeParser cpt = new ComplexPatternTreeParser(complexPtPath); // Passing empty page replacement policy will pick up the previous replacement policy // sysdefs.recreateBM(cpt.getBuf_size(), ""); while(true) { menuQueryPlans(); int choice2 = GetInput.getChoice(1,5); if (choice2 == 4) { flag = 1; break; } // Running query plans 1, 2 or 3 switch(choice2) { case 1: System.out.println("Running query1"); cpt.execute2(1); break; case 2: System.out.println("Running query2"); cpt.execute2(2); break; case 3: System.out.println("Running query3"); cpt.execute2(3); break; case 5: System.exit(0); break; default: cpt.execute2(2); System.out.println("Invalid choice. Enter choice again."); } break; } break; case 3: System.exit(0); break; default: System.exit(0); } } } } public class PatternTreeTest { public static void main(String[] args) { // TODO Auto-generated method stub String xmlPath; if (args.length == 0) { System.out.println("Enter xml input file path: "); xmlPath = GetInput.getString(); } else { xmlPath = args[0]; } File tmpDir = new File(xmlPath); while (!tmpDir.exists()) { System.out.println("XML input path does not exist. Please enter valid xml input file path: "); xmlPath = GetInput.getString(); tmpDir = new File(xmlPath); } Boolean noArgs = (args.length == 1 ? true : false); System.out.println("Parsing and exporting xml file in database..."); final String HEAPFILENAME = "xml.in"; //Parse the input xml and add the data into the database. PTDriver pttest = new PTDriver(xmlPath, HEAPFILENAME); pttest.runTests(noArgs, args, pttest.getSysdef(),HEAPFILENAME); } }<file_sep>package global; import bufmgr.PCounter; public interface GlobalConst { public static final int MINIBASE_MAXARRSIZE = 8000; public static final int NUMBUF = 100000; /** Size of page. */ public static final int MINIBASE_PAGESIZE = 8096; // in bytes public static final int PAGE_METADATA_SIZE = 16; public static final int TUPLE_SIZE = 34; public static final int TUPLE_BUFFER_SIZE = 4; /** Size of each frame. */ public static final int MINIBASE_BUFFER_POOL_SIZE = 8096; // in Frames public static final int MAX_SPACE = 8096; // in Frames /** * in Pages => the DBMS Manager tells the DB how much disk * space is available for the database. */ public static final int MINIBASE_DB_SIZE = 100000000; public static final int MINIBASE_MAX_TRANSACTIONS = 100; public static final int MINIBASE_DEFAULT_SHAREDMEM_SIZE = 1000; /** * also the name of a relation */ public static final int MAXFILENAME = 15; public static final int MAXINDEXNAME = 40; public static final int MAXATTRNAME = 15; public static final int MAX_NAME = 50; public static final int INVALID_PAGE = -1; public static final PCounter pcounter = PCounter.getSingletonInstance(); } <file_sep>const express = require('express') const bodyParser = require('body-parser') const exphbs = require("express-handlebars"); const passport = require('passport'); const flash = require('connect-flash'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const app = express(); var db = require("./models"); require('./config/passport')(passport) app.get('/' , (req,res) => { res.send('Hello World!') }) app.listen(8000, () => { console.log('Example app listening on port 8000!') })<file_sep>package tests; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import btree.BTreeFile; import btree.StringKey; import global.AttrOperator; import global.AttrType; import global.GlobalConst; import global.IndexType; import global.Intervaltype; import global.RID; import global.SystemDefs; import heap.HFBufMgrException; import heap.HFDiskMgrException; import heap.HFException; import heap.Heapfile; import heap.InvalidSlotNumberException; import heap.InvalidTupleSizeException; import heap.NodeTuple; import heap.Scan; import heap.SpaceNotAvailableException; import heap.Tuple; import index.IndexScan; import intervaltree.IntervalKey; import intervaltree.IntervalTreeFile; import iterator.CondExpr; import iterator.FldSpec; import iterator.Iterator; import iterator.NestedLoopsJoins; import iterator.NestedLoopsJoinsIndexScan; import iterator.RelSpec; public class IntervalTIndexTest { public static final String HEAPFILENAME = "xml2.in"; public static final String INDEXNAME = "BTreeIndexForNLJ"; public void createIndex() { // Creating Index on heapfile AttrType[] Stypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString) }; short[] Ssizes = new short[1]; Ssizes[0] = 10; // _______________________________________________________________ // *******************create an scan on the heapfile************** // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // create a tuple of appropriate size Tuple tt = new Tuple(); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } int sizett = tt.size(); tt = new Tuple(sizett); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } Heapfile f = null; try { f = new Heapfile(HEAPFILENAME); } catch (Exception e) { e.printStackTrace(); } Scan scan = null; try { scan = new Scan(f); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } // create the index file IntervalTreeFile btf = null; try { btf = new IntervalTreeFile(INDEXNAME, AttrType.attrInterval, 8, 1); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } RID rid = new RID(); Intervaltype key = null; Tuple temp = null; try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } while (temp != null) { tt.tupleCopy(temp); try { key = tt.getIntervalFld(1); } catch (Exception e) { e.printStackTrace(); } try { btf.insert(new IntervalKey(key), rid); } catch (Exception e) { e.printStackTrace(); } try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } } // close the file scan scan.closescan(); } public IntervalTIndexTest(String XMLPath) { super(); String dbpath = "/tmp/" + System.getProperty("user.name") + ".minibase.nljtestdb"; String logpath = "/tmp/" + System.getProperty("user.name") + ".nljlog"; String remove_cmd = "/bin/rm -rf "; String remove_logcmd = remove_cmd + logpath; String remove_dbcmd = remove_cmd + dbpath; String remove_joincmd = remove_cmd + dbpath; try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); Runtime.getRuntime().exec(remove_joincmd); } catch (IOException e) { System.err.println("" + e); } SystemDefs sysdef = new SystemDefs(dbpath, 100000, GlobalConst.NUMBUF, "Clock"); // creating the XML Interval relation AttrType[] Stypes = new AttrType[3]; Stypes[0] = new AttrType(AttrType.attrInterval); Stypes[1] = new AttrType(AttrType.attrInteger); Stypes[2] = new AttrType(AttrType.attrString); // SOS // Max Size of String is 5 chars short[] Ssizes = new short[1]; Ssizes[0] = 10; // first elt. is 30 Tuple t = new Tuple(); try { t.setHdr((short) Stypes.length, Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); e.printStackTrace(); } int size = t.size(); RID rid; Heapfile f = null; try { f = new Heapfile(HEAPFILENAME); } catch (Exception e) { System.err.println("*** error in Heapfile constructor ***"); e.printStackTrace(); } t = new Tuple(size); try { t.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); e.printStackTrace(); } System.out.println("Starting with the Parsing....."); List<NodeTuple> nodes = null; try { nodes = global.ParseXML.parse(XMLPath); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("Parsing Completed......"); /* * for (NodeTuple node : nodes) { try { t.setIntervalFld(1, * node.getNodeIntLabel()); t.setIntFld(2, node.getLevel()); t.setStrFld(3, * node.getName()); * * } catch (Exception e) { * System.err.println("*** Heapfile error in Tuple.setStrFld() ***"); * e.printStackTrace(); } * * try { rid = f.insertRecord(t.returnTupleByteArray()); } catch (Exception e) { * System.err.println("*** error in Heapfile.insertRecord() ***"); * e.printStackTrace(); } } */ try { f.insertRecordfromXML(nodes); } catch (InvalidSlotNumberException | InvalidTupleSizeException | SpaceNotAvailableException | HFException | HFBufMgrException | HFDiskMgrException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } System.out.println("Inserted Records successfully..."); } private void printAllIndex() { AttrType[] ltypes = new AttrType[3]; ltypes[0] = new AttrType(AttrType.attrInterval); ltypes[1] = new AttrType(AttrType.attrInteger); ltypes[2] = new AttrType(AttrType.attrString); short[] lsizes = new short[1]; lsizes[0] = 10; FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.Interval_Index); Iterator it = null; try { it = new IndexScan(b_index, HEAPFILENAME, INDEXNAME, ltypes, lsizes, 3, 3, lprojection, null, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(ltypes); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } } private void printBeforeIndex() { CondExpr[] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopLE); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrInterval); leftFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1); leftFilter[0].operand2.intervaltype = new Intervaltype(-299973,Integer.MIN_VALUE); leftFilter[0].flag =1; leftFilter[1] = null; AttrType[] ltypes = new AttrType[3]; ltypes[0] = new AttrType(AttrType.attrInterval); ltypes[1] = new AttrType(AttrType.attrInteger); ltypes[2] = new AttrType(AttrType.attrString); short[] lsizes = new short[1]; lsizes[0] = 10; FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.Interval_Index); Iterator it = null; try { it = new IndexScan(b_index, HEAPFILENAME, INDEXNAME, ltypes, lsizes, 3, 3, lprojection, leftFilter, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(ltypes); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } } private void printAfterIndex() { CondExpr[] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopGE); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrInterval); leftFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1); leftFilter[0].operand2.intervaltype = new Intervaltype(-299973,Integer.MAX_VALUE); leftFilter[0].flag =1; leftFilter[1] = null; AttrType[] ltypes = new AttrType[3]; ltypes[0] = new AttrType(AttrType.attrInterval); ltypes[1] = new AttrType(AttrType.attrInteger); ltypes[2] = new AttrType(AttrType.attrString); short[] lsizes = new short[1]; lsizes[0] = 10; FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.Interval_Index); Iterator it = null; try { it = new IndexScan(b_index, HEAPFILENAME, INDEXNAME, ltypes, lsizes, 3, 3, lprojection, leftFilter, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(ltypes); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } } private void printEqualIndex() { CondExpr[] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopEQ); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrInterval); leftFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1); leftFilter[0].operand2.intervaltype = new Intervaltype(-299973,Integer.MAX_VALUE); leftFilter[0].flag =1; leftFilter[1] = null; AttrType[] ltypes = new AttrType[3]; ltypes[0] = new AttrType(AttrType.attrInterval); ltypes[1] = new AttrType(AttrType.attrInteger); ltypes[2] = new AttrType(AttrType.attrString); short[] lsizes = new short[1]; lsizes[0] = 10; FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.Interval_Index); Iterator it = null; try { it = new IndexScan(b_index, HEAPFILENAME, INDEXNAME, ltypes, lsizes, 3, 3, lprojection, leftFilter, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(ltypes); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } } private void printSpanIndex() { CondExpr[] leftFilter = new CondExpr[3]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopLE); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrInterval); leftFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1); leftFilter[0].operand2.intervaltype = new Intervaltype(-299967,Integer.MIN_VALUE); leftFilter[0].flag =1; leftFilter[1] = new CondExpr(); leftFilter[1].next = null; leftFilter[1].op = new AttrOperator(AttrOperator.aopGE); leftFilter[1].type1 = new AttrType(AttrType.attrSymbol); leftFilter[1].type2 = new AttrType(AttrType.attrInterval); leftFilter[1].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1); leftFilter[1].operand2.intervaltype = new Intervaltype(-299973,Integer.MAX_VALUE); leftFilter[1].flag =1; leftFilter[2] = null; AttrType[] ltypes = new AttrType[3]; ltypes[0] = new AttrType(AttrType.attrInterval); ltypes[1] = new AttrType(AttrType.attrInteger); ltypes[2] = new AttrType(AttrType.attrString); short[] lsizes = new short[1]; lsizes[0] = 10; FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.Interval_Index); Iterator it = null; try { it = new IndexScan(b_index, HEAPFILENAME, INDEXNAME, ltypes, lsizes, 3, 3, lprojection, leftFilter, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } Tuple t; t = null; try { while ((t = it.get_next()) != null) { t.print(ltypes); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { it.close(); } catch (Exception e) { e.printStackTrace(); } } private void Disclaimer() { System.out.print("\n\nAny resemblance of persons in this database to" + " people living or dead\nis purely coincidental. The contents of " + "this database do not reflect\nthe views of the University," + " the Computer Sciences Department or the\n" + "developers...\n\n"); } public static void main(String argv[]) { boolean sortstatus = false; try { IntervalTIndexTest nlj = new IntervalTIndexTest(argv[0]); nlj.Disclaimer(); nlj.createIndex(); System.out.println("Hopefully created index"); //System.out.println("--------Iterating All Indexes----------"); //nlj.printAllIndex(); //System.out.println("--------Iterting 0- Before Indexes------"); //nlj.printBeforeIndex(); //System.out.println("--------Iterating 3- after Indexes-------"); nlj.printAfterIndex(); //System.out.println("--------Iterating Span Indexes----------"); //nlj.printSpanIndex(); sortstatus = true; System.out.println("Hopefully created index"); nlj.printEqualIndex(); } catch(Exception e){ e.printStackTrace(); } if (sortstatus != true) { System.out.println("Error ocurred during join tests"); } else { System.out.println("join tests completed successfully"); } } } <file_sep>package global; public class Intervaltype { public Intervaltype() { super(); } public Intervaltype(Intervaltype interval) { super(); this.start = interval.start; this.end = interval.end; } public Intervaltype(int starter, int ender) { super(); this.start = starter; this.end = ender; } private int start; private int end; public static int START_MIN_VALUE = -300000; public static int END_MIN_VALUE = -300000; public static int START_MAX_VALUE =300000; public static int END_MAX_VALUE = 300000; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public void assign(int a, int b) { if (a >= START_MIN_VALUE && a <= START_MAX_VALUE && (( b >= END_MIN_VALUE && b <= END_MAX_VALUE)|| (b==Integer.MIN_VALUE)) || (b==Integer.MAX_VALUE)) { this.start = a; this.end = b; } else { throw new IllegalStateException(); } } public static Intervaltype min_value() { Intervaltype type = new Intervaltype(); type.setStart(START_MIN_VALUE); type.setEnd(END_MIN_VALUE); return type; } public static Intervaltype max_value() { Intervaltype type = new Intervaltype(); type.setStart(START_MAX_VALUE); type.setEnd(END_MAX_VALUE); return type; } @Override public String toString() { return "Intervaltype [start=" + start + ", end=" + end + "]"; } } <file_sep># DBMSI-510-Project <file_sep>package tests; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import btree.BTreeFile; import btree.StringKey; import global.AttrOperator; import global.AttrType; import global.GlobalConst; import global.IndexType; import global.RID; import global.SystemDefs; import heap.Heapfile; import heap.NodeTuple; import heap.Scan; import heap.Tuple; import index.IndexScan; import iterator.CondExpr; import iterator.FldSpec; import iterator.Iterator; import iterator.NestedLoopsJoins; import iterator.NestedLoopsJoinsIndexScan; import iterator.RelSpec; public class NLJIndexTest { public static final String HEAPFILENAME = "xml2.in"; public static final String INDEXNAME = "BTreeIndexForNLJ"; public void createIndex() { // Creating Index on heapfile AttrType[] Stypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString) }; short[] Ssizes = new short[1]; Ssizes[0] = 10; // _______________________________________________________________ // *******************create an scan on the heapfile************** // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // create a tuple of appropriate size Tuple tt = new Tuple(); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } int sizett = tt.size(); tt = new Tuple(sizett); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { e.printStackTrace(); } Heapfile f = null; try { f = new Heapfile(HEAPFILENAME); } catch (Exception e) { e.printStackTrace(); } Scan scan = null; try { scan = new Scan(f); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } // create the index file BTreeFile btf = null; try { btf = new BTreeFile(INDEXNAME, AttrType.attrString, 8, 1); } catch (Exception e) { e.printStackTrace(); Runtime.getRuntime().exit(1); } RID rid = new RID(); String key = null; Tuple temp = null; try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } while (temp != null) { tt.tupleCopy(temp); try { key = tt.getStrFld(3); } catch (Exception e) { e.printStackTrace(); } try { btf.insert(new StringKey(key.trim()), rid); } catch (Exception e) { e.printStackTrace(); } try { temp = scan.getNext(rid); } catch (Exception e) { e.printStackTrace(); } } // close the file scan scan.closescan(); } public void QueryNLJwithIndex(String patternTreeFile) { System.out.print("**********************QueryNLJwithIndex starting *********************\n"); String st; try { BufferedReader br = new BufferedReader(new FileReader(patternTreeFile)); st = br.readLine(); int nodesCount = Integer.valueOf(st); HashMap<Integer, String> map = new HashMap<Integer, String>(); for (int i = 0; i < nodesCount; i++) { st = br.readLine(); map.put(i + 1, st); } NestedLoopsJoins inl = null; List<String> conditions = new ArrayList<String>(); while ((st = br.readLine()) != null) { conditions.add(st); } int dynamicCount = -1; HashMap<Integer, String> dynamic = new HashMap<Integer, String>(); // --------------------------------------Query Plan // Index----------------------------------------- // Uncomment QueryPlanExecutorIndex() to run Query Plan index /* * Query Plan that uses deep tree travsersal using Indexs B+ tree indexes are * created on Nodename field We can use indexScan on this B+ tree indexs. And * QueryIndex uses index */ System.out.println("Query plan :Index"); QueryPlanExecutorIndex(map, conditions, inl, 0, HEAPFILENAME, dynamicCount, dynamic, INDEXNAME); System.out.println("for index:" + SystemDefs.JavabaseBM.pcounter); } catch (Exception e) { } } public NLJIndexTest(String XMLPath) { super(); String dbpath = "/tmp/" + System.getProperty("user.name") + ".minibase.nljtestdb"; String logpath = "/tmp/" + System.getProperty("user.name") + ".nljlog"; String remove_cmd = "/bin/rm -rf "; String remove_logcmd = remove_cmd + logpath; String remove_dbcmd = remove_cmd + dbpath; String remove_joincmd = remove_cmd + dbpath; try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); Runtime.getRuntime().exec(remove_joincmd); } catch (IOException e) { System.err.println("" + e); } SystemDefs sysdef = new SystemDefs(dbpath, 1000, GlobalConst.NUMBUF, "Clock"); // creating the XML Interval relation AttrType[] Stypes = new AttrType[3]; Stypes[0] = new AttrType(AttrType.attrInterval); Stypes[1] = new AttrType(AttrType.attrInteger); Stypes[2] = new AttrType(AttrType.attrString); // SOS // Max Size of String is 5 chars short[] Ssizes = new short[1]; Ssizes[0] = 10; // first elt. is 30 Tuple t = new Tuple(); try { t.setHdr((short) Stypes.length, Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); e.printStackTrace(); } int size = t.size(); RID rid; Heapfile f = null; try { f = new Heapfile(HEAPFILENAME); } catch (Exception e) { System.err.println("*** error in Heapfile constructor ***"); e.printStackTrace(); } t = new Tuple(size); try { t.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); e.printStackTrace(); } System.out.println("Starting with the Parsing....."); List<NodeTuple> nodes = null; try { nodes = global.ParseXML.parse(XMLPath); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("Parsing Completed......"); for (NodeTuple node : nodes) { try { t.setIntervalFld(1, node.getNodeIntLabel()); t.setIntFld(2, node.getLevel()); t.setStrFld(3, node.getName()); } catch (Exception e) { System.err.println("*** Heapfile error in Tuple.setStrFld() ***"); e.printStackTrace(); } try { rid = f.insertRecord(t.returnTupleByteArray()); } catch (Exception e) { System.err.println("*** error in Heapfile.insertRecord() ***"); e.printStackTrace(); } } System.out.println("Inserted Records successfully..."); } private void Disclaimer() { System.out.print("\n\nAny resemblance of persons in this database to" + " people living or dead\nis purely coincidental. The contents of " + "this database do not reflect\nthe views of the University," + " the Computer Sciences Department or the\n" + "developers...\n\n"); } public void QueryPlanExecutorIndex(HashMap<Integer, String> map, List<String> conditions, Iterator it, int conditionCount, String heapFileName, int dynamicCount, HashMap<Integer, String> dynamic, String IndexName) { if (conditionCount >= conditions.size()) { NestedLoopsJoinsIndexScan nlj = (NestedLoopsJoinsIndexScan) it; int sizeofTuple = nlj.getFinalTupleSize(); AttrType[] outputtype = new AttrType[sizeofTuple]; for (int i = 0; i < sizeofTuple; i = i + 3) { outputtype[i] = new AttrType(AttrType.attrInterval); outputtype[i + 1] = new AttrType(AttrType.attrInteger); outputtype[i + 2] = new AttrType(AttrType.attrString); } Tuple t; t = null; try { while ((t = nlj.get_next()) != null) { t.print(outputtype); } } catch (Exception e) { System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println("\n"); try { nlj.close(); } catch (Exception e) { e.printStackTrace(); } return; } // ------------ String[] splited = conditions.get(conditionCount).split("\\s+"); int index = 0; String notRepatedElement = null; if (!dynamic.containsValue(map.get(Integer.valueOf(splited[0])))) { dynamic.put(++dynamicCount, map.get(Integer.valueOf(splited[0]))); notRepatedElement = map.get(Integer.valueOf(splited[0])); } else { for (Map.Entry<Integer, String> e : dynamic.entrySet()) { if (e.getValue().equals(map.get(Integer.valueOf(splited[0])))) { index = e.getKey(); break; } } } if (!dynamic.containsValue(map.get(Integer.valueOf(splited[1])))) { dynamic.put(++dynamicCount, map.get(Integer.valueOf(splited[1]))); notRepatedElement = map.get(Integer.valueOf(splited[1])); } else { for (Map.Entry<Integer, String> e : dynamic.entrySet()) { if (e.getValue().equals(map.get(Integer.valueOf(splited[1])))) { index = e.getKey(); break; } } } // parsing for condition expressions CondExpr[] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopEQ); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrString); leftFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 3); leftFilter[0].operand2.string = map.get(Integer.valueOf(splited[0])); leftFilter[1] = null; CondExpr[] rightFilter = new CondExpr[2]; rightFilter[0] = new CondExpr(); rightFilter[0].next = null; rightFilter[0].op = new AttrOperator(AttrOperator.aopEQ); rightFilter[0].type1 = new AttrType(AttrType.attrSymbol); rightFilter[0].type2 = new AttrType(AttrType.attrString); rightFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 3); if (notRepatedElement != null) rightFilter[0].operand2.string = notRepatedElement; else rightFilter[0].operand2.string = map.get(Integer.valueOf(splited[1])); rightFilter[1] = null; String relationship = splited[2]; CondExpr[] outFilter = new CondExpr[3]; outFilter[0] = new CondExpr(); outFilter[1] = new CondExpr(); outFilter[0].next = null; outFilter[0].op = new AttrOperator(AttrOperator.aopGT); outFilter[0].type1 = new AttrType(AttrType.attrSymbol); outFilter[0].type2 = new AttrType(AttrType.attrSymbol); outFilter[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), index * 3 + 1); outFilter[0].operand2.symbol = new FldSpec(new RelSpec(RelSpec.innerRel), 1); outFilter[0].flag = 1; // outFilter[1] = null; if (relationship.equals("PC")) { outFilter[1].next = null; outFilter[1].op = new AttrOperator(AttrOperator.aopLT); outFilter[1].type1 = new AttrType(AttrType.attrSymbol); outFilter[1].type2 = new AttrType(AttrType.attrSymbol); outFilter[1].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), index * 3 + 2); outFilter[1].operand2.symbol = new FldSpec(new RelSpec(RelSpec.innerRel), 2); outFilter[1].flag = 1; outFilter[2] = null; } else if (relationship.equals("AD")) { outFilter[1] = null; outFilter[2] = null; } AttrType[] ltypes = new AttrType[(conditionCount + 1) * 3]; for (int j = 0; j < (conditionCount + 1) * 3; j = j + 3) { ltypes[j] = new AttrType(AttrType.attrInterval); ltypes[j + 1] = new AttrType(AttrType.attrInteger); ltypes[j + 2] = new AttrType(AttrType.attrString); } short[] lsizes = new short[(conditionCount + 1)]; for (int j = 0; j < lsizes.length; j++) lsizes[j] = 10; AttrType[] rtypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString), }; short[] rsizes = new short[1]; rsizes[0] = 10; if (it == null) { FldSpec[] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; IndexType b_index = new IndexType(IndexType.B_Index); try { it = new IndexScan(b_index, heapFileName, IndexName, ltypes, lsizes, 3, 3, lprojection, leftFilter, 3, false); } catch (Exception e) { System.err.println("*** Error creating scan for Index scan"); System.err.println("" + e); Runtime.getRuntime().exit(1); } } // from 2nd condition--- int fieldCounts = (conditionCount + 2) * 3; FldSpec[] proj1 = new FldSpec[fieldCounts]; // for outer relations for (int i = 0; i < fieldCounts - 3; i = i + 3) { proj1[i] = new FldSpec(new RelSpec(RelSpec.outer), 1 + i); proj1[i + 1] = new FldSpec(new RelSpec(RelSpec.outer), 2 + i); proj1[i + 2] = new FldSpec(new RelSpec(RelSpec.outer), 3 + i); } // for inner relations proj1[fieldCounts - 3] = new FldSpec(new RelSpec(RelSpec.innerRel), 1); proj1[fieldCounts - 2] = new FldSpec(new RelSpec(RelSpec.innerRel), 2); proj1[fieldCounts - 1] = new FldSpec(new RelSpec(RelSpec.innerRel), 3); FldSpec[] Indexprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; NestedLoopsJoinsIndexScan inl = null; try { inl = new NestedLoopsJoinsIndexScan(ltypes, ltypes.length, lsizes, rtypes, 3, rsizes, 10, it, heapFileName, outFilter, rightFilter, proj1, fieldCounts, INDEXNAME, 3, 3, Indexprojection, 3, false); } catch (Exception e) { System.err.println("*** Error preparing for nested_loop_join"); System.err.println("" + e); e.printStackTrace(); Runtime.getRuntime().exit(1); } QueryPlanExecutorIndex(map, conditions, inl, conditionCount + 1, heapFileName, dynamicCount, dynamic, IndexName); } public static void main(String argv[]) { boolean sortstatus = false; try { NLJIndexTest nlj = new NLJIndexTest(argv[0]); nlj.Disclaimer(); nlj.createIndex(); nlj.QueryNLJwithIndex(argv[1]); sortstatus = true; } catch(Exception e){ e.printStackTrace(); } if (sortstatus != true) { System.out.println("Error ocurred during join tests"); } else { System.out.println("join tests completed successfully"); } } } <file_sep># First argument is the JDK path to be set. # All special characters should be escaped. eg. /usr/ => \/usr\/ if [ $# -eq 0 ] then var="JDKPATH = \$\(JAVA_HOME\)" else var="JDKPATH = $1" fi sed -i "1s/.*/$var/" ./catalog/Makefile sed -i "1s/.*/$var/" ./btree/Makefile sed -i "1s/.*/$var/" ./bufmgr/Makefile sed -i "1s/.*/$var/" ./chainexception/Makefile sed -i "1s/.*/$var/" ./global/Makefile sed -i "1s/.*/$var/" ./heap/Makefile sed -i "1s/.*/$var/" ./index/Makefile sed -i "1s/.*/$var/" ./iterator/Makefile sed -i "2s/.*/$var/" ./tests/Makefile sed -i "9s/.*/$var/" ./Makefile <file_sep>package tests; //originally from : joins.C import iterator.*; import iterator.Iterator; import heap.*; import global.*; import index.*; import java.io.*; import java.util.*; import java.lang.*; import diskmgr.*; import bufmgr.*; import btree.*; /** Here is the implementation for the tests. There are N tests performed. We start off by showing that each operator works on its own. Then more complicated trees are constructed. As a nice feature, we allow the user to specify a selection condition. We also allow the user to hardwire trees together. */ // //Define the Sailor schema // class Sailor { // public int sid; // public String sname; // public int rating; // public double age; // // public Sailor (int _sid, String _sname, int _rating,double _age) { // sid = _sid; // sname = _sname; // rating = _rating; // age = _age; // } // } // // //Define the Boat schema // class Boats { // public int bid; // public String bname; // public String color; // // public Boats (int _bid, String _bname, String _color) { // bid = _bid; // bname = _bname; // color = _color; // } // } // // //Define the Reserves schema // class Reserves { // public int sid; // public int bid; // public String date; // // public Reserves (int _sid, int _bid, String _date) { // sid = _sid; // bid = _bid; // date = _date; // } // } class SM_JoinTest implements GlobalConst { private boolean OK = true; private boolean FAIL = false; private Vector sailors; private Vector boats; private Vector reserves; /** Constructor */ public SM_JoinTest(String path) { String dbpath = "/tmp/"+System.getProperty("user.name")+".minibase.jointestdb"; String logpath = "/tmp/"+System.getProperty("user.name")+".joinlog"; String remove_cmd = "/bin/rm -rf "; String remove_logcmd = remove_cmd + logpath; String remove_dbcmd = remove_cmd + dbpath; String remove_joincmd = remove_cmd + dbpath; try { Runtime.getRuntime().exec(remove_logcmd); Runtime.getRuntime().exec(remove_dbcmd); Runtime.getRuntime().exec(remove_joincmd); } catch (IOException e) { System.err.println (""+e); } /* ExtendedSystemDefs extSysDef = new ExtendedSystemDefs( "/tmp/minibase.jointestdb", "/tmp/joinlog", 1000,500,200,"Clock"); */ SystemDefs sysdef = new SystemDefs( dbpath, 1000, GlobalConst.NUMBUF, "Clock" ); // creating the XML Interval relation AttrType [] Stypes = new AttrType[3]; Stypes[0] = new AttrType (AttrType.attrInterval); Stypes[1] = new AttrType (AttrType.attrInteger); Stypes[2] = new AttrType (AttrType.attrString); //SOS // Max Size of String is 5 chars short [] Ssizes = new short [1]; Ssizes[0] = 10; //first elt. is 30 Tuple t = new Tuple(); boolean status = true; try { t.setHdr((short) 3,Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); status = FAIL; e.printStackTrace(); } int size = t.size(); // inserting the tuple into file "sailors" RID rid; Heapfile f = null; try { f = new Heapfile("xml.in"); } catch (Exception e) { System.err.println("*** error in Heapfile constructor ***"); status = FAIL; e.printStackTrace(); } t = new Tuple(size); try { t.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { System.err.println("*** error in Tuple.setHdr() ***"); status = FAIL; e.printStackTrace(); } List<NodeTuple> nodes = null; try { nodes = global.ParseXML.parse(path); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (NodeTuple node : nodes) { try { t.setIntervalFld(1, node.getNodeIntLabel()); t.setIntFld(2, node.getLevel()); t.setStrFld(3, node.getName()); } catch (Exception e) { System.err.println("*** Heapfile error in Tuple.setStrFld() ***"); status = FAIL; e.printStackTrace(); } try { rid = f.insertRecord(t.returnTupleByteArray()); } catch (Exception e) { System.err.println("*** error in Heapfile.insertRecord() ***"); status = FAIL; e.printStackTrace(); } } if (status != OK) { //bail out System.err.println ("*** Error creating relation for sailors"); Runtime.getRuntime().exit(1); } } public boolean runTests() { Disclaimer(); //QueryXML(); QueryXML_Dynamic(); /* Query1(); Query2(); Query3(); Query4(); Query5(); Query6(); */ System.out.print ("Finished joins testing"+"\n"); return true; } private void QueryXML_CondExpr(CondExpr[] expr) { expr[0].next = null; expr[0].op = new AttrOperator(AttrOperator.aopGT); expr[0].type1 = new AttrType(AttrType.attrSymbol); expr[0].type2 = new AttrType(AttrType.attrSymbol); expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1); expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr[0].flag=1; expr[1] = null; } private void Query1_CondExpr(CondExpr[] expr) { expr[0].next = null; expr[0].op = new AttrOperator(AttrOperator.aopEQ); expr[0].type1 = new AttrType(AttrType.attrSymbol); expr[0].type2 = new AttrType(AttrType.attrSymbol); expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1); expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr[1].op = new AttrOperator(AttrOperator.aopEQ); expr[1].next = null; expr[1].type1 = new AttrType(AttrType.attrSymbol); expr[1].type2 = new AttrType(AttrType.attrInteger); expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2); expr[1].operand2.integer = 1; expr[2] = null; } private void Query2_CondExpr(CondExpr[] expr, CondExpr[] expr2) { expr[0].next = null; expr[0].op = new AttrOperator(AttrOperator.aopEQ); expr[0].type1 = new AttrType(AttrType.attrSymbol); expr[0].type2 = new AttrType(AttrType.attrSymbol); expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1); expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr[1] = null; expr2[0].next = null; expr2[0].op = new AttrOperator(AttrOperator.aopEQ); expr2[0].type1 = new AttrType(AttrType.attrSymbol); expr2[0].type2 = new AttrType(AttrType.attrSymbol); expr2[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),2); expr2[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr2[1].op = new AttrOperator(AttrOperator.aopEQ); expr2[1].next = null; expr2[1].type1 = new AttrType(AttrType.attrSymbol); expr2[1].type2 = new AttrType(AttrType.attrString); expr2[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),3); expr2[1].operand2.string = "red"; expr2[2] = null; } private void Query3_CondExpr(CondExpr[] expr) { expr[0].next = null; expr[0].op = new AttrOperator(AttrOperator.aopEQ); expr[0].type1 = new AttrType(AttrType.attrSymbol); expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1); expr[0].type2 = new AttrType(AttrType.attrSymbol); expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr[1] = null; } private CondExpr[] Query5_CondExpr() { CondExpr [] expr2 = new CondExpr[3]; expr2[0] = new CondExpr(); expr2[0].next = null; expr2[0].op = new AttrOperator(AttrOperator.aopEQ); expr2[0].type1 = new AttrType(AttrType.attrSymbol); expr2[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer),1); expr2[0].type2 = new AttrType(AttrType.attrSymbol); expr2[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr2[1] = new CondExpr(); expr2[1].op = new AttrOperator(AttrOperator.aopGT); expr2[1].next = null; expr2[1].type1 = new AttrType(AttrType.attrSymbol); expr2[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),4); expr2[1].type2 = new AttrType(AttrType.attrReal); expr2[1].operand2.real = (float)40.0; expr2[1].next = new CondExpr(); expr2[1].next.op = new AttrOperator(AttrOperator.aopLT); expr2[1].next.next = null; expr2[1].next.type1 = new AttrType(AttrType.attrSymbol); // rating expr2[1].next.operand1.symbol = new FldSpec ( new RelSpec(RelSpec.outer),3); expr2[1].next.type2 = new AttrType(AttrType.attrInteger); expr2[1].next.operand2.integer = 7; expr2[2] = null; return expr2; } private void Query6_CondExpr(CondExpr[] expr, CondExpr[] expr2) { expr[0].next = null; expr[0].op = new AttrOperator(AttrOperator.aopEQ); expr[0].type1 = new AttrType(AttrType.attrSymbol); expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1); expr[0].type2 = new AttrType(AttrType.attrSymbol); expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr[1].next = null; expr[1].op = new AttrOperator(AttrOperator.aopGT); expr[1].type1 = new AttrType(AttrType.attrSymbol); expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3); expr[1].type2 = new AttrType(AttrType.attrInteger); expr[1].operand2.integer = 7; expr[2] = null; expr2[0].next = null; expr2[0].op = new AttrOperator(AttrOperator.aopEQ); expr2[0].type1 = new AttrType(AttrType.attrSymbol); expr2[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),2); expr2[0].type2 = new AttrType(AttrType.attrSymbol); expr2[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); expr2[1].next = null; expr2[1].op = new AttrOperator(AttrOperator.aopEQ); expr2[1].type1 = new AttrType(AttrType.attrSymbol); expr2[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),3); expr2[1].type2 = new AttrType(AttrType.attrString); expr2[1].operand2.string = "red"; expr2[2] = null; } public void QueryPlanExecutor(HashMap<Integer,String > map, List<String> conditions,Iterator sm ,int conditionCount, String heapFileName,int dynamicCount,HashMap<Integer,String> dynamic ) { TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); if(conditionCount >= conditions.size()) { SortMerge sm_final = (SortMerge)sm; int sizeofTuple = sm_final.getFinalTupleSize(); AttrType [] outputtype = new AttrType[sizeofTuple]; for(int i=0;i< sizeofTuple;i=i+3) { outputtype[i]= new AttrType(AttrType.attrInterval); outputtype[i+1]=new AttrType(AttrType.attrInteger); outputtype[i+2]=new AttrType(AttrType.attrString); } Tuple t; t = null; try { int num=4; int sortFld=num*3; // SRTOperator(sm_final, outputtype, sizeofTuple,sortFld); // GRPOperator(sm_final, outputtype, sizeofTuple,sortFld); while ((t = sm_final.get_next()) != null) { t.print(outputtype); } } catch (Exception e) { System.err.println (""+e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.println ("\n"); try { sm_final.close(); } catch (Exception e) { e.printStackTrace(); } return ; } //------------ String[] splited=conditions.get(conditionCount).split("\\s+"); // if(dynamic.get(map.get(key))) // System.out.println(splited[0]); //System.out.println(splited[1]); int index=0; if(!dynamic.containsValue(map.get(Integer.valueOf(splited[0])))|| map.get(Integer.valueOf(splited[0])).equals("*")){ dynamic.put(++dynamicCount, map.get(Integer.valueOf(splited[0]))); }else { for(Map.Entry<Integer,String> e : dynamic.entrySet()) { if(e.getValue().equals(map.get(Integer.valueOf(splited[0])))) index = e.getKey(); } } System.out.println(splited[1]); if(!dynamic.containsValue(map.get(Integer.valueOf(splited[1]))) || map.get(Integer.valueOf(splited[1])).equals("*")){ dynamic.put(++dynamicCount, map.get(Integer.valueOf(splited[1]))); }else { for(Map.Entry<Integer,String> e : dynamic.entrySet()) { if(e.getValue().equals(map.get(Integer.valueOf(splited[1])))) index = e.getKey(); } } //parsing for condition expressions CondExpr [] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); if (map.get(Integer.parseInt(splited[0])).equals("*")) { leftFilter=null; } else { leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopEQ); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrString); leftFilter[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3); leftFilter[0].operand2.string = map.get(Integer.valueOf(splited[0])); leftFilter[1] = null; } CondExpr [] rightFilter = new CondExpr[2]; if (map.get(Integer.parseInt(splited[1])).equals("*")) { rightFilter=null; } else { rightFilter[0] = new CondExpr(); rightFilter[0].next = null; rightFilter[0].op = new AttrOperator(AttrOperator.aopEQ); rightFilter[0].type1 = new AttrType(AttrType.attrSymbol); rightFilter[0].type2 = new AttrType(AttrType.attrString); rightFilter[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3); rightFilter[0].operand2.string = map.get(Integer.valueOf(splited[1])); rightFilter[1] = null; } String relationship= splited[2]; CondExpr [] outFilter = new CondExpr[3]; outFilter[0] = new CondExpr(); outFilter[1] = new CondExpr(); outFilter[0].next = null; outFilter[0].op = new AttrOperator(AttrOperator.aopGT); outFilter[0].type1 = new AttrType(AttrType.attrSymbol); outFilter[0].type2 = new AttrType(AttrType.attrSymbol); outFilter[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),index*3+1); outFilter[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1); outFilter[0].flag=1; // outFilter[1] = null; if(relationship.equals("PC")) { outFilter[1].next = null; outFilter[1].op = new AttrOperator(AttrOperator.aopLT); outFilter[1].type1 = new AttrType(AttrType.attrSymbol); outFilter[1].type2 = new AttrType(AttrType.attrSymbol); outFilter[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),index*3+2); outFilter[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2); outFilter[1].flag=1; outFilter[2] = null; } else if(relationship.equals("AD")) { outFilter[1] = null; outFilter[2] = null; } AttrType [] ltypes = new AttrType[(conditionCount+1)*3]; for(int j=0;j<(conditionCount+1)*3;j=j+3) { ltypes[j] = new AttrType(AttrType.attrInterval); ltypes[j+1]=new AttrType(AttrType.attrInteger); ltypes[j+2]=new AttrType(AttrType.attrString); } short [] lsizes = new short[(conditionCount+1)]; for(int j=0;j<lsizes.length;j++) lsizes[j]=10; AttrType [] rtypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString), }; short [] rsizes = new short[1] ; rsizes[0] = 10; //for the first condition if(sm==null) { FldSpec [] lprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; boolean status=true; try { sm = new FileScan("xml.in", ltypes, lsizes, (short)3, (short)3, lprojection, leftFilter); /* am = new FileScan("xml.in", Stypes, Ssizes, (short)3, (short)3, Sprojection, leftFilter); */ Tuple sm_temp = null; System.out.println(); /* while( (sm_temp = sm.get_next()) != null) { System.out.println(sm_temp.getStrFld(3)); }*/ } catch (Exception e) { status = FAIL; System.err.println (""+e); e.printStackTrace(); } if (status != OK) { //bail out System.err.println ("*** Error setting up scan for sailors"); Runtime.getRuntime().exit(1); } } //from 2nd condition--- int fieldCounts = (conditionCount +2)*3; FldSpec [] proj1 = new FldSpec[fieldCounts]; int n_out_fld=0; //for outer relations for(int i=0;i< fieldCounts-3;i=i+3) { proj1[i]=new FldSpec(new RelSpec(RelSpec.outer), 1+i); proj1[i+1]=new FldSpec(new RelSpec(RelSpec.outer), 2+i); proj1[i+2]=new FldSpec(new RelSpec(RelSpec.outer), 3+i); } //for inner relations proj1[fieldCounts-3]=new FldSpec(new RelSpec(RelSpec.innerRel), 1); proj1[fieldCounts-2]=new FldSpec(new RelSpec(RelSpec.innerRel), 2); proj1[fieldCounts-1]=new FldSpec(new RelSpec(RelSpec.innerRel), 3); // SortMerge sm = null; FileScan am2 = null; try { { am2 = new FileScan("xml.in", rtypes, rsizes, (short)3, (short)3, proj1, rightFilter); } } catch (Exception e) { //status = FAIL; System.err.println (""+e); e.printStackTrace(); } try { n_out_fld=(conditionCount+2)*3; //System.out.println("recursion"); //int joinColumn=((Integer.valueOf(splited[0]))-1)*3+1; // System.out.println("the value of index" +index); int joinColumn=index*3+1; // System.out.println("Join column :" +joinColumn); //System.out.println(joinColumn); sm = new SortMerge(ltypes, ltypes.length, lsizes, rtypes, 3, rsizes, joinColumn, 8, 1, 8, (conditionCount+1)*10, sm, am2, false, false, ascending, outFilter, proj1, n_out_fld); } catch (Exception e) { System.err.println ("*** Error preparing for sm_join"); System.err.println (""+e); e.printStackTrace(); Runtime.getRuntime().exit(1); } QueryPlanExecutor(map, conditions, sm, conditionCount+1, heapFileName, dynamicCount, dynamic); } public void QueryXML() { System.out.print("**********************QueryXML strating static *********************\n"); boolean status = OK; TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); CondExpr [] leftFilter = new CondExpr[2]; leftFilter[0] = new CondExpr(); leftFilter[0].next = null; leftFilter[0].op = new AttrOperator(AttrOperator.aopEQ); leftFilter[0].type1 = new AttrType(AttrType.attrSymbol); leftFilter[0].type2 = new AttrType(AttrType.attrString); leftFilter[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3); leftFilter[0].operand2.string = "class"; leftFilter[1] = null; CondExpr [] rightFilter = new CondExpr[2]; rightFilter[0] = new CondExpr(); rightFilter[0].next = null; rightFilter[0].op = new AttrOperator(AttrOperator.aopEQ); rightFilter[0].type1 = new AttrType(AttrType.attrSymbol); rightFilter[0].type2 = new AttrType(AttrType.attrString); rightFilter[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3); rightFilter[0].operand2.string = "stud"; rightFilter[1] = null; CondExpr [] outFilter = new CondExpr[2]; outFilter[0] = new CondExpr(); QueryXML_CondExpr(outFilter); Tuple t = new Tuple(); t = null; AttrType [] Stypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString) }; short [] Ssizes = new short[1]; Ssizes[0] = 10; AttrType [] Rtypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString), }; short [] Rsizes = new short[1] ; Rsizes[0] = 10; FldSpec [] proj1 = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), new FldSpec(new RelSpec(RelSpec.innerRel), 1), new FldSpec(new RelSpec(RelSpec.innerRel), 2), new FldSpec(new RelSpec(RelSpec.innerRel), 3) }; // S.sname, R.bid /*FldSpec [] proj2 = { new FldSpec(new RelSpec(RelSpec.outer), 1) }; */ FldSpec [] Sprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; FldSpec [] Rprojection = { new FldSpec(new RelSpec(RelSpec.outer), 1), new FldSpec(new RelSpec(RelSpec.outer), 2), new FldSpec(new RelSpec(RelSpec.outer), 3), }; AttrType [] JJtype = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString), new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString), }; FileScan am = null; try { am = new FileScan("xml.in", Stypes, Ssizes, (short)3, (short)3, Sprojection, leftFilter); } catch (Exception e) { status = FAIL; System.err.println (""+e); e.printStackTrace(); } FileScan am2 = null; try { am2 = new FileScan("xml.in", Rtypes, Rsizes, (short)3, (short)3, Rprojection, rightFilter); } catch (Exception e) { status = FAIL; System.err.println (""+e); e.printStackTrace(); } SortMerge sm = null; try { // System.out.println(am.get_next().getStrFld(3)); sm = new SortMerge(Stypes, 3, Ssizes, Rtypes, 3, Rsizes, 1, 8, 1, 8, 10, am, am2, false, false, ascending, outFilter, proj1, 6); } catch (Exception e) { System.err.println("*** join error in SortMerge constructor ***"); status = FAIL; System.err.println (""+e); e.printStackTrace(); } if (status != OK) { //bail out System.err.println ("*** Error constructing SortMerge"); Runtime.getRuntime().exit(1); } // QueryCheck qcheck1 = new QueryCheck(1); t = null; try { while ((t = sm.get_next()) != null) { t.print(JJtype); //System.out.println("Tuple "+JJ.getStrFld(3)+" "+t.getIntervalFld(1).getStart()+" "+t.getIntervalFld(1).getEnd()+" "+t.getLength()); //qcheck1.Check(t); } } catch (Exception e) { System.err.println (""+e); e.printStackTrace(); status = FAIL; } if (status != OK) { //bail out System.err.println ("*** Error in get next tuple "); Runtime.getRuntime().exit(1); } //qcheck1.report(1); try { sm.close(); } catch (Exception e) { status = FAIL; e.printStackTrace(); } System.out.println ("\n"); if (status != OK) { //bail out System.err.println ("*** Error in closing "); Runtime.getRuntime().exit(1); } if (status != OK) { //bail out System.err.println ("*** Error setting up scan for sailors"); Runtime.getRuntime().exit(1); } } public void QueryXML_Dynamic() { System.out.print("**********************QueryXML strating *********************\n"); //read the input file File file = new File("/home/nisha/Downloads/input.txt"); boolean status_dynamic = OK; String st; try { BufferedReader br = new BufferedReader(new FileReader(file)); st = br.readLine(); int nodesCount = Integer.valueOf(st); HashMap<Integer,String > map= new HashMap<Integer,String>(); for(int i=0;i<nodesCount;i++) { st = br.readLine(); map.put(i+1, st); } SortMerge inl = null; List<String> conditions= new ArrayList<String>(); while ((st = br.readLine()) != null) { conditions.add(st); } int dynamicCount=-1; HashMap<Integer,String> dynamic= new HashMap<Integer,String>(); // Creating Index on heapfile AttrType [] Stypes = { new AttrType(AttrType.attrInterval), new AttrType(AttrType.attrInteger), new AttrType(AttrType.attrString) }; short [] Ssizes = new short[1]; Ssizes[0] = 10; //_______________________________________________________________ //*******************create an scan on the heapfile************** //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // create a tuple of appropriate size Tuple tt = new Tuple(); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { status_dynamic = FAIL; e.printStackTrace(); } int sizett = tt.size(); tt = new Tuple(sizett); try { tt.setHdr((short) 3, Stypes, Ssizes); } catch (Exception e) { status_dynamic = FAIL; e.printStackTrace(); } //-----------------------------------------Query Plan 1------------------------------------------ // Uncomment recursive() to run query plan 1 /* Query plan with left-deep tree traversal: This query will be * fast for data having large number of duplicate leaf values */ //Query 1 executing.. System.out.println("Query plan 1 executing...."); // System.out.println("Count of conditions: "+conditions.size()); //System.out.println(SystemDefs.JavabaseBM.pcounter); QueryPlanExecutor(map, conditions, inl,0,"new_xml.in",dynamicCount,dynamic); //System.out.println("for left:" + SystemDefs.JavabaseBM.pcounter); } catch( Exception e) { e.printStackTrace(); } } // System.out.print( "After nested loop join S.sid|><|R.sid.\n"); /* NestedLoopsJoins nlj = null; try { nlj = new NestedLoopsJoins (Jtypes, 2, Jsizes, Btypes, 3, Bsizes, 10, inl, "boats.in", outFilter2, null, proj2, 1); } catch (Exception e) { System.err.println ("*** Error preparing for nested_loop_join"); System.err.println (""+e); e.printStackTrace(); Runtime.getRuntime().exit(1); } System.out.print( "After nested loop join R.bid|><|B.bid AND B.color=red.\n"); TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); Sort sort_names = null; try { sort_names = new Sort (JJtype,(short)1, JJsize, (iterator.Iterator) nlj, 1, ascending, JJsize[0], 10); } catch (Exception e) { System.err.println ("*** Error preparing for sorting"); System.err.println (""+e); Runtime.getRuntime().exit(1); } System.out.print( "After sorting the output tuples.\n"); */ //QueryCheck qcheck6 = new QueryCheck(6); // // public void Query1() { // // System.out.print("**********************Query1 strating *********************\n"); // boolean status = OK; // // // Sailors, Boats, Reserves Queries. // System.out.print ("Query: Find the names of sailors who have reserved " // + "boat number 1.\n" // + " and print out the date of reservation.\n\n" // + " SELECT S.sname, R.date\n" // + " FROM Sailors S, Reserves R\n" // + " WHERE S.sid = R.sid AND R.bid = 1\n\n"); // // System.out.print ("\n(Tests FileScan, Projection, and Sort-Merge Join)\n"); // // CondExpr[] outFilter = new CondExpr[3]; // outFilter[0] = new CondExpr(); // outFilter[1] = new CondExpr(); // outFilter[2] = new CondExpr(); // // Query1_CondExpr(outFilter); // // Tuple t = new Tuple(); // // AttrType [] Stypes = new AttrType[4]; // Stypes[0] = new AttrType (AttrType.attrInteger); // Stypes[1] = new AttrType (AttrType.attrString); // Stypes[2] = new AttrType (AttrType.attrInteger); // Stypes[3] = new AttrType (AttrType.attrReal); // // //SOS // short [] Ssizes = new short[1]; // Ssizes[0] = 30; //first elt. is 30 // // FldSpec [] Sprojection = new FldSpec[4]; // Sprojection[0] = new FldSpec(new RelSpec(RelSpec.outer), 1); // Sprojection[1] = new FldSpec(new RelSpec(RelSpec.outer), 2); // Sprojection[2] = new FldSpec(new RelSpec(RelSpec.outer), 3); // Sprojection[3] = new FldSpec(new RelSpec(RelSpec.outer), 4); // // FldSpec [] Rprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3) // }; // // CondExpr [] selects = new CondExpr [1]; // selects = null; // // // FileScan am = null; // try { // am = new FileScan("sailors.in", Stypes, Ssizes, // (short)4, (short)4, // Sprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // // AttrType [] Rtypes = new AttrType[3]; // Rtypes[0] = new AttrType (AttrType.attrInteger); // Rtypes[1] = new AttrType (AttrType.attrInteger); // Rtypes[2] = new AttrType (AttrType.attrString); // // short [] Rsizes = new short[1]; // Rsizes[0] = 15; // FldSpec [] Rprojection1 = new FldSpec[3]; // Rprojection1[0] = new FldSpec(new RelSpec(RelSpec.outer), 1); // Rprojection1[1] = new FldSpec(new RelSpec(RelSpec.outer), 2); // Rprojection1[2] = new FldSpec(new RelSpec(RelSpec.outer), 3); // // FileScan am2 = null; // try { // am2 = new FileScan("reserves.in", Rtypes, Rsizes, // (short)3, (short) 3, // Rprojection1, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for reserves"); // Runtime.getRuntime().exit(1); // } // // // FldSpec [] proj_list = new FldSpec[2]; // proj_list[0] = new FldSpec(new RelSpec(RelSpec.outer), 2); // proj_list[1] = new FldSpec(new RelSpec(RelSpec.innerRel), 3); // // AttrType [] jtype = new AttrType[2]; // jtype[0] = new AttrType (AttrType.attrString); // jtype[1] = new AttrType (AttrType.attrString); // // TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); // SortMerge sm = null; // try { // sm = new SortMerge(Stypes, 4, Ssizes, // Rtypes, 3, Rsizes, // 1, 4, // 1, 4, // 10, // am, am2, // false, false, ascending, // outFilter, proj_list, 2); // } // catch (Exception e) { // System.err.println("*** join error in SortMerge constructor ***"); // status = FAIL; // System.err.println (""+e); // e.printStackTrace(); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error constructing SortMerge"); // Runtime.getRuntime().exit(1); // } // // // // QueryCheck qcheck1 = new QueryCheck(1); // // // t = null; // // try { // while ((t = sm.get_next()) != null) { // t.print(jtype); // // qcheck1.Check(t); // } // } // catch (Exception e) { // System.err.println (""+e); // e.printStackTrace(); // status = FAIL; // } // if (status != OK) { // //bail out // System.err.println ("*** Error in get next tuple "); // Runtime.getRuntime().exit(1); // } // // qcheck1.report(1); // try { // sm.close(); // } // catch (Exception e) { // status = FAIL; // e.printStackTrace(); // } // System.out.println ("\n"); // if (status != OK) { // //bail out // System.err.println ("*** Error in closing "); // Runtime.getRuntime().exit(1); // } // } // // public void Query2() {} // // // public void Query3() { // System.out.print("**********************Query3 strating *********************\n"); // boolean status = OK; // // // Sailors, Boats, Reserves Queries. // // System.out.print // ( "Query: Find the names of sailors who have reserved a boat.\n\n" // + " SELECT S.sname\n" // + " FROM Sailors S, Reserves R\n" // + " WHERE S.sid = R.sid\n\n" // + "(Tests FileScan, Projection, and SortMerge Join.)\n\n"); // // CondExpr [] outFilter = new CondExpr[2]; // outFilter[0] = new CondExpr(); // outFilter[1] = new CondExpr(); // // Query3_CondExpr(outFilter); // // Tuple t = new Tuple(); // t = null; // // AttrType Stypes[] = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrReal) // }; // short [] Ssizes = new short[1]; // Ssizes[0] = 30; // // AttrType [] Rtypes = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // }; // short [] Rsizes = new short[1]; // Rsizes[0] =15; // // FldSpec [] Sprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3), // new FldSpec(new RelSpec(RelSpec.outer), 4) // }; // // CondExpr[] selects = new CondExpr [1]; // selects = null; // // iterator.Iterator am = null; // try { // am = new FileScan("sailors.in", Stypes, Ssizes, // (short)4, (short) 4, // Sprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // // FldSpec [] Rprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3) // }; // // iterator.Iterator am2 = null; // try { // am2 = new FileScan("reserves.in", Rtypes, Rsizes, // (short)3, (short)3, // Rprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for reserves"); // Runtime.getRuntime().exit(1); // } // // FldSpec [] proj_list = { // new FldSpec(new RelSpec(RelSpec.outer), 2) // }; // // AttrType [] jtype = { new AttrType(AttrType.attrString) }; // // TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); // SortMerge sm = null; // try { // sm = new SortMerge(Stypes, 4, Ssizes, // Rtypes, 3, Rsizes, // 1, 4, // 1, 4, // 20, // am, am2, // false, false, ascending, // outFilter, proj_list, 1); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error constructing SortMerge"); // Runtime.getRuntime().exit(1); // } // // QueryCheck qcheck3 = new QueryCheck(3); // // // t = null; // // try { // while ((t = sm.get_next()) != null) { // t.print(jtype); // qcheck3.Check(t); // } // } // catch (Exception e) { // System.err.println (""+e); // e.printStackTrace(); // Runtime.getRuntime().exit(1); // } // // // qcheck3.report(3); // // System.out.println ("\n"); // try { // sm.close(); // } // catch (Exception e) { // status = FAIL; // e.printStackTrace(); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // } // // public void Query4() { // System.out.print("**********************Query4 strating *********************\n"); // boolean status = OK; // // // Sailors, Boats, Reserves Queries. // // System.out.print // ("Query: Find the names of sailors who have reserved a boat\n" // + " and print each name once.\n\n" // + " SELECT DISTINCT S.sname\n" // + " FROM Sailors S, Reserves R\n" // + " WHERE S.sid = R.sid\n\n" // + "(Tests FileScan, Projection, Sort-Merge Join and " // + "Duplication elimination.)\n\n"); // // CondExpr [] outFilter = new CondExpr[2]; // outFilter[0] = new CondExpr(); // outFilter[1] = new CondExpr(); // // Query3_CondExpr(outFilter); // // Tuple t = new Tuple(); // t = null; // // AttrType Stypes[] = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrReal) // }; // short [] Ssizes = new short[1]; // Ssizes[0] = 30; // // AttrType [] Rtypes = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // }; // short [] Rsizes = new short[1]; // Rsizes[0] =15; // // FldSpec [] Sprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3), // new FldSpec(new RelSpec(RelSpec.outer), 4) // }; // // CondExpr[] selects = new CondExpr [1]; // selects = null; // // iterator.Iterator am = null; // try { // am = new FileScan("sailors.in", Stypes, Ssizes, // (short)4, (short) 4, // Sprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // // FldSpec [] Rprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3) // }; // // iterator.Iterator am2 = null; // try { // am2 = new FileScan("reserves.in", Rtypes, Rsizes, // (short)3, (short)3, // Rprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for reserves"); // Runtime.getRuntime().exit(1); // } // // FldSpec [] proj_list = { // new FldSpec(new RelSpec(RelSpec.outer), 2) // }; // // AttrType [] jtype = { new AttrType(AttrType.attrString) }; // // TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); // SortMerge sm = null; // short [] jsizes = new short[1]; // jsizes[0] = 30; // try { // sm = new SortMerge(Stypes, 4, Ssizes, // Rtypes, 3, Rsizes, // 1, 4, // 1, 4, // 10, // am, am2, // false, false, ascending, // outFilter, proj_list, 1); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error constructing SortMerge"); // Runtime.getRuntime().exit(1); // } // // // DuplElim ed = null; // try { // ed = new DuplElim(jtype, (short)1, jsizes, sm, 10, false); // } // catch (Exception e) { // System.err.println (""+e); // Runtime.getRuntime().exit(1); // } // // QueryCheck qcheck4 = new QueryCheck(4); // // // t = null; // // try { // while ((t = ed.get_next()) != null) { // t.print(jtype); // qcheck4.Check(t); // } // } // catch (Exception e) { // System.err.println (""+e); // e.printStackTrace(); // Runtime.getRuntime().exit(1); // } // // qcheck4.report(4); // try { // ed.close(); // } // catch (Exception e) { // status = FAIL; // e.printStackTrace(); // } // System.out.println ("\n"); // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // } // // public void Query5() { // System.out.print("**********************Query5 strating *********************\n"); // boolean status = OK; // // Sailors, Boats, Reserves Queries. // // System.out.print // ("Query: Find the names of old sailors or sailors with " // + "a rating less\n than 7, who have reserved a boat, " // + "(perhaps to increase the\n amount they have to " // + "pay to make a reservation).\n\n" // + " SELECT S.sname, S.rating, S.age\n" // + " FROM Sailors S, Reserves R\n" // + " WHERE S.sid = R.sid and (S.age > 40 || S.rating < 7)\n\n" // + "(Tests FileScan, Multiple Selection, Projection, " // + "and Sort-Merge Join.)\n\n"); // // // CondExpr [] outFilter; // outFilter = Query5_CondExpr(); // // Tuple t = new Tuple(); // t = null; // // AttrType Stypes[] = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrReal) // }; // short [] Ssizes = new short[1]; // Ssizes[0] = 30; // // AttrType [] Rtypes = { // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrString), // }; // short [] Rsizes = new short[1]; // Rsizes[0] = 15; // // FldSpec [] Sprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3), // new FldSpec(new RelSpec(RelSpec.outer), 4) // }; // // CondExpr[] selects = new CondExpr [1]; // selects[0] = null; // // FldSpec [] proj_list = { // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3), // new FldSpec(new RelSpec(RelSpec.outer), 4) // }; // // FldSpec [] Rprojection = { // new FldSpec(new RelSpec(RelSpec.outer), 1), // new FldSpec(new RelSpec(RelSpec.outer), 2), // new FldSpec(new RelSpec(RelSpec.outer), 3) // }; // // AttrType [] jtype = { // new AttrType(AttrType.attrString), // new AttrType(AttrType.attrInteger), // new AttrType(AttrType.attrReal) // }; // // // iterator.Iterator am = null; // try { // am = new FileScan("sailors.in", Stypes, Ssizes, // (short)4, (short)4, // Sprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for sailors"); // Runtime.getRuntime().exit(1); // } // // iterator.Iterator am2 = null; // try { // am2 = new FileScan("reserves.in", Rtypes, Rsizes, // (short)3, (short)3, // Rprojection, null); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error setting up scan for reserves"); // Runtime.getRuntime().exit(1); // } // // TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); // SortMerge sm = null; // try { // sm = new SortMerge(Stypes, 4, Ssizes, // Rtypes, 3, Rsizes, // 1, 4, // 1, 4, // 10, // am, am2, // false, false, ascending, // outFilter, proj_list, 3); // } // catch (Exception e) { // status = FAIL; // System.err.println (""+e); // } // // if (status != OK) { // //bail out // System.err.println ("*** Error constructing SortMerge"); // Runtime.getRuntime().exit(1); // } // // QueryCheck qcheck5 = new QueryCheck(5); // //Tuple t = new Tuple(); // t = null; // // try { // while ((t = sm.get_next()) != null) { // t.print(jtype); // qcheck5.Check(t); // } // } // catch (Exception e) { // System.err.println (""+e); // Runtime.getRuntime().exit(1); // } // // qcheck5.report(5); // try { // sm.close(); // } // catch (Exception e) { // status = FAIL; // e.printStackTrace(); // } // System.out.println ("\n"); // if (status != OK) { // //bail out // System.err.println ("*** Error close for sortmerge"); // Runtime.getRuntime().exit(1); // } // } // // public void Query6(){} private void Disclaimer() { System.out.print ("\n\nAny resemblance of persons in this database to" + " people living or dead\nis purely coincidental. The contents of " + "this database do not reflect\nthe views of the University," + " the Computer Sciences Department or the\n" + "developers...\n\n"); } public void SRTOperator(SortMerge sm, AttrType[] output, int sizeofTuple,int sortFld) { short [] Ssizes = new short[sizeofTuple/3]; for(int i=0;i<sizeofTuple/3;i++) { Ssizes[i] = (short) 10; } AttrType [] ltypes = new AttrType[sizeofTuple]; for(int j=0;j<(sizeofTuple);j=j+3) { ltypes[j] = new AttrType(AttrType.attrInterval); ltypes[j+1]=new AttrType(AttrType.attrInteger); ltypes[j+2]=new AttrType(AttrType.attrString); } TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); try { Tuple t=null; Sort sorted= new Sort(ltypes, (short)sizeofTuple, Ssizes, (Iterator)sm, (short)sortFld, ascending, 10, 10); try { while((t=sorted.get_next())!=null) { t.print(output); } } catch(Exception e) { e.printStackTrace(); } } catch(Exception e) { e.printStackTrace(); } } public void GRPOperator(SortMerge sm, AttrType[] output, int sizeofTuple,int sortFld) { short [] Ssizes = new short[sizeofTuple/3]; // Map<String,List<List<String>>> groupedResults=new HashMap<>(); for(int i=0;i<sizeofTuple/3;i++) { Ssizes[i] = (short) 10; } AttrType [] ltypes = new AttrType[sizeofTuple]; for(int j=0;j<(sizeofTuple);j=j+3) { ltypes[j] = new AttrType(AttrType.attrInterval); ltypes[j+1]=new AttrType(AttrType.attrInteger); ltypes[j+2]=new AttrType(AttrType.attrString); } TupleOrder ascending = new TupleOrder(TupleOrder.Ascending); try { Tuple t=null; Tuple tempT=null;//new Tuple(sizeofTuple); Sort sorted= new Sort(ltypes, (short)sizeofTuple, Ssizes, (Iterator)sm, (short)sortFld, ascending, 10, 10); //List<List<String>> witnessTree=new ArrayList<>(); String currentGroup = null; int i=0; int currLevel = 0; Boolean newgroup=false; try { System.out.println("ROOT"); while((t=sorted.get_next())!=null) { if(!t.getStrFld(sortFld).equals(currentGroup)) { currentGroup=t.getStrFld(sortFld); newgroup=true; } else { newgroup=false; } if(newgroup) { System.out.println("\tSTR"+(i++)); } for(int j=3;j<sizeofTuple+1;j+=3) { currLevel = t.getIntFld(j-1); for (int i1 = 0; i1 < currLevel+2; i1++) { System.out.print("\t"); } System.out.println(t.getStrFld(j)); } // t.print(output); } /* * for(String s : witnessTree) { System.out.println(s); } for(String key : * groupedResults.keySet() ) { System.out.println("The key " + key +" value " * +groupedResults.get(key)); } */ // printGRPBY(groupedResults); } catch(Exception e) { e.printStackTrace(); } } catch(Exception e) { e.printStackTrace(); } } public void printGRPBY(Map<String,List<List<String>>> groupedResults) { int subtreeCount=groupedResults.size(); int i=0; StringBuffer output=new StringBuffer(); output.append("\t\t"); int currLevel = 0; if( subtreeCount!=0) { System.out.println("ROOT"); for(String key :groupedResults.keySet()) { System.out.println("\tSTR"+(i++)); for(List<String> subtree : groupedResults.get(key)) { for (int j =0; j<subtree.size();j++) { if ((j % 2) == 0) { currLevel = Integer.parseInt(subtree.get(j)); } else { for (int i1 = 0; i1 < currLevel + 2; i1++) { System.out.print("\t"); } System.out.println(subtree.get(j)); } } //System.out.println(key); } } } } public static void main(String argv[]) { boolean sortstatus; //SystemDefs global = new SystemDefs("bingjiedb", 100, 70, null); //JavabaseDB.openDB("/tmp/nwangdb", 5000); String path = "/home/nisha/Downloads/xml_sample_data.xml"; SM_JoinTest jjoin = new SM_JoinTest(path); sortstatus = jjoin.runTests(); if (sortstatus != true) { System.out.println("Error ocurred during join tests"); } else { System.out.println("join tests completed successfully"); } } }
2af38620f7c39464ee322c923ba9ca73b1173ec6
[ "JavaScript", "Java", "Markdown", "Shell" ]
9
Java
siddarthmadan09/DBMSI-510-Project
a40539bb4942ca791b281725c6171b6bb3d48f1e
b3a027656f5087b40e3560f4363d5c78d545b522
refs/heads/master
<repo_name>lunlun1992/openH264<file_sep>/h264decmain.c #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "libavutil/avutil.h" #include <libavcodec/avcodec.h> int main(int argc, char **argv) { AVCodecContext *pCodecCtx = NULL; AVCodecParserContext *pParserCtx = NULL; AVCodec *pCodec = NULL; AVPacket *pPacket = NULL; AVFrame *pFrame = NULL; int ret = 0; FILE *filein = NULL; FILE *fileout = NULL; int inputlength = 0; uint8_t *inputbytes = NULL; uint8_t *pdata = NULL; int lendata = 0; int i = 0; filein = fopen("in.h264", "rb"); if (!filein) { av_log(NULL, AV_LOG_ERROR, "open input file error\n"); goto fail; } fseek(filein, 0, SEEK_END); inputlength = ftell(filein); inputbytes = (uint8_t *)malloc(inputlength); if (!inputbytes) { av_log(NULL, AV_LOG_ERROR, "malloc fail\n"); goto fail; } fseek(filein, 0, SEEK_SET); if (inputlength != fread(inputbytes, 1, inputlength, filein)) { av_log(NULL, AV_LOG_ERROR, "read file error\n"); goto fail; } fclose(filein); filein = NULL; fileout = fopen("out.yuv", "wb"); avcodec_register_all(); pCodec = avcodec_find_decoder(AV_CODEC_ID_H264); if (!pCodec) { av_log(NULL, AV_LOG_ERROR, "find decoder error\n"); goto fail; } pCodecCtx = avcodec_alloc_context3(pCodec); if (!pCodecCtx) { av_log(NULL, AV_LOG_ERROR, "alloc decoder context error\n"); goto fail; } ret = avcodec_open2(pCodecCtx, pCodec, NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "codec open fail\n"); goto fail; } pParserCtx = av_parser_init(AV_CODEC_ID_H264); if (!pParserCtx) { av_log(NULL, AV_LOG_ERROR, "parser open fail\n"); goto fail; } pFrame = av_frame_alloc(); pPacket = av_packet_alloc(); pdata = inputbytes; lendata = inputlength; while(1) { ret = av_parser_parse2(pParserCtx, pCodecCtx, &pPacket->data, &pPacket->size, pdata, lendata, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if(ret < 0) { av_log(NULL, AV_LOG_ERROR, "parser parse fail\n"); goto fail; } pdata += ret; lendata -= ret; if(pPacket->size) { ret = avcodec_send_packet(pCodecCtx, pPacket); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "send packet fail\n"); goto fail; } while (ret >= 0) { ret = avcodec_receive_frame(pCodecCtx, pFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; else if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "receive frame fail\n"); goto fail; } av_log(NULL, AV_LOG_INFO, "receive %d frame, width: %d, height: %d\n", pCodecCtx->frame_number, pFrame->width, pFrame->height); for (i = 0; i < pFrame->height; i++) fwrite(pFrame->data[0] + i * pFrame->linesize[0], pFrame->width, 1, fileout); for (i = 0; i < (pFrame->height >> 1); i++) fwrite(pFrame->data[1] + i * pFrame->linesize[1], pFrame->width >> 1, 1, fileout); for (i = 0; i < (pFrame->height >> 1); i++) fwrite(pFrame->data[2] + i * pFrame->linesize[2], pFrame->width >> 1, 1, fileout); } //we must send 0 length into av_parser_parse2 to flush the parser for the last packet. //when flush the parser, there must be the last packet into this if condition if (lendata == 0) break; } } ret = avcodec_send_packet(pCodecCtx, NULL); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "send packet fail\n"); goto fail; } while (ret >= 0) { ret = avcodec_receive_frame(pCodecCtx, pFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; else if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "receive frame fail\n"); goto fail; } av_log(NULL, AV_LOG_INFO, "receive %d frame, width: %d, height: %d\n", pCodecCtx->frame_number, pFrame->width, pFrame->height); for (i = 0; i < pFrame->height; i++) fwrite(pFrame->data[0] + i * pFrame->linesize[0], pFrame->width, 1, fileout); for (i = 0; i < (pFrame->height >> 1); i++) fwrite(pFrame->data[1] + i * pFrame->linesize[1], pFrame->width >> 1, 1, fileout); for (i = 0; i < (pFrame->height >> 1); i++) fwrite(pFrame->data[2] + i * pFrame->linesize[2], pFrame->width >> 1, 1, fileout); } avcodec_free_context(&pCodecCtx); fclose(fileout); free(inputbytes); av_frame_free(&pFrame); av_packet_free(&pPacket); av_parser_close(pParserCtx); return 0; fail: if (pCodecCtx) avcodec_free_context(&pCodecCtx); if (filein) fclose(filein); if (inputbytes) free(inputbytes); if (fileout) free(fileout); av_frame_free(&pFrame); av_packet_free(&pPacket); av_parser_close(pParserCtx); return -1; } <file_sep>/README.md # openH264 H.264 decoder extract from FFmpeg <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) if (NOT DEFINED CMAKE_BUILD_TYPE) set (CMAKE_BUILD_TYPE Release CACHE STRING "Build type") endif () project(openH264wrapper) SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/MyCMakeScripts) message("DEBUG: CMAKE_SYSTEM_PROCESSOR = ${CMAKE_SYSTEM_PROCESSOR}") message("DEBUG: CMAKE_SYSTEM_NAME = ${CMAKE_SYSTEM_NAME}") macro (my_check_function_exists arg result) check_function_exists(${arg} ${result}) if(${result} STREQUAL "") set(${result} 0) endif() endmacro (my_check_function_exists) macro (my_check_include_files arg result) check_include_files(${arg} ${result}) if(${result} STREQUAL "") set(${result} 0) endif() endmacro (my_check_include_files) include(CheckTypeSize) check_type_size("void*" SIZEOF_VOID_P BUILTIN_TYPES_ONLY) message("DEBUG: SIZEOF_VOID_P = ${SIZEOF_VOID_P}") include(CheckFunctionExists) include(CheckIncludeFiles) include(OptimizeForArchitecture) OptimizeForArchitecture() my_check_function_exists(GetProcessAffinityMask GETPROCESSAFFINITYMASK_FOUND) my_check_function_exists(gettimeofday GETTIMEOFDAY_FOUND) my_check_function_exists(sched_getaffinity SCHED_GETAFFINITY_FOUND) my_check_function_exists(strerror_r STRERROR_R_FOUND) my_check_function_exists(sysconf SYSCONF_FOUND) my_check_function_exists(usleep USLEEP_FOUND) my_check_function_exists(localtime_r LOCALTIME_R_FOUND) my_check_function_exists(gmtime_r GMTIME_R_FOUND) my_check_include_files(fcntl.h FCNTL_H_FOUND) my_check_include_files(pthread.h PTHREADS_FOUND) my_check_include_files(unistd.h UNISTD_H_FOUND) my_check_include_files(windows.h WINDOWS_H_FOUND) #find asm compiler option (USE_YASM "Use YASM. If YASM is not enabled the assembly implementation will be disabled." ON) if (USE_YASM) find_package (Yasm) endif () # System architecture detection string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" SYSPROC) set(X86_ALIASES x86 i386 i686 x86_64 amd64) set(ARM_ALIASES armv6l armv7l) list(FIND X86_ALIASES "${SYSPROC}" X86MATCH) list(FIND ARM_ALIASES "${SYSPROC}" ARMMATCH) set(POWER_ALIASES ppc64 ppc64le) list(FIND POWER_ALIASES "${SYSPROC}" POWERMATCH) if("${SYSPROC}" STREQUAL "" OR X86MATCH GREATER "-1") if("${CMAKE_SIZEOF_VOID_P}" MATCHES 8) set(X86_64 TRUE) message(STATUS "Detected x86_64 target processor") else() set(X86_32 TRUE) message(STATUS "Detected x86_32 target processor") endif() elseif(POWERMATCH GREATER "-1") message(STATUS "Detected POWER target processor") set(POWER 1) if("${CMAKE_SIZEOF_VOID_P}" MATCHES 8) set(PPC64 1) message(STATUS "Detected POWER PPC64 target processor") endif() elseif(ARMMATCH GREATER "-1") message(STATUS "Detected ARM target processor") set(ARM 1) else() message(STATUS "CMAKE_SYSTEM_PROCESSOR value `${CMAKE_SYSTEM_PROCESSOR}` is unknown") message(STATUS "Please add this value near ${CMAKE_CURRENT_LIST_FILE}:${CMAKE_CURRENT_LIST_LINE}") endif() if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") configure_file(platform/arm/config.h ${PROJECT_BINARY_DIR}/config.h) else() configure_file(platform/x86/config.h.in ${PROJECT_BINARY_DIR}/config.h) configure_file(platform/x86/config.asm.in ${PROJECT_BINARY_DIR}/config.asm) endif() if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") enable_language(ASM) add_definitions( -DEXTERN_ASM= ) endif() if(WIN32) add_definitions( # -Dsnprintf=avpriv_snprintf # -Dvsnprintf=avpriv_vsnprintf -Dinline=__inline -Drestrict=__restrict ) endif() #define asm sources if(NOT ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") ) if(YASM_FOUND) set(YASM_NAMES libavutil/x86/cpuid.asm libavutil/x86/emms.asm libavutil/x86/imgutils.asm libavcodec/x86/h264_chromamc.asm libavcodec/x86/h264_chromamc_10bit.asm libavcodec/x86/h264_deblock.asm libavcodec/x86/h264_deblock_10bit.asm libavcodec/x86/h264_idct.asm libavcodec/x86/h264_idct_10bit.asm libavcodec/x86/h264_weight.asm libavcodec/x86/h264_weight_10bit.asm libavcodec/x86/h264_intrapred.asm libavcodec/x86/h264_intrapred_10bit.asm libavcodec/x86/h264_qpel_8bit.asm libavcodec/x86/h264_qpel_10bit.asm libavcodec/x86/fpel.asm libavcodec/x86/qpel.asm libavcodec/x86/idctdsp.asm libavcodec/x86/me_cmp.asm libavcodec/x86/pixblockdsp.asm libavcodec/x86/simple_idct10.asm libavcodec/x86/videodsp.asm ) endif(YASM_FOUND) endif(NOT ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") ) if(NOT ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") ) set(COMMON_YASM_ARGS -I./ -I "${CMAKE_CURRENT_SOURCE_DIR}" -P "${PROJECT_BINARY_DIR}/config.asm" -I "${CMAKE_CURRENT_SOURCE_DIR}/libavutil/x86/" -DPIC ) endif(NOT ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") ) if(YASM_FOUND) if(APPLE) set(YASM_ARGS -f macho64 -m amd64 -DPREFIX ${COMMON_YASM_ARGS}) elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") set(YASM_ARGS -f elf -m amd64 ${COMMON_YASM_ARGS}) elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686") set(YASM_ARGS -f elf -DX86_32 ${COMMON_YASM_ARGS}) else() set(YASM_ARGS -f win32 -m amd64 ${COMMON_YASM_ARGS}) endif() #compile all asm files foreach(_asm_file ${YASM_NAMES}) set(YASM_SRC "${CMAKE_CURRENT_SOURCE_DIR}/${_asm_file}") get_filename_component(BASENAME ${YASM_SRC} NAME_WE) set(YASM_OBJ "${CMAKE_CURRENT_BINARY_DIR}/${BASENAME}.o") add_custom_command( OUTPUT ${YASM_OBJ} COMMAND "${YASM_EXECUTABLE}" ARGS ${YASM_ARGS} -o ${YASM_OBJ} ${YASM_SRC} DEPENDS ${YASM_SRC} ) set(YASM_OBJECTS ${YASM_OBJECTS} ${YASM_OBJ}) endforeach() endif(YASM_FOUND) if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64") if(MINGW) AddCompilerFlag("-arch x86_64 -m64" C_FLAGS Vc_ARCHITECTURE_FLAGS) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-Bsymbolic") elseif(NOT APPLE) string(REGEX MATCH "clang*" CLANG_COMPILER "${CMAKE_C_COMPILER}") if ("${CLANG_COMPILER}" STREQUAL "clang") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-Bsymbolic") else() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wl,-Bsymbolic") endif() endif() elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686") #add_definitions("-DX86_32") endif() add_definitions("-DPIC") if(WIN32) AddCompilerFlag("-fPIC" C_FLAGS Vc_ARCHITECTURE_FLAGS) AddCompilerFlag("-fno-tree-vectorize" C_FLAGS Vc_ARCHITECTURE_FLAGS) else() AddCompilerFlag("-fpic" C_FLAGS Vc_ARCHITECTURE_FLAGS) AddCompilerFlag("-fno-tree-vectorize" C_FLAGS Vc_ARCHITECTURE_FLAGS) endif() set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${Vc_ARCHITECTURE_FLAGS}") set(libfilenames libavutil/avstring.c libavutil/atomic.c libavutil/base64.c libavutil/bprint.c libavutil/buffer.c libavutil/channel_layout.c libavutil/cpu.c libavutil/crc.c libavutil/des.c libavutil/dict.c libavutil/display.c libavutil/error.c libavutil/eval.c libavutil/file_open.c libavutil/frame.c libavutil/imgutils.c libavutil/intmath.c libavutil/log.c libavutil/log2_tab.c libavutil/mathematics.c libavutil/md5.c libavutil/mem.c libavutil/opt.c libavutil/parseutils.c libavutil/pixdesc.c libavutil/rational.c libavutil/random_seed.c libavutil/reverse.c libavutil/rc4.c libavutil/samplefmt.c libavutil/sha.c libavutil/stereo3d.c libavutil/time.c libavutil/timecode.c libavutil/utils.c libavcodec/allcodecs.c libavcodec/audioconvert.c libavcodec/avdct.c libavcodec/avpacket.c libavcodec/avpicture.c libavcodec/bitstream.c libavcodec/bitstream_filter.c libavcodec/bitstream_filters.c libavcodec/bsf.c libavcodec/codec_desc.c libavcodec/cabac.c libavcodec/d3d11va.c libavcodec/dirac.c libavcodec/dv_profile.c libavcodec/error_resilience.c libavcodec/fdctdsp.c libavcodec/idctdsp.c libavcodec/imgconvert.c libavcodec/jni.c libavcodec/mathtables.c libavcodec/mediacodec.c libavcodec/mpeg12framerate.c libavcodec/options.c libavcodec/mjpegenc_huffman.c libavcodec/pixblockdsp.c libavcodec/parser.c libavcodec/profiles.c libavcodec/pthread_frame.c libavcodec/qsv_api.c libavcodec/raw.c libavcodec/resample.c libavcodec/resample2.c libavcodec/utils.c libavcodec/vorbis_parser.c libavcodec/xiph.c libavcodec/h264dec.c libavcodec/h264_cabac.c libavcodec/h264_cavlc.c libavcodec/h264chroma.c libavcodec/h264_direct.c libavcodec/h264_loopfilter.c libavcodec/h264_mb.c libavcodec/h264_picture.c libavcodec/h264_parse.c libavcodec/h264_parser.c libavcodec/h264_picture.c libavcodec/h264_ps.c libavcodec/h264pred.c libavcodec/h264qpel.c libavcodec/h264_refs.c libavcodec/h264_sei.c libavcodec/h264_slice.c libavcodec/h264data.c libavcodec/h264dsp.c libavcodec/h2645_parse.c libavcodec/h264idct.c libavcodec/videodsp.c libavcodec/faandct.c libavcodec/faanidct.c libavcodec/jfdctint.c libavcodec/jfdctfst.c libavcodec/golomb.c libavcodec/jrevdct.c libavcodec/me_cmp.c libavcodec/startcode.c libavcodec/pthread.c libavcodec/pthread_slice.c libavcodec/simple_idct.c) if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l") list(APPEND libfilenames libavutil/arm/cpu.c libavutil/arm/asm.S libavcodec/arm/h264chroma_init_arm.c libavcodec/arm/h264dsp_init_arm.c libavcodec/arm/h264pred_init_arm.c libavcodec/arm/h264qpel_init_arm.c libavcodec/arm/h264cmc_neon.S libavcodec/arm/h264dsp_neon.S libavcodec/arm/h264idct_neon.S libavcodec/arm/h264pred_neon.S libavcodec/arm/h264qpel_neon.S libavcodec/arm/hpeldsp_neon.S) else() list(APPEND libfilenames libavutil/x86/cpu.c libavutil/x86/imgutils_init.c libavcodec/x86/h264chroma_init.c libavcodec/x86/h264dsp_init.c libavcodec/x86/h264_intrapred_init.c libavcodec/x86/h264_qpel.c libavcodec/x86/fdctdsp_init.c libavcodec/x86/fdct.c libavcodec/x86/idctdsp_init.c libavcodec/x86/me_cmp_init.c libavcodec/x86/constants.c libavcodec/x86/pixblockdsp_init.c libavcodec/x86/simple_idct.c libavcodec/x86/videodsp_init.c) endif() if(WIN32) list(APPEND libfilenames compat/strtod.c # compat/msvcrt/snprintf.c compat/getopt.c) endif() if(WIN32 OR ("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")) option (WRAPPER_BUILD_STATIC_LIBS "enabled static library instead of shared" ON) else() option (WRAPPER_BUILD_STATIC_LIBS "enabled static library instead of shared" OFF) endif() if(WIN32) include_directories(${PROJECT_SOURCE_DIR} ${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR}/compat ${PROJECT_SOURCE_DIR}/compat/atomics/win32) else() include_directories(${PROJECT_SOURCE_DIR} ${PROJECT_BINARY_DIR} ${PROJECT_SOURCE_DIR}/compat ${PROJECT_SOURCE_DIR}/compat/atomics/gcc) endif() if(WRAPPER_BUILD_STATIC_LIBS) add_library(openH264wrapper STATIC ${libfilenames} ${YASM_OBJECTS}) else() add_library(openH264wrapper SHARED ${libfilenames} ${YASM_OBJECTS}) endif() if(NOT WIN32) if(CRYPTOPP_FOUND) target_link_libraries(openH264wrapper cryptopp) else() target_link_libraries(openH264wrapper m) endif() endif() add_executable(h264decmain h264decmain.c) target_link_libraries(h264decmain openH264wrapper)
e9c090cb68a7b9ecb3ed5ca28f4d343de35afa31
[ "Markdown", "C", "CMake" ]
3
C
lunlun1992/openH264
50ee32c8dc7f51027494b0d9d6630566b0783f4f
18745c94f003855fac14d1af03bab905e37c1cf5
refs/heads/master
<repo_name>N3r03/Sport<file_sep>/SportLife/Models/Players.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace SportLife.Models { [Table("tblPlayers")] public class Players { [Key] public int playerID { get; set; } public string FullName { get; set; } public int Age { get; set; } public int SportID { get; set; } } }<file_sep>/SportLife/Controllers/SportController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SportLife.Models; namespace SportLife.Controllers { public class SportController : Controller { // GET: Sport public ActionResult Index() { PlayersContext PlayersContext = new PlayersContext(); List<Sport> Sports = PlayersContext.Sports.ToList(); return View(Sports); } } }<file_sep>/SportLife/Models/Sport.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace SportLife.Models { [Table("tblSport")] public class Sport { public int id { get; set; } public string Name { get; set; } public List<Players> Players { get; set; } } }<file_sep>/SportLife/Models/PlayersContext.cs using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations.Schema; namespace SportLife.Models { public class PlayersContext : DbContext { public DbSet<Sport> Sports { get; set; } public DbSet<Players> Players { get; set; } } }<file_sep>/SportLife/Controllers/PlayerController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SportLife.Models; namespace SportLife.Controllers { public class PlayerController : Controller { // GET: Player public ActionResult Index(int SportID) { PlayersContext PlayersContext = new PlayersContext(); List<Players> Players = PlayersContext.Players.Where(p => p.SportID == SportID).ToList(); return View(Players); } public ActionResult Details(int SportID) { PlayersContext PlayersContext = new PlayersContext(); Players Players1 = PlayersContext.Players.Single(pl => pl.SportID == SportID); return View(Players1); } } }
fcf02168934adde926d3da5e443095f6fbdd5c36
[ "C#" ]
5
C#
N3r03/Sport
5c4ffa3ed4114f3311d4924abf55757d5b582132
bec77aa304c39110510d8a49adb53035c77312e6
refs/heads/master
<file_sep>// // main.cpp // NeuralNet // // Created by <NAME> on 10/5/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include <vector> #include <cstdlib> #include <cassert> #include <cmath> using namespace std; struct Connection{ double weight; double deltaWeight; }; class Neuron; typedef vector<Neuron> Layer; // * * * * * * * * * * * * class Neuron * * * * * * * * * * * * * * * class Neuron { public: //tell Neuron how many neurons there are in the next layer Neuron(int numOutputs, unsigned myIndex); void setOutputVal(double val){ m_outputVal = val; } double getOutputVal(void) const{return m_outputVal;} void feedForward(const Layer &prevLayer); void calcOutputGradients(double targetVal); void calcHiddenGradients(const Layer &nextLayer); void updateInputWeights(Layer &prevLayer); private: static double transferFunction(double x); static double transferFunctionDerivative(double x); double m_outputVal; static double randomWeight(void) { return rand()/ double(RAND_MAX); } double sumDOW(const Layer &nextLayer) const; //Connection contains weight & deltaWeight vector<Connection> m_outputWeights; unsigned m_myIndex; double m_gradient; static double eta; //(0->1) static double alpha; //(0->n) }; // * * * * * * * * * * * * Net Declaration * * * * * * * * * * * * * * * double Neuron::eta = 0.15; //learning rate double Neuron::alpha = 0.5; //momentum Neuron::Neuron(int numOutputs, unsigned myIndex){ //c -> connection for (unsigned c = 0; c < numOutputs; ++c){ //you could make connection a class with a constructor that //gives Connection a random weight but we can do it here. m_outputWeights.push_back(Connection()); m_outputWeights.back().weight = randomWeight(); } m_myIndex = myIndex; } void Neuron::feedForward(const Layer &prevLayer){ double sum = 0.0; //loop through neurons in prev layer. //include bias neuron for(unsigned n = 0; n < prevLayer.size(); ++n){ sum += prevLayer[n].getOutputVal() * prevLayer[n].m_outputWeights[m_myIndex].weight; } m_outputVal = transferFunction(sum); } double Neuron::transferFunction(double x){ //tanh - output range [-1.0 -> 1.0] return tanh(x); } double Neuron::transferFunctionDerivative(double x){ //tanh derivative return 1.0 - x * x; } void Neuron::calcOutputGradients(double targetVal){ double delta = targetVal - m_outputVal; m_gradient = delta * Neuron::transferFunctionDerivative(m_outputVal); } void Neuron::calcHiddenGradients(const Layer &nextLayer){ double dow = sumDOW(nextLayer); m_gradient = dow * Neuron::transferFunctionDerivative(m_outputVal); } double Neuron::sumDOW(const Layer &nextLayer) const{ double sum = 0.0; for(unsigned n = 0; n < nextLayer.size() - 1; ++n){ sum += m_outputWeights[n].weight * nextLayer[n].m_gradient; } return sum; } void Neuron::updateInputWeights(Layer &prevLayer){ for(unsigned n = 0; n < prevLayer.size(); ++n){ Neuron &neuron = prevLayer[n]; double oldDeltaWeight = neuron.m_outputWeights[m_myIndex].deltaWeight; //individual input, magnified by gradient and train rate double newDeltaWeight = eta //training rate 0-slow .2-medium 1-reckless * neuron.getOutputVal() * m_gradient + alpha //alpha is momentum rate * oldDeltaWeight; //0 is no/ .5 is moderate momentum neuron.m_outputWeights[m_myIndex].deltaWeight = newDeltaWeight; neuron.m_outputWeights[m_myIndex].weight += newDeltaWeight; } } // * * * * * * * * * * * * class Net * * * * * * * * * * * * * * * class Net{ public: Net(const vector<unsigned> &topology); void feedForward(const vector<double> &inputVals); void backProp(const vector<double> &targetVals); void getResults(vector<double> &resultVals) const; private: vector<Layer> m_layers; // m_layers[layerNum][neuronNum] double m_error; double m_recentAverageError; double m_recentAverageSmoothingFactor; }; // * * * * * * * * * * * * Net Declaration * * * * * * * * * * * * * * * Net::Net(const vector<unsigned> &topology){ unsigned numLayers = topology.size(); for(unsigned layerNum = 0; layerNum < numLayers; ++layerNum){ //typedef constructor Layer() m_layers.push_back(Layer()); //if last layer, numoutputs = 0; else, numOutputs = topology[nextLayer] unsigned numOutputs = layerNum == topology.size() - 1 ? 0 : topology[layerNum+1]; // <= because we want a bias neuron at each layer for(unsigned neuronNum = 0; neuronNum <= topology[layerNum]; ++neuronNum){ //gives you the last element in the container m_layers.back().push_back(Neuron(numOutputs, neuronNum)); cout << "made a Neuron" << endl; } //make bias neuron 1.0 m_layers.back().back().setOutputVal(1.0); } } void Net::feedForward(const vector<double> &inputVals){ //check that the # of neurons and # of inputs match assert(inputVals.size()==m_layers[0].size() - 1); //assign input values to input neurons for(unsigned i = 0; i < inputVals.size(); ++i){ m_layers[0][i].setOutputVal(inputVals[i]); } //forward propagate: for(unsigned layerNum = 1; layerNum < m_layers.size(); ++layerNum){ Layer &prevLayer = m_layers[layerNum-1]; //for each nuron in a Layer for(unsigned n = 0; n < m_layers[layerNum].size() - 1; ++n){ //class neuron's feedForward function m_layers[layerNum][n].feedForward(prevLayer); } } } void Net::backProp(const vector<double> &targetVals){ //Calcualte overall net error (RMS of output errors) Layer &outputLayer = m_layers.back(); m_error = 0.0; for(unsigned n = 0; n < outputLayer.size() - 1; ++n){ double delta = targetVals[n] - outputLayer[n].getOutputVal(); m_error += delta * delta; } m_error /= outputLayer.size() - 1; m_error = sqrt(m_error); //RMS //implement a recent average measurement; error indication of how well the net is doing/being trained. m_recentAverageError = (m_recentAverageError * m_recentAverageSmoothingFactor + m_error) / (m_recentAverageSmoothingFactor + 1.0); //calc output layer gradients for(unsigned n = 0; n < outputLayer.size() - 1; ++n){ outputLayer[n].calcOutputGradients(targetVals[n]); } //calculate gradients on hidden layers for(unsigned layerNum = m_layers.size() - 2; layerNum > 0; --layerNum){ Layer &hiddenLayer = m_layers[layerNum]; Layer &nextLayer = m_layers[layerNum + 1]; for(unsigned n = 0; n < hiddenLayer.size(); ++n) { hiddenLayer[n].calcHiddenGradients(nextLayer); } } //for all layers from outputs to first hidden layer, update connection weights for(unsigned layerNum = m_layers.size() - 1; layerNum > 0; --layerNum){ Layer &layer = m_layers[layerNum]; Layer &prevLayer = m_layers[layerNum - 1]; for(unsigned n = 0; n < layer.size() - 1; ++n){ layer[n].updateInputWeights(prevLayer); } } } void Net::getResults(vector<double> &resultVals) const{ resultVals.clear(); for(unsigned n = 0; n < m_layers.back().size() - 1; ++n) { resultVals.push_back(m_layers.back()[n].getOutputVal()); } } int main(){ //create Neural Net //eg { 3, 2, 1 } vector<unsigned> topology; topology.push_back(3); //3 input neurons topology.push_back(2); //2 hidden neurons topology.push_back(1); //1 output neuron Net myNet(topology); // Train vector<double> inputVals; myNet.feedForward(inputVals); vector<double> targetVals; myNet.backProp(targetVals); //Use Neural Net vector<double> resultVals; myNet.getResults(resultVals); }
08917bff7d07749536e53f056ea8012b67122687
[ "C++" ]
1
C++
cmathews95/neuralnet
2f99d3b2386ba885cb340b7d8a2d11c5809696c2
67aa5424c3e06954aa0efe3b49d34f61f51180a7
refs/heads/master
<repo_name>krolesz94/Java-Basics<file_sep>/MinimumElementChallenge/src/com/Asd0cska/Main.java package com.Asd0cska; import java.util.Arrays; import java.util.Scanner; public class Main { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int[] array = readInteger(5); System.out.println("The content of the Array[]: " + Arrays.toString(array)); System.out.println("The minimum value of the array is: " + findMin(array)); } public static int[] readInteger(int count){ int[] array = new int[count]; System.out.println("Enter " + count + " number: "); for (int i = 0; i < array.length; i++){ array[i] = sc.nextInt(); } return array; } public static int findMin(int[] array){ int min = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++){ if (array[i] < min){ min = array[i]; } } return min; } } <file_sep>/Counter/src/com/Asd0cska/Timer.java package com.Asd0cska; import javax.swing.*; import java.awt.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; public class Timer extends javax.swing.JFrame{ private javax.swing.JButton but_Reset; private javax.swing.JButton but_Start; private javax.swing.JButton but_Stop; private javax.swing.JMenuBar jMenuBar; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JLabel lb_swDescription; private javax.swing.JLabel lb_swHours; private javax.swing.JLabel lb_swMinutes; private javax.swing.JLabel lb_swSeconds; private javax.swing.JTextField tf_swDescription; private static int milliseconds = 0; private static int seconds = 0; private static int minutes = 0; private static int hours = 0; private static boolean state = true; private String path; int storeHours; int storeMinutes; int storeSeconds; public Timer () { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2); //Center of the display initComponents(); } public void setPath(String path) { this.path = path; } private void initComponents() { lb_swHours = new javax.swing.JLabel(); lb_swMinutes = new javax.swing.JLabel(); lb_swSeconds = new javax.swing.JLabel(); lb_swDescription = new javax.swing.JLabel(); but_Start = new javax.swing.JButton(); but_Stop = new javax.swing.JButton(); but_Reset = new javax.swing.JButton(); tf_swDescription = new javax.swing.JTextField(); jMenuBar = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); //File jMenu2 = new javax.swing.JMenu(); //Edit jMenuItem1 = new javax.swing.JMenuItem(); //Exit jMenuItem2 = new javax.swing.JMenuItem(); //Counter jMenuItem3 = new javax.swing.JMenuItem(); //Save setTitle("Timer"); setResizable(false); setUndecorated(true); FrameDragListener frameDragListener = new FrameDragListener(this); this.addMouseListener(frameDragListener); this.addMouseMotionListener(frameDragListener); lb_swHours.setFont(new java.awt.Font("Magneto", 0, 36)); lb_swHours.setText("00 : "); lb_swMinutes.setFont(new java.awt.Font("Magneto", 0, 36)); lb_swMinutes.setText("00 : "); lb_swSeconds.setFont(new java.awt.Font("Magneto", 0, 36)); lb_swSeconds.setText("00 "); but_Start.setFont(new java.awt.Font("Serif", 0, 18)); but_Start.setText("Start"); but_Start.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt) { but_StartActionPerformed(evt); } }); but_Stop.setFont(new java.awt.Font("Serif",0,18)); but_Stop.setText("Stop"); but_Stop.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt){ but_StopActionPerformed(evt); } }); but_Reset.setFont(new java.awt.Font("Serif", 0,18)); but_Reset.setText("Reset"); but_Reset.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt){ but_ResetActionPerformed(evt); } }); lb_swDescription.setText("Title"); tf_swDescription.setText("UnNamed"); jMenu1.setText("File"); jMenuItem2.setText("Exit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuItem1.setText("Counter"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar.add(jMenu1); jMenu2.setText("Edit"); jMenuItem3.setText("Save"); jMenuItem3.addActionListener(new java.awt.event.ActionListener(){ public void actionPerformed(java.awt.event.ActionEvent evt){ jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); jMenuBar.add(jMenu2); setJMenuBar(jMenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lb_swHours) .addComponent(but_Start)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lb_swMinutes) .addComponent(but_Stop)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(but_Reset) .addComponent(lb_swSeconds))) .addGroup(layout.createSequentialGroup() .addComponent(lb_swDescription) .addGap(27, 27, 27) .addComponent(tf_swDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lb_swDescription) .addComponent(tf_swDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lb_swHours, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lb_swMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lb_swSeconds, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(but_Start) .addComponent(but_Stop) .addComponent(but_Reset)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); } private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { Counter counter = new Counter(); counter.setVisible(true); Timer timer = new Timer(); timer.setVisible(false); dispose(); } private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the program?", "Exit Program", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (confirmed == JOptionPane.YES_OPTION) { dispose(); } else { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); } } private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt){ Counter counter = new Counter(); path = counter.getPath(); counter.loadData(); int newHours = counter.getOldHours() + hours; int newMinutes = counter.getOldMinutes() + minutes; int newSeconds = counter.getOldSeconds() + seconds; if (newSeconds > 60) { newSeconds = 0; newMinutes++; } if (newMinutes > 60) { newMinutes = 0; newHours++; } String newHoursText; String newMinutesText; String newSecondsText; if (newHours < 10){ newHoursText = "0" + newHours; } else { newHoursText = String.valueOf(newHours); } if (newMinutes < 10) { newMinutesText = "0" + newMinutes; } else { newMinutesText = String.valueOf(newMinutes); } if (newSeconds < 10) { newSecondsText = "0" + newSeconds; } else { newSecondsText = String.valueOf(newSeconds); } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(System.currentTimeMillis()); String content = newHoursText + ":" + newMinutesText + ":" + newSecondsText + " - " + tf_swDescription.getText() + " | " + formatter.format(date) + "\n"; FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter(path + "Counter.txt", true); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println(content); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) out.close(); } } private void but_StartActionPerformed(java.awt.event.ActionEvent evt) { state = true; Thread t = new Thread(){ public void run(){ for (;;){ if (state == true){ try{ sleep(1); if (milliseconds > 1000) { milliseconds = 0; seconds++; } if (seconds > 60){ seconds = 0; minutes++; } if (minutes > 60){ minutes = 0; hours++; } milliseconds++; if (seconds < 10){ lb_swSeconds.setText("0" + seconds + ""); } else { lb_swSeconds.setText(seconds + ""); } if (minutes < 10){ lb_swMinutes.setText("0" + minutes + " : "); } else { lb_swMinutes.setText(minutes + " : "); } if (hours < 10){ lb_swHours.setText("0" + hours + " : "); } else { lb_swHours.setText(hours + " : "); } } catch (Exception e){ } } else { break; } } } }; t.start(); } private void but_StopActionPerformed(java.awt.event.ActionEvent evt) { state = false; storeHours = hours; storeMinutes = minutes; storeSeconds = seconds; } private void but_ResetActionPerformed(java.awt.event.ActionEvent evt) { state = false; milliseconds = 0; seconds = 0; minutes = 0; hours = 0; lb_swHours.setText("00 : "); lb_swMinutes.setText("00 : "); lb_swSeconds.setText("00"); } public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Timer().setVisible(true); } }); } } <file_sep>/Counter/src/com/Asd0cska/Counter.java package com.Asd0cska; import javax.swing.*; import java.awt.*; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import static java.lang.Integer.parseInt; public class Counter extends javax.swing.JFrame { //Declaring variables private javax.swing.JButton but_Show; private javax.swing.JMenu jMenu1; //File private javax.swing.JMenu jMenu2; //Edit private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; //Exit private javax.swing.JMenuItem jMenuItem2; //Load private javax.swing.JMenuItem jMenuItem3; //Save private javax.swing.JMenuItem jMenuItem4; //Create file private javax.swing.JMenuItem jMenuItem5; //Timer private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel lb_Hours; private javax.swing.JLabel lb_Minutes; private javax.swing.JLabel lb_Seconds; private javax.swing.JLabel lb_Sum; private javax.swing.JLabel lb_Description; private javax.swing.JList<String> ll_MinutesList; private javax.swing.JList<String> ll_SecondsList; private javax.swing.JTextField tf_HoursText; private javax.swing.JTextField tf_Description; int currentHours = 0; int currentMinutes; int currentSeconds; int oldHours; int oldMinutes; int oldSeconds; int newHours; int newMinutes; int newSeconds; String hoursString; String minutesString; String secondsString; private String path = System.getProperty("user.home") + File.separator + "Documents" + File.separator + "Counter" + File.separator; //Create constructor public Counter() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2); //Center of the display initComponents(); lb_Hours.setText("Hours"); lb_Minutes.setText("Minutes"); lb_Seconds.setText("Seconds"); lb_Sum.setText(""); but_Show.setText("Submit"); ll_MinutesList.setSelectedIndex(0); ll_SecondsList.setSelectedIndex(0); File file = new File(path + "Counter.txt"); if (!file.exists()){ lb_Sum.setText("00:00:00"); } else { loadData(); } } public String getPath() { return path; } public int getOldHours() { return oldHours; } public int getOldMinutes() { return oldMinutes; } public int getOldSeconds() { return oldSeconds; } //Define JFrame and set Button, Menu Items, Labels and List including the contents private void initComponents() { but_Show = new javax.swing.JButton(); lb_Minutes = new javax.swing.JLabel(); lb_Seconds = new javax.swing.JLabel(); lb_Hours = new javax.swing.JLabel(); lb_Sum = new javax.swing.JLabel(); lb_Description = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jScrollPane2 = new javax.swing.JScrollPane(); ll_MinutesList = new javax.swing.JList<>(); ll_SecondsList = new javax.swing.JList<>(); tf_HoursText = new javax.swing.JTextField(); tf_Description = new javax.swing.JTextField(); jMenuBar1 = new javax.swing.JMenuBar(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem4 = new javax.swing.JMenuItem(); jMenuItem5 = new javax.swing.JMenuItem(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); // setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setTitle("Counter"); setResizable(false); setUndecorated(true); FrameDragListener frameDragListener = new FrameDragListener(this); this.addMouseListener(frameDragListener); this.addMouseMotionListener(frameDragListener); but_Show.setText("jButton1"); but_Show.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { but_ShowActionPerformed(evt); } }); lb_Minutes.setText("jLabel1"); lb_Seconds.setText("jLabel2"); lb_Hours.setText("jLabel3"); lb_Description.setText("Title"); ll_MinutesList.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "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", "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", "52", "53", "54", "55", "56", "57", "58", "59", "60" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); ll_MinutesList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane1.setViewportView(ll_MinutesList); ll_SecondsList.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "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", "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", "52", "53", "54", "55", "56", "57", "58", "59", "60" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); ll_SecondsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(ll_SecondsList); tf_HoursText.setText("0"); tf_Description.setText("UnNamed"); lb_Sum.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lb_Sum.setText("jLabel4"); lb_Sum.setToolTipText("Summary of spent hours"); jMenu1.setText("File"); jMenuItem4.setText("Create file"); jMenuItem4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem4ActionPerformed(evt); } }); jMenu1.add(jMenuItem4); jMenuItem1.setText("Exit"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuItem2.setText("Load"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu2.add(jMenuItem2); jMenuItem3.setText("Save"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); jMenuItem5.setText("Timer"); jMenuItem5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem5ActionPerformed(evt); } }); jMenu2.add(jMenuItem5); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 46, Short.MAX_VALUE) .addComponent(but_Show) .addGap(41, 41, 41)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(lb_Sum, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lb_Hours, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lb_Minutes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lb_Seconds, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(lb_Description, javax.swing.GroupLayout.Alignment.LEADING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE) .addComponent(tf_HoursText) .addComponent(tf_Description)))) .addContainerGap(31, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tf_Description, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lb_Description)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lb_Hours) .addComponent(tf_HoursText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(lb_Minutes, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(lb_Seconds, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(lb_Sum, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(but_Show) .addGap(25, 25, 25)) ); pack(); } private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the program?", "Exit Program", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (confirmed == JOptionPane.YES_OPTION) { dispose(); } else { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); } } private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) { loadData(); } private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) { saveData(); } private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt){ createFile(); } private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt){ Counter counter = new Counter(); counter.setVisible(false); Timer timer = new Timer(); timer.setVisible(true); } private void but_ShowActionPerformed(java.awt.event.ActionEvent evt) { //loadData(); try { if (tf_HoursText.getText() == null) { currentHours = 0; } else { currentHours = parseInt(tf_HoursText.getText()); } } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "You can use only numbers", "Wrong input", JOptionPane.WARNING_MESSAGE); } currentMinutes = ll_MinutesList.getSelectedIndex(); currentSeconds = ll_SecondsList.getSelectedIndex(); currentHours += oldHours; currentMinutes += oldMinutes; currentSeconds += oldSeconds; if(currentMinutes >= 60) { currentHours += 1; currentMinutes = 0; } if(currentSeconds >= 60 ) { currentMinutes += 1; currentSeconds = 0; } hoursString = String.valueOf(currentHours); minutesString = String.valueOf(currentMinutes); secondsString = String.valueOf(currentSeconds); lb_Sum.setText(currentHours + ":" + currentMinutes + ":" +currentSeconds); //saveData(); } public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Counter().setVisible(true); } }); } //Store data into txt public void saveData () { newHours = currentHours; newMinutes = currentMinutes; newSeconds = currentSeconds; String newHoursText; String newMinutesText; String newSecondsText; if (newHours < 10){ newHoursText = "0" + newHours; } else { newHoursText = String.valueOf(newHours); } if (newMinutes < 10) { newMinutesText = "0" + newMinutes; } else { newMinutesText = String.valueOf(newMinutes); } if (newSeconds < 10) { newSecondsText = "0" + newSeconds; } else { newSecondsText = String.valueOf(newSeconds); } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(System.currentTimeMillis()); String content = newHoursText + ":" + newMinutesText + ":" + newSecondsText + " - " + tf_Description.getText() + " | " + formatter.format(date); FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter(path + "Counter.txt", true); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println(content); System.out.println("Done"); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) out.close(); } } public void loadData(){ String fileName = path + "Counter.txt"; StringBuilder contentBuilder = new StringBuilder(); String lastLine = ""; try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { contentBuilder.append(sCurrentLine).append("\n"); lastLine = sCurrentLine; } if (!lastLine.substring(0, 2).trim().equals(null) || !lastLine.substring(0, 2).trim().equals("00")) { oldHours = parseInt(lastLine.substring(0, 2).trim()); } else { oldHours = 0; } if (!lastLine.substring(3, 5).trim().equals(null) || !lastLine.substring(3, 5).trim().equals("00")){ oldMinutes = parseInt(lastLine.substring(3, 5).trim()); } else { oldMinutes = 0; } if (!lastLine.substring(6, 8).trim().equals(null) || !lastLine.substring(6, 8).trim().equals("00")){ oldSeconds = parseInt(lastLine.substring(6, 8).trim()); } else { oldSeconds = 0; } } catch (IOException e) { e.printStackTrace(); } System.out.println(newHours + ":" + newMinutes + ":" + newSeconds); lb_Sum.setText(newHours + ":" + newMinutes + ":" + newSeconds); } public void createFile (){ File customDir = new File(path); File file = new File(path + "Counter.txt"); String content = "00:00:00"; FileOutputStream fop = null; if (customDir.exists()){ System.out.println(customDir + " already exists"); } else if (customDir.mkdirs()){ System.out.println(customDir + " was created"); } else { System.out.println(customDir + " was not created"); } try { fop = new FileOutputStream(file); if (!file.exists()) file.createNewFile(); byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); } catch (IOException e){ e.printStackTrace(); } } } <file_sep>/secondsAndMinutesChallenge/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { getDurationString(61, 0); getDurationString(9_223_372_036_854_775_807L); } private static final String INVALID_VALUE_MESSAGE = "Invalid Value"; public static void getDurationString(long minutes, long seconds){ long hours = minutes / 60; minutes = minutes % 60; if (minutes >= 0 && ((seconds >=0) && (seconds <= 59))){ System.out.println(hours + "h " + minutes + "m " + seconds + "s"); }else{ System.out.println(INVALID_VALUE_MESSAGE); } } public static void getDurationString(long seconds){ if (seconds >= 0){ long minutes = seconds / 60; long remainingSeconds = seconds % 60; long hours = minutes / 60; long remainingMinutes = minutes % 60; long day = hours / 24; long remainingHours = hours % 24; long week = day / 7; long remainingDay = day % 7; long month = week / 30; long remainingWeek = week % 30; long year = month / 12; long remainingMonth = month % 12; long century = year / 100; long remainingYear = year % 100; long millenium = century / 10; long remainingCentury = century % 10; System.out.println(millenium + "m " + remainingCentury + "c " + remainingYear + "y " + remainingMonth + "m " + remainingWeek + "w " + remainingDay + "d " + remainingHours + "h " + remainingMinutes + "m " + remainingSeconds + "s"); }else{ System.out.println(INVALID_VALUE_MESSAGE); } } } <file_sep>/NumberToWords/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { numberToWords(123); numberToWords(1010); numberToWords(1000); numberToWords(-12); System.out.println(getDigitCount(0)); System.out.println(getDigitCount(123)); System.out.println(getDigitCount(-12)); System.out.println(getDigitCount(5200)); System.out.println(reverse(-121)); System.out.println(reverse(1212)); System.out.println(reverse(1234)); System.out.println(reverse(100)); } public static void numberToWords (int number) { if (number < 0){ System.out.println("Invalid Value"); } int digits = getDigitCount(number); int no = 0; number = reverse(number); for (int i = 0; i < digits; i++) { no = number % 10; number /= 10; switch (no) { case 0: System.out.println("Zero"); break; case 1: System.out.println("One"); break; case 2: System.out.println("Two"); break; case 3: System.out.println("Three"); break; case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); break; case 6: System.out.println("Six"); break; case 7: System.out.println("Seven"); break; case 8: System.out.println("Eight"); break; case 9: System.out.println("Nine"); break; } } } public static int reverse(int number) { boolean neg = false; if(number < 0){ neg = true; number *= -1; } int x; int y; int z = 0; int digits = getDigitCount(number) - 1; for (int i = digits; i >= 0; i--) { x = number % 10; y = x * (int) (Math.pow(10, i)); number /= 10; z += y; } if (neg){ z *= -1; return z; } return z; } public static int getDigitCount (int number) { if (number == 0) { int digits = 1; return digits; } else if (number < 0) { return -1; } else { int digits = 0; while (number != 0) { number /= 10; digits += 1; } return digits; } } } <file_sep>/MethodOverloading/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { int newScore = calculateScore("Bob", 500); System.out.println("New score is " + newScore); calculateScore(75); calculateScore(); //calcFeetAndInchesToCentimeters(12.5, 9.75); calcFeetAndInchesToCentimeters(156); } public static int calculateScore(String playerMame, int score){ System.out.println("Player " + playerMame + " scored " + score + " points"); return score * 1000; } public static int calculateScore(int score){ System.out.println("Unnamed player scored " + score + " points"); return score * 1000; } public static int calculateScore(){ System.out.println("No player name, no player score"); return 0; } public static double calcFeetAndInchesToCentimeters(double feet, double inch){ double centimeters = (feet * 12) *2.54; centimeters += inch * 2.54; if ((feet > 0) && (inch >= 0) && (inch <= 12)){ System.out.println(feet + " feet, " + inch + " inches = " + centimeters + " cm"); return centimeters; }else{ System.out.println("Invalid feet or inches"); return -1; } } public static double calcFeetAndInchesToCentimeters(double inch){ if (inch >= 0 && inch <= 12){ double feet = (int) inch / 12; double remaininggInches = (int) inch % 12; System.out.println(inch + " inches is equal to " + feet + " feet and " + remaininggInches + " inches"); return calcFeetAndInchesToCentimeters(feet, remaininggInches); }else{ return -1; } } } <file_sep>/OOPChallenge/src/com/Asd0cska/Main.java package com.Asd0cska; class Hamburger { //Beginning variable declaration private String breadRollType; private String meat; private boolean lettuce; private boolean tomato; private boolean cheddar; private boolean cucumber; private float baseBurgerValue; private float lettuceValue; private float tomatoValue; private float cheddarValue; private float cucumberValue; //End of variable declaration //Creating constructor public Hamburger(boolean lettuce, boolean tomato, boolean cheddar, boolean cucumber) { this.lettuce = lettuce; this.tomato = tomato; this.cheddar = cheddar; this.cucumber = cucumber; this.breadRollType = "White bread roll"; this.meat = "beaf"; this.baseBurgerValue = 2.5f; this.lettuceValue = 0.4f; this.tomatoValue = 0.3f; this.cheddarValue = 0.7f; this.cucumberValue = 0.4f; } //Getter public boolean isLettuce() { return lettuce; } public boolean isTomato() { return tomato; } public boolean isCheddar() { return cheddar; } public boolean isCucumber() { return cucumber; } public float getBaseBurgerValue() { return baseBurgerValue; } public float getLettuceValue() { return lettuceValue; } public float getTomatoValue() { return tomatoValue; } public float getCheddarValue() { return cheddarValue; } public float getCucumberValue() { return cucumberValue; } //Summarize the whole order public float sum (){ float total = baseBurgerValue; if (isLettuce()) total += lettuceValue; if (isTomato()) total += tomatoValue; if (isCheddar()) total += cheddarValue; if (isCucumber()) total += cucumberValue; return total; } } class HealthyBurger extends Hamburger { //Beginning variable declaration private String breadRollType; private boolean beanSprouts; private boolean cabbage; private float healthyBurgerValue; private float beanSproutsValue; private float cabbageValue; //End of variable declaration //Creating constructor public HealthyBurger(boolean lettuce, boolean tomato, boolean cheddar, boolean cucumber, boolean beanSprouts, boolean cabbage) { super(lettuce, tomato, cheddar, cucumber); this.beanSprouts = beanSprouts; this.cabbage = cabbage; this.breadRollType = "Brown rye bread roll"; this.healthyBurgerValue = 3.2f; this.beanSproutsValue = 0.9f; this.cabbageValue = 1.2f; } //Getter public boolean isBeanSprouts() { return beanSprouts; } public boolean isCabbage() { return cabbage; } //Summarize the whole order for HealthyBurger @Override public float sum () { float total = healthyBurgerValue; if (isLettuce()) total += getLettuceValue(); if (isTomato()) total += getTomatoValue(); if (isCheddar()) total += getCheddarValue(); if (isCucumber()) total += getCucumberValue(); if (isBeanSprouts()) total += beanSproutsValue; if (isCabbage()) total += cabbageValue; return total; } } class DeluxeBurger extends Hamburger{ //Beginning variable declaration private float chipsValue; private float drinkValue; //End of variable declaration //Creating constructor public DeluxeBurger(boolean lettuce, boolean tomato, boolean cheddar, boolean cucumber) { super(lettuce, tomato, cheddar, cucumber); this.chipsValue = 1.2f; this.drinkValue = 0.8f; } //Summarize the whole order for DeluxeBurger @Override public float sum () { float total = getBaseBurgerValue() + chipsValue + drinkValue; if (isLettuce()) total += getLettuceValue(); if (isTomato()) total += getTomatoValue(); if (isCheddar()) total += getCheddarValue(); if (isCucumber()) total += getCucumberValue(); return total; } } public class Main { public static void main(String[] args) { Hamburger hamburger = new Hamburger(true, false, true, true); System.out.println("Base burger value: " + hamburger.sum()); System.out.println("---------------------------"); HealthyBurger healthyBurger = new HealthyBurger(true,false,true,true,true,true); System.out.println("Healthy burger value: " + healthyBurger.sum()); System.out.println("---------------------------"); DeluxeBurger deluxeBurger = new DeluxeBurger(true, false, true, true); System.out.println("Deluxe burger value: " + deluxeBurger.sum()); } } <file_sep>/Home/src/com/Asd0cska/Settings/Settings.java package com.Asd0cska.Settings; import com.Asd0cska.Home.Home; import javax.swing.*; public class Settings extends javax.swing.JFrame { private javax.swing.JRadioButton Celsius; private javax.swing.JComboBox City; private javax.swing.JRadioButton Fahrenheit; private javax.swing.JLabel SaveBt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private String location; private String unitDegree; public Settings() { initComponents(); location = "Budapest"; unitDegree = "c"; } private void initComponents() { SaveBt = new javax.swing.JLabel(); City = new javax.swing.JComboBox(); Celsius = new javax.swing.JRadioButton(); Fahrenheit = new javax.swing.JRadioButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(690, 450)); setMinimumSize(new java.awt.Dimension(690, 450)); setUndecorated(true); setPreferredSize(new java.awt.Dimension(690, 450)); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); SaveBt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/saveBtn.png"))); // NOI18N SaveBt.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { SaveBtMouseClicked(evt); } public void mouseEntered(java.awt.event.MouseEvent evt) { SaveBtMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { SaveBtMouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { SaveBtMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { SaveBtMouseReleased(evt); } }); getContentPane().add(SaveBt, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 340, 210, -1)); City.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N City.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Budapest", "Bukarest", "Bécs"})); getContentPane().add(City, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, 280, 60)); Celsius.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/Cel.png"))); // NOI18N Celsius.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CelsiusMouseClicked(evt); } }); getContentPane().add(Celsius, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 100, -1, -1)); Fahrenheit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/Far.png"))); // NOI18N Fahrenheit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { FahrenheitMouseClicked(evt); } }); getContentPane().add(Fahrenheit, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 100, -1, -1)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/closeBtn.png"))); // NOI18N jLabel2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel2MouseClicked(evt); } }); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 10, -1, -1)); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/minimizeBtn.png"))); // NOI18N jLabel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel3MouseClicked(evt); } }); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 10, -1, -1)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/window.png"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 702, -1)); pack(); setLocationRelativeTo(null); } private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) { dispose(); } private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) { this.setState(this.ICONIFIED); } private void CelsiusMouseClicked(java.awt.event.MouseEvent evt) { JOptionPane.showMessageDialog(null, "Celsius Option Selected", "Option Clicked" , JOptionPane.WARNING_MESSAGE); this.unitDegree = "c"; } private void FahrenheitMouseClicked(java.awt.event.MouseEvent evt) { JOptionPane.showMessageDialog(null, "Fahrenheit Option Selected", "Option Clicked" , JOptionPane.WARNING_MESSAGE); this.unitDegree = "f"; } private void SaveBtMouseEntered(java.awt.event.MouseEvent evt) { SaveBt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/saveBtnHover.png"))); } private void SaveBtMouseExited(java.awt.event.MouseEvent evt) { SaveBt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/saveBtn.png"))); } private void SaveBtMousePressed(java.awt.event.MouseEvent evt) { SaveBt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/saveBtnPressed.png"))); } private void SaveBtMouseReleased(java.awt.event.MouseEvent evt) { SaveBt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/Asd0cska/Settings/saveBtn.png"))); } private void SaveBtMouseClicked(java.awt.event.MouseEvent evt) { this.location = City.getSelectedItem().toString(); JOptionPane.showMessageDialog(null, "Settings are now updated."); Home home = new Home(); home.changeLocation(this.location); home.changeUnitDegrees(this.unitDegree); home.setVisible(true); this.dispose(); } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Settings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Settings().setVisible(true); } }); } } <file_sep>/LastDigitCheckerChallenge/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { System.out.println(hasSameLastDigit(41,22,71)); System.out.println(hasSameLastDigit(23,32,42)); System.out.println(hasSameLastDigit(9,99,999)); System.out.println(isValid(10)); System.out.println(isValid(468)); System.out.println(isValid(1051)); } public static boolean hasSameLastDigit (int a, int b, int c) { int leftA = a % 10; int leftB = b % 10; int leftC = c % 10; if (!isValid(a) || !isValid(b) || !isValid(c)){ return false; }else{ if ((leftA == leftB) || (leftA == leftC) || (leftB == leftC)){ return true; }else{ return false; } } } public static boolean isValid (int number) { if ((number < 10) || (number > 1000)){ return false; }else { return true; } } } <file_sep>/TeennumberChecker/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { // write your code here } public static boolean hasTeen(int a, int b, int c){ if (a >= 13 && a <= 19){ return true; }else if(b >= 13 && b <= 19){ return true; }else if(c >= 13 && c <= 19){ return true; }else{ return false; } } public static boolean isTeen(int year){ if (year <= 19 && year >= 13){ return true; }else{ return false; } } } <file_sep>/ForLoop/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { // System.out.println("10,000 at 2% interest = " + calculatedInterest(10000,2.0)); // System.out.println("10,000 at 3% interest = " + calculatedInterest(10000,3.0)); // System.out.println("10,000 at 4% interest = " + calculatedInterest(10000,4.0)); // System.out.println("10,000 at 5% interest = " + calculatedInterest(10000,5.0)); for (int i = 2; i <= 8; i++) { System.out.println("10,000 at " + i + "% interest = " + String.format("%.2f", calculatedInterest(10000, i))); } System.out.println("\n"); for (int i = 8; i >= 2; i--) { System.out.println("10,000 at " + i + "% interest = " + String.format("%.2f", calculatedInterest(10000, i))); } System.out.println("\n\n"); int count = 0; int range = 100; System.out.print("Prime numbers are: "); for (int i = 0; i <= range; i++) { // range++; if (isPrime(i)){ System.out.print(i + " | "); count++; } // if (count == 3){ // System.out.println("The prime count is reached 3!"); // break; // } } System.out.println("\nThe prime count is: " + count); } public static double calculatedInterest(float amount, float interestRate){ return (amount * (interestRate/100)); } public static boolean isPrime(int n){ if (n == 1) { return false; } for (int i = 2; i <= (long) Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } } <file_sep>/ArrayChallenge/src/com/Asd0cska/Main.java package com.Asd0cska; import java.awt.*; import java.util.Scanner; public class Main { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { printArray(sortInteger(getInteger(5))); } public static int[] getInteger(int numbers){ int [] integerArray = new int[numbers]; System.out.println("Enter " + numbers + " integer values:\r"); for (int i = 0; integerArray.length > i; i++){ integerArray[i] += sc.nextInt(); } return integerArray; } public static void printArray(int[] array){ for (int i = 0; i < array.length; i++){ System.out.println("The " + i + ".place contains the following value: " + array[i]); } } public static int[] sortInteger(int[] array){ for (int i = 0; i < array.length - 1; i++){ for (int j = 0; j < array.length - 1; j++){ if (array[j] < array[j + 1]) { array[j] *= array[j + 1]; array[j + 1] = array[j] / array[j + 1]; array[j] /= array[j + 1]; } } } return array; } } <file_sep>/AreaCalculator/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { area(12); area(1, 2); area(1, 2); } public static final String INVALID_VALUE_MESSAGE = "Invalid Value"; public static double area(double radius) { if (radius < 0) { System.out.println(INVALID_VALUE_MESSAGE); return -1.0; } else { double cirleArea = radius * radius * Math.PI; System.out.println("The area of this circle is: " + cirleArea); return cirleArea; } } public static double area(double x, double y) { if (x < 0 || y < 0) { System.out.println(INVALID_VALUE_MESSAGE); return -1.0; } else { double rectangleArea = x * y; System.out.println("The area of this rectangle is: " + rectangleArea); return rectangleArea; } } }<file_sep>/InputCalculator/src/com/Asd0cska/Main.java package com.Asd0cska; import java.util.Scanner; public class Main { public static void main(String[] args) { inputThenPrintSumAndAverage(); } public static void inputThenPrintSumAndAverage () { Scanner sc = new Scanner(System.in); double avg = 0; int sum = 0; int counter = 0; while (true) { boolean isAnInt = sc.hasNextInt(); if (isAnInt) { int number = sc.nextInt(); counter++; sum += number; } else { break; } } if ((counter == 0) || (sum == 0)){ avg = 0; } else { avg = (double) sum / counter; } System.out.println("SUM = " + sum + " AVG = " + Math.round(avg)); sc.close(); } } <file_sep>/SpeedConverter/src/com/Asd0cska/Main.java package com.Asd0cska; public class Main { public static void main(String[] args) { printConversion(1.5); printConversion(10.25); printConversion(-5.6); printConversion(25.42); printConversion(75.114); } public static long toMilesPerHour(double kilometersPerHour){ double conversion = 0.621371192; long calculated = (long) (Math.ceil(kilometersPerHour * conversion)); if (kilometersPerHour >= 0){ return calculated; }else{ return (long) -1; } } public static void printConversion(double kilometersPerHour){ if (kilometersPerHour < 0){ System.out.println("Invalid Value"); }else { System.out.println(kilometersPerHour + " km/h = " + toMilesPerHour(kilometersPerHour) + " mi/h"); } } } <file_sep>/Counter_Update/src/com/Asd0cska/SystemTrayClass.java package com.Asd0cska; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.net.URL; public class SystemTrayClass { static TrayIcon trayIcon; final SystemTray tray = SystemTray.getSystemTray(); private boolean isActive; boolean state = false; CheckboxMenuItem task = new CheckboxMenuItem("Task", state); public SystemTrayClass(){ show(); } public boolean isActive() { return this.isActive; } public void show() { if (!SystemTray.isSupported()) { System.exit(0); } trayIcon = new TrayIcon(CreateIcon("/res/notebook.png", "Icon")); trayIcon.setToolTip("Counter v2.1"); try{ tray.add(trayIcon); } catch (AWTException e){ e.printStackTrace(); } final PopupMenu menu = new PopupMenu(); task.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { isActive = true; if (e.getStateChange() == ItemEvent.SELECTED){ // TaskReminder taskReminder = new TaskReminder(); System.out.println("Checked"); }else { System.out.println("Dechecked"); isActive = false; } } }); MenuItem counter = new MenuItem("Counter"); counter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { counterActionPerformed(evt); } }); MenuItem stopWatch = new MenuItem("Stop Watch"); stopWatch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { stopWatchActionPerformed(evt); } }); MenuItem about = new MenuItem("About"); about.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutActionPerformed(evt); } }); MenuItem exit = new MenuItem("Exit"); exit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitActionPerformed(evt); } }); menu.add(task); menu.add(counter); menu.add(stopWatch); menu.add(about); menu.addSeparator(); menu.add(exit); trayIcon.setPopupMenu(menu); } protected static Image CreateIcon(String path, String desc) { URL imageURL = SystemTrayClass.class.getResource(path); return (new ImageIcon(imageURL, desc)).getImage(); } private void exitActionPerformed(java.awt.event.ActionEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the program?", "Exit Program", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (confirmed == JOptionPane.YES_OPTION) { tray.remove(trayIcon); System.exit(0); } } private void counterActionPerformed(java.awt.event.ActionEvent evt) { Counter counter = new Counter(); counter.setVisible(true); } private void stopWatchActionPerformed(java.awt.event.ActionEvent evt) { Timer timer = new Timer(); timer.setVisible(true); } private void aboutActionPerformed(java.awt.event.ActionEvent evt) { JOptionPane.showMessageDialog(null, "Operation helper v2.1 \nAuthor by: \n<NAME>"); } public static void main(String[] args){ SystemTrayClass tray = new SystemTrayClass(); } }
63f35ee6191a28863359c13e71110bc5b8d859b8
[ "Java" ]
16
Java
krolesz94/Java-Basics
bfb1c03998874e0090a09d647147b4fd51f7cccd
6d0a3084349e307177470dbb2aedc66a941b8bd4
refs/heads/master
<repo_name>cgddgc/captcha-tensorflow<file_sep>/capt/train_set.py import urllib.request,time,os,random from damatuWeb import DamatuApi from PIL import Image import numpy as np from cfg.py import dmtusr,dmtpwd class train_data(): def __init__(self): pass def get_img(n): imgpath="D:/gitrepos/captcha-tensorflow/vcode/" url = "https://jwxt.jnu.edu.cn/ValidateCode.aspx" i=0 while(i<=n): fname=imgpath+str(i)+".png" req=urllib.request.Request(url) req.addheaders=[('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0')] try: result=urllib.request.urlopen(req) except: print("timeout") time.sleep(5) result=urllib.request.urlopen(req) else: img=open(fname,'wb') img.write(result.read()) img.close() print(fname) i+=1 def ren(self,n,dmtusr,dmtpwd): dmt=DamatuApi(dmtusr,dmtpwd) path1="D:/gitrepos/captcha-tensorflow/test/" path2="D:/gitrepos/captcha-tensorflow/vcode/" err=0 use=0 for i in range(n): imgs=os.listdir(path2) f=random.choice(imgs) fname=path2+f print(fname) code=dmt.decode(fname,42) use+=1 print(code) while(code=='ERROR' or str(code)[0:1]=='-'): err+=1 code=dmt.decode(fname,42) use+=1 #pass code=str(code) i+=1 newname=path1+code+".png" c=1 while(os.path.exists(newname)): newname=path1+code+str(c)+".png" c+=1 print(i,newname) print("#######") os.rename(fname,newname) print("Total Request:"+str(use)) print(i) print(err) def get_text_img(self,imgpath): imgs=os.listdir(imgpath) img=random.choice(imgs) code=img[0:4] fname=imgpath+img im=Image.open(fname) im=im.convert("RGB") #im.show() im=np.array(im) return code, im if __name__=='__main__': td=train_data() #td.get_text_img() td.ren(500,dmtusr,dmtpwd)<file_sep>/capt/1.py #! python2 #-*-coding:utf-8-*- ''' import urllib, urllib.request, sys,base64 host = 'http://dm-55.data.aliyun.com' path = '/rest/160601/ocr/ocr_english.json' method = 'POST' appcode = '1<KEY>' querys = '' bodys = {} url = host + path img="D:/gitrepos/captcha-tensorflow/vcode/0.png" img=open(img,"rb").read() img=str(base64.b64encode(img),'utf-8') #print(img) bodys= "cid=1&content="+img+"&ext=.png" #bodys=urllib.parse.urlencode(bodys).encode(encoding='UTF8') #post_data={'cid':'1','content':img,'ext':'.png'} post_data="\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": img}}]}" #post_data=urllib.parse.urlencode(post_data).encode(encoding='UTF8') request = urllib.request.Request(url, post_data) print(post_data) request.add_header('Authorization', 'APPCODE ' + appcode) request.add_header('Content-Type', 'application/json; charset=UTF-8') response = urllib.request.urlopen(request) content = response.read() if (content): print(content) ''' import urllib, urllib2, sys,base64 img="D:/gitrepos/captcha-tensorflow/vcode/3257hq.png" img=open(img,"rb").read() img=base64.b64encode(img) #img=str(img,'utf-8') print img url = 'http://dm-55.data.aliyun.com/rest/160601/ocr/ocr_english.json' method = 'POST' appcode = '1cf203228a8f488ba3f7b19a1904fcc7' Querys = '' Headers = '' post_data = '{"inputs":{"image":{"dataType":50,"dataValue":img}}}' #post_data = urllib.urlencode(post_data).encode('utf8') #print post_data request = urllib2.Request(url,post_data) request.add_header('Authorization', 'APPCODE ' + appcode) request.add_header('Content-Type', 'application/json; charset=UTF-8') response = urllib2.urlopen(request) content = response.read() if (content): print content ''' '''<file_sep>/capt/test.py #coding=utf-8 import tensorflow as tf tensor = tf.zeros(shape=(2,2,3)) session = tf.InteractiveSession() a = tf.Variable(tensor) session.run(tf.initialize_all_variables()) print(session.run(a))<file_sep>/capt/2.py #! python2 #coding=utf-8 import sys,base64,os img="D:/gitrepos/captcha-tensorflow/vcode/3257hq.png" img=open(img,"rb").read() img=base64.b64encode(img) sh='curl -i -k -X POST \"https://dm-55.data.aliyun.com/rest/160601/ocr/ocr_english.json\" -H \"Authorization:APPCODE <KEY>\" --data \'{"inputs": [{"image": {"dataType": 50,"dataValue":'+'\"'+img+'\"'+'}}]}\' -H \"Content-Type:application/json; charset=UTF-8\"' sh1='curl -i -X POST \"http://ocr.market.alicloudapi.com/aliyunapp/[userid]\" -H \"Authorization:APPCODE <KEY>\" --data \"cid=1\&content='+img+'\&ext=.png\" -H \"Content-Type:application/json; charset=UTF-8\"' #print sh1 print sh print os.system(sh) <file_sep>/capt/predict.py #coding=utf-8 """ 专门做预测的 """ import time import os import numpy as np import tensorflow as tf from PIL import Image from cfg import MAX_CAPTCHA, CHAR_SET_LEN, model_path from cnn_sys import crack_captcha_cnn, X, keep_prob from gen_captcha import wrap_gen_captcha_text_and_image from utils import convert2gray, vec2text def hack_function(sess, predict, captcha_image): """ 装载完成识别内容后, :param sess: :param predict: :param captcha_image: :return: """ text_list = sess.run(predict, feed_dict={X: [captcha_image], keep_prob: 1}) text = text_list[0].tolist() vector = np.zeros(MAX_CAPTCHA * CHAR_SET_LEN) i = 0 for n in text: vector[i * CHAR_SET_LEN + n] = 1 i += 1 #print(vector) return vec2text(vector) def batch_hack_captcha(): """ 批量生成验证码,然后再批量进行识别 :return: """ # 定义预测计算图 output = crack_captcha_cnn() predict = tf.argmax(tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2) saver = tf.train.Saver() with tf.Session() as sess: #saver = tf.train.import_meta_graph(s_path) saver.restore(sess, tf.train.latest_checkpoint(model_path)) stime = time.time() #imgpath="D:/gitrepos/captcha-tensorflow/work/crack/y-capt-data/capt-python-36/train" imgpath="E:/MyProjects/captcha-tensorflow/vcode1" imgs=os.listdir(imgpath) task_cnt = len(imgs) right_cnt = 0 for i in imgs: #text, image = wrap_gen_captcha_text_and_image() text=i.replace('.png','') img=(imgpath+"/"+i) #print(text) #img = tf.read_file(img) #img = tf.image.decode_png(img) #img = tf.image.convert_image_dtype(img, dtype=tf.uint8) img = Image.open(img) img=img.convert("RGB") #img=img.resize((160,60),Image.ANTIALIAS) img=np.array(img) #print(img) image = convert2gray(img) image = image.flatten()/255 predict_text = hack_function(sess, predict, image) if text == predict_text: right_cnt += 1 else: print("标记: {} 预测: {}".format(text, predict_text)) pass # print("标记: {} 预测: {}".format(text, predict_text)) print('task:', task_cnt, ' cost time:', (time.time() - stime), 's') print('right/total-----', right_cnt, '/', task_cnt) print('正确率:',right_cnt/task_cnt) if __name__ == '__main__': batch_hack_captcha() print('end...')
705b2fdfc62a5d4f2a8dfec4d8824d65a8ad6f6e
[ "Python" ]
5
Python
cgddgc/captcha-tensorflow
ec3f564ced4b822a3c475903fc2a1ad1d4926a44
7b79ec89245986e45b1ffaf962371dd12d3cc588
refs/heads/master
<file_sep>WDL Viewer ========== This is the open-source release of the World Digital Library's book viewer: e.g. http://www.wdl.org/en/item/211/view/ Prerequisites & Notes --------------------- * Compass:: gem install --user-install compass --pre * JSHint: see http://www.jshint.com/install/ * We don't duplicate the OpenSeadragon sprites: external/openseadragon is a git submodule which pulls in the soon-to-be-released OpenSeadragon v0.9.129 release and the ``make sprite`` target will symlink it to where Compass expects to find it * Note that for your projects, wdl-viewer.scss attempts to abstract the parts you'd most want to customize – i.e. the seadragon controls and colors — so more involved reskinning projects should simply be able to define a ``seadragon-controls`` sprite with custom images or set the variables controlling viewport size breakpoints or colors by creating a project-specific fork of wdl-viewer.scss. Building -------- 1. ``make`` will compile the CSS and sprites 2. ``make runserver`` will launch a local webserver for development 3. open http://127.0.0.1:8000/examples/first-folio.html Integration ----------- The ``examples/first-folio.html`` file shows what a full integration scenario looks like, including several polyfills for browser feature fallbacks, and the use of jQuery custom events to interact with the viewer or react to stage changes by doing things like recording page views in your analytics service. The current implementation is a jQuery plugin which adds a `wdlViewer` method which takes a configuration object. Until formal documentation is available, consult the first-folio.html example. <file_sep>SPRITE_ROOT=src/img/sprites all: openseadragon jshint static clean: rm -rf build/wdl-viewer.* cd external/openseadragon && grunt clean openseadragon: cd external/openseadragon && grunt jshint: jshint src/js/wdl-viewer.js tidy: tidy-html5 -utf8 -m -quiet --tidy-mark no --wrap 0 --indent yes --indent-spaces 4 examples/*.html sprite: mkdir -p ${SPRITE_ROOT}/seadragon-controls/ for f in external/openseadragon/images/*_{rest,hover,pressed}.png; do \ DEST_FILE=$${f##*/}; \ DEST_FILE=$${DEST_FILE/_rest/}; \ DEST_FILE=$${DEST_FILE/_pressed/_active}; \ ln -f $$f ${SPRITE_ROOT}/seadragon-controls/$${DEST_FILE}; \ done static: sprite compass compile runserver: all python -m SimpleHTTPServer<file_sep># See http://www.compass-style.org/ # On OS X "gem install --user-install compass-notify" to have status messages in the Notification Center begin require 'compass-notify' rescue LoadError end cache_path = "/tmp/compass-cache" sass_options = { :cache_location => "/tmp/sass-cache", } relative_assets = true sass_dir = "src/css" css_dir = "build" images_dir = "src/img" generated_images_dir = "build/img" javascripts_dir = "src/js" line_comments = false on_sprite_saved do |filename| system("optipng", "-o7", "-q", filename) system("advpng", "-z4", "-q", filename) end
73a8313fcb18a6cc4ec7a89deefd387e78c4c637
[ "Makefile", "Ruby", "reStructuredText" ]
3
reStructuredText
klingerf2/wdl-viewer
183c9be631702030fab2eb653ccc4044fdf6e424
65966a616a2148d35754baeff6d9a7fe30e0aa86
refs/heads/main
<repo_name>jbaraniuk/DiceGame<file_sep>/Game.java package diceGame; /** * @author <NAME> * Game object class. */ import java.util.Random; import java.util.ArrayList; public class Game { private CircularlyDoublyLinkedList<Player> list; public Game(){ list = new CircularlyDoublyLinkedList<>(); } public void addPlayer(Player player) { list.addFirst(player); } public void startGame() { Random roll = new Random(); ArrayList<String> eliminated = new ArrayList<>(); Player player; boolean reverse = false; do { // Get player player = list.first(); // Roll dice int die1 = roll.nextInt(6) + 1; int die2 = roll.nextInt(6) + 1; // Display roll result System.out.print(player.getName() + " rolled " + die1 + " and " + die2); // Calculate score if ((die1 == 2 || die2 == 2) && die1 + die2 != 7) { player.setScore(2 * (die1 + die2)); System.out.println(". Lucky 2, score is now " + player.getScore()); } else if (die1 + die2 == 7) { player.setScore(-7); System.out.println(". Unlucky 7, score is now " + player.getScore()); } else if (die1 == 6 && die2 == 6) { player.setScore(0); System.out.println(", score is now " + player.getScore()); } else if (die1 == 1 && die2 == 1) { eliminated.add(player.getName()); System.out.println(". Snake eyes! Player eliminated :("); reverse = !reverse; list.removeFirst(); } else { player.setScore(die1 + die2); System.out.println(", score is now " + player.getScore()); } // Rotate list if (!reverse) { list.rotate(); } else { list.rotateReverse(); } } while (player.getScore() < 100 && list.size() != 1); // Display winner and final score System.out.println(player.getName() + " has won the game :)"); System.out.println(); System.out.println("Final scores are: "); for (int i = 1; i <= list.size(); i++) { if (i != list.size()) { System.out.print(list.first() + ", "); } else { System.out.print(list.first()); } list.rotate(); } // Display any eliminated players if (eliminated.size() > 0) { System.out.print("\n (Eliminated: "); for (int i = 0; i < eliminated.size(); i++) { if (i != eliminated.size() - 1) System.out.print(eliminated.get(i) + ", "); else System.out.println(eliminated.get(i) + ")"); } } } } <file_sep>/README.md # diceGame Multiplayer dice game; first to 100 wins! In this simple turn-based multiplayer game, each player takes a turn rolling a pair of dice. After each roll their score is increased by the result (the score of 2 dice added together) and the next player will have their turn. If a player’s roll includes a 2, increase the score by double the roll amount If a player’s roll results in a total of 7, their score is decreased by 7 points Note that scores do not go below 0 If a player rolls a pair of 6s, their score is reset to 0 and the turn-taking order is reversed If the player rolls a pair of 1s, they are eliminated from the game. This will continue until a winner is declared: either someone reaches 100 points or there is only one player left in the game. <file_sep>/DiceGameDriver.java package diceGame; /** * @author <NAME> * Driver for Dice game. */ public class DiceGameDriver { public static void main(String[] args) { Game game = new Game(); Player player1 = new Player("Justin"); Player player2 = new Player("Tiffany"); Player player3 = new Player("Tom"); Player player4 = new Player("Viola"); game.addPlayer(player1); game.addPlayer(player2); game.addPlayer(player3); game.addPlayer(player4); game.startGame(); } }
4c27bf5c957c2fce60689b0a3b8dc84ae85c9d5d
[ "Markdown", "Java" ]
3
Java
jbaraniuk/DiceGame
f7fdb7a3f75fcb1de4fd7b2e3097f19add2b1a7d
68c82e7168f6b6e9cc52341052b002f17b8c04b0
refs/heads/master
<repo_name>eockim/memberinfo-reactive<file_sep>/README.md # memberinfo-reactive ##info spring5 reactive 구성원 정보 제공 api <file_sep>/src/main/java/com/hj/cmi/CmiApplication.java package com.hj.cmi; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j @SpringBootApplication @EnableAsync public class CmiApplication { @Data @RequiredArgsConstructor static class MemberLogin { @NonNull private String radioCheck; @NonNull private String id; @NonNull private String pw; private String result; private String gd_name; private String name; private String post_name; private String type; } @Data @RequiredArgsConstructor static class MemberSearch { @NonNull private String search_keyword; @NonNull private String sch_grade; @NonNull private String sch_YN; @NonNull private String sch_sex; @NonNull private String sch_order; } @Data @AllArgsConstructor static class Member<T> { private T userEmail; private T userBye; private T userId; private T bookLocation; private T postName; private T lastYearUseVoc; private T thisYearUseVoc; private T userU2; private T annualVocation; private T monthlyVacation; private T userName; private T leftVoc; private T gdOrder; private T userGrade; private T userHphone; private T userCphone; } @Data @AllArgsConstructor static class Project{ private String rptFlag; private String pos; private String dept; private String prjPost; private String prjStatus; private String name; private String prjClient; private String prjContent; private String regId; private String prjCode; private String userId; private String fromDt; private String toDt; private String endDt; private String userName; private String prjStatusName; private String color; private String result; private String user_name; private String list; public Project(){} } @Service public static class MyService { // final ObjectMapper mapper = new ObjectMapper(); @Async public CompletableFuture<List<Member<String>>> list(Map<String, Object> req) { Stream<Map<String, Object>> stream = ((List<Map<String, Object>>) req.get("list")) .stream(); List<Member<String>> memberList = stream.map(x -> new Member<String>(x.get("USER_EMAIL")+"", x.get("USER_BYE")+"", x.get("USER_ID")+"", x.get("BOOK_LOCATION")+"", x.get("POST_NAME")+"" , x.get("LAST_YEAR_USE_VOC")+"", x.get("THIS_YEAR_USE_VOC")+"", x.get("USER_U2")+"", x.get("ANNUAL_VACATION")+"" , x.get("MONTHLY_VACATION")+"", x.get("USER_NAME")+"", x.get("LEFT_VOC")+"", x.get("GD_ORDER")+"", x.get("USER_GRADE")+"", x.get("USER_HPHONE")+"", x.get("USER_CPHONE")+"") ).collect(Collectors.toList()); return CompletableFuture.completedFuture(memberList); } @Async public CompletableFuture<List<Project>> listProject(Map<String, Object> req) { Stream<Map<String, Object>> stream = ((List<Map<String, Object>>) req.get("list")).stream(); return CompletableFuture.completedFuture(stream.map(x -> mapper.convertValue(x, Project.class) ).collect(Collectors.toList()) .stream() .sorted((cp1, cp2) -> cp1.getUserName().compareTo(cp2.getUserName())) .collect(Collectors.toList()) ); } @Async public CompletableFuture<Map<String, String>> login(ClientResponse res) { Map<String, String> loginMap = new HashMap<String, String>(); loginMap = res.bodyToMono(Map.class).block(); try { loginMap.put("loginToken", res.cookies().getFirst("loginToken").getValue()); loginMap.put("name", URLEncoder.encode(loginMap.get("name").toString(), "UTF-8")); loginMap.put("type", URLEncoder.encode(loginMap.get("type").toString(), "UTF-8")); loginMap.put("post_name", URLEncoder.encode(loginMap.get("post_name").toString(), "UTF-8")); loginMap.put("gd_name", URLEncoder.encode(loginMap.get("gd_name").toString(), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return CompletableFuture.completedFuture(loginMap); } @Async public CompletableFuture<List<Map<String, String>>> vacationSort(List<Member<String>> res, String sort){ AtomicInteger sortNum = new AtomicInteger(1); Optional.<String>ofNullable(sort) .ifPresent(s -> sortNum.set(s.equals("desc") ? -1 : s.equals("asc") ? 1 : 1 )); return CompletableFuture.completedFuture( res.stream() .sorted((c1, c2) -> Double.compare(Double.parseDouble(c1.getThisYearUseVoc()), Double.parseDouble(c2.getThisYearUseVoc())) * sortNum.intValue()) .map(x -> { Map<String, String> map = new HashMap<String, String>(); map.put("name", x.getUserName()); map.put("userId", x.getUserId()); map.put("thisYearUseVoc", x.getThisYearUseVoc()); map.put("bookLocation", x.getBookLocation()); map.put("postName", x.getPostName()); return map; }) .collect(Collectors.toList())); } } @RestController public static class Controller { WebClient client = WebClient.create(); @Autowired private MyService myService; @GetMapping("/hello") public Publisher<String> hello(String name) { return new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { s.onNext("Hello " + name); s.onComplete(); } @Override public void cancel() { } }); } }; } @GetMapping("/cmi") public Mono<List<Member<String>>> cmi(String rt) { return getMemberMono(Optional.ofNullable(rt).isPresent() ? rt.toUpperCase().equals("Y") ? true : false : false ); } @GetMapping("/cmi/vacation") public Mono<List<Map<String, String>>> vacation(String sort, String rt){ return getMemberMono(Optional.ofNullable(rt).isPresent() ? rt.toUpperCase().equals("Y") ? true : false : false ) .flatMap(res -> Mono.fromCompletionStage(myService.vacationSort(res, sort))); } @GetMapping("/cmi/projects") public Mono<List<Project>> projects(){ Mono<List<Project>> result = getLogin("hj-kim", "1234") .flatMap(body -> client.get() .uri(URI.create("http://gw.dkitec.com:8080/intranet-api/project/list?orderby=1")) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .acceptCharset(Charset.forName("UTF-8")) .cookie("SESSION_USER_ID", body.get("id")) .cookie("SESSION_USER_NAME", body.get("name")) .cookie("SESSION_CHECK_ID", body.get("type")) .cookie("SESSION_POST_NAME", body.get("post_name")) .cookie("SESSION_GD_NAME", body.get("gd_name")) .cookie("loginToken", body.get("loginToken")) .exchange() ) .flatMap(c -> c.bodyToMono(HashMap.class)) .flatMap(c2 -> Mono.fromCompletionStage(myService.listProject(c2))); return result; } private Mono<Map<String, String>> getLogin(String userId, String pass){ return client .post() .uri(URI.create("http://gw.dkitec.com:8080/intranet-api/login")) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .body(BodyInserters.fromObject(new MemberLogin("1", userId, pass))) .exchange() .flatMap(r -> Mono.fromCompletionStage(myService.login(r))); } private Mono<List<Member<String>>> getMemberMono(boolean isRtm) { return getLogin("hj-kim", "1234") .flatMap(body -> client.post() .uri(URI.create("http://gw.dkitec.com:8080/intranet-api/member/list")) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .acceptCharset(Charset.forName("UTF-8")) .cookie("SESSION_USER_ID", body.get("id")) .cookie("SESSION_USER_NAME", body.get("name")) .cookie("SESSION_CHECK_ID", body.get("type")) .cookie("SESSION_POST_NAME", body.get("post_name")) .cookie("SESSION_GD_NAME", body.get("gd_name")) .cookie("loginToken", body.get("loginToken")) .body(BodyInserters.fromObject(new MemberSearch("", "", isRtm ? "Y":"N", "", ""))) .exchange() ) .flatMap(c2 ->c2.bodyToMono(Map.class)) .flatMap(res2 ->Mono.fromCompletionStage(myService.list(res2))); } } public static void main(String[] args) { SpringApplication.run(CmiApplication.class, args); } } <file_sep>/settings.gradle rootProject.name = 'cmi' <file_sep>/src/main/java/com/hj/cmi/react/CmiPublish.java package com.hj.cmi.react; import lombok.extern.slf4j.Slf4j; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j public class CmiPublish { public static void main(String[] args){ Publisher<Integer> pub = iterPub(Stream.iterate(1, x -> x + 1).limit(10).collect(Collectors.toList())); //Publisher<List> mapPub = mapPub(pub, s -> Collections.singletonList(s)); //Publisher<Integer> sumPub = sumPub(pub); Publisher<StringBuilder> reducePub = reducePub(pub, new StringBuilder(), (a, b) -> a.append(b+",") .append("..")); reducePub.subscribe(logSub()); } private static <T, R> Publisher<R> reducePub(Publisher<T> pub, R init, BiFunction<R, T, R> bf) { return new Publisher<R>() { @Override public void subscribe(Subscriber<? super R> sub) { pub.subscribe(new DelegateSub<T, R>(sub){ R result = init; @Override public void onNext(T integer) { result = bf.apply(result, integer); } // // @Override // public void onNext(T integer) { // result = bf.apply(result, integer); // } @Override public void onComplete() { sub.onNext(result); sub.onComplete(); } }); } }; } private static <T> Publisher<T> sumPub(Publisher<T> pub) { return new Publisher<T>() { @Override public void subscribe(Subscriber<? super T> sub) { pub.subscribe(new DelegateSub(sub){ int sum = 0; @Override public void onNext(Object integer) { sub.onNext(integer); } @Override public void onComplete() { sub.onNext(sum); sub.onComplete(); } }); } }; } private static <T, R> Publisher<R> mapPub(Publisher<T> pub, Function<T, R> f) { return new Publisher<R>(){ @Override public void subscribe(Subscriber<? super R> sub) { pub.subscribe(new DelegateSub<T, R>(sub) { @Override public void onNext(T integer) { sub.onNext(f.apply(integer)); } }); } }; } //, private static <T> Subscriber<T> logSub() { return new Subscriber<T>() { @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); log.debug("onSubscribe"); } @Override public void onNext(T integer) { log.debug("onNext : {}", integer); } @Override public void onError(Throwable t) { log.debug("onError : {}", t); } @Override public void onComplete() { log.debug("onComplete"); } }; } private static Publisher<Integer> iterPub(Iterable<Integer> iter) { return new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> sub) { sub.onSubscribe(new Subscription() { @Override public void request(long n) { try{ iter.forEach(s->sub.onNext(s)); sub.onComplete(); }catch(Throwable t){ sub.onError(t); } } @Override public void cancel() { } }); } }; } }
4b4465173d4b494ff633b57febc7891d713bec90
[ "Markdown", "Java", "Gradle" ]
4
Markdown
eockim/memberinfo-reactive
6b049b8375e031aa9487d83e971fe687838c43bb
b227e853c88b898eba674bcf1bdf41a9b4128e33
refs/heads/master
<repo_name>doriclaudino/relatorio-zabbix<file_sep>/tracking.php <?php header('Content-type: text/html; charset=ISO-8859-1'); // Allow access from anywhere. Can be domains or * (any) header('Access-Control-Allow-Origin: *'); // Allow these methods of data retrieval header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these header types header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); include "fhost.php"; $id = $_GET["id"]; if(!is_null($id)){ $queryPrimeiroAcesso = registraPrimeiroAcesso($id); $queryUltimoAcesso = registraUltimoAcesso($id); $queryQtdAcesso = registraQtdAcesso($id); debugl("Primeiro Primeiro Acesso? $queryPrimeiroAcesso"); debugl("Atribuiu Ultimo Acesso? $queryUltimoAcesso"); debugl("Atribuiu QtdAcesso? $queryQtdAcesso"); } function registraPrimeiroAcesso($id){ $query = "UPDATE historico SET data_primeiro_acesso = CURRENT_TIMESTAMP where id = $id and data_primeiro_acesso is null and (data_envio is not null and data_revisao is not null)"; return Update($query); } function registraQtdAcesso($id){ $query = "UPDATE historico SET qtd_acesso = qtd_acesso + 1 where id = $id and (data_envio is not null and data_revisao is not null) "; return Update($query); } function registraUltimoAcesso($id){ $query = "UPDATE historico SET data_ultimo_acesso = CURRENT_TIMESTAMP where id = $id and (data_envio is not null and data_revisao is not null) "; return Update($query); } ?><file_sep>/fheader.php <?php /** * getTrackingHTML * * Insere uma imagem 1px x 1px que quando acessada passa os mesmos parametros para a pagina tracking.php * * @param (type) (id) identificador unico do email. * @param (type) (codhost) identificador do codigo do host. */ function getTrackingHTML($id,$tracking){ if(strcmp($tracking,"true") == 0) return "<img src=\"http://helpdesk.nvl.inf.br/painel/report/tracking.php?id=$id\" alt=\"\" width=\"1\" height=\"1\" border=\"0\" />"; } /** * getSubCategoriaHeaderHTML * * Insere o começo do html e o header principal com o nome do host * * @param (type) (header_string) texto exibido no header principal. */ function getSubCategoriaHeaderHTML($header_string){ $html = ""; $html .= ' <span style="display:none!important;font-size:1px;color:transparent;min-height:0;width:0"></span>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;border-collapse:collapse;width:100%!important;font-family:Helvetica,Arial,sans-serif;margin:0;padding:0" bgcolor="#DFDFDF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td colspan="3">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:5px;font-size:5px;line-height:5px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="table-layout:fixed" border="0" cellpadding="0" cellspacing="0" width="100%" align="center">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td align="center">'; $html .= ' <table id="dori_header_nome_host" style="font-family:Helvetica,Arial,sans-serif;min-width:290px" border="0" cellpadding="0" cellspacing="0" width="900">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td style="font-family:Helvetica,Arial,sans-serif">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#333333" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="100%">'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td valign="middle" align="left">'; $html .= ' <div style="color:#ffffff;font-size:22px;font-weight:lighter;text-align:left">'; $html .= '<center>' . $header_string . '</center>'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; return $html; } /** * getCategoriaHeaderHTML * * Insere o header de categoria com o nome da categoria * * @param (type) (header_string) texto exibido no header de categoria. */ function getCategoriaHeaderHTML($header_string){ $html = ""; $html .= '<body>'; $html .= ' <span style="display:none!important;font-size:1px;color:transparent;min-height:0;width:0"></span>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;border-collapse:collapse;width:100%!important;font-family:Helvetica,Arial,sans-serif;margin:0;padding:0" bgcolor="#DFDFDF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td colspan="3">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:5px;font-size:5px;line-height:5px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="table-layout:fixed" border="0" cellpadding="0" cellspacing="0" width="100%" align="center">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td align="center">'; $html .= ' <table id="dori_header_nome_host" style="font-family:Helvetica,Arial,sans-serif;min-width:290px" border="0" cellpadding="0" cellspacing="0" width="900">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td style="font-family:Helvetica,Arial,sans-serif">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:8px;font-size:8px;line-height:8px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:8px;font-size:8px;line-height:8px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#333333" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="100%">'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td valign="middle" align="left">'; $html .= ' <div style="color:#ffffff;font-size:22px;font-weight:lighter;text-align:left">'; $html .= '<center>' . $header_string . '</center>'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; return $html; } /** * getHeaderHTML * * Insere o header de subcategoria com o nome da subcategoria, logo acima do grafico * * @param (type) (header_string) texto exibido no header de subcategoria. */ function getHeaderHTML($header_string){ $html = ""; $html .= '<html id="html"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8">'; $html .= '</head>'; $html .= '<body>'; $html .= ' <span style="display:none!important;font-size:1px;color:transparent;min-height:0;width:0"></span>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;border-collapse:collapse;width:100%!important;font-family:Helvetica,Arial,sans-serif;margin:0;padding:0" bgcolor="#DFDFDF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td colspan="3">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:5px;font-size:5px;line-height:5px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="table-layout:fixed" border="0" cellpadding="0" cellspacing="0" width="100%" align="center">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td align="center">'; $html .= ' <table id="dori_header_nome_host" style="font-family:Helvetica,Arial,sans-serif;min-width:290px" border="0" cellpadding="0" cellspacing="0" width="900">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td style="font-family:Helvetica,Arial,sans-serif">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:8px;font-size:8px;line-height:8px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#DDDDDD" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td style="min-height:15px;min-width:95px;" valign="middle" align="left"><img class="CToWUd" src="http://helpdesk.nvl.inf.br/painel/report/logomarca/logo_transparent_400x.png" alt="NVL IT LOGO" style="border:none;text-decoration:none;min-height:15px;min-width:95px;"></td>'; $html .= ' <td width="15">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="15">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' '; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; //$html .= ' <td valign="bottom" align="left"><span style="color:#666666;font-size:16px">Relatorios</span></td>'; $html .= ' <td valign="bottom" align="left"></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:8px;font-size:8px;line-height:8px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#333333" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="100%">'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td valign="middle" align="left">'; $html .= ' <div style="color:#ffffff;font-size:22px;font-weight:lighter;text-align:left">'; $html .= '<center>' . $header_string . '</center>'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:14px;font-size:14px;line-height:14px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; return $html; } ?><file_sep>/fbody.php <?php /** * getBodyHTML * * Insere html com a imagem que retorna da API do HighChart, insere tambem quando tiver a quantidade de eventos nas chaves contidas no grafico. * * @param (type) (identificador) identificador da imagem. * @param (type) (string_json) string com os dados para plotar o grafico. * @param (type) (qtd_eventos) quantidade de eventos no ultimo mes para as chaves do grafico. */ function getBodyHTML($identificador,$string_json,$qtd_eventos){ //agora passamos direto a url do servidor atual; $url_encoded = $string_json; /** * URL do webservice do highchart * $url = 'http://export.highcharts.com/?content=options&options=' . $string_json . '&type=image/png&width=800&scale=&constr=Chart'; $url_encoded = 'http://export.highcharts.com/?content=options&options='. utf8_decode(urlencode($string_json)) .'&type=image/png&width=800&scale=&constr=Chart'; **/ $html = ''; $html .= ' <!--CARD-xx-->'; $html .= ' <table id="dori_card_com_grafico" class="card" style="font-family:Helvetica,Arial,sans-serif;width:900px;table-layout:fixed;text-align:left;background:#ffffff;border:1px solid #ffffff;border-bottom:2px solid #bcbcbc;border-left:1px solid #cecece;border-right:1px solid #cecece" border="0" cellpadding="0" cellspacing="0" width="900">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;font-size:12px;line-height:15px;word-wrap:break-word" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:20px;font-size:20px;line-height:20px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' '; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td style="font-size:18px;line-height:22px">'; $html .= ' <div class="container_imagem" style="vertical-align:middle; text-align:center">'; $html .= ' <img id="grafico_png_'.$identificador.'" src="' . $url_encoded . '"></img>'; $html .= ' </div>'; $html .= ' '; $html .= ' </td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' '; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; /*** ** Trata se houve algum evento no periodo, imprime uma imagem com o nome do analista e um comentario simples com a quantidade de eventos no periodo ***/ if($qtd_eventos>0){ $msg_padrao_evento = "1 evento"; if($qtd_eventos>1) $msg_padrao_evento = $qtd_eventos ." eventos"; $html .= ' <!-- dori nessa linha contem a imagem do analista e o comentario do grafico -->'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;background:#eeeeee" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:5px;font-size:5px;line-height:5px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td width="30"><a href="" style="text-decoration:none" target="_blank"><img class="CToWUd" src="https://media.licdn.com/mpr/mpr/shrink_100_100/AAEAAQAAAAAAAAKLAAAAJGJiNDU2NmNlLWMxNTYtNDhjNy05NDBhLWFmZDE2ZDM5NDEzYg.jpg" alt="Dori" style="border:none;outline:none;text-decoration:none;display:block" height="30" width="30"></a></td>'; $html .= ' <td width="9">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="9">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;font-size:11px" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td><a href="" style="color:#333333;text-decoration:none;font-size:11px" target="_blank">Dori</a></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:3px;font-size:3px;line-height:3px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td class="comentario" style="text-decoration:none;font-size:13px;color:#333333">Identificamos ' . $msg_padrao_evento . ' no monitoramento, favor abrir um chamado.</td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td style="border-bottom:2px solid #fff">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:5px;font-size:5px;line-height:5px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td><a href="" style="color:#2d8cd7;text-decoration:none;font-size:0;max-height:0;min-height:0" target="_blank"><span>Adicionar comentário </span><img class="CToWUd" src="https://ci6.googleusercontent.com/proxy/HCUMHnecoxt3Zo71p9peVaGBl8qNKK5_pReAVHn6DSxmdh0bI2JqByMGXf5cK0OSAXwmLQNGU9LCFqZ4P0fRDL2lcA7VHtSl3bWG-lOBSByCKKl2NasgWCn8Yw=s0-d-e1-ft#https://static.licdn.com/scds/common/u/img/email/arrow_right_blue.png" style="border:none;outline:none;text-decoration:none;max-height:0;min-height:0;font-size:0" alt="" height="8" width="4"></a></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; } $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:30px;font-size:30px;line-height:30px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' <td width="20">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="20">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; /** ** Cria um espacamento entre os "cards" **/ $html .= ' <!--ESPACAMENTO-xx-->'; $html .= ' <table id="espacamento_entre_card" style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td height="10">'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:0px;font-size:0px;line-height:0px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; return $html; } ?><file_sep>/sendMailLote.php <?php ini_set( 'display_errors', true ); error_reporting( E_ALL ); include "fhost.php"; require("PHPMailer/class.phpmailer.php"); // path to the PHPMailer class $configMail = parse_ini_file('email.ini'); $mail = new PHPMailer(); $mail->IsSMTP(); $mail->IsHTML($configMail['ishtml']); $mail->Mailer = $configMail['mailer']; $mail->CharSet = $configMail['charset']; $mail->Host = $configMail['host']; $mail->Port = $configMail['port']; $mail->SMTPAuth = $configMail['smtpauth']; $mail->Username = $configMail['username']; $mail->Password = $configMail['<PASSWORD>']; $mail->FromName = $configMail['fromname']; $mail->From = $configMail['from']; $host = new stdClass; $ArrayObjetos64 = getObjectsToSend(); debugl("Emails pendentes: " . count($ArrayObjetos64)); foreach ($ArrayObjetos64 as $Obj64){ debugl(""); $base64string = $Obj64["phpbase64"]; $mailid = $Obj64["id"]; debugl("Mailid : $mailid"); debugl("base64string : $base64string"); $host = unserialize(base64_decode($base64string)); if(is_null($host->emailResponsavel)){ echo ("<h1>Não encontramos o registro do e-mail do responsável! mailid=$mailid :("); exit(); }else{ $mail->Subject = "Subject Empresa($host->nomeEmpresa) host($host->nome) mail($mailid)"; $mail->AddAddress($host->emailResponsavel); $ArrayCopiasControladas = $host->CopiasControladas; if(!is_null($ArrayCopiasControladas)){ foreach ($ArrayCopiasControladas as $Copia){ $mail->AddCC($Copia["email"], $Copia["nome"]); debugl("Cc nome:" . $Copia["nome"] . " e-mail:" . $Copia["email"]); } } $mail->Body = processaRelatorioHost($mailid,$host); if(!$mail->Send()) { echo "Message was not sent"; echo "Mailer error: " . $mail->ErrorInfo; } else { echo "Message has been sent (mailid=$mailid)<br>"; if(setDataEnvio($mailid)) echo "Marcado como enviado(mailid=$mailid)<br>"; else echo "Não Marcado como enviado(mailid=$mailid) #erro"; } } } ?><file_sep>/createImageFromUrl.php <?php $nome_fonte = $argv[0]; $url = $argv[1]; $unique = $argv[2]; createLocalImage($url,$unique); function createLocalImage($url,$unique){ $extension = ".png"; $filename = $unique . $extension; $path = "images/"; $img = @imagecreatefrompng($url); imagepng($img, $path . $filename); chown($path . $filename ,"apache"); } ?><file_sep>/index.php <?php header('Content-type: text/html; charset=ISO-8859-1'); // Allow access from anywhere. Can be domains or * (any) header('Access-Control-Allow-Origin: *'); // Allow these methods of data retrieval header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these header types header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); include "fhost.php"; $codhost = $_GET["codhost"]; $tracking = $_GET["tracking"]; $preview = $_GET["preview"]; if(is_null($codhost)){ debugl("<h1>Informe um codigo de hostname</h1>"); exit(); } else{ /** * Cria o objeto de host com todos os valores possiveis. **/ $identificador = generateID(); $host = createHost($codhost); debugl("Grafico ID -> $identificador"); debugl("Inseridos -> " . registraGeracaoHTML($identificador,$host)); if(strcmp($preview,"true") == 0){ echo processaRelatorioHost($identificador,$host); } echo "<h2>Id Gerado: $identificador<h2>"; } ?> <file_sep>/ffooter.php <?php /** * getFooterHTML * * Insere o rodape da pagina com o nome da empresa e o nome do responsavel. * * @param (type) (empresa_nome) nome da empresa. * @param (type) (responsavel_nome) nome do responsavel principal na empresa. */ function getFooterHTML($empresa_nome,$responsavel_nome){ $html = ''; $html .= ' <!--CARD-final-->'; $html .= ' <table id="card_final" style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="900">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td align="left">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td align="left">'; $html .= ' <table style="font-family:Helvetica,Arial,sans-serif;font-size:11px;font-family:Helvetica,Arial,sans-serif;color:#999999" border="0" cellpadding="0" cellspacing="0" width="100%">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="0" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td align="center">Você está recebendo e-mails resumindo as atividades monitoradas pelo ZABBIX. <a style="text-decoration:none;color:#0077b5" href="link_cancelar" target="_blank">Cancelar inscrição</a></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td align="center">Este e-mail foi enviado para ' . $responsavel_nome . ' (' . $empresa_nome . '). <a style="text-decoration:none;color:#0077b5" href="link_saiba_pq" target="_blank">Saiba por que incluí­mos isto.</a></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:10px;font-size:10px;line-height:10px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td dir="ltr" align="center">© 2015 NVL IT é um nome comercial registrado da <NAME> ME.</td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td dir="ltr" align="center">Registrada no Brasil como uma empresa Privada e Ltda. Registro número 13.317.092/0001-80.</td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td dir="ltr" align="center">Estamos na Frei Estanislau Schaette, 1326, Sala 02, Agua Verde, Blumenau, SC, CEP 89037-002</td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <table border="0" cellpadding="1" cellspacing="0" width="1">'; $html .= ' <tbody>'; $html .= ' <tr>'; $html .= ' <td>'; $html .= ' <div style="min-height:20px;font-size:20px;line-height:20px">'; $html .= ' &nbsp;'; $html .= ' </div></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <!--começa o fim do html-->'; $html .= ' </td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table></td>'; $html .= ' </tr>'; $html .= ' </tbody>'; $html .= ' </table>'; $html .= ' <img class="CToWUd" src="" style="width:1px;min-height:1px"><div class="yj6qo"></div><div class="adL">'; $html .= ' </div>'; $html .= '</body></html>'; return $html; } ?><file_sep>/fhost.php <?php header('Content-type: text/html; charset=ISO-8859-1'); // Allow access from anywhere. Can be domains or * (any) header('Access-Control-Allow-Origin: *'); // Allow these methods of data retrieval header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these header types header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); //configuracoes do banco de dados //include "database_config.php"; include "fheader.php"; include "fbody.php"; include "ffooter.php"; function processaRelatorioHost($id,$host){ $html = ""; $html .= getHeaderHTML($host->headerPrincipal); $codhost = $host->codhost; $tracking = isTracking(); $total_categorias = count($host->categoria); $total_subcategoria = count($host->subcategoria); $total_json = count($host->ArrayJson); $total_eventos = count($host->ArrayEventos); debugl("total_categorias-> $total_categorias"); debugl("total_subcategoria -> $total_subcategoria"); debugl("total_json -> $total_json"); debugl("total_eventos -> $total_eventos"); //simula 2 instancias //$host->subcategoria[2] = 'produtttt'; $cria_header_categoria = false; $old_categoria = null; $cria_header_subcategoria = false; $old_subcategoria = null; for ($x = 0; $x < $total_categorias; $x++) { if(strcmp ( $old_categoria, $host->categoria[$x]) == 0) $cria_header_categoria = false; else $cria_header_categoria = true; if($cria_header_categoria){ debugl("[CRIAR HEADER]". $host->categoria[$x]); $host->categoria[$x] = $host->categoria[$x]; $html .= getCategoriaHeaderHTML($host->categoria[$x]); //echo "[CRIAR HEADER]". $host->categoria[$x] . "</br>"; $old_categoria = $host->categoria[$x]; $cria_header_categoria = false; } if(is_null($host->subcategoria[$x])) $cria_header_subcategoria = false; if(strcmp ( $old_subcategoria, $host->subcategoria[$x]) == 0) $cria_header_subcategoria = false; else $cria_header_subcategoria = true; if($cria_header_subcategoria){ debugl("[CRIAR SUBHEADER]". $host->subcategoria[$x]); //echo "[CRIAR SUBHEADER]". $host->subcategoria[$x]; $host->subcategoria[$x] = $host->subcategoria[$x]; $html .= getSubCategoriaHeaderHTML($host->subcategoria[$x]); $old_subcategoria = $host->subcategoria[$x]; $cria_header_subcategoria = false; } //$html .= getBodyHTML($x,$host->ArrayJson[$x],$host->ArrayEventos[$x]); $html .= getBodyHTML($x,$host->images[$x],$host->ArrayEventos[$x]); } $html .= getFooterHTML($host->nomeEmpresa,$host->responsavel); //adiciona uma imagem com id $html .= getTrackingHTML($id,$tracking); return $html; } /** * inicio * * Processa toda a logica e loops em cima das categorias, subcagegorias (quando tiver), graficos, chaves, chaves dinamicas (quando tive) * analisa se o grafico plotara apenas uma chave e 3 medias ou varias chaves e apenas suas medias. * * @param (type) (id) identificador do e-mail. */ function createHost($codhost){ $host = new stdClass; $dadosEmpresa = buscaEmpresa($codhost); $host->codhost = $codhost; $host->nomeEmpresa = $dadosEmpresa["empresa_nome"]; $host->nome = $dadosEmpresa["host_nome"]; $host->headerPrincipal = 'RESUMO DE PERFORMANCE DO SERVIDOR - ' . $dadosEmpresa["host_nome"]; $host->responsavel = $dadosEmpresa["responsavel_nome"]; $host->emailResponsavel = $dadosEmpresa["responsavel_email"]; $host->CopiasControladas = getCopiasControladas($codhost); $host->ArrayJson = []; $host->ArrayEventos = []; $host->categoria = []; $host->subcategoria = []; $host->images = []; $host->numMaxPeriodAnalise = getMaxPeriodAnalise(); $host->numMaxObjetosGrafico = getMaxObjetosGrafico(); $host->numeroMesesEventos = numMaxPeriodoEvento(); /** * Categorias * * Processa pelas categorias, cada categoria tem uma ordem de execucao */ $ArrayCategorias = buscaCategorias($codhost); foreach ($ArrayCategorias as $categoria){ debug("<hr>"); debugl("[Categoria]" . $categoria["nome"]); /** * SubCategoria/Instancia * * Verifica quais chaves possuem dois espacos em branco ou o caracter de percentual (%), * Caso retorne alguma chave o objeto pode ter uma subcagegoria/instancia. */ $ArrayPossiveisInstancias = buscaPossiveisInstancias($codhost,$categoria["categoria_id"],$host->numMaxPeriodAnalise); if(is_null($ArrayPossiveisInstancias)) $ArrayPossiveisInstancias[]["subcategoria"] = null; /** * SubCategorias/Instancias * * Processa cada subcategoria/instancia */ debugl("Instancias: " .count($ArrayPossiveisInstancias)); foreach($ArrayPossiveisInstancias as $instancia){ $nome_instancia = $instancia["subcategoria"]; debugl("[SubCategoria]".$instancia["subcategoria"]); /** * Graficos da Categoria/subcategoria * * Busca os graficos */ $ArrayGraficos = buscaGraficos($codhost,$categoria["categoria_id"]); /** * Graficos da Categoria/subcategoria * * Processa cada grafico */ foreach ($ArrayGraficos as $grafico){ debug("<hr>"); /** * Altera o json com o nome do titulo e subtitulo do grafico */ $json = $grafico["json"]; /** * Busca as chaves cadastradas neste grafico */ $ArrayChavesCadastradas = buscaChavesCadastradas($codhost,$grafico["grafico_id"]); foreach ($ArrayChavesCadastradas as $chave){ debugl("[ChaveBusca]" . $chave["valor"]); } /** * Busca apenas as maiores chaves nao apenas 5, dependendo do parametro. * Nome da instancia pra filtrar apenas as chaves que possuem o nome da instancia tambem (se existir instancia) */ $ArrayCincoMaioresChaves = buscaCincoMaioresChaves($codhost,$nome_instancia,$ArrayChavesCadastradas,$host->numMaxObjetosGrafico,$host->numMaxPeriodAnalise); $QtdEventos = buscaQtdEventos($codhost,$ArrayChavesCadastradas,$host->numMaxPeriodAnalise); /** * Dependendo do total de chaves retornadas, o grafico tera varias chaves ou apenas uma que entao mostrara min,med,max */ $total = count($ArrayCincoMaioresChaves); $series = Array(); $categories = Array(); /** * Processa cada chave encontrada */ $alterou_titulo = false; foreach ($ArrayCincoMaioresChaves as $chaveMaior){ debugl("[ChaveRetorno]" . $chaveMaior["Chave"]); //retorna a legenda da primeira chave que encontrar baseada em uma das chaves com maior valor //echo "Teste de legenda...para " . $chaveMaior["Chave"]; $legenda = null; $legendaChave = null; $legenda = buscaLegendaChaveCadastrada($ArrayChavesCadastradas,$chaveMaior["Chave"]); $legendaChave = buscaRegexObjetoNovoRegex2($chaveMaior["Chave"],$legenda); if(is_null($legendaChave)) $legendaChave = $chaveMaior["Chave"]; if($alterou_titulo === false){ $titulo_grafico = $grafico["titulo"]; $subtitulo_grafico = $grafico["subtitulo"]; $titulo_grafico = buscaRegexObjetoNovoRegex2($chaveMaior["Chave"],$grafico["titulo"]); $subtitulo_grafico = buscaRegexObjetoNovoRegex2($chaveMaior["Chave"],$grafico["subtitulo"]); $json = str_replace('$titulo_grafico',$titulo_grafico,$json); $json = str_replace('$subtitulo_grafico',$subtitulo_grafico,$json); $alterou_titulo = true; } /** * Para cada chave busca seus valores, medias e datas por mes. */ $ArrayValoresChave = buscaValoresPorChave($codhost,$chaveMaior["Chave"],$host->numMaxPeriodAnalise); /** * Ponto onde decide se a legenda sera min,med,max ou o nome de cada legendaChave plotado */ if($total>1){ debugl("[TipoPlotagem]"."print apenas as medias"); array_push($series,processaValoresMultiplos($legendaChave,$ArrayValoresChave)); /** * apresentar novo nome para o objeto **/ //debugl(json_encode($series, JSON_NUMERIC_CHECK)); }else{ debugl("[TipoPlotagem]"."print min/med/max"); $series = processaMedias($ArrayValoresChave); //debugl(json_encode($series, JSON_NUMERIC_CHECK)); } /** * Abrevia o array de datas de 01 para Jan por exemplo */ $categories = processaDatas($ArrayValoresChave,$host->numMaxPeriodAnalise); } /** * Faz um replace em $categorias colocando as data abreviadas no json */ debugl("Json limpo: ".$json); $json = str_replace('"$categorias"',json_encode($categories, JSON_NUMERIC_CHECK),$json); debugl("Json \$categorias: ".$json); /** * Faz um replace em $series colocando os nomes e valores de cada serie a ser plotada */ $json = str_replace('"$series"',json_encode($series, JSON_NUMERIC_CHECK),$json); debugl("Json \$series: ".$json); //debugl("? eventos ? ".$QtdEventos); //criando imagens locais (bug gmail) $url_encoded = createWebServiceURL($json); debugl("\$url_encoded: $url_encoded"); $imagem = createLocalImage($url_encoded); /* imagem em base64 * $imagem = createBase64Image($url_encoded); * */ /** * Armazena tudo em um unico objeto */ array_push($host->categoria,$categoria["nome"]); array_push($host->subcategoria,$instancia["subcategoria"]); array_push($host->ArrayJson,$json); array_push($host->images,$imagem); array_push($host->ArrayEventos,$QtdEventos); } } } return $host; } function getCopiasControladas($codhost){ $query = "select d.nome,d.email from empresa_destinatario ed inner join empresa e on (e.id = ed.empresa_id) inner join destinatario d on (ed.destinatario_id = d.id) inner join empresa_host eh on (eh.empresa_id = e.id) where e.responsavel <> d.id and eh.host_id = $codhost"; $rows = Select($query); return $rows; } function getNomeLegenda($string){ $queryLegenda = "select nome_legenda from chave where valor = \"$string\""; $rows = Select($queryLegenda); return $rows[0]["nome_legenda"]; } /** * createWebServiceURL * * Recebe um json contendo as opcoes do grafico, datasource, etc. * * @param (type) (url) url contendo imagem. * @return (type) (urlWebservice) url do webservice. */ function createWebServiceURL($json){ $urlWebservice = 'http://export.highcharts.com/?content=options&options='. utf8_decode(urlencode($json)) .'&type=image/png&width=800&scale=&constr=Chart'; return $urlWebservice; } /** * createLocalImage * * Recebe uma url contendo uma imagem cria a imagem no disco e retorna o caminho/url. * * @param (type) (url) url contendo imagem. * @return (type) retorna url com endereço da imagem. */ function createLocalImage($url){ $extension = ".png"; $unique = uniqid(rand(), true); $filename = $unique . $extension; $path = "images/"; $url_path = "http://helpdesk.nvl.inf.br/painel/report/" . $path; exec("php createImageFromUrl.php \"$url\" $unique > /dev/null 2>/dev/null &"); /* $img = @imagecreatefrompng($url); imagepng($img, $path . $filename); */ return $url_path . $filename; } /** * createBase64Image * * Recebe uma url contendo uma imagem e retorna a imagem na base64. * * @param (type) (url) url contendo imagem. * @return (type) retorna imagem na base64. */ function createBase64Image($url){ $img = file_get_contents($url); $type = "png"; $imgbase64 = base64_encode($img); return "data:image/" . $type . ";base64," . $imgbase64; } /** * registraGeracaoHTML * * Insere no banco que o email foi enviado. * * @param (type) (id) identificador do e-mail. */ function registraGeracaoHTML($id,$host){ $codhost = $host->codhost; $safe_string_host = base64_encode(serialize($host)); $query = "INSERT INTO historico (id, host_id, phpbase64) values ($id, $codhost, '".$safe_string_host."')"; return Update($query); } /** * generateID * * Faz um fake-insert incrementando a sequence no banco e logo em seguida recuperando a mesma. * * @return (type) (id) identificador do e-mail. */ //retorna nova sequence no mysql function generateID(){ $config = parse_ini_file('database.ini'); $conexao = mysqli_connect($config['ip'],$config['username'],$config['password'],$config['dbname']); $query = "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = " . " \"" . $config['dbname'] . "\" AND TABLE_NAME = 'historico' "; $result = Select($query); return $result[0]["AUTO_INCREMENT"]; } function getMaxPeriodAnalise(){ return isset($_GET["maxperiodanalise"]) ? $_GET["maxperiodanalise"] : 3; } function getMaxObjetosGrafico(){ return isset($_GET["maxobj"]) ? $_GET["maxobj"] : 5; } function numMaxPeriodoEvento(){ return isset($_GET["maxobj"]) ? $_GET["maxobj"] : 1; } function isTracking(){ return isset($_GET["tracking"]) ? $_GET["tracking"] : null; } /** * buscaPossiveisInstancias * * Busca todas as chaves que tenham percentual (%) e busca na base do Zabbix um padrao de nomes para instancias/subcategorias. * * @param (type) (categoria_id) filtro para buscar apenas chaves da categoria. * @return (type) (rows) array com nomes de possiveis instancias. */ function buscaPossiveisInstancias($codhost,$categoria_id,$mesesAnalisados){ /** * Verifica quais chaves possuem dois espacos em branco ou o caracter de percentual (%), * Caso retorne alguma chave o objeto pode ter uma subcagegoria/instancia. */ $query_otimizadora = "select distinct valor from view_grafico_host where host_id = $codhost and categoria_id = $categoria_id and (valor like '%\%%' or valor like '% % %')"; $string_auxiliar = montaQueryAuxiliar(Select($query_otimizadora)); if(is_null($string_auxiliar)) return null; $query_possiveis_instancias = "SELECT DISTINCT SUBSTRING(key_, LOCATE(' ', key_), LOCATE(' ', key_, (LOCATE(' ', key_) + 1)) - LOCATE(' ', key_)) AS subcategoria FROM (SELECT b.key_ FROM zabbix.trends a, zabbix.items b, zabbix.hosts c WHERE a.itemid = b.itemid AND b.hostid = c.hostid and b.key_ like '% % %' and b.hostid = $codhost " . $string_auxiliar . " AND clock >= UNIX_TIMESTAMP(DATE_FORMAT(DATE_ADD(DATE_ADD(CURRENT_DATE, INTERVAL - DAY(CURRENT_DATE) + 1 DAY), INTERVAL - $mesesAnalisados MONTH), '%Y%m%d%H%i%s')) AND clock <= UNIX_TIMESTAMP(DATE_FORMAT(DATE_ADD(DATE_ADD(CURRENT_DATE, INTERVAL - DAY(CURRENT_DATE) + 1 DAY), INTERVAL - 1 SECOND), '%Y%m%d%H%i%s')) UNION SELECT b.key_ FROM zabbix.trends_uint a, zabbix.items b, zabbix.hosts c WHERE a.itemid = b.itemid AND b.hostid = c.hostid and b.key_ like '% % %' and b.hostid = $codhost" . $string_auxiliar . " AND clock >= UNIX_TIMESTAMP(DATE_FORMAT(DATE_ADD(DATE_ADD(CURRENT_DATE, INTERVAL - DAY(CURRENT_DATE) + 1 DAY), INTERVAL - $mesesAnalisados MONTH), '%Y%m%d%H%i%s')) AND clock <= UNIX_TIMESTAMP(DATE_FORMAT(DATE_ADD(DATE_ADD(CURRENT_DATE, INTERVAL - DAY(CURRENT_DATE) + 1 DAY), INTERVAL - 1 SECOND), '%Y%m%d%H%i%s'))) x where length(SUBSTRING(key_, LOCATE(' ', key_), LOCATE(' ', key_, (LOCATE(' ', key_) + 1)) - LOCATE(' ', key_)))>1 order by subcategoria"; debugl("\$query_possiveis_instancias: $query_possiveis_instancias"); $rows = Select($query_possiveis_instancias); //gambiarra para atender nova solicitacao do gomes if(count($rows)<1) return null; return $rows; } /** * buscaChavesZabbix * * Recebe um array com todas as chaves cadastradas e compara quais existem na base do zabbix, retornando apenas as chaves em ambas as bases. * * @param (type) (ArrayChavesCadastradas) array com todas as chaves cadastradas. * @return (type) (rows) array com chaves unicas cadastradas em ambas as bases. */ function buscaChavesZabbix($codhost, $ArrayChavesCadastradas,$mesesAnalisados){ $string_auxiliar = montaQueryAuxiliar($ArrayChavesCadastradas); $query_chave_zabbix = "select distinct substring(b.key_, LOCATE(' ', b.key_), LOCATE(' ', b.key_, (LOCATE(' ', b.key_) + 1)) - LOCATE(' ', b.key_)) as subcategoria from zabbix.trends a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost . $string_auxiliar . "and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) union select distinct substring(b.key_, LOCATE(' ', b.key_), LOCATE(' ', b.key_, (LOCATE(' ', b.key_) + 1)) - LOCATE(' ', b.key_)) as subcategoria from zabbix.trends_uint a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost . $string_auxiliar . "and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) "; $rows = Select($query_chave_zabbix); return $rows; } /** * buscaQtdEventos * * Conta todos os eventos disparados pelas chaves do grafico no periodo informado. * * @param (type) (rows) array de chaves. * @return (type) ($evento["quantidade"]) quantidade de eventos disparados pelas chaves no periodo. */ function buscaQtdEventos($codhost,$rows,$mesesAnalisadosEventos){ $string_auxiliar = montaQueryAuxiliar($rows); $query_eventos = "select count(*) quantidade from zabbix.items b left join zabbix.hosts h on b.hostid = h.hostid left join zabbix.functions f on b.itemid = f.itemid left join zabbix.triggers t on f.triggerid = t.triggerid left join zabbix.events e on f.triggerid = e.objectid where h.hostid = $codhost" . $string_auxiliar . "and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisadosEventos MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) and t.status = 0 and b.status = 0"; $rows = Select($query_eventos); foreach ($rows as $evento){ return $evento["quantidade"]; } } /** * processaDatas * * Retorna em formado abreviado os meses processados no grafico. * * @param (type) (ArrayValoresChave) array com meses em valores decimais. * @param (type) (categories) array com meses em valores abreviados. */ function processaDatas($ArrayValoresChave,$mesesAnalisados){ $categories = Array(); $meses_ano = array('', 'Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'); foreach($ArrayValoresChave as $item){ if(count($categories) < $mesesAnalisados){ $ano = substr($item['data'],0,4); $mes = $meses_ano[(int)substr($item['data'],5,2)]; $data_ajustada = $mes . '/' . $ano; array_push($categories, $data_ajustada); } } return $categories; } /** * processaMedias * * Recebe um array com valores de medias, cria um array externo e coloca os valores em sequencia, separando media, maxima, minima. * Usado quando o grafico possui apenas uma chave em ambas as bases. * * @param (type) (ArrayValoresChave) array com tres medias por indice ou por mes. * @return (type) (series) array multidimensional onde o nome de cada array sera a legenda do grafico, neste caso o tipo de media. */ function processaMedias($ArrayValoresChave){ $series = Array(); $array_maxima['name'] = 'Maxima'; $array_media['name'] = 'Media'; $array_minima['name'] = 'Minima'; foreach($ArrayValoresChave as $item){ $array_maxima['data'][] = $item['maxima']; $array_media['data'][] = $item['media']; $array_minima['data'][] = $item['minima']; } array_push($series,$array_maxima); array_push($series,$array_media); array_push($series,$array_minima); return $series; } /** * processaValoresMultiplos * * * * @param (type) (Objeto) nome do objeto, sera uma da(s) legenda(s). * @param (type) (ArrayValoresChave) array com os valores medianos de cada mes. * @param (type) (array_object) array multidimensional onde o nome de cada array sera a legenda do grafico, neste caso o nome do objeto. */ function processaValoresMultiplos($Objeto,$ArrayValoresChave){ $array_object['name'] = $Objeto; foreach($ArrayValoresChave as $item){ $array_object['data'][] = $item['media']; } return $array_object; } function buscaLegendaChaveCadastrada($arrayCadastrada,$chaveZabbix){ foreach($arrayCadastrada as $chaveCadastrada){ $tmppattern = ''; //altera os caracteres especiais para . (ponto) $tmppattern = preg_replace("/([\.\[\]])/i", ".", $chaveCadastrada["valor"]); //altera o caractere % para .* (qualquer string e inumeras vezes) $tmppattern = preg_replace("/(\%)/i", ".*", $tmppattern); $tmppattern = "/" . $tmppattern . "/i"; //se a string contem o regex montado entao retorna a legenda if(preg_match($tmppattern,$chaveZabbix, $matches_out)){ return $chaveCadastrada["legenda_chave"]; } } return null; } function buscaRegexObjetoNovoRegex2($input_str,$string_replace){ if(is_null($string_replace)) return $input_str; $pattern = '/([^\w\/]+)/i'; preg_match_all($pattern, $input_str, $matches_out); $pattern = '/'; for($i=0; $i<count($matches_out[0]); $i++){ $pattern .= '([\w\/]+)[^\w\/]+'; } $pattern .= '/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); return $string_replace; } /** * $string_default = system.cpu.load[all,avg5] * $string_replace = Objeto - $3 * $regex_pattern = /(.*)(\,)(.*)(\])/i * $resultado = Objeto - avg5 **/ function buscaRegexObjetoNovoRegex($input_str,$string_replace){ if(is_null($string_replace)) return $input_str; $pattern = '/.*\[(\w*)[ ,](\w*)[ ,](\w*)[ ,](\w*)[ ,](\w*)\]/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); $pattern = '/.*\[(\w*)[ ,](\w*)[ ,](\w*)[ ,](\w*)\]/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); $pattern = '/.*\[(\w*)[ ,](\w*)[ ,](\w*)\]/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); $pattern = '/.*\[(\w*)[ ,](\w*)\]/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); $pattern = '/.*\[(\w*)\]/i'; if (preg_match($pattern, $input_str, $matches_out)) return preg_replace($pattern, $string_replace, $input_str); return $string_replace; } /** * buscaRegexObjetoGOMES * * Busca string conforme pattern. * [string string objeto] * * @param (type) (input_str) string a ser analisada. * @return (type) ($matches_out[1]) string encontrada. */ function buscaRegexObjetoGOMES($input_str){ //padrao banco de dados [string string nome] $pattern = "/\[\S+\s+\S+\s+(\S+)+\]/"; if (preg_match($pattern, $input_str, $matches_out)) return $matches_out[1]; else return null; } /** * buscaRegexObjetoZabbix * * Busca string conforme pattern. * [string string objeto] * * @param (type) (input_str) string a ser analisada. * @return (type) ($matches_out[1]) string encontrada. */ function buscaRegexObjetoZabbix($input_str){ //padrao banco de dados [string string nome] $pattern = "/\[(\S+)+,/"; if (preg_match($pattern, $input_str, $matches_out)) return $matches_out[1]; else return null; } /** * buscaRegexInicioChave * * Busca o inicio da chave, antecedendo do caracter "[" e seguido de espaco em branco ate o final com "]". * [objeto string string] * * @param (type) (input_str) string a ser analisada. * @return (type) ($matches_out[1]) string encontrada. */ function buscaRegexInicioChave($input_str){ $pattern = "/\[\S+\s+\S+\s+(\S+)+\]/"; if (preg_match($pattern, $input_str, $matches_out)) return $matches_out[1]; else return null; } /** * buscaRegexSubCategoria * * Insere no banco que o email foi enviado. * [string objeto string] * * @param (type) (input_str) string a ser analisada. * @return (type) ($matches_out[1]) string encontrada. */ function buscaRegexSubCategoria($input_str){ $pattern = "/\[\S+\s+(\S+)+\s+\S+\]/"; if (preg_match($pattern, $input_str, $matches_out)) return $matches_out[1]; else return null; } /** * buscaValoresPorChave * * Busca na base do Zabbix os valores para a chave informada no periodo de meses a analisar para tras. * * @param (type) (oneOfTop5keys) chave para consulta de valores. * @return (type) (rows) array com minima, media, maxima, data. */ function buscaValoresPorChave($codhost,$oneOfTop5keys,$mesesAnalisados){ $query_valores_por_chave = "select round(min(value_min),2) as minima, round(max(value_max),2) as maxima, round(sum(value_max)/count(*),2) as media, date_format(FROM_UNIXTIME(clock),'%Y-%m') as data, b.key_ as key_ from zabbix.trends a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost ." and b.key_ = '" . $oneOfTop5keys . "' and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) group by b.key_,date_format(FROM_UNIXTIME(clock),'%Y-%m') union select round(min(value_min),2) as minima, round(max(value_max),2) as maxima, round(sum(value_max)/count(*),2) as media, date_format(FROM_UNIXTIME(clock),'%Y-%m') as data, b.key_ as key_ from zabbix.trends_uint a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost ." and b.key_ = '" . $oneOfTop5keys . "' and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) group by b.key_,date_format(FROM_UNIXTIME(clock),'%Y-%m') order by key_,data"; $rows = Select($query_valores_por_chave); return $rows; } /** * buscaCincoMaioresChaves * * Busca as chaves com maiores valores, levando em consideracao parametros de meses e quantidade de chaves para retorno. * * @param (type) (nome_instancia) nome da instancia para filtrar a query e chave. * @param (type) (rows) array com todas as chaves. * @return (type) (rows) array com as 5 chaves que possuem o maior valor no periodo analisado. */ function buscaCincoMaioresChaves($codhost, $nome_instancia, $rows,$seriesAnalisadas,$mesesAnalisados){ $string_auxiliar = montaQueryAuxiliar($rows); if(!is_null($nome_instancia)) $string_auxiliar .= " and b.key_ like '%". $nome_instancia ."%' "; $query_top5_keys = "select distinct x.key_ as Chave, object_dinamico from (select round(sum(value_max)/count(*),2) as media,b.key_, SUBSTRING(SUBSTRING_INDEX(b.key_,' ',-1), 1, CHAR_LENGTH(SUBSTRING_INDEX(b.key_,' ',-1)) - 1) as object_dinamico from zabbix.trends a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost . $string_auxiliar . "and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) group by b.key_ union select round(sum(value_max)/count(*),2) as media,b.key_, SUBSTRING(SUBSTRING_INDEX(b.key_,' ',-1), 1, CHAR_LENGTH(SUBSTRING_INDEX(b.key_,' ',-1)) - 1) as object_dinamico from zabbix.trends_uint a,zabbix.items b, zabbix.hosts c where a.itemid = b.itemid and b.hostid = c.hostid and b.hostid = ". $codhost . $string_auxiliar . "and clock >= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY),interval -$mesesAnalisados MONTH), '%Y%m%d%H%i%s')) and clock <= UNIX_TIMESTAMP(DATE_FORMAT(date_add(date_add(CURRENT_DATE,interval -DAY(CURRENT_DATE)+1 DAY), interval -1 second), '%Y%m%d%H%i%s')) group by b.key_) x order by media desc,object_dinamico limit $seriesAnalisadas"; $rows = Select($query_top5_keys); return $rows; } /** * montaQueryAuxiliar * * Recebe varias chaves e coloca cada uma dentro de varias clausulas or.. or.. or.. * * @param (type) (rows) array de chaves. * @return (type) (string_auxiliar) string para concatenar na query e filtrar as chaves. */ function montaQueryAuxiliar($rows){ $string_auxiliar = null; foreach ($rows as $chave){ //Se essa chave possui objeto dinamico if(strpos($chave["valor"], '%')){ //inicia a variavel if(is_null($string_auxiliar)) $string_auxiliar = " and (b.key_ like '" . $chave["valor"] . "'"; else //concatena a variavel $string_auxiliar = $string_auxiliar . " or b.key_ like '" . $chave["valor"] . "'"; } //Se a chave nao possui objeto dinamico else{ //inicia a variavel if(is_null($string_auxiliar)) $string_auxiliar = " and (b.key_ = '" . $chave["valor"] . "'"; else //concatena a variavel $string_auxiliar = $string_auxiliar . " or b.key_ = '" . $chave["valor"] . "'"; } } if(!is_null($string_auxiliar)) $string_auxiliar .= ") "; return $string_auxiliar; } /** * buscaChavesCadastradas * * Busca todas as chaves cadastradas para este grafico. * * @param (type) (grafico_id) filtro do grafico. * @return (type) (rows) array com chaves cadastradas. */ function buscaChavesCadastradas($codhost, $grafico_id){ $query_chaves = "select distinct chave_id, valor, legenda_chave from view_grafico_host where host_id = $codhost and grafico_id = $grafico_id order by chave_id"; $rows = Select($query_chaves); return $rows; } /** * buscaGraficos * * Busca todos os graficos cadastrados para a categoria e host. * * @param (type) (categoria_id) identificador do e-mail. * @return (type) (rows) array de graficos, titulos, subtitulos. */ function buscaGraficos($codhost, $categoria_id){ $query_graficos = "select distinct grafico_id, titulo, subtitulo, json from view_grafico_host where host_id = $codhost and categoria_id = $categoria_id"; $rows = Select($query_graficos); return $rows; } /** * buscaCategorias * * Insere no banco que o email foi enviado. * * @param (type) (id) identificador do e-mail. */ function buscaCategorias($codhost){ $query_categorias = "select distinct categoria_id, nome from view_grafico_host where host_id = $codhost order by ordem"; $rows = Select($query_categorias); return $rows; } /** * buscaEmpresa * * Insere no banco que o email foi enviado. * * @param (type) (id) identificador do e-mail. */ function buscaEmpresa($codhost){ $query_categorias = "select empresa_id, empresa_nome, responsavel_nome, responsavel_email, host_id, host_nome from view_hosts where host_id = $codhost"; $rows = Select($query_categorias); return $rows[0]; } /** * debug * * Verifica se foi passado o parametro debug=true, insere a string sem quebra linha no final. * * @param (type) (text) texto para inserir no html. */ function debug($text){ $debug = isset($_GET["debug"]) ? $_GET["debug"] : null; if($debug === strtolower("true")){ echo($text); } } /** * debugl * * Verifica se foi passado o parametro debug=true, insere a string com um quebra linha no final. * * @param (type) (text) texto para inserir no html. */ function debugl($text){ $debug = isset($_GET["debug"]) ? $_GET["debug"] : null; if($debug === strtolower("true")){ echo($text."</br>"); } } function RecuperaHistoricoGrafico($mailid) { $query_grafico = "select phpbase64 from historico where id = $mailid "; $rows = Select($query_grafico); return $rows[0]["phpbase64"]; } /** * Select * * Processa query retornando um array associativo. * * @param (type) (query) querystring. * @param (type) (resultado) array associativo. */ function Select($query){ $config = parse_ini_file('database.ini'); $conexao = mysqli_connect($config['ip'],$config['username'],$config['password'],$config['dbname']); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }else{ $cursor = mysqli_query($conexao, $query); $resultado = mysqli_fetch_all($cursor, MYSQLI_ASSOC); mysqli_close($conexao); return $resultado; } } /** * Update * * Processa query retornando um array associativo. * * @param (type) (query) querystring. * @param (type) (resultado) array associativo. */ function Update($query){ $config = parse_ini_file('database.ini'); $conexao = mysqli_connect($config['ip'],$config['username'],$config['password'],$config['dbname']); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); }else{ $cursor = mysqli_query($conexao, $query); $resultado = mysqli_fetch_all($cursor, MYSQLI_ASSOC); $total = mysqli_affected_rows($conexao); mysqli_close($conexao); return $total; } } function setDataEnvio($mailid){ $query = "UPDATE historico set data_envio = CURRENT_TIMESTAMP where id = $mailid "; return Update($query); } function getObjectsToSend(){ $query = "select id, phpbase64 from historico where data_geracao is not null and data_revisao is not null and data_envio is null "; $rows = Select($query); return $rows; } ?><file_sep>/review.php <?php header('Content-type: text/html; charset=ISO-8859-1'); // Allow access from anywhere. Can be domains or * (any) header('Access-Control-Allow-Origin: *'); // Allow these methods of data retrieval header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); // Allow these header types header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); include "fhost.php"; $mailid = isset($_GET["mailid"]) ? $_GET["mailid"] : null; $tracking = isset($_GET["tracking"]) ? $_GET["tracking"] : null; $object = isset($_GET["object"]) ? $_GET["object"] : null; $host = new stdClass; if(!is_null($object)){ $host = unserialize(base64_decode($object)); echo processaRelatorioHost($mailid,$host); }else if (is_null($mailid)) { echo ("<h1>Informe um codigo de email enviado</h1>"); exit(); } else { $resultado = RecuperaHistoricoGrafico($mailid); $host = unserialize(base64_decode($resultado)); if (is_null($host->nome)) { echo ("<h1>Não encontramos o registro do e-mail ($mailid) para o host ($codhost) </br>:("); exit(); } echo processaRelatorioHost($mailid,$host); } ?>
7ead8a7fabb9783c3d52fa060c7aa8c962a0af24
[ "PHP" ]
9
PHP
doriclaudino/relatorio-zabbix
84c9508746b1355efc2fbbdae927248940906dc7
b009aeabb7142684cb894b9028e56e20419eb75c
refs/heads/master
<file_sep>import re import pytest import numpy as np import torch from obp.types import BanditFeedback from obp.ope import ( InverseProbabilityWeighting, SelfNormalizedInverseProbabilityWeighting, InverseProbabilityWeightingTuning, ) from conftest import generate_action_dist def test_ipw_init(): # lambda_ with pytest.raises( TypeError, match=r"`lambda_` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ): InverseProbabilityWeighting(lambda_=None) with pytest.raises( TypeError, match=r"`lambda_` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ): InverseProbabilityWeighting(lambda_="") with pytest.raises(ValueError, match=r"`lambda_`= -1.0, must be >= 0.0."): InverseProbabilityWeighting(lambda_=-1.0) with pytest.raises(ValueError, match=r"lambda_ must not be nan"): InverseProbabilityWeighting(lambda_=np.nan) # lambdas with pytest.raises( TypeError, match=r"`an element of lambdas` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ): InverseProbabilityWeightingTuning(lambdas=[None]) with pytest.raises( TypeError, match=r"`an element of lambdas` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ): InverseProbabilityWeightingTuning(lambdas=[""]) with pytest.raises( ValueError, match="`an element of lambdas`= -1.0, must be >= 0.0." ): InverseProbabilityWeightingTuning(lambdas=[-1.0]) with pytest.raises(ValueError, match="an element of lambdas must not be nan"): InverseProbabilityWeightingTuning(lambdas=[np.nan]) with pytest.raises(ValueError, match="lambdas must not be empty"): InverseProbabilityWeightingTuning(lambdas=[]) with pytest.raises(TypeError, match="lambdas must be a list"): InverseProbabilityWeightingTuning(lambdas="") with pytest.raises(TypeError, match="lambdas must be a list"): InverseProbabilityWeightingTuning(lambdas=None) # prepare ipw instances ipw = InverseProbabilityWeighting() snipw = SelfNormalizedInverseProbabilityWeighting() ipw_tuning = InverseProbabilityWeightingTuning(lambdas=[10, 1000]) # action_dist, action, reward, pscore, position, description invalid_input_of_ipw = [ ( generate_action_dist(5, 4, 3), None, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), None, # np.ones(5), np.random.choice(3, size=5), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), None, # np.random.choice(3, size=5), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=float), # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "action elements must be non-negative integers", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int) - 1, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "action elements must be non-negative integers", ), ( generate_action_dist(5, 4, 3), "4", # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros((3, 2), dtype=int), # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int) + 8, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), r"action elements must be smaller than`", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), "4", # np.ones(5), np.random.choice(3, size=5), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros((3, 2), dtype=int), # np.ones(5), np.random.choice(3, size=5), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(4, dtype=int), # np.ones(5), np.random.choice(3, size=5), "Expected `action.shape[0]", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), "4", # np.random.choice(3, size=5), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones((5, 3)), # np.random.choice(3, size=5), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones(4), # np.random.choice(3, size=5), "Expected `action.shape[0]", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.arange(5), # np.random.choice(3, size=5), "pscore must be positive", ), ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, description", invalid_input_of_ipw, ) def test_ipw_using_invalid_input_data( action_dist: np.ndarray, action: np.ndarray, reward: np.ndarray, pscore: np.ndarray, position: np.ndarray, description: str, ) -> None: with pytest.raises(ValueError, match=f"{description}*"): _ = ipw.estimate_policy_value( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = ipw.estimate_interval( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = snipw.estimate_policy_value( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = snipw.estimate_interval( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = ipw_tuning.estimate_policy_value( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = ipw_tuning.estimate_interval( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) # action_dist, action, reward, pscore, position, description invalid_input_tensor_of_ipw = [ ( torch.from_numpy(generate_action_dist(5, 4, 3)), None, # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "action must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), None, # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "reward must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.float32), None, # torch.from_numpy(np.random.choice(3, size=5)), "pscore must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.float64), # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "action elements must be non-negative integers", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.float64) - 1, # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "action elements must be non-negative integers", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), "4", # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "action must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros((3, 2), dtype=torch.int64), # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "action must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64) + 8, # torch.zeros(5, dtype=torch.float32), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), r"action elements must be smaller than`", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), "4", # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "reward must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros((3, 2), dtype=torch.float32), # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "reward must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(4, dtype=torch.float32), # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "Expected `action.shape[0]", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.float32), "4", # torch.from_numpy(np.random.choice(3, size=5)), "pscore must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.float32), torch.ones((5, 3)), # torch.from_numpy(np.random.choice(3, size=5)), "pscore must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.float32), torch.ones(4), # torch.from_numpy(np.random.choice(3, size=5)), "Expected `action.shape[0]", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.float32), torch.from_numpy(np.arange(5)), # torch.from_numpy(np.random.choice(3, size=5)), "pscore must be positive", ), ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, description", invalid_input_tensor_of_ipw, ) def test_ipw_using_invalid_input_tensor_data( action_dist: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, pscore: torch.Tensor, position: torch.Tensor, description: str, ) -> None: with pytest.raises(ValueError, match=f"{description}*"): _ = ipw.estimate_policy_value_tensor( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) with pytest.raises(ValueError, match=f"{description}*"): _ = snipw.estimate_policy_value_tensor( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, ) def test_ipw_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the format of ipw variants using synthetic bandit data and random evaluation policy """ action_dist = random_action_dist # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist # ipw estimators can be used without estimated_rewards_by_reg_model for estimator in [ipw, snipw, ipw_tuning]: estimated_policy_value = estimator.estimate_policy_value(**input_dict) assert isinstance( estimated_policy_value, float ), f"invalid type response: {estimator}" # remove necessary keys del input_dict["reward"] del input_dict["pscore"] del input_dict["action"] for estimator in [ipw, snipw]: with pytest.raises( TypeError, match=re.escape( "estimate_policy_value() missing 3 required positional arguments: 'reward', 'action', and 'pscore'" ), ): _ = estimator.estimate_policy_value(**input_dict) input_tensor_dict = { k: v if v is None else torch.from_numpy(v) for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_tensor_dict["action_dist"] = torch.from_numpy(action_dist) for estimator in [ipw, snipw]: estimated_policy_value = estimator.estimate_policy_value_tensor( **input_tensor_dict ) assert isinstance( estimated_policy_value, torch.Tensor ), f"invalid type response: {estimator}" # remove necessary keys del input_tensor_dict["reward"] del input_tensor_dict["pscore"] del input_tensor_dict["action"] for estimator in [ipw, snipw]: with pytest.raises( TypeError, match=re.escape( "estimate_policy_value_tensor() missing 3 required positional arguments: 'reward', 'action', and 'pscore'" ), ): _ = estimator.estimate_policy_value_tensor(**input_tensor_dict) def test_boundedness_of_snipw_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the boundedness of snipw estimators using synthetic bandit data and random evaluation policy """ action_dist = random_action_dist # prepare snipw snipw = SelfNormalizedInverseProbabilityWeighting() # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist # make pscore too small (to check the boundedness of snipw) input_dict["pscore"] = input_dict["pscore"] ** 3 estimated_policy_value = snipw.estimate_policy_value(**input_dict) assert ( estimated_policy_value <= 1 ), f"estimated policy value of snipw should be smaller than or equal to 1 (because of its 1-boundedness), but the value is: {estimated_policy_value}" input_tensor_dict = { k: v if v is None else torch.from_numpy(v) for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_tensor_dict["action_dist"] = torch.from_numpy(action_dist) # make pscore too small (to check the boundedness of snipw) input_tensor_dict["pscore"] = input_tensor_dict["pscore"] ** 3 estimated_policy_value_tensor = snipw.estimate_policy_value_tensor( **input_tensor_dict ) assert ( estimated_policy_value_tensor.item() <= 1 ), f"estimated policy value of snipw should be smaller than or equal to 1 (because of its 1-boundedness), but the value is: {estimated_policy_value_tensor.item()}" <file_sep>import argparse import yaml from pathlib import Path from pandas import DataFrame from sklearn.experimental import enable_hist_gradient_boosting # noqa from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression from obp.dataset import ( SyntheticBanditDataset, linear_behavior_policy, logistic_reward_function, ) from obp.policy import IPWLearner, NNPolicyLearner, Random from obp.ope import ( RegressionModel, InverseProbabilityWeighting, SelfNormalizedInverseProbabilityWeighting, DirectMethod, DoublyRobust, SelfNormalizedDoublyRobust, DoublyRobustWithShrinkage, ) # hyperparameters of the regression model used in model dependent OPE estimators with open("./conf/hyperparams.yaml", "rb") as f: hyperparams = yaml.safe_load(f) base_model_dict = dict( logistic_regression=LogisticRegression, lightgbm=HistGradientBoostingClassifier, random_forest=RandomForestClassifier, ) ope_estimator_dict = dict( dm=DirectMethod(), ipw=InverseProbabilityWeighting(), snipw=SelfNormalizedInverseProbabilityWeighting(), dr=DoublyRobust(), sndr=SelfNormalizedDoublyRobust(), dros=DoublyRobustWithShrinkage(lambda_=1.0), ) if __name__ == "__main__": parser = argparse.ArgumentParser( description="evaluate off-policy estimators with synthetic bandit data." ) parser.add_argument( "--n_rounds", type=int, default=10000, help="number of rounds for synthetic bandit feedback.", ) parser.add_argument( "--n_actions", type=int, default=10, help="number of actions for synthetic bandit feedback.", ) parser.add_argument( "--dim_context", type=int, default=5, help="dimensions of context vectors characterizing each round.", ) parser.add_argument( "--base_model_for_evaluation_policy", type=str, choices=["logistic_regression", "lightgbm", "random_forest"], required=True, help="base ML model for evaluation policy, logistic_regression, random_forest or lightgbm.", ) parser.add_argument( "--base_model_for_reg_model", type=str, choices=["logistic_regression", "lightgbm", "random_forest"], required=True, help="base ML model for regression model, logistic_regression, random_forest or lightgbm.", ) parser.add_argument( "--ope_estimator", type=str, choices=["dm", "ipw", "snipw", "dr", "sndr", "dros"], required=True, help="OPE estimator for NNPolicyLearner, dm, ipw, snipw, dr, sndr, or dros.", ) parser.add_argument( "--n_hidden", type=int, default=100, help="the size of hidden layers", ) parser.add_argument( "--n_layers", type=int, default=1, help="the number of hidden layers", ) parser.add_argument( "--activation", type=str, choices=["identity", "logistic", "tanh", "relu"], default="relu", help="activation function for the NN Policy Learner", ) parser.add_argument( "--solver", type=str, choices=["lbfgs", "sgd", "adam"], default="adam", help="optimizer for the NN Policy Learner", ) parser.add_argument( "--batch_size", type=int, default=None, help="batch size for the NN Policy Learner", ) parser.add_argument( "--early_stopping", action="store_true", help="use early stopping in training of the NN Policy Learner", ) parser.add_argument("--random_state", type=int, default=12345) args = parser.parse_args() print(args) # configurations n_rounds = args.n_rounds n_actions = args.n_actions dim_context = args.dim_context base_model_for_evaluation_policy = args.base_model_for_evaluation_policy base_model_for_reg_model = args.base_model_for_reg_model ope_estimator = args.ope_estimator n_hidden = args.n_hidden n_layers = args.n_layers activation = args.activation solver = args.solver batch_size = args.batch_size if args.batch_size else "auto" early_stopping = args.early_stopping random_state = args.random_state # synthetic data generator dataset = SyntheticBanditDataset( n_actions=n_actions, dim_context=dim_context, reward_function=logistic_reward_function, behavior_policy_function=linear_behavior_policy, random_state=random_state, ) # sample new training and test sets of synthetic logged bandit feedback bandit_feedback_train = dataset.obtain_batch_bandit_feedback(n_rounds=n_rounds) bandit_feedback_test = dataset.obtain_batch_bandit_feedback(n_rounds=n_rounds) # estimate the mean reward function of the train set of synthetic bandit feedback with ML model regression_model = RegressionModel( n_actions=dataset.n_actions, action_context=dataset.action_context, base_model=base_model_dict[base_model_for_reg_model]( **hyperparams[base_model_for_reg_model] ), ) estimated_rewards_by_reg_model = regression_model.fit_predict( context=bandit_feedback_train["context"], action=bandit_feedback_train["action"], reward=bandit_feedback_train["reward"], n_folds=3, # 3-fold cross-fitting random_state=random_state, ) # define random evaluation policy random_policy = Random(n_actions=dataset.n_actions, random_state=random_state) # define evaluation policy using IPWLearner ipw_learner = IPWLearner( n_actions=dataset.n_actions, base_classifier=base_model_dict[base_model_for_evaluation_policy]( **hyperparams[base_model_for_evaluation_policy] ), ) # define evaluation policy using NNPolicyLearner nn_policy_learner = NNPolicyLearner( n_actions=dataset.n_actions, dim_context=dim_context, off_policy_objective=ope_estimator_dict[ ope_estimator ].estimate_policy_value_tensor, hidden_layer_size=tuple((n_hidden for _ in range(n_layers))), activation=activation, solver=solver, batch_size=batch_size, early_stopping=early_stopping, random_state=random_state, ) # train the evaluation policy on the training set of the synthetic logged bandit feedback ipw_learner.fit( context=bandit_feedback_train["context"], action=bandit_feedback_train["action"], reward=bandit_feedback_train["reward"], pscore=bandit_feedback_train["pscore"], ) nn_policy_learner.fit( context=bandit_feedback_train["context"], action=bandit_feedback_train["action"], reward=bandit_feedback_train["reward"], pscore=bandit_feedback_train["pscore"], estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) # predict the action decisions for the test set of the synthetic logged bandit feedback random_action_dist = random_policy.compute_batch_action_dist(n_rounds=n_rounds) ipw_learner_action_dist = ipw_learner.predict( context=bandit_feedback_test["context"], ) nn_policy_learner_action_dist = nn_policy_learner.predict_proba( context=bandit_feedback_test["context"], ) # evaluate learners' performances using ground-truth polocy values random_policy_value = dataset.calc_ground_truth_policy_value( expected_reward=bandit_feedback_test["expected_reward"], action_dist=random_action_dist, ) ipw_learner_policy_value = dataset.calc_ground_truth_policy_value( expected_reward=bandit_feedback_test["expected_reward"], action_dist=ipw_learner_action_dist, ) nn_policy_learner_policy_value = dataset.calc_ground_truth_policy_value( expected_reward=bandit_feedback_test["expected_reward"], action_dist=nn_policy_learner_action_dist, ) policy_value_df = DataFrame( [ [random_policy_value], [ipw_learner_policy_value], [nn_policy_learner_policy_value], ], columns=["policy value"], index=[ "random_policy", "ipw_learner", f"nn_policy_learner (with {ope_estimator})", ], ).round(6) print("=" * 45) print(f"random_state={random_state}") print("-" * 45) print(policy_value_df) print("=" * 45) # save results of the evaluation of off-policy learners in './logs' directory. log_path = Path("./logs") log_path.mkdir(exist_ok=True, parents=True) policy_value_df.to_csv(log_path / "policy_value_of_off_policy_learners.csv") <file_sep>import re import pytest import numpy as np import torch from obp.types import BanditFeedback from obp.ope import ( DirectMethod, DoublyRobust, DoublyRobustTuning, DoublyRobustWithShrinkage, DoublyRobustWithShrinkageTuning, SwitchDoublyRobust, SwitchDoublyRobustTuning, SelfNormalizedDoublyRobust, ) from conftest import generate_action_dist # lambda_, err, description invalid_input_of_dr_init = [ ( "", TypeError, r"`lambda_` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ), ( None, TypeError, r"`lambda_` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ), (-1.0, ValueError, "`lambda_`= -1.0, must be >= 0.0."), (np.nan, ValueError, "lambda_ must not be nan"), ] @pytest.mark.parametrize( "lambda_, err, description", invalid_input_of_dr_init, ) def test_dr_init_using_invalid_inputs( lambda_, err, description, ): with pytest.raises(err, match=f"{description}*"): _ = DoublyRobust(lambda_=lambda_) with pytest.raises(err, match=f"{description}*"): _ = DoublyRobustWithShrinkage(lambda_=lambda_) # lambdas, err, description invalid_input_of_dr_tuning_init = [ ( "", TypeError, "lambdas must be a list", ), ( None, TypeError, "lambdas must be a list", ), ( [""], TypeError, r"`an element of lambdas` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ), ( [None], TypeError, r"`an element of lambdas` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ), ( [], ValueError, "lambdas must not be empty", ), ([-1.0], ValueError, "`an element of lambdas`= -1.0, must be >= 0.0."), ([np.nan], ValueError, "an element of lambdas must not be nan"), ] @pytest.mark.parametrize( "lambdas, err, description", invalid_input_of_dr_tuning_init, ) def test_dr_tuning_init_using_invalid_inputs( lambdas, err, description, ): with pytest.raises(err, match=f"{description}*"): _ = DoublyRobustTuning(lambdas=lambdas) with pytest.raises(err, match=f"{description}*"): _ = DoublyRobustWithShrinkageTuning( lambdas=lambdas, ) # tau, err, description invalid_input_of_switch_dr_init = [ ( "", TypeError, r"`tau` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ), ( None, TypeError, r"`tau` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ), (-1.0, ValueError, "`tau`= -1.0, must be >= 0.0."), (np.nan, ValueError, "tau must not be nan"), ] @pytest.mark.parametrize( "tau, err, description", invalid_input_of_switch_dr_init, ) def test_switch_dr_init_using_invalid_inputs( tau, err, description, ): with pytest.raises(err, match=f"{description}*"): _ = SwitchDoublyRobust(tau=tau) # taus, err, description invalid_input_of_switch_dr_tuning_init = [ ( "", TypeError, "taus must be a list", ), ( None, TypeError, "taus must be a list", ), ( [""], TypeError, r"`an element of taus` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'str'>.", ), ( [None], TypeError, r"`an element of taus` must be an instance of \(<class 'int'>, <class 'float'>\), not <class 'NoneType'>.", ), ( [], ValueError, "taus must not be empty", ), ([-1.0], ValueError, "`an element of taus`= -1.0, must be >= 0.0."), ([np.nan], ValueError, "an element of taus must not be nan"), ] @pytest.mark.parametrize( "taus, err, description", invalid_input_of_switch_dr_tuning_init, ) def test_switch_dr_tuning_init_using_invalid_inputs( taus, err, description, ): with pytest.raises(err, match=f"{description}*"): _ = SwitchDoublyRobustTuning(taus=taus) valid_input_of_dr_init = [ (np.inf, "infinite lambda_tau"), (3.0, "float lambda_tau"), (2, "integer lambda_tau"), ] @pytest.mark.parametrize( "lambda_tau, description", valid_input_of_dr_init, ) def test_dr_init_using_valid_input_data(lambda_tau: float, description: str) -> None: _ = DoublyRobust(lambda_=lambda_tau) _ = DoublyRobustWithShrinkage(lambda_=lambda_tau) _ = SwitchDoublyRobust(tau=lambda_tau) valid_input_of_dr_tuning_init = [ ([3.0, np.inf, 100.0], "float lambda_tau"), ([2], "integer lambda_tau"), ] @pytest.mark.parametrize( "lambdas_taus, description", valid_input_of_dr_tuning_init, ) def test_dr_tuning_init_using_valid_input_data(lambdas_taus, description): _ = DoublyRobustTuning(lambdas=lambdas_taus) _ = DoublyRobustWithShrinkageTuning( lambdas=lambdas_taus, ) _ = SwitchDoublyRobustTuning( taus=lambdas_taus, ) # prepare instances dm = DirectMethod() dr = DoublyRobust() dr_tuning = DoublyRobustTuning(lambdas=[1, 100], estimator_name="dr_tuning") dr_os_0 = DoublyRobustWithShrinkage(lambda_=0.0) dr_os_tuning = DoublyRobustWithShrinkageTuning( lambdas=[1, 100], estimator_name="dr_os_tuning" ) dr_os_max = DoublyRobustWithShrinkage(lambda_=np.inf) sndr = SelfNormalizedDoublyRobust() switch_dr_0 = SwitchDoublyRobust(tau=0.0) switch_dr_tuning = SwitchDoublyRobustTuning( taus=[1, 100], estimator_name="switch_dr_tuning" ) switch_dr_max = SwitchDoublyRobust(tau=np.inf) dr_estimators = [ dr, dr_tuning, dr_os_0, dr_os_tuning, sndr, switch_dr_0, switch_dr_tuning, ] # dr and self-normalized dr # action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, description invalid_input_of_dr = [ ( generate_action_dist(5, 4, 3), None, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), None, # np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), None, # np.random.choice(3, size=5), np.zeros((5, 4, 3)), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), None, # "estimated_rewards_by_reg_model must be 3D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=float), # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "action elements must be non-negative integers", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int) - 1, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "action elements must be non-negative integers", ), ( generate_action_dist(5, 4, 3), "4", # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros((3, 2), dtype=int), # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "action must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int) + 8, # np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), r"action elements must be smaller than`", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), "4", # np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros((3, 2), dtype=int), # np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "reward must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(4, dtype=int), # np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), "Expected `action.shape[0]", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), "4", # np.random.choice(3, size=5), np.zeros((5, 4, 3)), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones((5, 3)), # np.random.choice(3, size=5), np.zeros((5, 4, 3)), "pscore must be 1D array", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones(4), # np.random.choice(3, size=5), np.zeros((5, 4, 3)), "Expected `action.shape[0]", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.arange(5), # np.random.choice(3, size=5), np.zeros((5, 4, 3)), "pscore must be positive", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), np.zeros((5, 4, 2)), # "Expected `estimated_rewards_by_reg_model.shape == action_dist.shape`, but found it False", ), ( generate_action_dist(5, 4, 3), np.zeros(5, dtype=int), np.zeros(5, dtype=int), np.ones(5), np.random.choice(3, size=5), "4", # "estimated_rewards_by_reg_model must be 3D array", ), ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, description", invalid_input_of_dr, ) def test_dr_using_invalid_input_data( action_dist: np.ndarray, action: np.ndarray, reward: np.ndarray, pscore: np.ndarray, position: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, description: str, ) -> None: # estimate_intervals function raises ValueError of all estimators for estimator in [dr, sndr, dr_tuning]: with pytest.raises(ValueError, match=f"{description}*"): _ = estimator.estimate_policy_value( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) with pytest.raises(ValueError, match=f"{description}*"): _ = estimator.estimate_interval( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) # dr and self-normalized dr # action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, description invalid_input_tensor_of_dr = [ ( torch.from_numpy(generate_action_dist(5, 4, 3)), None, # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "action must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), None, # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "reward must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), None, # torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "pscore must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), None, # "estimated_rewards_by_reg_model must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.float32), # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "action elements must be non-negative integers", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64) - 1, # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "action elements must be non-negative integers", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), "4", # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "action must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros((3, 2), dtype=torch.int64), # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "action must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64) + 8, # torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), r"action elements must be smaller than`", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), "4", # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "reward must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros((3, 2), dtype=torch.int64), # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "reward must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(4, dtype=torch.int64), # torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "Expected `action.shape[0]", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), "4", # torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "pscore must be Tensor", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.ones((5, 3)), # torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "pscore must be 1-dimensional", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.ones(4), # torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "Expected `action.shape[0]", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.from_numpy(np.arange(5)), # torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), "pscore must be positive", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 2)), # "Expected `estimated_rewards_by_reg_model.shape == action_dist.shape`, but found it False", ), ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.zeros(5, dtype=torch.int64), torch.zeros(5, dtype=torch.int64), torch.ones(5), torch.from_numpy(np.random.choice(3, size=5)), "4", # "estimated_rewards_by_reg_model must be Tensor", ), ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, description", invalid_input_tensor_of_dr, ) def test_dr_using_invalid_input_tensor_data( action_dist: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, pscore: torch.Tensor, position: torch.Tensor, estimated_rewards_by_reg_model: torch.Tensor, description: str, ) -> None: # estimate_intervals function raises ValueError of all estimators for estimator in [dr, sndr]: with pytest.raises(ValueError, match=f"{description}*"): _ = estimator.estimate_policy_value_tensor( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) # dr variants valid_input_of_dr_variants = [ ( generate_action_dist(5, 4, 3), np.random.choice(4, size=5), np.zeros(5, dtype=int), np.random.uniform(low=0.5, high=1.0, size=5), np.random.choice(3, size=5), np.zeros((5, 4, 3)), 0.5, "all arguments are given and len_list > 1", ) ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, hyperparameter, description", valid_input_of_dr_variants, ) def test_dr_variants_using_valid_input_data( action_dist: np.ndarray, action: np.ndarray, reward: np.ndarray, pscore: np.ndarray, position: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, hyperparameter: float, description: str, ) -> None: # check dr variants switch_dr = SwitchDoublyRobust(tau=hyperparameter) switch_dr_tuning = SwitchDoublyRobustTuning( taus=[hyperparameter, hyperparameter * 10] ) dr_os = DoublyRobustWithShrinkage(lambda_=hyperparameter) dr_os_tuning = DoublyRobustWithShrinkageTuning( lambdas=[hyperparameter, hyperparameter * 10] ) for estimator in [switch_dr, switch_dr_tuning, dr_os, dr_os_tuning]: est = estimator.estimate_policy_value( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) assert est == 0.0, f"policy value must be 0, but {est}" # dr variants valid_input_tensor_of_dr_variants = [ ( torch.from_numpy(generate_action_dist(5, 4, 3)), torch.from_numpy(np.random.choice(4, size=5)), torch.zeros(5, dtype=torch.int64), torch.from_numpy(np.random.uniform(low=0.5, high=1.0, size=5)), torch.from_numpy(np.random.choice(3, size=5)), torch.zeros((5, 4, 3)), 0.5, "all arguments are given and len_list > 1", ) ] @pytest.mark.parametrize( "action_dist, action, reward, pscore, position, estimated_rewards_by_reg_model, hyperparameter, description", valid_input_tensor_of_dr_variants, ) def test_dr_variants_using_valid_input_tensor_data( action_dist: torch.Tensor, action: torch.Tensor, reward: torch.Tensor, pscore: torch.Tensor, position: torch.Tensor, estimated_rewards_by_reg_model: torch.Tensor, hyperparameter: float, description: str, ) -> None: # check dr variants dr_os = DoublyRobustWithShrinkage(lambda_=hyperparameter) for estimator in [dr_os]: est = estimator.estimate_policy_value_tensor( action_dist=action_dist, action=action, reward=reward, pscore=pscore, position=position, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) assert est.item() == 0.0, f"policy value must be 0, but {est.item()}" def test_dr_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the format of dr variants using synthetic bandit data and random evaluation policy """ expected_reward = synthetic_bandit_feedback["expected_reward"][:, :, np.newaxis] action_dist = random_action_dist # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist input_dict["estimated_rewards_by_reg_model"] = expected_reward # dr estimators require all arguments for estimator in dr_estimators: estimated_policy_value = estimator.estimate_policy_value(**input_dict) assert isinstance( estimated_policy_value, float ), f"invalid type response: {estimator}" # remove necessary keys del input_dict["reward"] del input_dict["pscore"] del input_dict["action"] del input_dict["estimated_rewards_by_reg_model"] for estimator in dr_estimators: with pytest.raises( TypeError, match=re.escape( "estimate_policy_value() missing 4 required positional arguments: 'reward', 'action', 'pscore', and 'estimated_rewards_by_reg_model'" ), ): _ = estimator.estimate_policy_value(**input_dict) # prepare input dict input_tensor_dict = { k: v if v is None else torch.from_numpy(v) for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_tensor_dict["action_dist"] = torch.from_numpy(action_dist) input_tensor_dict["estimated_rewards_by_reg_model"] = torch.from_numpy( expected_reward ) # dr estimators require all arguments for estimator in dr_estimators: if estimator.estimator_name == "switch-dr": with pytest.raises( NotImplementedError, match=re.escape( "This is not implemented for Switch-DR because it is indifferentiable." ), ): _ = estimator.estimate_policy_value_tensor(**input_tensor_dict) elif "tuning" not in estimator.estimator_name: estimated_policy_value = estimator.estimate_policy_value_tensor( **input_tensor_dict ) assert isinstance( estimated_policy_value, torch.Tensor ), f"invalid type response: {estimator}" # remove necessary keys del input_tensor_dict["reward"] del input_tensor_dict["pscore"] del input_tensor_dict["action"] del input_tensor_dict["estimated_rewards_by_reg_model"] for estimator in dr_estimators: if estimator.estimator_name == "switch-dr": with pytest.raises( NotImplementedError, match=re.escape( "This is not implemented for Switch-DR because it is indifferentiable." ), ): _ = estimator.estimate_policy_value_tensor(**input_tensor_dict) elif "tuning" not in estimator.estimator_name: with pytest.raises( TypeError, match=re.escape( "estimate_policy_value_tensor() missing 4 required positional arguments: 'reward', 'action', 'pscore', and 'estimated_rewards_by_reg_model'" ), ): _ = estimator.estimate_policy_value_tensor(**input_tensor_dict) def test_boundedness_of_sndr_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the boundedness of sndr estimators using synthetic bandit data and random evaluation policy """ expected_reward = synthetic_bandit_feedback["expected_reward"][:, :, np.newaxis] action_dist = random_action_dist # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist input_dict["estimated_rewards_by_reg_model"] = expected_reward # make pscore too small (to check the boundedness of sndr) input_dict["pscore"] = input_dict["pscore"] ** 3 estimated_policy_value = sndr.estimate_policy_value(**input_dict) assert ( estimated_policy_value <= 2 ), f"estimated policy value of sndr should be smaller than or equal to 2 (because of its 2-boundedness), but the value is: {estimated_policy_value}" # prepare input dict input_tensor_dict = { k: v if v is None else torch.from_numpy(v) for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_tensor_dict["action_dist"] = torch.from_numpy(action_dist) input_tensor_dict["estimated_rewards_by_reg_model"] = torch.from_numpy( expected_reward ) # make pscore too small (to check the boundedness of sndr) input_tensor_dict["pscore"] = input_tensor_dict["pscore"] ** 3 estimated_policy_value = sndr.estimate_policy_value_tensor(**input_tensor_dict) assert ( estimated_policy_value.item() <= 2 ), f"estimated policy value of sndr should be smaller than or equal to 2 (because of its 2-boundedness), but the value is: {estimated_policy_value.item()}" def test_dr_osage_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the dr shrinkage estimators using synthetic bandit data and random evaluation policy """ expected_reward = synthetic_bandit_feedback["expected_reward"][:, :, np.newaxis] action_dist = random_action_dist # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist input_dict["estimated_rewards_by_reg_model"] = expected_reward dm_value = dm.estimate_policy_value(**input_dict) dr_value = dr.estimate_policy_value(**input_dict) dr_os_0_value = dr_os_0.estimate_policy_value(**input_dict) dr_os_max_value = dr_os_max.estimate_policy_value(**input_dict) assert ( dm_value == dr_os_0_value ), "DoublyRobustWithShrinkage (lambda=0) should be the same as DirectMethod" assert ( np.abs(dr_value - dr_os_max_value) < 1e-5 ), "DoublyRobustWithShrinkage (lambda=inf) should be almost the same as DoublyRobust" # prepare input dict input_tensor_dict = { k: v if v is None else torch.from_numpy(v) for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_tensor_dict["action_dist"] = torch.from_numpy(action_dist) input_tensor_dict["estimated_rewards_by_reg_model"] = torch.from_numpy( expected_reward ) dm_value = dm.estimate_policy_value_tensor(**input_tensor_dict) dr_value = dr.estimate_policy_value_tensor(**input_tensor_dict) dr_os_0_value = dr_os_0.estimate_policy_value_tensor(**input_tensor_dict) dr_os_max_value = dr_os_max.estimate_policy_value_tensor(**input_tensor_dict) assert ( dm_value.item() == dr_os_0_value.item() ), "DoublyRobustWithShrinkage (lambda=0) should be the same as DirectMethod" assert ( np.abs(dr_value.item() - dr_os_max_value.item()) < 1e-5 ), "DoublyRobustWithShrinkage (lambda=inf) should be almost the same as DoublyRobust" def test_switch_dr_using_random_evaluation_policy( synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray ) -> None: """ Test the switch_dr using synthetic bandit data and random evaluation policy """ expected_reward = synthetic_bandit_feedback["expected_reward"][:, :, np.newaxis] action_dist = random_action_dist # prepare input dict input_dict = { k: v for k, v in synthetic_bandit_feedback.items() if k in ["reward", "action", "pscore", "position"] } input_dict["action_dist"] = action_dist input_dict["estimated_rewards_by_reg_model"] = expected_reward dm_value = dm.estimate_policy_value(**input_dict) dr_value = dr.estimate_policy_value(**input_dict) switch_dr_0_value = switch_dr_0.estimate_policy_value(**input_dict) switch_dr_max_value = switch_dr_max.estimate_policy_value(**input_dict) assert ( dm_value == switch_dr_0_value ), "SwitchDR (tau=0) should be the same as DirectMethod" assert ( dr_value == switch_dr_max_value ), "SwitchDR (tau=1e10) should be the same as DoublyRobust" <file_sep># Copyright (c) <NAME>, <NAME>, and ZOZO Technologies, Inc. All rights reserved. # Licensed under the Apache 2.0 License. """Off-Policy Estimators with built-in hyperparameter tuning.""" from dataclasses import dataclass, field from typing import Dict, Optional, List import numpy as np from sklearn.utils import check_scalar from .estimators import ( BaseOffPolicyEstimator, InverseProbabilityWeighting, DoublyRobust, SwitchDoublyRobust, DoublyRobustWithShrinkage, ) from ..utils import check_ope_inputs, check_array @dataclass class BaseOffPolicyEstimatorTuning: """Base Class for Off-Policy Estimator with built-in hyperparameter tuning base_ope_estimator: BaseOffPolicyEstimator An OPE estimator with a hyperparameter (such as IPW/DR with clipping, Switch-DR, and DR with Shrinkage). candidate_hyperparameter_list: List[float] A list of candidate hyperparameter values. References ---------- <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Policy Evaluation and Optimization.", 2014. <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Off-Policy Evaluation with Shrinkage.", 2020. """ base_ope_estimator: BaseOffPolicyEstimator = field(init=False) candidate_hyperparameter_list: List[float] = field(init=False) def __new__(cls, *args, **kwargs): dataclass(cls) return super().__new__(cls) def _check_candidate_hyperparameter_list(self, hyperparam_name: str) -> None: """Check type and value of candidate_hyperparameter_list.""" if isinstance(self.candidate_hyperparameter_list, list): if len(self.candidate_hyperparameter_list) == 0: raise ValueError(f"{hyperparam_name} must not be empty") for hyperparam_ in self.candidate_hyperparameter_list: check_scalar( hyperparam_, name=f"an element of {hyperparam_name}", target_type=(int, float), min_val=0.0, ) if hyperparam_ != hyperparam_: raise ValueError(f"an element of {hyperparam_name} must not be nan") else: raise TypeError(f"{hyperparam_name} must be a list") def _tune_hyperparam( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: Optional[np.ndarray] = None, position: Optional[np.ndarray] = None, ) -> None: """Find the best hyperparameter value from the given candidate set.""" self.estimated_mse_score_dict = dict() for hyperparam_ in self.candidate_hyperparameter_list: estimated_mse_score = self.base_ope_estimator( hyperparam_ )._estimate_mse_score( reward=reward, action=action, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, position=position, ) self.estimated_mse_score_dict[hyperparam_] = estimated_mse_score self.best_hyperparam = min( self.estimated_mse_score_dict.items(), key=lambda x: x[1] )[0] def estimate_policy_value_with_tuning( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: Optional[np.ndarray] = None, position: Optional[np.ndarray] = None, ) -> float: """Estimate the policy value of evaluation policy with a tuned hyperparameter. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list), default=None Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. Returns ---------- V_hat: float Policy value estimated by the DR estimator. """ # tune hyperparameter if necessary if not hasattr(self, "best_hyperparam"): self._tune_hyperparam( reward=reward, action=action, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, position=position, ) return self.base_ope_estimator(self.best_hyperparam).estimate_policy_value( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) def estimate_interval_with_tuning( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: Optional[np.ndarray] = None, position: Optional[np.ndarray] = None, alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, **kwargs, ) -> Dict[str, float]: """Estimate confidence interval of policy value by nonparametric bootstrap procedure. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list), default=None Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. alpha: float, default=0.05 Significance level. n_bootstrap_samples: int, default=10000 Number of resampling performed in the bootstrap procedure. random_state: int, default=None Controls the random seed in bootstrap sampling. Returns ---------- estimated_confidence_interval: Dict[str, float] Dictionary storing the estimated mean and upper-lower confidence bounds. """ # tune hyperparameter if necessary if not hasattr(self, "best_hyperparam"): self._tune_hyperparam( reward=reward, action=action, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, position=position, ) return self.base_ope_estimator(self.best_hyperparam).estimate_interval( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, alpha=alpha, n_bootstrap_samples=n_bootstrap_samples, random_state=random_state, ) class InverseProbabilityWeightingTuning(BaseOffPolicyEstimatorTuning): """Inverse Probability Weighting (IPW) with built-in hyperparameter tuning. Parameters ---------- lambdas: List[float] A list of candidate clipping hyperparameters. The automatic hyperparameter tuning proposed by Su et al.(2020) will choose the best hyperparameter value from the data. estimator_name: str, default='ipw'. Name of the estimator. References ---------- <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Policy Evaluation and Optimization.", 2014. <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Off-Policy Evaluation with Shrinkage.", 2020. """ lambdas: List[float] = None estimator_name: str = "ipw" def __post_init__(self) -> None: """Initialize Class.""" self.base_ope_estimator = InverseProbabilityWeighting self.candidate_hyperparameter_list = self.lambdas super()._check_candidate_hyperparameter_list(hyperparam_name="lambdas") def estimate_policy_value( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, position: Optional[np.ndarray] = None, **kwargs, ) -> np.ndarray: """Estimate the policy value of evaluation policy. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. Returns ---------- V_hat: float Estimated policy value (performance) of a given evaluation policy. """ check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_policy_value_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, ) def estimate_interval( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, position: Optional[np.ndarray] = None, alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, **kwargs, ) -> Dict[str, float]: """Estimate confidence interval of policy value by nonparametric bootstrap procedure. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities by the evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. alpha: float, default=0.05 Significance level. n_bootstrap_samples: int, default=10000 Number of resampling performed in the bootstrap procedure. random_state: int, default=None Controls the random seed in bootstrap sampling. Returns ---------- estimated_confidence_interval: Dict[str, float] Dictionary storing the estimated mean and upper-lower confidence bounds. """ check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_interval_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, alpha=alpha, n_bootstrap_samples=n_bootstrap_samples, random_state=random_state, ) @dataclass class DoublyRobustTuning(BaseOffPolicyEstimatorTuning): """Doubly Robust (DR) with built-in hyperparameter tuning. Parameters ---------- lambdas: List[float] A list of candidate clipping hyperparameters. The automatic hyperparameter tuning proposed by Su et al.(2020) will choose the best hyperparameter value from the data. estimator_name: str, default='dr'. Name of the estimator. References ---------- <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Policy Evaluation and Optimization.", 2014. <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Off-Policy Evaluation with Shrinkage.", 2020. """ lambdas: List[float] = None estimator_name: str = "dr" def __post_init__(self) -> None: """Initialize Class.""" self.base_ope_estimator = DoublyRobust self.candidate_hyperparameter_list = self.lambdas super()._check_candidate_hyperparameter_list(hyperparam_name="lambdas") def estimate_policy_value( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, ) -> float: """Estimate the policy value of evaluation policy with a tuned hyperparameter. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. Returns ---------- V_hat: float Policy value estimated by the DR estimator. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_policy_value_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) def estimate_interval( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, **kwargs, ) -> Dict[str, float]: """Estimate confidence interval of policy value by nonparametric bootstrap procedure. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. alpha: float, default=0.05 Significance level. n_bootstrap_samples: int, default=10000 Number of resampling performed in the bootstrap procedure. random_state: int, default=None Controls the random seed in bootstrap sampling. Returns ---------- estimated_confidence_interval: Dict[str, float] Dictionary storing the estimated mean and upper-lower confidence bounds. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_interval_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, alpha=alpha, n_bootstrap_samples=n_bootstrap_samples, random_state=random_state, ) @dataclass class SwitchDoublyRobustTuning(BaseOffPolicyEstimatorTuning): """Switch Doubly Robust (Switch-DR) with build-in hyperparameter tuning. Parameters ---------- taus: List[float] A list of candidate switching hyperparameters. The automatic hyperparameter tuning proposed by Su et al.(2020) will choose the best hyperparameter value from the data. estimator_name: str, default='switch-dr'. Name of the estimator. References ---------- <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Policy Evaluation and Optimization.", 2014. <NAME>, <NAME>, and <NAME>. "Optimal and Adaptive Off-policy Evaluation in Contextual Bandits", 2016. """ taus: List[float] = None estimator_name: str = "switch-dr" def __post_init__(self) -> None: """Initialize Class.""" self.base_ope_estimator = SwitchDoublyRobust self.candidate_hyperparameter_list = self.taus super()._check_candidate_hyperparameter_list(hyperparam_name="taus") def estimate_policy_value( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, ) -> float: """Estimate the policy value of evaluation policy with a tuned hyperparameter. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. Returns ---------- V_hat: float Policy value estimated by the DR estimator. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_policy_value_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) def estimate_interval( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, **kwargs, ) -> Dict[str, float]: """Estimate confidence interval of policy value by nonparametric bootstrap procedure. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. alpha: float, default=0.05 Significance level. n_bootstrap_samples: int, default=10000 Number of resampling performed in the bootstrap procedure. random_state: int, default=None Controls the random seed in bootstrap sampling. Returns ---------- estimated_confidence_interval: Dict[str, float] Dictionary storing the estimated mean and upper-lower confidence bounds. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_interval_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, alpha=alpha, n_bootstrap_samples=n_bootstrap_samples, random_state=random_state, ) @dataclass class DoublyRobustWithShrinkageTuning(BaseOffPolicyEstimatorTuning): """Doubly Robust with optimistic shrinkage (DRos) with built-in hyperparameter tuning. Parameters ---------- lambdas: List[float] A list of candidate shrinkage hyperparameters. The automatic hyperparameter tuning proposed by Su et al.(2020) will choose the best hyperparameter value from the data. estimator_name: str, default='dr-os'. Name of the estimator. References ---------- <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Policy Evaluation and Optimization.", 2014. <NAME>, <NAME>, <NAME>, and <NAME>. "Doubly Robust Off-Policy Evaluation with Shrinkage.", 2020. """ lambdas: List[float] = None estimator_name: str = "dr-os" def __post_init__(self) -> None: """Initialize Class.""" self.base_ope_estimator = DoublyRobustWithShrinkage self.candidate_hyperparameter_list = self.lambdas super()._check_candidate_hyperparameter_list(hyperparam_name="lambdas") def estimate_policy_value( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, ) -> float: """Estimate the policy value of evaluation policy with a tuned hyperparameter. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. Returns ---------- V_hat: float Policy value estimated by the DR estimator. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_policy_value_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) def estimate_interval( self, reward: np.ndarray, action: np.ndarray, pscore: np.ndarray, action_dist: np.ndarray, estimated_rewards_by_reg_model: np.ndarray, position: Optional[np.ndarray] = None, alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, **kwargs, ) -> Dict[str, float]: """Estimate confidence interval of policy value by nonparametric bootstrap procedure. Parameters ---------- reward: array-like, shape (n_rounds,) Reward observed in each round of the logged bandit feedback, i.e., :math:`r_t`. action: array-like, shape (n_rounds,) Action sampled by behavior policy in each round of the logged bandit feedback, i.e., :math:`a_t`. pscore: array-like, shape (n_rounds,) Action choice probabilities of behavior policy (propensity scores), i.e., :math:`\\pi_b(a_t|x_t)`. action_dist: array-like, shape (n_rounds, n_actions, len_list) Action choice probabilities of evaluation policy (can be deterministic), i.e., :math:`\\pi_e(a_t|x_t)`. estimated_rewards_by_reg_model: array-like, shape (n_rounds, n_actions, len_list) Expected rewards given context, action, and position estimated by regression model, i.e., :math:`\\hat{q}(x_t,a_t)`. position: array-like, shape (n_rounds,), default=None Position of recommendation interface where action was presented in each round of the given logged bandit feedback. alpha: float, default=0.05 Significance level. n_bootstrap_samples: int, default=10000 Number of resampling performed in the bootstrap procedure. random_state: int, default=None Controls the random seed in bootstrap sampling. Returns ---------- estimated_confidence_interval: Dict[str, float] Dictionary storing the estimated mean and upper-lower confidence bounds. """ check_array( array=estimated_rewards_by_reg_model, name="estimated_rewards_by_reg_model", expected_dim=3, ) check_array(array=reward, name="reward", expected_dim=1) check_array(array=action, name="action", expected_dim=1) check_array(array=pscore, name="pscore", expected_dim=1) check_ope_inputs( action_dist=action_dist, position=position, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, ) if position is None: position = np.zeros(action_dist.shape[0], dtype=int) return super().estimate_interval_with_tuning( reward=reward, action=action, position=position, pscore=pscore, action_dist=action_dist, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, alpha=alpha, n_bootstrap_samples=n_bootstrap_samples, random_state=random_state, ) <file_sep>import pytest import numpy as np from sklearn.linear_model import LogisticRegression, LinearRegression import torch from obp.policy.offline import IPWLearner from obp.policy.offline import NNPolicyLearner from obp.policy.policy_type import PolicyType from obp.ope.estimators import InverseProbabilityWeighting base_classifier = LogisticRegression() base_regressor = LinearRegression() # n_actions, len_list, base_classifier, description invalid_input_of_ipw_learner_init = [ ( 0, # 1, base_classifier, "n_actions must be an integer larger than 1", ), ( 10, -1, # base_classifier, "len_list must be a positive integer", ), ( 10, 20, # base_classifier, "Expected `n_actions", ), (10, 1, base_regressor, "base_classifier must be a classifier"), ] valid_input_of_ipw_learner_init = [ ( 10, 1, None, "valid input", ), ( 10, 1, base_classifier, "valid input", ), ] @pytest.mark.parametrize( "n_actions, len_list, base_classifier, description", invalid_input_of_ipw_learner_init, ) def test_ipw_learner_init_using_invalid_inputs( n_actions, len_list, base_classifier, description, ): with pytest.raises(ValueError, match=f"{description}*"): _ = IPWLearner( n_actions=n_actions, len_list=len_list, base_classifier=base_classifier, ) @pytest.mark.parametrize( "n_actions, len_list, base_classifier, description", valid_input_of_ipw_learner_init, ) def test_ipw_learner_init_using_valid_inputs( n_actions, len_list, base_classifier, description, ): ipw_learner = IPWLearner( n_actions=n_actions, len_list=len_list, base_classifier=base_classifier, ) # policy_type assert ipw_learner.policy_type == PolicyType.OFFLINE def test_ipw_learner_init_base_classifier_list(): # base classifier len_list = 2 learner1 = IPWLearner(n_actions=2, len_list=len_list) assert isinstance(learner1.base_classifier, LogisticRegression) for i in range(len_list): assert isinstance(learner1.base_classifier_list[i], LogisticRegression) from sklearn.naive_bayes import GaussianNB learner2 = IPWLearner(n_actions=2, len_list=len_list, base_classifier=GaussianNB()) assert isinstance(learner2.base_classifier, GaussianNB) for i in range(len_list): assert isinstance(learner2.base_classifier_list[i], GaussianNB) def test_ipw_learner_create_train_data_for_opl(): context = np.array([1.0, 1.0]).reshape(1, -1) learner = IPWLearner(n_actions=2) action = np.array([0]) reward = np.array([1.0]) pscore = np.array([0.5]) X, sample_weight, y = learner._create_train_data_for_opl( context=context, action=action, reward=reward, pscore=pscore ) assert np.allclose(X, np.array([1.0, 1.0]).reshape(1, -1)) assert np.allclose(sample_weight, np.array([2.0])) assert np.allclose(y, np.array([0])) def test_ipw_learner_fit(): n_rounds = 1000 dim_context = 5 n_actions = 3 len_list = 2 context = np.ones((n_rounds, dim_context)) action = np.random.choice(np.arange(len_list, dtype=int), size=n_rounds) reward = np.random.choice(np.arange(2), size=n_rounds) position = np.random.choice(np.arange(len_list, dtype=int), size=n_rounds) # inconsistency with the shape desc = "Expected `context.shape[0]" with pytest.raises(ValueError, match=f"{desc}*"): learner = IPWLearner(n_actions=n_actions, len_list=len_list) variant_context = np.random.normal(size=(n_rounds + 1, n_actions)) learner.fit( context=variant_context, action=action, reward=reward, position=position, ) # len_list > 2, but position is not set desc = "When `self.len_list=1" with pytest.raises(ValueError, match=f"{desc}*"): learner = IPWLearner(n_actions=n_actions, len_list=len_list) learner.fit(context=context, action=action, reward=reward) # position must be non-negative desc = "position elements must be non-negative integers" with pytest.raises(ValueError, match=f"{desc}*"): negative_position = position - 1 learner = IPWLearner(n_actions=n_actions, len_list=len_list) learner.fit( context=context, action=action, reward=reward, position=negative_position ) # IPWLearner cannot handle negative rewards desc = "A negative value is found in" with pytest.raises(ValueError, match=f"{desc}*"): negative_reward = reward - 1.0 learner = IPWLearner(n_actions=n_actions, len_list=len_list) learner.fit( context=context, action=action, reward=negative_reward, position=position ) def test_ipw_learner_predict(): n_actions = 2 len_list = 1 # shape error desc = "context must be 2D array" with pytest.raises(ValueError, match=f"{desc}*"): context = np.array([1.0, 1.0]) learner = IPWLearner(n_actions=n_actions, len_list=len_list) learner.predict(context=context) # shape consistency of action_dist # n_rounds is 5, dim_context is 2 context = np.array([1.0, 1.0, 1.0, 1.0]).reshape(2, -1) action = np.array([0, 1]) reward = np.array([1.0, 0.0]) position = np.array([0, 0]) learner = IPWLearner(n_actions=2, len_list=1) learner.fit(context=context, action=action, reward=reward, position=position) context_test = np.array([i for i in range(10)]).reshape(5, 2) action_dist = learner.predict(context=context_test) assert np.allclose( action_dist.sum(1), np.ones_like((context_test.shape[0], len_list)) ) assert action_dist.shape[0] == 5 assert action_dist.shape[1] == n_actions assert action_dist.shape[2] == len_list def test_ipw_learner_sample_action(): n_actions = 2 len_list = 1 context = np.array([1.0, 1.0, 1.0, 1.0]).reshape(2, -1) action = np.array([0, 1]) reward = np.array([1.0, 0.0]) position = np.array([0, 0]) learner = IPWLearner(n_actions=n_actions, len_list=len_list) learner.fit(context=context, action=action, reward=reward, position=position) desc = "context must be 2D array" with pytest.raises(ValueError, match=f"{desc}*"): invalid_type_context = [1.0, 2.0] learner.sample_action(context=invalid_type_context) with pytest.raises(ValueError, match=f"{desc}*"): invalid_ndim_context = np.array([1.0, 2.0, 3.0, 4.0]) learner.sample_action(context=invalid_ndim_context) context = np.array([1.0, 1.0, 1.0, 1.0]).reshape(2, -1) n_rounds = context.shape[0] sampled_action = learner.sample_action(context=context) assert sampled_action.shape[0] == n_rounds assert sampled_action.shape[1] == n_actions assert sampled_action.shape[2] == len_list ipw = InverseProbabilityWeighting() # n_actions, len_list, dim_context, off_policy_objective, hidden_layer_size, activation, solver, alpha, # batch_size, learning_rate_init, max_iter, shuffle, random_state, tol, momentum, nesterovs_momentum, # early_stopping, validation_fraction, beta_1, beta_2, epsilon, n_iter_no_change, max_fun, description invalid_input_of_nn_policy_learner_init = [ ( 0, # 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "n_actions must be an integer larger than 1", ), ( 10, -1, # 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "len_list must be a positive integer", ), ( 10, 1, -1, # ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "dim_context must be a positive integer", ), ( 10, 1, 2, None, # (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "off_policy_objective must be callable", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, ""), # "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "hidden_layer_size must be tuple of positive integers", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "None", # "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "activation must be one of 'identity', 'logistic', 'tanh', or 'relu'", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "None", # 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "solver must be one of 'adam', 'lbfgs', or 'sgd'", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", -1, # "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "alpha must be a non-negative float", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, 0, # 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "batch_size must be a positive integer or 'auto'", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0, # 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "learning_rate_init must be a positive float", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 0, # True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "max_iter must be a positive integer", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, None, # 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "shuffle must be a bool", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, "", # 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "'' cannot be used to seed", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, -1, # 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "tol must be a positive float", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 2, # True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "momentum must be a float in [0., 1.]", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, "", # True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "nesterovs_momentum must be a bool", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, None, # 0.1, 0.9, 0.999, 1e-8, 10, 15000, "early_stopping must be a bool", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "lbfgs", # 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, # 0.1, 0.9, 0.999, 1e-8, 10, 15000, "if early_stopping is True, solver must be one of 'sgd' or 'adam'", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 2, # 0.9, 0.999, 1e-8, 10, 15000, "validation_fraction must be a float in", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 2, # 0.999, 1e-8, 10, 15000, "beta_1 must be a float in [0. 1.]", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 2, # 1e-8, 10, 15000, "beta_2 must be a float in [0., 1.]", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, -1, # 10, 15000, "epsilon must be a non-negative float", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 0, # 15000, "n_iter_no_change must be a positive integer", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 0, # "max_fun must be a positive integer", ), ] valid_input_of_nn_policy_learner_init = [ ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "relu", "adam", 0.001, "auto", 0.0001, 200, True, 123, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "valid input", ), ( 10, 1, 2, ipw.estimate_policy_value_tensor, (100, 50, 100), "logistic", "sgd", 0.001, 50, 0.0001, 200, True, None, 1e-4, 0.9, True, True, 0.1, 0.9, 0.999, 1e-8, 10, 15000, "valid input", ), ] @pytest.mark.parametrize( "n_actions, len_list, dim_context, off_policy_objective, hidden_layer_size, activation, solver, alpha, batch_size, learning_rate_init, max_iter, shuffle, random_state, tol, momentum, nesterovs_momentum, early_stopping, validation_fraction, beta_1, beta_2, epsilon, n_iter_no_change, max_fun, description", invalid_input_of_nn_policy_learner_init, ) def test_nn_policy_learner_init_using_invalid_inputs( n_actions, len_list, dim_context, off_policy_objective, hidden_layer_size, activation, solver, alpha, batch_size, learning_rate_init, max_iter, shuffle, random_state, tol, momentum, nesterovs_momentum, early_stopping, validation_fraction, beta_1, beta_2, epsilon, n_iter_no_change, max_fun, description, ): with pytest.raises(ValueError, match=f"{description}*"): _ = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=dim_context, off_policy_objective=off_policy_objective, hidden_layer_size=hidden_layer_size, activation=activation, solver=solver, alpha=alpha, batch_size=batch_size, learning_rate_init=learning_rate_init, max_iter=max_iter, shuffle=shuffle, random_state=random_state, tol=tol, momentum=momentum, nesterovs_momentum=nesterovs_momentum, early_stopping=early_stopping, validation_fraction=validation_fraction, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, n_iter_no_change=n_iter_no_change, max_fun=max_fun, ) @pytest.mark.parametrize( "n_actions, len_list, dim_context, off_policy_objective, hidden_layer_size, activation, solver, alpha, batch_size, learning_rate_init, max_iter, shuffle, random_state, tol, momentum, nesterovs_momentum, early_stopping, validation_fraction, beta_1, beta_2, epsilon, n_iter_no_change, max_fun, description", valid_input_of_nn_policy_learner_init, ) def test_nn_policy_learner_init_using_valid_inputs( n_actions, len_list, dim_context, off_policy_objective, hidden_layer_size, activation, solver, alpha, batch_size, learning_rate_init, max_iter, shuffle, random_state, tol, momentum, nesterovs_momentum, early_stopping, validation_fraction, beta_1, beta_2, epsilon, n_iter_no_change, max_fun, description, ): nn_policy_learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=dim_context, off_policy_objective=off_policy_objective, hidden_layer_size=hidden_layer_size, activation=activation, solver=solver, alpha=alpha, batch_size=batch_size, learning_rate_init=learning_rate_init, max_iter=max_iter, shuffle=shuffle, random_state=random_state, tol=tol, momentum=momentum, nesterovs_momentum=nesterovs_momentum, early_stopping=early_stopping, validation_fraction=validation_fraction, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, n_iter_no_change=n_iter_no_change, max_fun=max_fun, ) assert isinstance(nn_policy_learner, NNPolicyLearner) def test_nn_policy_learner_create_train_data_for_opl(): context = np.ones((100, 2), dtype=np.int32) action = np.zeros((100,), dtype=np.int32) reward = np.ones((100,), dtype=np.float32) pscore = np.array([0.5] * 100, dtype=np.float32) estimated_rewards_by_reg_model = np.ones((100, 2), dtype=np.float32) position = np.zeros((100,), dtype=np.int32) ipw = InverseProbabilityWeighting() learner1 = NNPolicyLearner( n_actions=2, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) training_loader, validation_loader = learner1._create_train_data_for_opl( context=context, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, position=position, ) assert isinstance(training_loader, torch.utils.data.DataLoader) assert validation_loader is None learner2 = NNPolicyLearner( n_actions=2, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, early_stopping=True, ) training_loader, validation_loader = learner2._create_train_data_for_opl( context=context, action=action, reward=reward, pscore=pscore, estimated_rewards_by_reg_model=estimated_rewards_by_reg_model, position=position, ) assert isinstance(training_loader, torch.utils.data.DataLoader) assert isinstance(validation_loader, torch.utils.data.DataLoader) def test_nn_policy_learner_fit(): context = np.ones((100, 2), dtype=np.float32) action = np.zeros((100,), dtype=int) reward = np.ones((100,), dtype=np.float32) pscore = np.array([0.5] * 100, dtype=np.float32) ipw = InverseProbabilityWeighting() # inconsistency with the shape desc = "Expected `context.shape[0]" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=2, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) variant_context = np.ones((101, 2), dtype=np.float32) learner.fit( context=variant_context, action=action, reward=reward, pscore=pscore ) # inconsistency between dim_context and context desc = "Expected `context.shape[1]" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=2, dim_context=3, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) def test_nn_policy_learner_predict(): n_actions = 2 len_list = 1 context = np.ones((100, 2), dtype=np.float32) context_test = np.array([i for i in range(10)], dtype=np.float32).reshape(5, 2) action = np.zeros((100,), dtype=int) reward = np.ones((100,), dtype=np.float32) pscore = np.array([0.5] * 100, dtype=np.float32) ipw = InverseProbabilityWeighting() # shape error desc = "context must be 2D array" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([1.0, 1.0], dtype=np.float32) learner.predict(context=invalid_context) # inconsistency between dim_context and context desc = "Expected `context.shape[1]" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([[1.0, 1.0, 1.0]], dtype=np.float32) learner.predict(context=invalid_context) # shape consistency of action_dist # n_rounds is 5, dim_context is 2 learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) action_dist = learner.predict(context=context_test) assert np.allclose( action_dist.sum(1), np.ones_like((context_test.shape[0], len_list)) ) assert action_dist.shape[0] == 5 assert action_dist.shape[1] == n_actions assert action_dist.shape[2] == len_list def test_nn_policy_learner_sample_action(): n_actions = 2 len_list = 1 context = np.ones((100, 2), dtype=np.float32) context_test = np.array([i for i in range(10)], dtype=np.float32).reshape(5, 2) action = np.zeros((100,), dtype=int) reward = np.ones((100,), dtype=np.float32) pscore = np.array([0.5] * 100, dtype=np.float32) ipw = InverseProbabilityWeighting() # shape error desc = "context must be 2D array" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([1.0, 1.0], dtype=np.float32) learner.sample_action(context=invalid_context) # inconsistency between dim_context and context desc = "Expected `context.shape[1]" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([[1.0, 1.0, 1.0]], dtype=np.float32) learner.sample_action(context=invalid_context) learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) action_dist = learner.sample_action(context=context_test) assert np.allclose( action_dist.sum(1), np.ones_like((context_test.shape[0], len_list)) ) assert action_dist.shape[0] == context_test.shape[0] assert action_dist.shape[1] == n_actions assert action_dist.shape[2] == len_list def test_nn_policy_learner_predict_proba(): n_actions = 2 len_list = 1 context = np.ones((100, 2), dtype=np.float32) context_test = np.array([i for i in range(10)], dtype=np.float32).reshape(5, 2) action = np.zeros((100,), dtype=int) reward = np.ones((100,), dtype=np.float32) pscore = np.array([0.5] * 100, dtype=np.float32) ipw = InverseProbabilityWeighting() # shape error desc = "context must be 2D array" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([1.0, 1.0], dtype=np.float32) learner.predict_proba(context=invalid_context) # inconsistency between dim_context and context desc = "Expected `context.shape[1]" with pytest.raises(ValueError, match=f"{desc}*"): learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) invalid_context = np.array([[1.0, 1.0, 1.0]], dtype=np.float32) learner.predict_proba(context=invalid_context) learner = NNPolicyLearner( n_actions=n_actions, len_list=len_list, dim_context=2, off_policy_objective=ipw.estimate_policy_value_tensor, ) learner.fit(context=context, action=action, reward=reward, pscore=pscore) action_dist = learner.predict_proba(context=context_test) assert np.allclose( action_dist.sum(1), np.ones_like((context_test.shape[0], len_list)) ) assert action_dist.shape[0] == context_test.shape[0] assert action_dist.shape[1] == n_actions assert action_dist.shape[2] == len_list
9079ec78da35aa8fa407ff46517b7a7ba66a3f38
[ "Python" ]
5
Python
yuan776/zr-obp
b77b4a6faf041604b0a7873de60adbcc57bd2ee2
c88663e72c6e08eccd9559debe97993922e1705d
refs/heads/master
<repo_name>SpringBlossomsy/HelloPark<file_sep>/park/urls.py from django.conf.urls import url from park import views from django.views.generic.base import TemplateView urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^setSei/$', views.setSei, name='setSei'), url(r'^center/$', views.center, name='center'), # 登录/注册 url(r'^send_message/$', views.send_message, name='send_message'), url(r'^send_message2/$', views.send_message2, name='send_message2'), url(r'^login/$', views.my_login, name='login'), url(r'^login_yz/$', views.my_login_yz, name='login_yz'), url(r'^logout/$', views.my_logout, name='logout'), url(r'^register/$', views.my_register, name='register'), # 钱包 url(r'^wallet/$', views.my_wallet, name='wallet'), url(r'^wallet_invest/$', views.my_wallet_invest, name='wallet_invest'), url(r'^wallet_pay/(?P<number>.+)/$', views.my_wallet_pay, name='wallet_pay'), url(r'^ddpay/$', views.ddpay, name='ddpay'), url(r'^wallet_datail/$', views.my_wallet_datail, name='wallet_datail'), url(r'^wallet_datail_more/(?P<walletId>.+)/$', views.my_wallet_datail_more, name='wallet_datail_more'), # 我的车辆 url(r'^car_bind/$', views.car_bind, name='car_bind'), url(r'^car_number/$', views.car_number, name='car_number'), url(r'^car_save/$', views.car_save, name='car_save'), url(r'^car_delete/$', views.car_delete, name='car_delete'), # 停车位 url(r'^park/$', views.park, name='park'), url(r'^park_detail/(?P<parkId>.+)/$', views.park_detail, name='park_detail'), url(r'^park_change/$', views.park_change, name='park_change'), url(r'^add_park/$',views.add_park, name='add_park'), url(r'^add_park_inform/$', views.add_park_inform, name='add_park_inform'), url(r'^park_save/$', views.park_save, name='park_save'), url(r'^park_check/$', views.park_check, name='park_check'), # 主功能-停车 url(r'^park_info/(?P<parkId>.+)/$', views.park_info, name='park_info'), url(r'^put_order/$', views.put_order, name='put_order'), url(r'^cancel_order/$', views.cancel_order, name='cancel_order'), url(r'^self_lock/(?P<parkId>.+)/$', views.self_lock, name='self_lock'), # 车位主人 使用 url(r'^self_lock_lock/(?P<parkId>.+)/$', views.self_lock_lock, name='self_lock_lock'), url(r'^self_lock_unlock/(?P<parkId>.+)/$', views.self_lock_unlock, name='self_lock_unlock'), url(r'^lock/(?P<parkId>.+)/(?P<orderId>.+)/$', views.lock, name='lock'), # 停车的人使用 url(r'^lock_start/&', views.lock_start, name='lock_start'), url(r'^lock_stop/&', views.lock_stop, name='lock_stop'), # 订单 url(r'^order/$', views.order, name='order'), url(r'^test/$', views.test, name='test'), ] <file_sep>/park/migrations/0005_auto_20190626_1514.py # Generated by Django 2.2.2 on 2019-06-26 15:14 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('park', '0004_auto_20190625_2306'), ] operations = [ migrations.AddField( model_name='order', name='order_time', field=models.CharField(blank=True, max_length=2048), ), migrations.AlterField( model_name='order', name='source', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_source', to='park.UserPrakSeat'), ), ] <file_sep>/park/views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from registration.backends.simple.views import RegistrationView import re from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.http import * from django.urls import reverse from django.contrib.auth.models import User, Group from park.forms import * from park.models import * import json import datetime import time import os from django.db.models import Q from django.conf import settings import random import urllib import http.client from decimal import * key = '<KEY>' class MyRegistrationView(RegistrationView): # 用户成功注册后重定向到其他页面 def get_success_url(self, user): return reverse('index') def index(request): us = UserPrakSeat.objects.all() ls = [] print(us) for t in us: ls.append([t.pioaddress, float(t.lat), float(t.lng), float(t.price), t.id]) print('***',t) print(float(3.14159562)) return render(request, 'index.html', {'userSeats': ls}) @csrf_exempt def setSei(request): if request.method == 'POST': request.session['local_lat'] = request.POST.get('lat') request.session['local_lng'] = request.POST.get('lng') return HttpResponse("ok") def center(request): return render(request, 'center.html') # -----------------发送短信的视图函数--------------------------------------------------------------- # 请求的路径 host = "106.ihuyi.com" sms_send_uri = "/webservice/sms.php?method=Submit" # 用户名是登录ihuyi.com账号名(例如:cf_demo123) account = "C03611718" # 密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY password = "<PASSWORD>" def message(request, mobile): # 定义一个字符串,存储生成的6位数验证码 message_code = '' for i in range(6): i = random.randint(0, 9) message_code += str(i) # 拼接成发出的短信 text = "您的验证码是:" + message_code + "。请不要把验证码泄露给其他人。" # 把请求参数编码 params = urllib.parse.urlencode( {'account': account, 'password': <PASSWORD>, 'content': text, 'mobile': mobile, 'format': 'json'}) # 请求头 headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} # 通过全局的host去连接服务器 conn = http.client.HTTPConnection(host, port=80, timeout=30) # 向连接后的服务器发送post请求,路径sms_send_uri是全局变量,参数,请求头 conn.request("POST", sms_send_uri, params, headers) # 得到服务器的响应 response = conn.getresponse() # 获取响应的数据 response_str = response.read() # 关闭连接 conn.close() # 把验证码放进session中 request.session['message_code'] = message_code # print(eval(response_str.decode())) # 使用eval把字符串转为json数据返回 return JsonResponse(eval(response_str.decode())) def send_message(request): """发送信息的视图函数""" # 获取ajax的get方法发送过来的手机号码 mobile = request.GET.get('mobile') # 通过手机去查找用户是否已经注册 user = User.objects.filter(username=mobile) if len(user) == 1: return JsonResponse({'msg': "该手机已经注册"}) return message(request, mobile) def send_message2(request): """发送信息的视图函数""" # 获取ajax的get方法发送过来的手机号码 mobile = request.GET.get('mobile') # 通过手机去查找用户是否已经注册 user = User.objects.filter(username=mobile) if len(user) == 0: return JsonResponse({'msg': "该手机尚未注册"}) return message(request, mobile) # ----------------登录-------------------------------------------------------------------------- def my_login(request): if request.method == "POST": username = request.POST.get("username", "") password = request.POST.get("password", "") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('index') return render(request, 'login_register.html') def my_login_yz(request): if request.method == "POST": username = request.POST.get("username", "") code = request.POST.get("code", "") try: if code == request.session['message_code']: user = User.objects.get(username=username) if user is not None: login(request, user) return redirect('index') except: pass return render(request, 'login_register.html') def my_logout(request): logout(request) return redirect('index') # ----------------注册-------------------------------------------------------------------------- def my_register(request): if request.method == 'POST': if request.POST.get('code') == request.session['message_code']: u = User.objects.create_user(username=request.POST.get('mobile'), password=request.POST.get('password')) up = UserProfile.objects.get_or_create(user=u) return HttpResponse('注册成功') return render(request, 'login_register.html') # ------------------------- 车位--------------------------------------------- @login_required def park(request): s = '' try: u = UserProfile.objects.get(user=request.user) s = UserPrakSeat.objects.filter(user=u) except: pass ls = [] for t in s: temp = [t.pioaddress, t.note, t.price] string = '' if t.time02 == True: string = string + '00:00-02:00,' if t.time24 == True: string = string + '02:00-04:00,' if t.time46 == True: string = string + '04:00-06:00,' if t.time68 == True: string = string + '06:00-08:00,' if t.time810 == True: string = string + '08:00-10:00,' if t.time1012 == True: string = string + '10:00-12:00,' if t.time1214 == True: string = string + '12:00-14:00,' if t.time1416 == True: string = string + '14:00-16:00,' if t.time1618 == True: string = string + '16:00-18:00,' if t.time1820 == True: string = string + '18:00-20:00,' if t.time2022 == True: string = string + '20:00-22:00,' if t.time2224 == True: string = string + '22:00-24:00,' temp.append(string) temp.append(t.id) status = '' if t.status == '0': status = '未通过' elif t.status == '1': status = '审核通过' elif t.status == '2': status = '审核中' temp.append(status) ls.append(temp) return render(request, 'My_Park.html', {'seats': ls}) @login_required def park_detail(request, parkId): t = UserPrakSeat.objects.get(id=parkId) temp = [t.id, t.pioaddress, t.note, t.price] string = '' if t.time02 == True: string = string + '00:00-02:00,' if t.time24 == True: string = string + '02:00-04:00,' if t.time46 == True: string = string + '04:00-06:00,' if t.time68 == True: string = string + '06:00-08:00,' if t.time810 == True: string = string + '08:00-10:00,' if t.time1012 == True: string = string + '10:00-12:00,' if t.time1214 == True: string = string + '12:00-14:00,' if t.time1416 == True: string = string + '14:00-16:00,' if t.time1618 == True: string = string + '16:00-18:00,' if t.time1820 == True: string = string + '18:00-20:00,' if t.time2022 == True: string = string + '20:00-22:00,' if t.time2224 == True: string = string + '22:00-24:00,' temp.append(string) return render(request, 'My_Park_Detail.html', {'t': temp}) @csrf_exempt def park_change(request): id = request.POST.get('id') us = UserPrakSeat.objects.get(id=id) us.price = request.POST.get('price') # 修改原来的时间 us.time02 = False us.stat02 = False us.time24 = False us.stat24 = False us.time46 = False us.stat46 = False us.time68 = False us.stat68 = False us.time810 = False us.stat810 = False us.time1012 = False us.stat1012 = False us.time1214 = False us.stat1214 = False us.time1416 = False us.stat1416 = False us.time1618 = False us.stat1618 = False us.time1820 = False us.stat1820 = False us.time2022 = False us.stat2022 = False us.time2224 = False us.stat2224 = False # 添加时间 choiceTime = request.POST.get('choiceTime').split(',') choiceTime = [x[0:2] for x in choiceTime] # print(choiceTime) for t in choiceTime: if t == '00': us.time02 = True us.stat02 = True elif t == '02': us.time24 = True us.stat24 = True elif t == '04': us.time46 = True us.stat46 = True elif t == '06': us.time68 = True us.stat68 = True elif t == '08': us.time810 = True us.stat810 = True elif t == '10': us.time1012 = True us.stat1012 = True elif t == '12': us.time1214 = True us.stat1214 = True elif t == '14': us.time1416 = True us.stat1416 = True elif t == '16': us.time1618 = True us.stat1618 = True elif t == '18': us.time1820 = True us.stat1820 = True elif t == '20': us.time2022 = True us.stat2022 = True elif t == '22': us.time2224 = True us.stat2224 = True us.save() return HttpResponse("ok") @login_required def add_park(request): return render(request, 'My_Park_Add.html') @csrf_exempt def add_park_inform(request): informations = json.loads(request.POST.get('informations')) # print(informations, informations['latlng']) lat = informations['latlng']['lat'] lng = informations['latlng']['lng'] poiaddress = informations['poiaddress'] local_lat = request.session.get('local_lat', 29.818722) local_lng = request.session.get('local_lng', 121.563897) return render(request, 'My_Park_Add_Inform.html', { 'poiaddress': poiaddress, 'lat': lat, 'lng': lng, 'local_lat': local_lat, 'local_lng': local_lng }) @csrf_exempt def park_save(request): u = UserProfile.objects.get(user=request.user) informs = request.POST.get('informs') price = request.POST.get('price') lat = request.POST.get('lat') lng = request.POST.get('lng') poiaddress = request.POST.get('poiaddress') us = UserPrakSeat.objects.create(user=u, lat=lat, lng=lng, pioaddress=poiaddress, note=informs, price=int(price), status='2') choiceTime = request.POST.get('choiceTime').split(',') choiceTime = [x[0:2] for x in choiceTime] # print(choiceTime) for t in choiceTime: if t == '00': us.time02 = True us.stat02 = True elif t == '02': us.time24 = True us.stat24 = True elif t == '04': us.time46 = True us.stat46 = True elif t == '06': us.time68 = True us.stat68 = True elif t == '08': us.time810 = True us.stat810 = True elif t == '10': us.time1012 = True us.stat1012 = True elif t == '12': us.time1214 = True us.stat1214 = True elif t == '14': us.time1416 = True us.stat1416 = True elif t == '16': us.time1618 = True us.stat1618 = True elif t == '18': us.time1820 = True us.stat1820 = True elif t == '20': us.time2022 = True us.stat2022 = True elif t == '22': us.time2224 = True us.stat2224 = True us.save() return HttpResponse("ok") @login_required def park_check(request): return render(request, 'My_Park_Check.html') # --------------------- 车辆 --------------------------------------------------------------- @login_required def car_bind(request): u = UserProfile.objects.get(user=request.user) card = '' if len(u.licence_number) == 7: card = u.licence_number return render(request, 'My_Car_Bind.html', {'card': card}) @login_required def car_number(request): return render(request, 'My_Car_Number.html') @login_required def car_save(request): u = UserProfile.objects.get(user=request.user) try: p = request.GET.get('value') except: pass else: if len(p) == 7: u.licence_number = p u.save() return redirect('car_bind') @login_required def car_delete(request): u = UserProfile.objects.get(user=request.user) u.licence_number = '' u.save() return redirect('car_bind') # --------------------- 钱包 --------------------------------------------------------------- @login_required def my_wallet(request): u = UserProfile.objects.get(user=request.user) money = u.account return render(request, 'My_Wallet.html', {'money': money}) @login_required def my_wallet_invest(request): return render(request, 'My_Wallet_Invest.html') @login_required def my_wallet_pay(request, number): u = UserProfile.objects.get(user=request.user) u.account = float(u.account) + float(int(number)) u.save() w = WalletDetail() w.user = u w.source = '充值' w.price = float(int(number)) w.status = False w.save() return redirect('wallet') # return render(request, 'My_Wallet_Pay.html') @login_required def ddpay(request): return render(request, 'ddpay.html') @login_required def my_wallet_datail(request): details = WalletDetail.objects.filter(user=UserProfile.objects.get(user=request.user)) return render(request, 'My_Wallet_Detail.html', {'details': details}) @login_required def my_wallet_datail_more(request, walletId): d = WalletDetail.objects.get(id=walletId) return render(request, 'My_Wallet_Detail_More.html', {'detail': d}) # --------------------- 主功能:车位详情-生成订单 --------------------------------------------------------------- @login_required def park_info(request, parkId): up = UserPrakSeat.objects.get(id=parkId) time_list = [] if up.stat02 == True: time_list.append('00:00-02:00') if up.stat24 == True: time_list.append('02:00-04:00') if up.stat46 == True: time_list.append('04:00-06:00') if up.stat68 == True: time_list.append('06:00-08:00') if up.stat810 == True: time_list.append('08:00-10:00') if up.stat1012 == True: time_list.append('10:00-12:00') if up.stat1214 == True: time_list.append('12:00-14:00') if up.stat1416 == True: time_list.append('14:00-16:00') if up.stat1618 == True: time_list.append('16:00-18:00') if up.stat1820 == True: time_list.append('18:00-20:00') if up.stat2022 == True: time_list.append('20:00-22:00') if up.stat2224 == True: time_list.append('22:00-24:00') return render(request, 'Park_Info.html', {'parkinfo': up, 'timeList': time_list}) @csrf_exempt def put_order(request): test = Order.objects.filter(Q(user=UserProfile.objects.get(user=request.user)) & Q(status='0')) # 如果存在一个进行中的订单 if test: return redirect('order') # 如果余额为负数 if UserProfile.objects.get(user=request.user).account < 0: return redirect('order') ls = request.POST.getlist('chongzhi1') string = '' # 改变 车位的时间锁定 seat = UserPrakSeat.objects.get(id=request.POST.get('ids')) for t in ls: string = string + t + ',' temp = t[:2] if temp == '00': seat.stat02 = False elif temp == '02': seat.stat24 = False elif temp == '04': seat.stat46 = False elif temp == '06': seat.stat68 = False elif temp == '08': seat.stat810 = False elif temp == '10': seat.stat1012 = False elif temp == '12': seat.stat1214 = False elif temp == '14': seat.stat1416 = False elif temp == '16': seat.stat1618 = False elif temp == '18': seat.stat1820 = False elif temp == '20': seat.stat2022 = False elif temp == '22': seat.stat2224 = False seat.save() # 提交订单 o = Order() o.user = UserProfile.objects.get(user=request.user) o.source = seat o.price = request.POST.get('sum_price') o.order_time = string o.save() return redirect('order') # --------------------- 订单 --------------------------------------------------------------- @login_required def order(request): u = UserProfile.objects.get(user=request.user) finish = Order.objects.filter(Q(status='1') & Q(user=u)) now = Order.objects.filter(Q(status='0') & Q(user=u)) cancel = Order.objects.filter(Q(status='2') & Q(user=u)) # print(finish, now, cancel) t = '' if now: t= now[0] return render(request, 'My_Orders.html', { 'finish': finish, 'now': t, 'cancel': cancel }) @login_required def cancel_order(request): u = UserProfile.objects.get(user=request.user) n = Order.objects.filter(Q(status='0') & Q(user=u)) myclock = n[0].order_time[:2] nowclock = time.strftime("%H", time.localtime()) print(nowclock, int(nowclock), myclock, nowclock < myclock) if int(nowclock) < int(myclock): tt = Order.objects.get(id=n[0].id) tt.status = '2' print(tt.status) tt.save() print(tt.status) seat = UserPrakSeat.objects.get(id=tt.source.id) # 车位的时间使用状态对应订单里的order_time改变为True; times = tt.order_time.split(',') # print(times[:-1]) for temp in times[:-1]: temp = temp[:2] if temp == '00': seat.stat02 = True elif temp == '02': seat.stat24 = True elif temp == '04': seat.stat46 = True elif temp == '06': seat.stat68 = True elif temp == '08': seat.stat810 = True elif temp == '10': seat.stat1012 = True elif temp == '12': seat.stat1214 = True elif temp == '14': seat.stat1416 = True elif temp == '16': seat.stat1618 = True elif temp == '18': seat.stat1820 = True elif temp == '20': seat.stat2022 = True elif temp == '22': seat.stat2224 = True seat.save() return redirect('order') @login_required def self_lock(request, parkId): t = Lock_Seat.objects.get(seat=UserPrakSeat.objects.get(id=parkId)) return render(request, 'Self_Lock.html', {'parkid': parkId, 'status': t.status}) @login_required def self_lock_lock(request, parkId): t = Lock_Seat.objects.get(seat=UserPrakSeat.objects.get(id=parkId)) t.status = True t.save() return redirect('self_lock', parkId=parkId) @login_required def self_lock_unlock(request, parkId): t = Lock_Seat.objects.get(seat=UserPrakSeat.objects.get(id=parkId)) t.status = False t.save() return redirect('self_lock', parkId=parkId) @login_required def lock(request, parkId, orderId): t = Lock_Seat.objects.get(seat=UserPrakSeat.objects.get(id=parkId)) return render(request, 'Lock.html', {'parkid': parkId, 'status': t.status, 'orderid': orderId}) @login_required @csrf_exempt def lock_start(request): # 开始订单,同时解锁 try: parkId = request.POST.get('pid') seat = UserPrakSeat.objects.get(id=parkId) t = Lock_Seat.objects.get(seat=seat) t.status = False t.save() o = Order.objects.get(id=request.POST.get('oid')) o.start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) o.save() return HttpResponse("ok") except Exception as e: print(e) return HttpResponse("error") @csrf_exempt def lock_stop(request): # 结束订单,同时上锁;改变订单的结束时间、价钱、状态显示完成1;车锁对应表改变状态为True锁定; try: # 车位的时间使用状态对应订单里的order_time改变为True;钱包余额扣款;钱包明细增加。 parkId = request.POST.get('pid') # 改变订单的结束时间、价钱、状态显示完成1; o = Order.objects.get(id=request.POST.get('oid')) seat = UserPrakSeat.objects.get(id=parkId) nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) nowTime = datetime.datetime.strptime(nowTime, '%Y-%m-%d %H:%M:%S') x = int(o.order_time[:2]) o.end_time = nowTime print(o.start_time, nowTime, x) cha_time = nowTime - o.start_time print(cha_time.days, cha_time.seconds) price = 0.00 msg ='' n = 1 if cha_time.days > 0: price = seat.price * 24 msg = ':由于您时间超时,按24小时停车扣款' else: sum = int(cha_time.seconds) + 3600 n = int(sum / 3600) print('*-', int(sum / 3600)) price = seat.price * n o.price = price o.status = '1' print('n=', n, price, '-------') # 车位的时间使用状态对应订单里的order_time改变为True; times = o.order_time.split(',') # print(times[:-1]) for temp in times[:-1]: temp = temp[:2] if temp == '00': seat.stat02 = True elif temp == '02': seat.stat24 = True elif temp == '04': seat.stat46 = True elif temp == '06': seat.stat68 = True elif temp == '08': seat.stat810 = True elif temp == '10': seat.stat1012 = True elif temp == '12': seat.stat1214 = True elif temp == '14': seat.stat1416 = True elif temp == '16': seat.stat1618 = True elif temp == '18': seat.stat1820 = True elif temp == '20': seat.stat2022 = True elif temp == '22': seat.stat2224 = True # 车锁对应表改变状态为True锁定; t = Lock_Seat.objects.get(seat=seat) t.status = True # 钱包余额扣款;钱包明细增加。 # 付款的人 u = UserProfile.objects.get(user=request.user) u.account = u.account - price u.save() uw = WalletDetail() uw.user = u uw.source = '车位编号:P' + str(seat.id) uw.price = price uw.note = '停车扣款' + msg # 收款的人 seat.user.account = seat.user.account + Decimal(float(price)*0.8) sw = WalletDetail() sw.user = seat.user sw.source = '车位收入:P' + str(seat.id) sw.price = Decimal.from_float(float(price) * 0.8) sw.status = False sw.note = '车位收入:扣除20%的手续费' # 存数据 o.save() seat.save() t.save() u.save() uw.save() seat.user.save() sw.save() return HttpResponse("ok") except Exception as e: print(e) return HttpResponse("error") # ----------------qita------------------------------------------------------------------------- def test(request): return render(request, 'base.html') <file_sep>/park/forms.py from park.models import * from django import forms <file_sep>/park/migrations/0006_auto_20190626_1716.py # Generated by Django 2.2.2 on 2019-06-26 17:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('park', '0005_auto_20190626_1514'), ] operations = [ migrations.CreateModel( name='CarLock', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=1024)), ('status', models.BooleanField(default=True)), ('note', models.CharField(blank=True, max_length=1024)), ], ), migrations.RemoveField( model_name='userprofile', name='has_seat', ), migrations.RemoveField( model_name='userprofile', name='id_number', ), migrations.RemoveField( model_name='userprofile', name='seat_number', ), migrations.CreateModel( name='Lock_Seat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.BooleanField(default=False)), ('lock', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='carlock', to='park.CarLock')), ('seat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='park.UserPrakSeat')), ], ), ] <file_sep>/README.md # HelloPark Hello-Park, the first try. <file_sep>/venv/Lib/site-packages/gmapify/templatetags/gmapify.py from django import template register = template.Library() @register.inclusion_tag('gmapify/map.html') def gmapify(html_id, lat, lng, **kwargs): """ {% gmapify <html_id> <lat> <lng> [zoom=<zoom>] [map_type=<map_type>] [marker_title=<marker_title>] %} """ zoom = kwargs.get('zoom', 15) map_type = kwargs.get('map_type', 'ROADMAP') marker_title = kwargs.get('marker_title') data = { 'html_id': html_id, 'lat': lat, 'lng': lng, 'zoom': zoom, 'map_type': map_type } if marker_title: data['marker_title'] = marker_title return data <file_sep>/park/migrations/0004_auto_20190625_2306.py # Generated by Django 2.2.2 on 2019-06-25 23:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('park', '0003_userprakseat_status'), ] operations = [ migrations.AddField( model_name='userprakseat', name='stat02', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat1012', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat1214', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat1416', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat1618', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat1820', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat2022', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat2224', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat24', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat46', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat68', field=models.BooleanField(default=False), ), migrations.AddField( model_name='userprakseat', name='stat810', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='order', name='status', field=models.CharField(default='0', max_length=32), ), ] <file_sep>/park/migrations/0002_order_userprakseat_walletdetail.py # Generated by Django 2.2.2 on 2019-06-25 13:13 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('park', '0001_initial'), ] operations = [ migrations.CreateModel( name='WalletDetail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('source', models.CharField(max_length=500)), ('price', models.DecimalField(decimal_places=2, max_digits=10)), ('status', models.BooleanField(default=True)), ('time', models.DateTimeField(default=django.utils.timezone.now)), ('note', models.CharField(blank=True, max_length=1024)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='park.UserProfile')), ], ), migrations.CreateModel( name='UserPrakSeat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('lat', models.DecimalField(decimal_places=6, max_digits=12)), ('lng', models.DecimalField(decimal_places=6, max_digits=12)), ('pioaddress', models.CharField(blank=True, max_length=512)), ('note', models.CharField(blank=True, max_length=2048)), ('price', models.DecimalField(decimal_places=2, max_digits=10)), ('time02', models.BooleanField(default=False)), ('time24', models.BooleanField(default=False)), ('time46', models.BooleanField(default=False)), ('time68', models.BooleanField(default=False)), ('time810', models.BooleanField(default=False)), ('time1012', models.BooleanField(default=False)), ('time1214', models.BooleanField(default=False)), ('time1416', models.BooleanField(default=False)), ('time1618', models.BooleanField(default=False)), ('time1820', models.BooleanField(default=False)), ('time2022', models.BooleanField(default=False)), ('time2224', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='park.UserProfile')), ], ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.DecimalField(decimal_places=2, max_digits=10)), ('time', models.DateTimeField(default=django.utils.timezone.now)), ('status', models.BooleanField(default=False)), ('note', models.CharField(blank=True, max_length=1024)), ('source', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_source', to='park.UserProfile')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='park.UserProfile')), ], ), ] <file_sep>/park/models.py from django.db import models from django.contrib.auth.models import User import django.utils.timezone as timezone # 用户数据表 class UserProfile(models.Model): # 建立与User模型之间的关系. 账户名即为手机号 user = models.OneToOneField(User, on_delete=models.CASCADE) # 想增加的属性 account = models.DecimalField(max_digits=7, decimal_places=2, default=0.00) # gender = models.BooleanField(default=True) # 性别:默认男 # qq = models.CharField(max_length=12) # weixin = models.CharField(max_length=20) licence_number = models.CharField(max_length=20) # 车牌号 # has_seat = models.BooleanField(default=False) # 是否有注册车位 # seat_number = models.CharField(max_length=40) # 车位号 # id_number = models.CharField(max_length=18) # 身份证 def __str__(self): return self.user.username # 用户停车位 class UserPrakSeat(models.Model): user = models.ForeignKey('UserProfile', on_delete=models.CASCADE) lat = models.DecimalField(max_digits=12, decimal_places=6, blank=False) # 坐标 lng = models.DecimalField(max_digits=12, decimal_places=6, blank=False) # 坐标 pioaddress = models.CharField(max_length=512, blank=True) # 位置描述 note = models.CharField(max_length=2048, blank=True) # 详细描述 # 每两个小时单价 price = models.DecimalField(max_digits=10, decimal_places=2, blank=False) # 开放时间选择 time02 = models.BooleanField(default=False) # 开放时间选择:0:00-02:00 time24 = models.BooleanField(default=False) time46 = models.BooleanField(default=False) time68 = models.BooleanField(default=False) time810 = models.BooleanField(default=False) time1012 = models.BooleanField(default=False) time1214 = models.BooleanField(default=False) time1416 = models.BooleanField(default=False) time1618 = models.BooleanField(default=False) time1820 = models.BooleanField(default=False) time2022 = models.BooleanField(default=False) time2224 = models.BooleanField(default=False) # 使用状态 stat02 = models.BooleanField(default=False) # 默认有人使用 stat24 = models.BooleanField(default=False) stat46 = models.BooleanField(default=False) stat68 = models.BooleanField(default=False) stat810 = models.BooleanField(default=False) stat1012 = models.BooleanField(default=False) stat1214 = models.BooleanField(default=False) stat1416 = models.BooleanField(default=False) stat1618 = models.BooleanField(default=False) stat1820 = models.BooleanField(default=False) stat2022 = models.BooleanField(default=False) stat2224 = models.BooleanField(default=False) # 审核状态 status = models.CharField(max_length=32, default='0') # 默认审核未通过0;审核通过1;审核中2; # 停车位数据表 # class ParkSeat(models.Model): # # id车位编号 # owner_id = models.ForeignKey("UserProfile", on_delete=models.CASCADE) # 车位主编号 # parking_lot = models.CharField(max_length=40) # 停车场 # floor = models.IntegerField() # 停车库 # seat_number = models.CharField(max_length=40) # 车位号 # coodinates = models.DecimalField(max_digits=12, decimal_places=6, blank=False) # 坐标 # district = models.CharField(max_length=50) # 街区 # status = models.BooleanField(default=True) # 占空状态,默认占用 # price = models.DecimalField(max_digits=3, decimal_places=1, blank=False) # 单价 # open_time = models.CharField(max_length=400) # 开放时间 # detail = models.CharField(max_length=1024) # 详细说明 # # # # 停车场数据表 # class Park(models.Model): # # 停车场编号、名称、坐标、开放时间 # name = models.CharField(max_length=40) # coordinate = models.DecimalField(max_digits=12, decimal_places=6, blank=False) # open_time = models.CharField(max_length=400) # 开放时间 # 钱包明细表 class WalletDetail(models.Model): user = models.ForeignKey('UserProfile', on_delete=models.CASCADE) source = models.CharField(max_length=500, blank=False) # 汇款人/支付对象;格式:“车位编号:P1”,“车位收入:P1” price = models.DecimalField(max_digits=10, decimal_places=2, blank=False) status = models.BooleanField(default=True) # 默认支出 time = models.DateTimeField(default=timezone.now) note = models.CharField(max_length=1024, blank=True) # 备注 # 用户订单表 class Order(models.Model): user = models.ForeignKey('UserProfile', on_delete=models.CASCADE) source = models.ForeignKey('UserPrakSeat', on_delete=models.CASCADE, related_name='user_source') # 车位 price = models.DecimalField(max_digits=10, decimal_places=2, blank=False) order_time = models.CharField(max_length=2048, blank=True) # 订单计费开始时间 start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(default=timezone.now) time = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=32, default='0') # 默认进行中0;已完成1;已取消2; note = models.CharField(max_length=1024, blank=True) # 备注 # 车位锁 class CarLock(models.Model): name = models.CharField(max_length=1024, blank=False) # 车锁名字 status = models.BooleanField(default=True) # 车位锁能否使用 note = models.CharField(max_length=1024, blank=True) # 备注 # 车锁对应表 class Lock_Seat(models.Model): lock = models.ForeignKey('CarLock', on_delete=models.CASCADE, related_name='carlock') seat = models.ForeignKey('UserPrakSeat', on_delete=models.CASCADE) status = models.BooleanField(default=False) # 车位锁状态,默认锁关闭 <file_sep>/park/admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(UserProfile) admin.site.register(UserPrakSeat) admin.site.register(WalletDetail) admin.site.register(Order) admin.site.register(CarLock) admin.site.register(Lock_Seat) <file_sep>/park/migrations/0009_auto_20190627_1554.py # Generated by Django 2.2.2 on 2019-06-27 15:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('park', '0008_auto_20190627_1020'), ] operations = [ migrations.RemoveField( model_name='userprofile', name='gender', ), migrations.RemoveField( model_name='userprofile', name='qq', ), migrations.RemoveField( model_name='userprofile', name='weixin', ), ] <file_sep>/park/migrations/0003_userprakseat_status.py # Generated by Django 2.2.2 on 2019-06-25 14:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('park', '0002_order_userprakseat_walletdetail'), ] operations = [ migrations.AddField( model_name='userprakseat', name='status', field=models.CharField(default='0', max_length=32), ), ]
06003fe4fa2044a02a8b6b2bc3ea1659ad62fa6d
[ "Markdown", "Python" ]
13
Python
SpringBlossomsy/HelloPark
87c5746aa88090e4d762e92a93ea542f82fd0370
229b5225e95faec4ade2e199ffc4bdd48cd78201
refs/heads/main
<file_sep># pset3 Cosyne 2021 RNN tutorial pset3 <file_sep>#!/usr/bin/env python3 """ ipython from PINningDevIdealBump import wrap wrap(plot=True) """ import datetime import math import numpy as np import scipy.io import matplotlib.pyplot as plt def wrap(bottled_noise=False, learn=True, run=True, save=False, plot=False): if plot is True: plt.ion() if bottled_noise is True: loaded = scipy.io.loadmat('shared_randoms.mat') g = 1.5 nRunTot = 125 nFree = 5 dtData = 0.0641 dt = 0.001 # integration step tau = 0.01 # 10ms time constant P0 = 1 tauWN = 1 ampIn = 1 N = 500 nLearn = 50 epochs = 165 if bottled_noise is True: learnList = loaded['learnList'].astype(int) - 1 learnList = learnList.ravel() else: learnList = np.random.permutation(N) cL = learnList[0:nLearn] assert(cL.size == nLearn) assert(cL.shape == (nLearn,)) nCL = learnList[nLearn:] tData = np.arange(0, (epochs+1)*dtData, dtData) t = np.arange(0, tData[-1], dt) xBump = np.zeros((N, len(tData))) sig = 0.0343*N # % scaled correctly in neuron space!!! for i in range(N): xBump[i, :] = np.exp(-((float(i+1) - N * tData / tData[-1]) ** 2.0) / (2 * sig ** 2)) hBump = np.log((xBump + 0.01)/(1 - xBump + 0.01)) # current from rate ampWN = math.sqrt(tauWN/dt) if bottled_noise is True: iWN = ampWN*loaded['wn_rand'] else: iWN = ampWN*np.random.randn(N, len(t)) input = np.ones((N, len(t))) for tt in range(1, len(t)): input[:, tt] = iWN[:, tt] + (input[:, tt - 1] - iWN[:, tt])*np.exp(- (dt / tauWN)) input = ampIn*input noiseLevel = 0.5 sigN = noiseLevel * math.sqrt(tau / dt) if bottled_noise is True: J = g * loaded['weights_rand'] / math.sqrt(N) else: J = g * np.random.randn(N, N) / math.sqrt(N) J0 = J.copy() R = np.zeros((N, len(t))) JR = np.zeros((N, 1)) # if save is True: # timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M") # with open('initials_{}.npz'.format(timestamp) , 'wb') as outfile: # np.savez(outfile, xBump=xBump, hBump=hBump, J0=J0, input=input) if run is True: if learn is True: PJ = P0 * np.eye(nLearn, nLearn) rightTrial = False for nRun in range(0, nRunTot): print(nRun) H = xBump[:, 0, np.newaxis] tLearn = 0 iLearn = 1 for tt in range(1, len(t)): tLearn = tLearn + dt R[:, tt, np.newaxis] = 1/(1+np.exp(-H)) if bottled_noise is True: noise = loaded['stupid_rand'] else: noise = np.random.randn(N, 1) JR = input[:, tt, np.newaxis] + sigN * noise + J.dot(R[:, tt]).reshape((N, 1)) H = H + dt * (-H + JR) / tau if learn is True and tLearn >= dtData and nRun < (nRunTot - nFree): tLearn = 0 err = JR[0:N, :] - hBump[0:N, iLearn, np.newaxis] iLearn = iLearn + 1 r_slice = R[cL, tt].reshape(nLearn, 1) k = PJ.dot(r_slice) rPr = (r_slice).T.dot(k)[0, 0] c = 1.0/(1.0 + rPr) PJ = PJ - c*(k.dot(k.T)) J[0:N, cL.flatten()] = J[:, cL.reshape((nLearn))] - c*np.outer(err.flatten(), k.flatten()) if plot is True: plt.clf() plt.imshow(R/R.max()) plt.colorbar() plt.gca().set_aspect(15, adjustable='box') plt.draw() plt.pause(0.1) if save is True: timestamp = datetime.datetime.now().strftime("%Y%m%dT%H%M") with open('finals_{}.npz'.format(timestamp) , 'wb') as outfile: np.savez(outfile, J=J, err=err, R=R) if __name__ == '__main__': # wrap(run=True, learn=True, save=True, bottled_noise=True) wrap(run=True, learn=True)
0c8c5dd1384a2f5211df62f53c4a6658490f7630
[ "Markdown", "Python" ]
2
Markdown
rajanlab/pset3
af09e69661ebdedfc936b10f61d8e57158fe25e0
f5eb1a7bc7f8cfec5a8f9cefc64313fd4158e74f
refs/heads/master
<file_sep>const dotenv = require("dotenv"); const sqlite3 = require("sqlite3").verbose(); const async = require("async"); dotenv.config(); const httpOptions = { method: "GET", headers: { accept: "application/json", "api-key": process.env.API_KEY, }, }; async function doFetch({ endpoint }) { const response = await fetch( `https://api.sendinblue.com/v3/${endpoint}`, httpOptions ); return await response.json(); } async function getContactIds() { const contactsInfo = await doFetch({ endpoint: "contacts?limit=1" }); const numberOfContacts = contactsInfo.count; console.log(`Retrieving ${numberOfContacts} contacts...`); const limit = 1000; const allContacts = []; for (let offset = 0; offset < numberOfContacts; offset += limit) { const contacts = await doFetch({ endpoint: `contacts?limit=${limit}&offset=${offset}`, limit, offset, }); allContacts.push(...contacts.contacts.map((contact) => contact.id)); console.log(` ...${allContacts.length} / ${numberOfContacts}`); } return allContacts; } const getContactEvents = (progress, contactId) => async (timePeriod) => { const contactEvents = await doFetch({ endpoint: `contacts/${contactId}/campaignStats?startDate=${timePeriod[0]}&endDate=${timePeriod[1]}`, }); const events = []; if (contactEvents.delivered) { events.push( ...contactEvents.delivered.map((event) => { return { contactId, campaignId: event.campaignId, time: event.eventTime, type: "delivered", }; }) ); } if (contactEvents.opened) { events.push( ...contactEvents.opened.map((event) => { return { contactId, campaignId: event.campaignId, count: event.count, time: event.eventTime, // don't include event.ip type: "opened", }; }) ); } if (contactEvents.clicked) { for (const event of contactEvents.clicked) { for (const link of event.links) { events.push({ contactId, campaignId: event.campaignId, count: link.count, time: link.eventTime, link: link.url, type: "clicked", }); } } } progress.increment(); return events; }; async function saveEventsToDB(events) { const db = new sqlite3.Database("sib.db"); db.serialize(function () { db.run("DROP TABLE IF EXISTS events"); db.run(` CREATE TABLE events ( contactId INTEGER NOT NULL, campaignId INTEGER NOT NULL, count INTEGER, time DATETIME NOT NULL, link TEXT, type TEXT NOT NULL ); `); console.log("Inserting events into DB..."); db.run("begin transaction"); for (const [index, event] of events.entries()) { db.run( ` INSERT INTO events (contactId, campaignId, count, time, link, type) VALUES (${event.contactId}, ${event.campaignId}, ${event.count || "NULL"}, "${ event.time }", "${event.link || "NULL"}", "${event.type}"); ` ); console.log(`...${index + 1} / ${events.length}`); } db.run("commit"); }); db.close(); } class Progress { constructor(total) { this.total = total; this.current = 0; } increment() { this.current += 1; console.log(this.current, "/", this.total); } } async function extractContactData() { const timePeriods = [ ["2022-01-01", "2022-03-31"], ["2022-04-01", "2022-06-29"], ["2022-06-30", "2022-09-28"], ["2022-09-29", "2022-12-28"], ["2022-12-29", "2023-03-12"], ]; const contactIds = await getContactIds(); console.log("Retrieving contact events..."); const maxParallel = 15; const progress = new Progress(contactIds.length * timePeriods.length); const events = await async.concatLimit( contactIds, maxParallel, async (contactId) => await async.concatSeries( timePeriods, getContactEvents(progress, contactId) ) ); console.log(events); if (events.length > 0) { await saveEventsToDB(events); } } async function getCampaigns() { const campaignsInfo = await doFetch({ endpoint: "emailCampaigns?status=sent&limit=1", }); const numberOfCampaigns = campaignsInfo.count; console.log(`Retrieving ${numberOfCampaigns} campaigns...`); const limit = 100; const allCampaigns = []; for (let offset = 0; offset < numberOfCampaigns; offset += limit) { const campaigns = await doFetch({ endpoint: `emailCampaigns?status=sent&limit=${limit}&offset=${offset}`, limit, offset, }); allCampaigns.push( ...campaigns.campaigns.map((campaign) => { return { id: campaign.id, name: campaign.name, sentDate: campaign.sentDate, subject: campaign.subject, testSent: campaign.testSent, type: campaign.type, status: campaign.status, }; }) ); console.log(` ...${allCampaigns.length} / ${numberOfCampaigns}`); } return allCampaigns; } async function saveCampaignsToDB(campaigns) { const db = new sqlite3.Database("sib.db"); db.serialize(function () { db.run("DROP TABLE IF EXISTS campaigns"); db.run(` CREATE TABLE campaigns ( id INTEGER NOT NULL, name TEXT NOT NULL, sentDate DATETIME NOT NULL, subject TEXT NOT NULL, testSent BOOLEAN, type TEXT NOT NULL, status TEXT NOT NULL ); `); console.log("Inserting campaigns into DB..."); db.run("begin transaction"); for (const [index, campaign] of campaigns.entries()) { db.run( ` INSERT INTO campaigns (id, name, sentDate, subject, testSent, type, status) VALUES (${campaign.id}, "${campaign.name}", "${campaign.sentDate}", "${campaign.subject}", ${campaign.testSent}, "${campaign.type}", "${campaign.status}"); ` ); console.log(`...${index + 1} / ${campaigns.length}`); } db.run("commit"); }); db.close(); } async function extractCampaignData() { const campaigns = await getCampaigns(); if (campaigns.length > 0) { await saveCampaignsToDB(campaigns); } } async function main() { await extractContactData(); await extractCampaignData(); } main(); <file_sep>SELECT contactId, date(campaigns.sentDate, 'start of month') as month, count(*) as total, case when (count(*) >= 1) then 1 else 0 end as open_1, case when (count(*) >= 5) then 1 else 0 end as open_5 FROM events LEFT JOIN campaigns ON events.campaignId = campaigns.id WHERE events."type" = 'opened' AND campaigns.sentDate >= "2022-01-01" AND campaigns.sentDate <= "2023-03-12" GROUP BY contactId, date(campaigns.sentDate, 'start of month') ORDER BY contactId, month; SELECT contactId, sum(open_at_least_1_per_month), sum(open_at_least_5_per_month) FROM ( SELECT contactId, date(campaigns.sentDate, 'start of month') as month, count(*) as total, case when (count(*) >= 1) then 1 else 0 end as open_at_least_1_per_month, case when (count(*) >= 5) then 1 else 0 end as open_at_least_5_per_month FROM events LEFT JOIN campaigns ON events.campaignId = campaigns.id WHERE events."type" = 'opened' AND campaigns.sentDate >= "2022-01-01" AND campaigns.sentDate <= "2022-12-31" GROUP BY contactId, date(campaigns.sentDate, 'start of month') ORDER BY contactId, month) GROUP BY contactId; SELECT type_mailing, count(*) as nb_contacts_who_opened_at_least_one_NL_in_the_year, sum(open_at_least_1_per_month_each_month) as nb_contacts_who_opened_at_least_one_NL_each_month, sum(open_at_least_5_per_month_each_month) as nb_contacts_who_opened_at_least_5_NL_each_month from ( SELECT contactId, case when (sum(open_at_least_1_per_month) = 12) then 1 else 0 end as open_at_least_1_per_month_each_month, case when (sum(open_at_least_5_per_month) = 12) then 1 else 0 end as open_at_least_5_per_month_each_month, type_mailing FROM ( SELECT contactId, date(campaigns.sentDate, 'start of month') as month, count(*) as total, case when (count(*) >= 1) then 1 else 0 end as open_at_least_1_per_month, case when (count(*) >= 5) then 1 else 0 end as open_at_least_5_per_month, case when (campaigns.subject LIKE "%contact.VILLE%") then "VILLE" else "ACTU" end as type_mailing FROM events LEFT JOIN campaigns ON events.campaignId = campaigns.id WHERE events."type" = 'opened' AND campaigns.sentDate >= "2022-01-01" AND campaigns.sentDate <= "2022-12-31" GROUP BY contactId, date(campaigns.sentDate, 'start of month'), type_mailing ORDER BY contactId, month) GROUP BY contactId, type_mailing) GROUP BY type_mailing; SELECT count(distinct(contactId)) as nb_contacts_who_received_at_least_one_NL_in_the_year, case when (campaigns.subject LIKE "%contact.VILLE%") then "VILLE" else "ACTU" end as type_mailing FROM events LEFT JOIN campaigns ON events.campaignId = campaigns.id WHERE events."type" = 'delivered' AND campaigns.sentDate >= "2022-01-01" AND campaigns.sentDate <= "2022-12-31" GROUP BY type_mailing; <file_sep># Export data Sendinblue et analyse des données - Script nodejs d'export des données de campagne et d'événements des contacts SendInBlue dans une base sqlite, via : ```javascript yarn node process_data.js ``` - requêtes d'analyse des données de la base sqlite dans le fichier `data_analysis.sql`. <file_sep>#!/bin/bash set -u set -x set -o pipefail WORKING_DIR=$(pwd) SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) echo "---- Starting migration in dir $WORKING_DIR" git checkout -b sre/migrate-to-kube-workflow mkdir -p .kube-workflow/common/templates for e in dev preprod prod do mkdir -p .kube-workflow/env/$e/templates done mv .socialgouv/chart/values.project.yaml .kube-workflow/common/values.yaml for e in dev preprod prod do mv .socialgouv/environments/$e/*.{configmap,sealed-secret}.yaml .kube-workflow/env/$e/templates done for file in review preproduction production do if ! grep -q "kube-workflow" ".github/workflows/$file.yml"; then cp $SCRIPT_DIR/.github/workflows/$file.yml .github/workflows/$file.yml fi done mv .socialgouv/__tests__ .kube-workflow/__tests__ git add .kube-workflow git add .socialgouv git add .github
aa8c5d40a5d7c5596e55e0d8927bcd5d60afa3cb
[ "JavaScript", "SQL", "Markdown", "Shell" ]
4
JavaScript
SocialGouv/sre-scripts
b261137218a92e3190fc51833166462244509db1
4b9de62030000f8787a41607a9d9363877f65537
refs/heads/master
<repo_name>askito/askito<file_sep>/app/models/display_element.rb class DisplayElement < Content end <file_sep>/app/models/content.rb class Content < ActiveRecord::Base belongs_to :questionnaire has_many :options, :foreign_key => 'question_id', :order => 'options.position', :dependent => :destroy has_many :answers, :foreign_key => 'question_id' has_many :answer_texts, :foreign_key => 'question_id' has_many :answer_dates, :foreign_key => 'question_id' acts_as_list :order => 'contents.position' # acts_as_textiled :text serialize :settings named_scope :pagebreaks, lambda{{ :conditions => "template = 'pagebreak'", :order => 'contents.position' }} named_scope :between_positions, lambda{|i,j|{ :conditions => ["contents.position BETWEEN ? AND ?", i + 1, j - 1] }} def copy Content.new(self.attributes.reject{|key,value| exclude_attributes_from_duplication.include?(key)}) end def exclude_attributes_from_duplication %w[id type created_at updated_at code questionnaire_id] end end <file_sep>/lib/save_answer_texts.rb module SaveAnswerTexts def new_answer_text_attributes=(answer_text_attributes) answer_texts_on_current_page.reject{|at| !at.new_record?}.each do |answer_text| value = answer_text_attributes[answer_text.question.id.to_s] assign_answer_text(answer_text, value) end end def existing_answer_text_attributes=(answer_text_attributes) answer_texts_on_current_page.reject(&:new_record?).each do |answer_text| value = answer_text_attributes[answer_text.id.to_s] assign_answer_text(answer_text, value) end end protected def assign_answer_text(answer_text, value) answer_text.value = value if value.blank? && answer_text.valid? answer_texts.delete(answer_text) answer_texts_on_current_page.delete(answer_text) end end def save_answer_texts answer_texts_on_current_page.each(&:save) end end<file_sep>/app/controllers/contents_controller.rb class ContentsController < ApplicationController before_filter :find_questionnaire before_filter :find_content, :only => [:edit, :update, :destroy] # skip_before_filter :verify_authenticity_token, :only => [:sort] def new if template = find_content_type @content = new_content(:questionnaire => @questionnaire, :template => template) @content.assets.build if template == 'image' @successful = true end end def edit end def create # if template = find_content_type # @content = new_content(:questionnaire => @questionnaire, :template => template) # save # end # render :text => params.inspect @content = new_content(:questionnaire => @questionnaire) save end def update save # render :text => params.inspect end def destroy @content.destroy respond_to do |wants| wants.html { redirect_to @questionnaire } wants.js end end def sort if request.xhr? params[:contents].each_with_index do |id, position| Content.update(id, :position => position + 1) end render :nothing => true end end protected def find_questionnaire @questionnaire = Questionnaire.find(params[:questionnaire_id]) end def find_content @content = @questionnaire.contents.find(params[:id]) instance_variable_set("@#{@content.class.name.underscore}", @content) end def save @content.attributes = content_params @content.save! respond_to do |wants| wants.html { redirect_to @questionnaire } wants.js { @successful = true } end rescue ActiveRecord::RecordInvalid respond_to do |wants| wants.html { render_invalid_record(@content) } wants.js { @successful = false } end end end <file_sep>/app/helpers/questionnaires_helper.rb module QuestionnairesHelper def questionnaire_tab_items items = [] items << ['Design', url_for(@questionnaire)] items << ['Settings', ''] items << ['Collect data', ''] items << ['Analyze', ''] items << ['Export', ''] end def arrange_contents_link arrange_text = icon(:sort, "Sort contents") arrange_text += content_tag("span","Sort") done_text = icon(:save) done_text += content_tag("span","Done") link_to_function "#{arrange_text}", toggle_contents + "if(this.down('span').innerHTML == 'Done'){ this.innerHTML = '#{arrange_text}'; } else { this.innerHTML = '#{done_text}'; }" end def toggle_contents "$$('.content').each( function(el){ if(el.hasClassName('drag')){ el.removeClassName('drag') } else { el.addClassName('drag') } el.childElements().each( function(innerEl){ if(!innerEl.hasClassName('text')){ innerEl.toggle() } } ) } );" end def sort_contents_script "Sortable.create('contents', {onUpdate:function(){ new Ajax.Request('#{sort_questionnaire_contents_path(@questionnaire)}', { asynchronous:true, evalScripts:true, method:'put', parameters:Sortable.serialize('contents') }) }});" end end <file_sep>/app/controllers/display_elements_controller.rb class DisplayElementsController < ContentsController def self.controller_path ContentsController.controller_path end protected def new_content(attributes = {}) DisplayElement.new(attributes) end def find_content_type QUESTIONNAIRE_CONTENT_TYPES['display_elements'].detect{|t| t['name'] == "#{params[:content_type]}"}['name'] end def content_params params[:display_element] end end<file_sep>/config/routes.rb ActionController::Routing::Routes.draw do |map| map.connect '/', :controller => 'questionnaires', :action => 'index' # map.home '/', :controller => 'questionnaires' map.resources :questionnaires, :member => {:duplicate => :post} do |questionnaire| questionnaire.resources :contents, :member => { :copy => :get }, :collection => { :sort => :put } questionnaire.resources :questions, :member => { :copy => :get } questionnaire.resources :display_elements, :member => { :copy => :get } # questionnaire.resources :profile_attributes, :member => { :copy => :get } # # questionnaire.resources :descriptive_texts, :member => { :copy => :get } # questionnaire.resources :answers # questionnaire.resources :respondents # questionnaire.resources :exports end map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.login '/login', :controller => 'sessions', :action => 'new' map.register '/register', :controller => 'users', :action => 'create' map.signup '/signup', :controller => 'users', :action => 'new' map.resources :users # map.resource :session, :controller => 'sessions' map.resources :sessions map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end <file_sep>/app/models/question.rb class Question < Content after_create :set_code has_many :options, :order => 'options.position', :dependent => :destroy validates_uniqueness_of :code, :scope => :questionnaire_id, :allow_nil => true validates_presence_of :code, :on => :update def option_attributes=(options_string) set_option_attributes(options_string) end def option_attributes get_option_attributes end def row_option_attributes=(options_string) set_option_attributes(options_string, 'row') end def row_option_attributes get_option_attributes('row') end def col_option_attributes=(options_string) set_option_attributes(options_string, 'col') end def col_option_attributes get_option_attributes('col') end def collect_headings headings = [] case content_type.name when 'multiple_choice' labels = options.map(&:label) headings = labels.collect{|label| "#{self.code}[#{label}]"} if labels when 'rating_scale' labels = options.reject{|o| o.option_type == 'col'}.map(&:label) headings = labels.collect{|label| "#{self.code}[#{label}]"} if labels else headings << self.code end headings end def copy copy = Question.new(self.attributes.reject{|key,value| exclude_attributes_from_duplication.include?(key)}) options.each do |option| copy.options.build(option.attributes.reject{|key,value| exclude_attributes_from_duplication.include?(key)}) end copy end def answer_model question_type = QUESTIONNAIRE_CONTENT_TYPES['questions'].detect{|t| t['name'] == template} question_type['answer_model'] ? question_type['answer_model'] : 'Answer' end protected def set_code(number = nil) update_attribute(:code, "q_#{self.id}") if code.blank? end def set_option_attributes(options_string, option_type = nil) if o = options.find(:first, :order => 'value desc') @count = o.value else @count = 0 end labels_array = options_string.split(',').each {|o| o.strip!}.uniq collection = option_collection(option_type) collection.each do |option| unless labels_array.include?(option.label) options.delete(option) end end labels_array.each_with_index do |label, i| if option = collection.detect{|o| o.label == label} option.update_attribute(:position, i+1) else options.build(:label => label, :position => i + 1, :option_type => option_type, :value => @count + 1) end @count += 1 end end def option_collection(option_type) if option_type == 'row' options.option_rows elsif option_type == 'col' options.option_columns else options.option_choices end end def get_option_attributes(type = nil) options.collect{|option| option if option.option_type == type}.compact.map(&:label).join(', ') end end <file_sep>/app/controllers/application.rb # Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => '<KEY>' # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters # from your application log (in this case, all fields with names like "password"). # filter_parameter_logging :password include AuthenticatedSystem before_filter :login_required class AccessDenied < StandardError; end protected def render_invalid_record(record) flash[:error] = record.errors.full_messages.to_sentence respond_to do |format| format.html { render :action => (record.new_record? ? 'new' : 'edit') } format.xml { render :xml => record.errors, :status => :unprocessable_entity } format.js do render :update do |page| page.replace_html "flashes", :partial => "shared/flash" page.delay(15) do page.replace_html "flashes", "" end end end end end def default_flash_message(object) case params[:action] when 'create' flash[:notice] = "The #{object.class.name.titleize.downcase} was successfully created." when 'update' flash[:notice] = "The #{object.class.name.titleize.downcase} was updated." when 'destroy' flash[:notice] = "The #{object.class.name.titleize.downcase} was deleted." end end def reset_flash flash[:notice] = nil flash[:error] = nil end end <file_sep>/app/models/answer_date.rb class AnswerDate < ActiveRecord::Base belongs_to :respondent belongs_to :question named_scope :find_by_contents, lambda{|ids|{ :conditions => ["answer_dates.question_id in (?)", ids] }} end <file_sep>/app/controllers/questionnaires_controller.rb class QuestionnairesController < ApplicationController before_filter :find_questionnaire, :only => [:edit, :update, :destroy, :duplicate] after_filter :set_flash_message, :only => [:create, :update, :destroy] def index @questionnaires = current_user.questionnaires end def show @questionnaire = Questionnaire.find(params[:id], :include => [:contents => [:options]]) end def new @questionnaire = Questionnaire.new find_templates end def edit end def create @questionnaire = Questionnaire.new(params[:questionnaire].merge(:user => current_user)) @questionnaire.save! unless params[:questionnaire][:template_id].blank? if @template = QuestionnaireTemplate.find(params[:questionnaire][:template_id]) @questionnaire.duplicate_contents(@template) end end redirect_to @questionnaire rescue ActiveRecord::RecordInvalid find_templates render_invalid_record(@questionnaire) end def update @questionnaire.attributes = params[:questionnaire] redirect_to @questionnaire end def destroy @questionnaire.destroy redirect_to questionnaires_url end def duplicate @copy = @questionnaire.duplicate flash[:notice] = "#{@copy.class.name} was successfully duplicated." redirect_to @copy end protected def find_questionnaire @questionnaire ||= current_user.questionnaires.find(params[:id]) end def find_templates @templates = QuestionnaireTemplate.all :order => :title end def set_flash_message default_flash_message(@questionnaire) end end <file_sep>/config/initializers/askito.rb include QuestionnaireQuestionsBuilder include QuestionnaireDisplayElementsBuilder # include QuestionnaireProfileAttributesBuilder # APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV] NAVIGATION = YAML.load_file("#{RAILS_ROOT}/config/navigation.yml") QUESTIONNAIRE_CONTENT_TYPES = YAML.load_file("#{RAILS_ROOT}/config/questionnaire_content_types.yml")<file_sep>/lib/save_answer_dates.rb module SaveAnswerDates def new_answer_date_attributes=(answer_date_attributes) answer_dates_on_current_page.reject{|at| !at.new_record?}.each do |answer_date| value = answer_date_attributes[answer_date.question.id.to_s] assign_answer_date(answer_date, value) end end def existing_answer_date_attributes=(answer_date_attributes) answer_dates_on_current_page.reject(&:new_record?).each do |answer_date| value = answer_date_attributes[answer_date.id.to_s] assign_answer_date(answer_date, value) end end protected def assign_answer_date(answer_date, value) answer_date.value = value if value.blank? && answer_date.valid? answer_dates.delete(answer_date) answer_dates_on_current_page.delete(answer_date) end end def save_answer_dates answer_dates_on_current_page.each(&:save) end end<file_sep>/app/models/questionnaire.rb class Questionnaire < ActiveRecord::Base # include Page attr_accessor :current_page # this is necessary when # a quesitonnaire is duplicated # or saved as template before_create :reset_respondents_count validates_presence_of :title, :user_id belongs_to :user belongs_to :questionnaire_template has_many :contents, :class_name => 'Content', :dependent => :destroy, :order => 'contents.position' has_many :questions, :order => 'contents.position' # has_many :users, :through => :respondents, :order => 'users.login' # has_many :exports, :order => 'exports.created_at desc', :dependent => :destroy def duplicate rejected_attributes = %w[id type created_at updated_at respondents_count] questionnaire = self.class.name.constantize.new(self.attributes.reject{|key,value| rejected_attributes.include?(key)}) questionnaire.save contents.each do |content| copy = content.copy questionnaire.contents << copy # copy.clone_assets(content) end questionnaire end def pages @pages ||= calculate_pages end def previous_page if @current_page pages.reverse.find{|p| p[:id] < @current_page[:id]} else nil end end def previous_page? !previous_page.nil? end def next_page if @current_page pages.find{|p| p[:id] > @current_page[:id]} else nil end end def next_page? !next_page.nil? end def last_page pages.any? ? pages.last : nil end def last_page?(page = nil) if @current_page @current_page[:id] == last_page[:id] elsif pages.any? false else true end end def find_page(id = nil) if pages.any? if id pages.find{|p| p[:id].to_i == id.to_i} else pages.sort_by{|p| p[:id]}.first end else nil end end def find_page_by_position(position) pages.find{|p| (p[:from]..p[:to]).include?(position)} end def current_page=(page) @current_page = find_page(page) end def find_contents_for_current_page if current_page contents.between_positions(current_page[:from], current_page[:to]) else contents end end protected def calculate_pages pages = [] pagebreaks = contents.pagebreaks if pagebreaks pagebreaks.each_with_index do |pb, i| from = @to || 0 @to = pb.position page = {:id => i + 1} page.merge!(:from => from) page.merge!(:to => @to) pages << page end pages << { :id => pagebreaks.length + 1, :from => @to, :to => 1e6} end pages end def reset_respondents_count respondents_count = 0 end end <file_sep>/db/migrate/20081118034027_create_respondents.rb class CreateRespondents < ActiveRecord::Migration def self.up create_table :respondents do |t| t.references :questionnaire t.string :ip_address t.datetime :created_at, :started_at, :completed_at end add_index :respondents, :questionnaire_id add_index :respondents, :completed_at end def self.down drop_table :respondents end end <file_sep>/app/models/answer_text.rb class AnswerText < ActiveRecord::Base belongs_to :respondent belongs_to :question validates_presence_of :value, :message => "is required", :if => proc { |answer_text| answer_text.required? } named_scope :find_by_contents, lambda{|ids|{ :conditions => ["answer_texts.question_id in (?)", ids] }} def data_type question.content_type.data_type end def calculate_value case data_type when 'date' self.value = convert_date(self.value) self.value = self.value.to_s(:db) if self.value return self.value end end def required? !question.nil? && question.requires_answer? end end <file_sep>/lib/save_answers.rb module SaveAnswers def new_answer_attributes=(answer_attributes) answers_on_current_page.reject{|at| !at.new_record?}.each do |answer| value = answer_attributes.blank? ? nil : answer_attributes[answer.question.id.to_s] assign_answer(answer, value) end end def existing_answer_attributes=(answer_attributes) answers_on_current_page.reject(&:new_record?).each do |answer| value = answer_attributes.blank? ? nil : answer_attributes[answer.id.to_s] assign_answer(answer, value) end end def assign_answer(answer, value = nil) case answer.question.template when 'rating_scale', 'semantic_differential' assign_rating_scale(answer, value) when 'multiple_choice' assign_multiple_choice(answer, value) else assign_single_choice(answer, value) end end protected def save_answers answers_on_current_page.each(&:save) end def assign_single_choice(answer, value = nil) unless value.blank? answer.option_id = value else unless answer.required? answers_on_current_page.delete(answer) answers.delete(answer) end end end def assign_multiple_choice(answer, value = nil) unless value.blank? unless value.include?(answer.option_id.to_s) answers.delete(answer) answers_on_current_page.delete(answer) end else if answer.required? remaining_options = self.answers_on_current_page.reject{|a| a.question_id != answer.question_id} count = remaining_options.nil? ? 0 : remaining_options.length if count > 1 answers.delete(answer) answers_on_current_page.delete(answer) end else answers.delete(answer) answers_on_current_page.delete(answer) end end end def assign_rating_scale(answer, value = nil) unless value.blank? if value.detect{|k,v| k == answer[:row_id].to_s} answer.col_id = value[answer[:row_id].to_s] end else unless answer.required? answers_on_current_page.delete(answer) answers.delete(answer) end end end end<file_sep>/app/controllers/questions_controller.rb class QuestionsController < ContentsController def self.controller_path ContentsController.controller_path end protected def new_content(attributes = {}) Question.new(attributes) end def find_content_type QUESTIONNAIRE_CONTENT_TYPES['questions'].detect{|t| t['name'] == "#{params[:content_type]}"}['name'] end def content_params params[:question] end end<file_sep>/public/javascripts/application.js function adjustTextarea(textarea, collapsed) { var lines = textarea.value.split("\n"); var count = lines.length; lines.each(function(line) { count += parseInt(line.length / 70); }); var rows = parseInt(collapsed / 20); if (count > rows) { textarea.style.height = (collapsed * 2) + 'px'; } if (count <= rows) { textarea.style.height = collapsed + 'px'; } }<file_sep>/app/helpers/application_helper.rb # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def navigation if logged_in? @navigation ||= calculate_navigation end end def calculate_navigation navArray = [] NAVIGATION.sort.each do |item| navArray << navigation_item(item[1]) end navArray.join("\n") end def navigation_item(item) link = link_to(item['title'], "/#{item['resource']}") # style = controller.controller_name == item['resource'] ? 'current' : nil style = item['controllers'].split(',').each{|i| i.strip!}.include?(controller.controller_name) ? 'current' : nil content_tag("li", link, :class => style) end def print_excerpt(text, str = '', radius = 300) excerpt(text, str, radius) end def print_flash if !flash[:error].blank? content_tag("div", flash[:error], :class => "flash-error") elsif !flash[:notice].blank? content_tag("div", flash[:notice], :class => "flash-notice") end end def reset_flash_with_delay(delay = 15000) javascript_tag(" setTimeout(function(){ Element.update('flashes',''); }, #{delay}); ") end def toggle_box_body_link l = link_to_function "(show/hide)", "this.up(1).next().toggle()" content_tag("small", l) end def icon(purpose, label = nil) case purpose when :new i = 'add' when :delete i = 'cross' when :edit i = 'pencil' when :copy i = 'copy' when :sort i = 'arrow_switch' when :save i = 'tick' when :chat i = 'chat_small' end image_tag("icons/#{i}.png", :title => label.blank? ? purpose : label) end def show_tab(tab) "this.up('.tabs').siblings('.tab-content').each(function(el){el.hide();});" + "this.up('.tabs').childElements('.tab').each(function(el){el.removeClassName('current')});" + "this.up().addClassName('current');" + "$('#{tab}').show();" end def textilize(text) text.blank? ? '' : RedCloth.new(text).to_html end end <file_sep>/db/migrate/20081118034302_create_answer_dates.rb class CreateAnswerDates < ActiveRecord::Migration def self.up create_table :answer_dates do |t| t.references :respondent, :question t.datetime :value end add_index :answer_dates, :respondent_id add_index :answer_dates, :question_id end def self.down drop_table :answer_dates end end <file_sep>/config/deploy.rb set :domain, '192.168.3.11' set :port, '30000' role :web, domain role :app, domain role :db, domain, :primary => true set :application, "askito" default_run_options[:pty] = true set :repository, "git://github.com/askito/askito.git" set :scm, "git" set :user, "deploy" set :branch, "master" set :runner, user set :ssh_options, { :forward_agent => true, :paranoid => false } set :deploy_to, "/home/#{user}/public_html/#{application}" set :rails_env, "production" namespace :deploy do task :start do # nothing # overwrite default because we dont need method script/spin end task :stop do # nothing end desc "Tell Passenger to restart the app." task :restart do run "touch #{release_path}/tmp/restart.txt" end desc "Symlink shared configs and folders on each release." task :symlink_shared do run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml" # run "ln -nfs #{shared_path}/vendor/rails #{release_path}/vendor" # run "ln -nfs #{release_path}/vendor/plugins/restful_authentication/lib #{release_path}/lib/" run "ln -nfs #{shared_path}/vendor/gems #{release_path}/vendor" end desc "Run this after every successful deployment" task :after_default do cleanup end end after 'deploy:update_code', 'deploy:symlink_shared' <file_sep>/lib/questionnaire_display_elements_builder.rb module QuestionnaireDisplayElementsBuilder def descriptive_text(content) nil end def pagebreak(content) nil end def image(content) images = [] content.assets.each do |asset| if asset.image? if content.settings && content.settings[:gallery] == '1' rel = content.assets.size > 1 ? "gallery_#{dom_id(content)}" : nil images << thickbox_link(asset, rel) else images << image_tag(asset.public_filename(:big), :style => 'width:100%;', :alt => h(asset.alt), :title => h(asset.caption)) images << content_tag("p", h(asset.caption), :class => 'image-caption') unless asset.caption.blank? end end end images.join end def fields_for_descriptive_text(content, form_obj) if defined? TextileEditorHelper # use haml helper puts find_and_preserve(textile_editor('content', 'text', :class => 'l', :onbeforepaste => "adjustTextarea(this, 150)", :oninput => "adjustTextarea(this, 150)", :onkeypress => "adjustTextarea(this, 150)")) textile_editor_initialize else form_obj.text_area(:text, :class => 'l') end end def fields_for_image(content, form_obj) haml_tag :ul, :id => 'assets' do content.assets.each do |asset| puts fields_for_asset_item(asset) end end # haml_tag :p do # puts link_to_function("Add image", update_page{|page| page.insert_html :bottom, 'assets', render(:text => fields_for_asset_item(Asset.new))}) # end # puts link_to_function("Add image", update_page{|page| page.insert_html :bottom, 'assets', a = fields_for_asset_item(Asset.new)}) haml_tag :fieldset do haml_tag :legend, 'Settings' haml_tag :p do # content.settings ||= {} fields_for 'content[settings]', content.settings ||= {} do |cs| puts cs.check_box(:gallery, {:checked => content.settings[:gallery] == '1'}) haml_tag "span", "Display as gallery?" end end end end protected def thickbox_link(asset, rel = nil) link_to(image_tag(asset.public_filename(:thumb)), asset.public_filename, :title => asset.caption, :class => 'thickbox', :rel => rel) end def fields_for_asset_item(asset) prefix = asset.new_record? ? 'new' : 'existing' # haml_tag :li, :class => 'clear' do content_tag "li", :class => 'clear' do airbudd_fields_for "content[#{prefix}_asset_attributes][]", asset do |a| haml_tag :fieldset, :class => 'clear' do haml_tag :div, :class => 'left-half' do puts image_tag(asset.public_filename(:thumb)) unless asset.new_record? end haml_tag :div, :class => 'right-half' do a.text_field(:caption, :class => 'l') a.text_field(:alt, :label => 'Description', :class => 'l') a.file_field(:uploaded_data, :label => 'Upload file', :size => 10) end end end end end # def fields_for_asset_item(asset) # prefix = asset.new_record? ? 'new' : 'existing' # airbudd_fields_for "content[#{prefix}_asset_attributes][]", asset do |a| # haml_tag :fieldset do # haml_tag :div, :class => 'thumb' do # puts image_tag(asset.public_filename(:thumb)) unless asset.new_record? # end # haml_tag :div, :class => 'meta' do # puts a.text_field(:caption, :class => 'l') # puts a.text_field(:alt, :label => 'ALT', :class => 'l') # puts a.file_field(:uploaded_data, :label => 'Upload file', :size => 30) # end # end # end # end end<file_sep>/db/migrate/20081117192033_create_options.rb class CreateOptions < ActiveRecord::Migration def self.up create_table :options do |t| t.references :question t.string :label, :option_type t.integer :value t.integer :position, :default => 1 t.integer :answers_count, :default => 0 t.timestamps end add_index :options, :question_id end def self.down drop_table :options end end <file_sep>/test/unit/answer_text_test.rb require 'test_helper' class AnswerTextTest < ActiveSupport::TestCase # Replace this with your real tests. def test_truth assert true end end <file_sep>/db/migrate/20081117190550_create_contents.rb class CreateContents < ActiveRecord::Migration def self.up create_table :contents do |t| t.references :questionnaire t.string :type, :template, :limit => 50 t.integer :position, :default => 1 t.text :text, :settings # Attributes for questions t.string :hint, :code t.boolean :requires_answer t.timestamps end add_index :contents, :questionnaire_id end def self.down drop_table :contents end end <file_sep>/app/helpers/contents_helper.rb module ContentsHelper def new_content_link(controller, content_type) url_params = {:controller => controller, :questionnaire_id => @questionnaire.id} title = content_type['title'] || content_type['name'] unless content_type['name'] == 'pagebreak' url_params.merge!(:action => 'new', :content_type => content_type['name']) method = :get else url_params.merge!(:action => 'create', controller.singularize => {:template => content_type['name']}) method = :post end link_to_remote(title.humanize, :url => url_for(url_params), :method => method, :html => {:title => "New #{content_type['name'].humanize.downcase}"}) end def content_form_id if @content.new_record? 'new_content_form' else "edit_#{dom_id(@content)}_form" end end def url_for_content_form c = @content.class.name.underscore.pluralize if @content.new_record? # questionnaire_contents_path(@questionnaire) url_for(:controller => c, :action => 'create', :questionnaire_id => @questionnaire) else # questionnaire_content_path(@questionnaire, @content) url_for(:controller => c, :action => 'update', :questionnaire_id => @questionnaire, :id => @content) end end def template(content = nil) content ? content.template : @content.template end def toggle_actions_script javascript_tag(" Event.addBehavior({ '#contents .content:mouseover': function() { this.down('.actions').show(); }, '#contents .content:mouseout': function() { this.down('.actions').hide(); } }) ") end end <file_sep>/lib/questionnaire_questions_builder.rb # HAML gem and plugin are required # textile_editor_helper plugin is required module QuestionnaireQuestionsBuilder # *************************************************************************************** # Methods for displaying the content type # *************************************************************************************** def single_choice(question) # print_question_options(question, 'single_choice') answer = find_answer_xxx(question) haml_tag :ul, :class => 'options' do question.options.each do |option| haml_tag :li, :class => 'option' do puts radio_button_tag("#{answer_name(question, answer)}", option.id.to_s, answer.option_id == option.id && !answer.new_record?) haml_tag :label, option.label end end end print_validation_errors(answer) end def multiple_choice(question) # print_question_options(question, 'multiple_choice') haml_tag :ul, :class => 'options' do question.options.each do |option| haml_tag :li, :class => 'option' do answer = find_answer_xxx(question, option) puts check_box_tag("#{answer_name(question, answer)}[]", option.id.to_s, answer.option_id == option.id && !answer.new_record?) haml_tag :label, option.label print_validation_errors(answer) end end end end def open_single_line(question) answer = find_answer_xxx(question, nil, 'AnswerText') puts text_field_tag(answer_name(question, answer), answer.value) end def open_multiple_lines(question) answer = find_answer_xxx(question, nil, 'AnswerText') puts text_area_tag(answer_name(question, answer), answer.value) end def rating_scale(question) rows = question.options.option_rows cols = question.options.option_columns generate_table(question, rows, cols, 'rating_scale') end def semantic_differential(question) rows = question.options.option_rows cols = question.options.option_columns generate_table(question, rows, cols, 'semantic_differential') end # *************************************************************************************** # Methods for editing the content type # *************************************************************************************** def fields_for_single_choice(content, form_obj) haml_tag :div do puts print_question_heading_field(form_obj) puts print_question_hint_field(form_obj) puts print_question_option_attributes_field(form_obj) puts print_requires_answer(form_obj) end end alias_method :fields_for_multiple_choice, :fields_for_single_choice def fields_for_open_single_line(question, form_obj) haml_tag :div do puts print_question_heading_field(form_obj) puts print_question_hint_field(form_obj) puts print_requires_answer(form_obj) end end alias_method :fields_for_open_multiple_lines, :fields_for_open_single_line def fields_for_rating_scale(question, form_obj) haml_tag :div do puts print_question_heading_field(form_obj) puts print_question_hint_field(form_obj) puts form_obj.text_area(:row_option_attributes, :label => 'Row choices', :class => 's', :hint => "separate entries with a comma, eg: movie 1, movie 2, movie 3") puts form_obj.text_area(:col_option_attributes, :label => 'Column choices', :class => 's', :hint => "separate entries with a comma, eg: bad, ok, good") puts print_requires_answer(form_obj) end end def fields_for_semantic_differential(question, form_obj) haml_tag :div do puts print_question_heading_field(form_obj) puts print_question_hint_field(form_obj) puts form_obj.text_area(:row_option_attributes, :label => 'Row choices', :class => 's', :hint => "Delimite the adjective pair by '-' and separate the rows with a comma, eg: strong-weak, active-passive") puts form_obj.text_area(:col_option_attributes, :label => 'Column choices', :class => 's', :hint => "separate entries with a comma, eg: 1, 2, 3") puts print_requires_answer(form_obj) end end def fields_for_date(question, form_obj) haml_tag :div do puts print_question_heading_field(form_obj) puts print_question_hint_field(form_obj) end haml_tag :fieldset do haml_tag :legend, "Settings" question.settings ||= {} question.settings.merge!(:display => nil) unless question.settings[:display] airbudd_fields_for "question[settings]", question.settings do |s| haml_tag :div, :class => 'clear' do haml_tag :div, :class => 'left-half' do haml_tag :div, :class => 'left-half' do puts s.text_field(:year_from, :class => 's') end haml_tag :div, :class => 'right-half' do puts s.text_field(:year_to, :class => 's') end end haml_tag :div, :class => 'right-half' do haml_tag :label, "Display as" haml_tag :ul, :class => 'options clear' do puts s.radio_button(:display, :value => 'select', :label => 'Select') puts s.radio_button(:display, :value => 'text', :label => 'Text') end end end end # puts '' end end protected # *************************************************************************************** # Helper methods to find the answer for a specific question # *************************************************************************************** # find answer by question and respondent # if it is a multiple choice then find the answer by option instead of question # if it is a rating scale then find the answer by question and row # def find_answer_xxx(question, key = nil, model = "Answer") # begin # # make sure the answers are assigned in the controller # # eg @answers, @answer_texts, etc. # answers = instance_variable_get("@#{model.underscore.pluralize}") # # debugger # case question.template # when 'multiple_choice' # answers.detect {|a| a.option_id == key.id} # when 'rating_scale' # answers.detect{|a| a.question_id == question.id && a.row_id == key.id} # else # answers.detect {|a| a.question_id == question.id} # end # rescue # model.constantize.new # end # end def find_answer_xxx(question, key = nil, model = "Answer") begin case question.template when 'multiple_choice' # @answers[model.underscore.pluralize.to_sym].detect {|a| a.option_id == key.id} answer = @respondent.answers_on_current_page.detect {|a| a.option_id == key.id} when 'rating_scale', 'semantic_differential' # @answers[model.underscore.pluralize.to_sym].detect{|a| a.question_id == question.id && a.row_id == key.id} unless answer = @respondent.answers_on_current_page.detect{|a| a.question_id == question.id && a.row_id == key.id} answer = Answer.new(:question => question, :row_id => key_id) end when 'open_single_line', 'open_multiple_lines' answer = @respondent.answer_texts_on_current_page.detect {|a| a.question_id == question.id} when 'date' answer = @respondent.answer_dates_on_current_page.detect {|a| a.question_id == question.id} else answer = @respondent.answers_on_current_page.detect {|a| a.question_id == question.id} end # answer.nil? ? model.constantize.new(:question => question) : answer answer ||= model.constantize.new(:question => question) rescue # This is used in design mode: chataca.com/surveys/123 # Because there are no answers available in Design mode model.constantize.new(:question => question) end end # set the name of the attribute def answer_name(question, answer) prefix = answer.new_record? ? 'new' : 'existing' model = answer.class.name.underscore id = answer.new_record? ? question.id : answer.id "respondent[#{prefix}_#{model}_attributes][#{id}]" end # *************************************************************************************** # Fields for editing the content attributes # *************************************************************************************** # edit question heading # edit question's text method def print_question_heading_field(obj) haml_tag :p do haml_tag :label, 'Question (format with Textile)' puts find_and_preserve(textile_editor('question', 'text', :class => 's', :onbeforepaste => "adjustTextarea(this, 60)", :oninput => "adjustTextarea(this, 60)", :onkeypress => "adjustTextarea(this, 60)")) # if defined? TextileEditorHelper # puts find_and_preserve(textile_editor('question', 'text', :class => 's')) # else # puts obj.text_area(:text, :class => 's') # end end end # edit question's hint method def print_question_hint_field(obj) obj.text_field :hint, :class => 'l' end # edit question's option_attributes method def print_question_option_attributes_field(obj) obj.text_area :option_attributes, :label => 'Options', :class => 's', :hint => "separate entries with a comma" end def generate_table(question, rows, cols, template) haml_tag :table do haml_tag :thead do haml_tag :tr do haml_tag :th cols.each do |col| haml_tag :th, :style => 'text-align:center;' do puts h(col.label) end end haml_tag :th if template == 'semantic_differential' end end rows.each do |row| answer = find_answer_xxx(question, row) haml_tag :tr do if template == 'semantic_differential' label = h(row.label.split('-')[0]) else label = h(row.label) end haml_tag :td, :style => 'text-align:right;' do puts label haml_tag :br print_validation_errors(answer) end columns_count = cols.length columns_count += template == 'semantic_differential' ? 2 : 1 cols.each do |col| name = answer_name(question, answer) selected = answer.row_id == row.id && answer.col_id == col.id && !answer.new_record? haml_tag :td, :style => "width:#{100/(columns_count)}%;text-align:center;" do puts radio_button_tag("#{name}[#{row.id}]", col.id.to_s, selected) end end if template == 'semantic_differential' haml_tag :td, :style => 'text-align:left;' do puts h(row.label.split('-')[1]) end end end end end end def print_requires_answer(obj) haml_tag :ul, :class => 'options' do puts obj.check_box(:requires_answer, :label => 'Answer required?') end end def print_validation_errors(answer) if answer.errors.any? haml_tag :span, :class => 'feedback' do puts answer.errors.full_messages.to_sentence end end end end <file_sep>/db/migrate/20081118034149_create_answers.rb class CreateAnswers < ActiveRecord::Migration def self.up create_table :answers do |t| t.references :respondent, :question, :option t.integer :row_id, :col_id end add_index :answers, :respondent_id add_index :answers, :question_id add_index :answers, :option_id end def self.down drop_table :answers end end <file_sep>/app/models/answer.rb class Answer < ActiveRecord::Base belongs_to :question, :counter_cache => true belongs_to :option, :counter_cache => true belongs_to :respondent named_scope :find_by_contents, lambda{|ids|{ :conditions => ["answers.question_id in (?)", ids] }} def validate unless question.template == 'multiple_choice' errors.add_to_base("Answer is required") if required? && option_id.blank? else errors.add_to_base("Answer is required") if required? end end def required? !question.nil? && question.requires_answer? end end <file_sep>/app/models/respondent.rb class Respondent < ActiveRecord::Base include SaveAnswers include SaveAnswerTexts include SaveAnswerDates after_update :save_answers, :save_answer_texts, :save_answer_dates belongs_to :questionnaire has_many :answers has_many :answer_texts has_many :answer_dates def completed? !completed_at.blank? end def active? !started_at.blank? && !completed? end def pending? !active? && !completed? end def state if completed? 'completed' elsif active? 'active' else 'pending' end end def start! self.update_attribute(:started_at, Time.now) end def complete! self.update_attribute(:completed_at, Time.now) self.task.complete! end def self.find_for_export(questionnaire) find :all, :conditions => ["respondents.questionnaire_id = ?", questionnaire], :include => [ [:questionnaire => [:questions => [:content_type, :options]]], :answers, :answer_texts ] end def collect_answers_by_question(question) values = [] case question.content_type.name when 'multiple_choice' values << get_values_for_multiple_choice(question) when 'rating_scale' values << get_values_for_rating_scale(question) when 'single_choice' values << get_value_for_single_choice(question) else unless question.content_type.category.downcase == 'profile attributes' values << get_value_for_answer_text(question) else values << nil end end values end def assign_answer_unless_exists(question) case question.answer_model when 'AnswerText' unless a = answer_texts.detect{ |a| a.question_id == question.id } a = answer_texts.build(:question => question) end answer_texts_on_current_page << a when 'AnswerDate' unless a = answer_dates.detect{ |a| a.question_id == question.id } a = answer_dates.build(:question => question) end answer_dates_on_current_page << a when 'Answer' case question.template when 'rating_scale', 'semantic_differential' question.options.option_rows.each do |row| unless a = answers.detect{|a| a.question_id == question.id && a.row_id == row.id} a = answers.build(:question => question, :row_id => row.id) end answers_on_current_page << a end when 'multiple_choice' question.options.each do |option| unless a = answers.detect{|a| a.option_id == option.id} a = answers.build(:question => question, :option => option) end answers_on_current_page << a end else unless a = answers.detect{ |a| a.question_id == question.id } a = answers.build(:question => question) end answers_on_current_page << a end end end def answers_on_current_page @answers_on_current_page ||= [] end def answers_on_current_page=(answer) @answers_on_current_page << answer end def answer_texts_on_current_page @answer_texts_on_current_page ||= [] end def answer_texts_on_current_page=(answer) @answer_texts_on_current_page << answer end def answer_dates_on_current_page @answer_dates_on_current_page ||= [] end def answer_dates_on_current_page=(answer) @answer_dates_on_current_page << answer end def answers_valid? answers_on_current_page_valid? && answer_texts_on_current_page_valid? && answer_dates_on_current_page_valid? end private def get_values_for_multiple_choice(question) values = [] question.options.each do |option| if answer = answers.detect{|a| a.option_id == option.id} values << option.id else values << nil end end values end def get_values_for_rating_scale(question) values = [] rows = question.options.reject{|o| o.option_type == 'col'}.map(&:id) cols = question.options.reject{|o| o.option_type == 'row'}.map(&:id) debugger rows.each do |row| if answer = answers.detect{|a| rows.include?(a.row_id)} values << answer.col_id else values << nil end end values end def get_value_for_single_choice(question) if answer = answers.detect{|a| a.question_id == question.id} answer.option_id else nil end end def get_value_for_answer_text(question) if answer_text = answer_texts.detect{|a| a.question_id == question.id} answer_text.value else nil end end def answers_on_current_page_valid? valid = true answers_on_current_page.each do |a| valid = false if !a.valid? end valid end def answer_texts_on_current_page_valid? valid = true answer_texts_on_current_page.each do |a| valid = false if !a.valid? end valid end def answer_dates_on_current_page_valid? valid = true answer_dates_on_current_page.each do |a| valid = false if !a.valid? end valid end end <file_sep>/app/models/questionnaire_template.rb class QuestionnaireTemplate < Questionnaire end <file_sep>/app/models/option.rb class Option < ActiveRecord::Base belongs_to :question has_many :answers, :dependent => :destroy validates_presence_of :value validates_uniqueness_of :value, :scope => [:question_id, :option_type], :allow_nil => true named_scope :option_choices, :conditions => "options.option_type is null" named_scope :option_rows, :conditions => "options.option_type = 'row'" named_scope :option_columns, :conditions => "options.option_type = 'col'" end <file_sep>/db/migrate/20081118034229_create_answer_texts.rb class CreateAnswerTexts < ActiveRecord::Migration def self.up create_table :answer_texts do |t| t.references :respondent, :question t.text :value end add_index :answer_texts, :respondent_id add_index :answer_texts, :question_id end def self.down drop_table :answer_texts end end
73abc9bc0c0b6c146f2231a207cafcb5ffc1feda
[ "JavaScript", "Ruby" ]
34
Ruby
askito/askito
96a446809f4024bf18c2cdd23fc4965a2755254c
2ef6c7b6edfb7d611bcaf3b1ac83f96515b487e8
refs/heads/main
<file_sep>import './App.scss'; import React, { Component } from 'react'; import { Button, Grid, Paper } from '@material-ui/core'; import TimerButton from './TimerButton'; // import { render } from 'node-sass'; // https://www.reddit.com/r/heroesofthestorm/comments/bmb5dk/camps_and_objective_timer_cheatsheet/ const mapList = { gardenOfTerror: [{ name: 'Seige (Giants)', initalSeconds: 10, respawnSeconds: 5, }, { name: 'Bruiser (Knights)', initalSeconds: 10, respawnSeconds: 10, }, { name: 'Objective (Seed)', initalSeconds: 10, respawnSeconds: 12, } ] } export default class App extends Component { constructor(props) { super(props); this.state = {gameStarted: false}; } startGame = () => { this.setState({gameStarted: true}) } renderButtons = () => { if (this.state.gameStarted) { return mapList.gardenOfTerror.map(timer => <TimerButton key={timer.name} {...timer} /> ); } return <Button variant="contained" size="large" color='primary' onClick={this.startGame}> Game has started </Button>; } render() { return ( <div className="App"> <Grid container direction="row" justify="space-evenly" alignItems="flex-start" spacing={3} > <Paper elevation={3}>{this.renderButtons()}</Paper> </Grid> </div> ); } } <file_sep>import React, { Component } from 'react'; import { Button } from '@material-ui/core'; import { Alarm, Refresh } from '@material-ui/icons'; export default class TimerButton extends Component { constructor(props) { super(props); this.state = {timeRemaining: props.initalSeconds}; setTimeout(this.updateTimer, 1000, props.initalSeconds); } updateTimer = (passedRemaining) => { console.log(passedRemaining); if (passedRemaining <= 0) return; this.setState({timeRemaining: passedRemaining - 1}); setTimeout(this.updateTimer, 1000, passedRemaining - 1); } handleClick = () => { if (this.props.onClick) this.props.onClick(); if (this.props.respawnSeconds && this.state.timeRemaining <= 0) this.respawnTimer(); } respawnTimer = () => { this.setState({timeRemaining: this.props.respawnSeconds}); setTimeout(this.updateTimer, 1000, this.props.respawnSeconds); } render() { let timeLabel = this.state.timeRemaining; let buttonColor = "primary"; let icon = <Alarm /> if (this.state.timeRemaining <= 0) { timeLabel = 'READY!'; buttonColor = 'secondary'; icon = this.props.respawnSeconds ? <Refresh /> : '' } return ( <Button variant="outlined" size="large" color={buttonColor} onClick={this.handleClick} >{icon} &nbsp; { this.props.name} - {timeLabel }</Button> ); } } <file_sep>import React, { Component } from 'react'; import { Button, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@material-ui/core'; export default class Announce extends Component { constructor(props) { super(props); this.state = {open: true}; } closeDialog = () => { this.setState({open: false}); this.props.onClose(); } render() { // <Dialog onClose={this.handleClose} aria-labelledby="simple-dialog-title" open={true}> return ( <Dialog onClose={ this.closeDialog } aria-labelledby="simple-dialog-title" open={this.state.open}> <DialogTitle>Timer complete</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> Timer {this.props.name} is up! </DialogContentText> </DialogContent> <DialogActions> <Button onClick={ this.closeDialog } color="primary" autoFocus> Ok </Button> </DialogActions> </Dialog> ) } }
127e2c27c330271ee7ae78e937103e0ccc2800f3
[ "JavaScript" ]
3
JavaScript
stephencattaneo/hots-timers
58702d935ed561c83a8ab93b12bd98383ef8c693
cea4a4b8f01fba00a95d1d8d23bf23baa71f846e
refs/heads/master
<repo_name>braianflorian/rest-ws-votos<file_sep>/api/services/MessageTableService.js /** * get_error * @param {*} token * @param {*} tag * * Retorna un mensaje de error especifico por medio de una etiqueta */ module.exports.get_error = function (token = "", tag = "") { switch (tag) { case "mandatory_param": return "El paremetro " + token + " es obligatorio"; case "method_unvailable": return "Metodo no disponible"; default: return token; } }; module.exports.get_message = function (tag = "") { switch (tag) { case "voto_emited_ok": return "Voto exitoso"; case "mesa_create_ok": return "Mesa registrada"; case "consulta_ok": return "Consulta exitosa"; case "info_mesa_ok": return "Información de mesa"; default: return token; } };<file_sep>/api/controllers/VotosController.js /** * VotosController * * @description :: Server-side actions for handling incoming requests. * @help :: See https://sailsjs.com/docs/concepts/actions */ module.exports = { /** * votar * @dpi * @id */ votar: async function (req, res) { //Verificar que el json se haya recibido correctamente let dpi = req.param('dpi'), idpartido = req.param('id_partido'); //de no estar correcto, retornar un error if (!dpi) return ResponseService.res_err( res, MessageTableService.get_error("dpi", "mandatory_param") ); if (!idpartido) return ResponseService.res_err( res, MessageTableService.get_error("idpartido", "mandatory_param") ); var data = {}; var msg = MessageTableService.get_message('voto_emited_ok'); return ResponseService.res(res, data, msg); } };<file_sep>/config/routes.js module.exports.routes = { 'POST /ws/rest/mesas': 'MesasController.create', 'GET /ws/rest/mesas': 'MesasController.findOneDPI', 'PUT /ws/rest/mesas': 'ErrorController.undefined', 'DELETE /ws/rest/mesas': 'ErrorController.undefined', 'POST /ws/rest/mesas/:id_mesa': 'ErrorController.undefined', 'GET /ws/rest/mesas/:id_mesa': 'MesasController.findOne', 'PUT /ws/rest/mesas/:id_mesa': 'ErrorController.undefined', 'DELETE /ws/rest/mesas/:id_mesa': 'ErrorController.undefined', 'POST /ws/rest/votos/:id_partido': 'VotosController.votar', 'GET /ws/rest/votos/:id_partido': 'ErrorController.undefined', 'PUT /ws/rest/votos/:id_partido': 'ErrorController.undefined', 'DELETE /ws/rest/votos/:id_partido': 'ErrorController.undefined', }; <file_sep>/config/datastores.js module.exports.datastores = { default: { adapter: 'sails-mongo', host: 'localhost', port: 27017, // user: 'username', //optional // password: '<PASSWORD>', //optional database: 'ws-votos' //optional }, };<file_sep>/test/integration/controllers/VotosController.test.js // test/integration/controllers/VotosController.test.js var supertest = require('supertest'); describe('VotosController.votar', function () { describe('#votar()', function () { it('return json', function (done) { supertest(sails.hooks.http.app) .post('/ws/rest/votos/4') .send({ dpi: 3454 }) .expect(200, done); }); }); });
5387561089a3fa9330fb673134107ac267c19361
[ "JavaScript" ]
5
JavaScript
braianflorian/rest-ws-votos
99ebde3a9a1861bb54d0e5a3e0e66a1e85d1c413
c9e9ebcd2f008a5043103f5ff1c8f150d44051f0
refs/heads/master
<repo_name>navyTensor/airtools<file_sep>/tests/test.py #!/usr/bin/env python """selftest""" import logging from numpy.linalg import svd from numpy import array,mat,squeeze from scipy import sparse from numpy.testing import assert_array_almost_equal, assert_allclose,run_module_suite """ generate test problems from Julia by using MatrixDepot matrixdepot("deriv2",3,false) """ A = array([[-0.0277778, -0.0277778, -0.00925926], [-0.0277778, -0.0648148, -0.0277778], [-0.00925926,-0.0277778, -0.0277778 ]]) b = array([-0.01514653483985129, -0.03474793286789414, -0.022274315940957783]) x_true = array([0.09622504486493762, 0.28867513459481287, 0.48112522432468807]) def test_kaczmarz(): from airtools.kaczmarz import kaczmarz x = kaczmarz(A,b,200,lamb=1.)[0] assert_array_almost_equal(x,x_true) def test_maxent(): from airtools.maxent import maxent x = maxent(A,b,lamb=.000025)[0] assert_array_almost_equal(x,x_true) def test_rzr(): from airtools.rzr import rzr A = array([[1,2,3], [0,0,0], [4,5,6]]) b = array([1,2,3]) Ar,br,g = rzr(A,b) assert_array_almost_equal(Ar,array([[1,2,3], [4,5,6]])) assert_array_almost_equal(br,array([1,3])) def test_picard(): from airtools.picard import picard U,s,V = svd(array([[3,2,2], [2,3,-2], [2,3,4]])) eta = picard(U,s,V)[0] assert_array_almost_equal(eta,[ 0.02132175, 0.00238076, 0.04433971]) def test_lsqlin(): try: from cvxopt import matrix except (ImportError,RuntimeError): logging.error('skipped LSQ test due to missing CVXOPT library') return import airtools.lsqlin as lsqlin # simple Testing routines C = array(mat('''0.9501,0.7620,0.6153,0.4057; 0.2311,0.4564,0.7919,0.9354; 0.6068,0.0185,0.9218,0.9169; 0.4859,0.8214,0.7382,0.4102; 0.8912,0.4447,0.1762,0.8936''')) sC = sparse.coo_matrix(C) csC = lsqlin.scipy_sparse_to_spmatrix(sC) A = array(mat('''0.2027,0.2721,0.7467,0.4659; 0.1987,0.1988,0.4450,0.4186; 0.6037,0.0152,0.9318,0.8462''')) sA = sparse.coo_matrix(A) csA = lsqlin.scipy_sparse_to_spmatrix(sA) d = array([0.0578, 0.3528, 0.8131, 0.0098, 0.1388]) md = matrix(d) b = array([0.5251, 0.2026, 0.6721]) mb = matrix(b) lb = array([-0.1] * 4) mlb = matrix(lb) mmlb = -0.1 ub = array([2] * 4) mub = matrix(ub) mmub = 2 opts = {'show_progress': False} for iC in [C, sC, csC]: for iA in [A, sA, csA]: for iD in [d, md]: for ilb in [lb, mlb, mmlb]: for iub in [ub, mub, mmub]: for ib in [b, mb]: ret = lsqlin.lsqlin(iC, iD, 0, iA, ib, None, None, ilb, iub, None, opts) assert_allclose(squeeze(ret['x']),[-1.00e-01, -1.00e-01, 2.15e-01, 3.50e-01],rtol=1e-2) #test lsqnonneg C = array([[0.0372, 0.2869], [0.6861, 0.7071], [0.6233, 0.6245], [0.6344, 0.6170]]); d = array([0.8587, 0.1781, 0.0747, 0.8405]); ret = lsqlin.lsqnonneg(C, d, {'show_progress': False}) assert_allclose(squeeze(ret['x']),[2.5e-7,6.93e-1],rtol=1e-2) if __name__ == '__main__': # test_kaczmarz() #test_maxent() run_module_suite() <file_sep>/tests/test_octave.py #!/usr/bin/env python """ Tests Python code vs. Matlab by original luminiferous authors ...using Octave, of course """ from numpy import array from numpy.testing import run_module_suite, assert_array_almost_equal from oct2py import Oct2Py """ generate test problems from Julia by using MatrixDepot matrixdepot("deriv2",3,false) """ A = array([[-0.0277778, -0.0277778, -0.00925926], [-0.0277778, -0.0648148, -0.0277778], [-0.00925926,-0.0277778, -0.0277778 ]]) b = array([-0.01514653483985129, -0.03474793286789414, -0.022274315940957783]) x_true = array([0.09622504486493762, 0.28867513459481287, 0.48112522432468807]) oc = Oct2Py(timeout=10,convert_to_float=True,oned_as='column') oc.addpath('../matlab') def test_maxent(): #%% first with Python from airtools.maxent import maxent from airtools.logmart import logmart x_python,rho,eta = maxent(A,b,0.00002) assert_array_almost_equal(x_python,x_true) x_pylog = logmart(A,b,0.00002,0.)[0] #%% then with Octave using original Matlab code x_matlab = oc.maxent(A,b,0.00002).squeeze() assert_array_almost_equal(x_matlab,x_true) def test_kaczmarz(): from airtools.kaczmarz import kaczmarz x_python = kaczmarz(A,b,200)[0] assert_array_almost_equal(x_python,x_true) x_matlab = oc.kaczmarz(A,b,200).squeeze() assert_array_almost_equal(x_matlab,x_true) if __name__ == '__main__': run_module_suite() <file_sep>/airtools/picard.py from __future__ import division import logging import numpy as np from matplotlib.pyplot import figure ''' PICARD Visual inspection of the Picard condition. eta = picard(U,s,b,d) eta = picard(U,sm,b,d) , sm = [sigma,mu] Plots the singular values, s(i), the abs. value of the Fourier coefficients, |U(:,i)'*b|, and a (possibly smoothed) curve of the solution coefficients eta(i) = |U(:,i)'*b|/s(i). If s = [sigma,mu], where gamma = sigma./mu are the generalized singular values, then this routine plots gamma(i), |U(:,i)'*b|, and (smoothed) eta(i) = |U(:,i)'*b|/gamma(i). The smoothing is a geometric mean over 2*d+1 points, centered at point # i. If nargin = 3, then d = 0 (i.e, no smothing). Reference: <NAME>, "The discrete Picard condition for discrete ill-posed problems", BIT 30 (1990), 658-672. Per <NAME>, IMM, April 14, 2001. ported to Python by <NAME> ''' def picard(U,s,b,d=0): n,ps = np.atleast_2d(s).T.shape beta = np.abs( np.asfortranarray(U[:,:n]).T.dot(b) ) eta = np.zeros(n,order='F') if ps==2: s = s[:,0] / s[:,1] d21 = 2 * d + 1 keta = np.arange(d,n-d) if (s==0).any(): #10**-14 is OK? logging.warning('** picard: Division by zero: singular values') for i in keta: es = np.s_[i-d:i+d+1] eta[i] = ( beta[es].prod()**(1/d21)) / s[i] return eta,n,s,beta,keta,ps def plotpicard(n,s,beta,eta,keta,ps): ni = np.arange(n) ax = figure().gca() ax.semilogy(ni, s, '.-') #breaks for inf ax.semilogy(ni, beta, 'x') #breaks for inf ax.semilogy(keta, eta[keta], 'o') ax.set_xlabel('i') ax.set_title('Picard plot') #ax.autoscale(True,tight=True) if ps==1: ax.legend( ('$\sigma_i$','$|u_i^T b|$','$|u_i^T b|/\sigma_i$'),loc='lower left' ) else: ax.legend( ('$\sigma_i/\mu_i$','$|u_i^T b|$','$|u_i^T b|/ (\sigma_i/\mu_i)$') ,loc='lower left') <file_sep>/setup.py #!/usr/bin/env python install_requires = ['numpy','scipy',] tests_require=['nose','coveralls'] # %% from setuptools import setup,find_packages setup(name='pyAIRtools', packages=find_packages(), description='Python port of Matlab AIRtools and ReguTools regularization toolbox', url='https://github.com/scivision/airtools', author='<NAME>, Ph.D.', version = '1.0.0', long_description=open('README.rst').read(), install_requires=install_requires, python_requires='>=2.7', extras_require={'plot':['matplotlib'], 'cvx':['cvxopt'], 'octave':['oct2py'], 'tests':tests_require}, tests_require=tests_require, ) <file_sep>/airtools/kaczmarz.py from __future__ import division import logging from numpy import zeros, unique,asarray from numpy.linalg import norm from scipy.sparse import issparse ''' <NAME> 2014 tested with Dense and Sparse arrays. (Aug 2014) inputs: A: M x N 2-D projection matrix b: N x 1 1-D vector of observations maxIter: maximum number of ART iterations x0: N x 1 1-D vector of initialization (a guess at x) lamb: relaxation parameter (see Herman Ch.11.2) stopmode: {None, MDP} stop before maxIter if solution is good enough (MDP is Morozov Discrepancy Principle) nonneg: enforces non-negativity of solution outputs: x: the estimated solution of A x = b residual: the error b-Ax References: <NAME>. " Fundamentals of Computerized Tomography", 2nd Ed., Springer, 2009 <NAME>. "The mathematics of computed tomography", SIAM, 2001 ''' def kaczmarz(A,b,maxIter=8,x0=None,lamb=1,stopmode=None,taudelta=0,nonneg=True): assert 0. <= lamb <= 2.,'unstable relaxation parameter' #%% user parameters residual = None #init n = A.shape[1] #only need rows if x0 is None: # we'll use zeros x0 = zeros(n,order='F') #1-D vector if stopmode is None or stopmode.lower() =='iter': # just use number of iterations sr = 0 elif stopmode.lower() == 'mdp' or stopmode.lower()== 'dp': sr = 1 if taudelta==0: logging.warning('you used tauDelta=0, which effectively disables Morozov discrepancy principle') else: sr = 0 logging.error("didn't understand stopmode command, defaulted to maximum iterations") #%% disregard all-zero columns of A if issparse(A): A = A.tocsr() #save time if it was csc sparse # speedup: compute norms along columns at once, and retrieve RowNormSq = asarray(A.multiply(A).sum(axis=1)).squeeze() # 50 times faster than dense for 1024 x 100000 A else: #is dense A # speedup: compute norms along columns at once, and retrieve RowNormSq = norm(A,ord=2,axis=1)**2 #timeit same for norm() and A**2.sum(axis=1) goodRows = unique(A.nonzero()[0]) x = x0.copy() # we'll leave the original x0 alone, and make a copy in x iIter = 0 stop = False # will always run at least once while not stop: #for each iteration for iRow in goodRows: #only not all-zero rows #denominator AND numerator are scalar! #den = np.linalg.norm(A[iRow,:],2)**2 #print(RowNormSq[iRow] == den) #num = ( b[iRow] - A[iRow,:].dot(x) ) #x = x + np.dot( lamb * num/den , A[iRow,:] ) x += lamb * ( b[iRow] - A[iRow,:].dot(x) ) / RowNormSq[iRow] * A[iRow,:] #first two terms are scalar always if nonneg: x[x<0] = 0 iIter += 1 #handle stop rule stop = iIter > maxIter if sr == 0: # no stopping till iterations are done pass elif sr == 1: residual = b - A.dot(x) residualNorm = norm(residual,2) stop |= (residualNorm <= taudelta) if iIter % 200 == 0: #print update every N loop iterations for user comfort residualNorm = norm(b - A.dot(x),2) # NOT a duplicate for sr==0 ! print('Iteration {}, ||residual|| = {:.2f}'.format(iIter,residualNorm) ) return x,residual,iIter-1 <file_sep>/README.rst .. image:: https://travis-ci.org/scivision/airtools.svg?branch=master :target: https://travis-ci.org/scivision/airtools .. image:: https://coveralls.io/repos/scivision/airtools/badge.svg?branch=master&service=github :target: https://coveralls.io/github/scivision/airtools?branch=master .. image:: https://api.codeclimate.com/v1/badges/07d00b91f79c958c073a/maintainability :target: https://codeclimate.com/github/scivision/airtools/maintainability :alt: Maintainability =============== python-AIRtools =============== Limited subset of <NAME> and <NAME> `AIRtools 1.0 <http://www2.compute.dtu.dk/~pcha/AIRtoolsII/>`_ Matlab suite of inversion / regularization tools, along with some ReguTools functions. Also includes linear constrained least squares solver using cvxopt in ``lsqlin.py`` We only converted the functions we needed, many more are available in Matlab from `AIRtools 2 <https://github.com/jakobsj/AIRToolsII>`_. .. contents:: Install ======= :: python -m pip install -e . Usage ===== Just paste the code from each test into your console for the function you're interested in. Would you like to submit a pull request for an inversion example making a cool plot? ================ =========== Function Description ================ =========== picard.py Picard Plot kaczmarz.py Kaczmarz ART maxent.py Maximum Entropy Regularization (from ReguTools) rzr.py remove unused or little used rows from tomographic projection matrix. lsqlin.py linear constrained least squares solver matlab/logmart.m Implementation of log-MART used by Joshua Semeter in several publications fortran/logmart.f90 log-MART in Fortran ================ =========== Examples -------- See ``tests/test.py``. Tests ----- You can run a comparison of the Python code with the Matlab code in the ``matlab/`` directory by:: ./tests/test_octave.py which runs the Matlab version via `Oct2Py <https://blink1073.github.io/oct2py/>`_. <file_sep>/airtools/logmart.py #!/usr/bin/env python """ solve b=Ax using parallel log-ent mart. Original Matlab by <NAME> port to Python by <NAME> """ from numpy import ones_like,zeros_like,ones,sqrt def logmart(A,b,relax=1.,x0=None,sigma=None,max_iter=200): """ Displays delta Chisquare. Program is stopped if Chisquare increases. A is NxM array Y is Nx1 vector returns Mx1 vector relax user specified relaxation constant (default is 20.) x0 user specified initial guess (N vector) (default is backproject y, i.e., y#A) max_iter user specified max number of iterations (default is 20) AUTHOR: <NAME> LAST MODIFIED: 5-2015 Simple test problem A = diag([5, 5, 5]) x = array([1,2,3]) y = A.dot(x) or A @ x for python >= 3.5 """ #%% parameter check assert b.ndim==1,'y must be a column vector' assert A.ndim==2,'A must be a matrix' assert A.shape[0] == b.size,'A and y row numbers must match' assert isinstance(relax,float),'relax is a scalar float' b = b.copy() # needed to avoid modifying outside this function! #%% set defaults if sigma is None: sigma=ones_like(b) if x0 is None: # backproject x = A.T.dot(b) / A.ravel().sum() xA = A.dot(x) x = x * b.max() / xA.max() elif isinstance(x0,(float,int)) or x0.size == 1: # replicate x = x0*ones_like(b); else: x=x0 #%% make sure there are no 0's in y b[b<=1e-8] = 1e-8 # W=sigma; # W=linspace(1,0,size(A,1))'; # W=rand(size(A,1),1); W = ones(A.shape[0]) W = W / W.sum() i=0 done=False arg= ((A.dot(x) - b)/sigma)**2. chi2 = sqrt(arg.sum()) while not done: #%% iterate solution, plot estimated data (diag elems of x#A) i+=1 xold = x xA = A.dot(x) t = (1./(xA)).min() C = relax*t*(1.-(xA/b)) x = x / (1-x*(A.T.dot(W*C))) #%% monitor solution chiold = chi2 chi2 = sqrt( (((xA - b)/sigma)**2).sum() ) # dchi2=(chi2-chiold); done= ((chi2>chiold) & (i>2)) | (i==max_iter) | (chi2<0.7) #%% plot # figure(9); clf; hold off; # Nest=reshape(x,69,83); # imagesc(Nest); caxis([0,1e11]); # set(gca,'YDir','normal'); set(gca,'XDir','normal'); # pause(0.02) y_est = A.dot(xold) return xold,y_est,chi2,i
471a7d89483a12c40c58ae2f70b99dfaf57130c4
[ "Python", "reStructuredText" ]
7
Python
navyTensor/airtools
23ac4752477851d82982bd1387179598ffef858c
847a26f25093d865743adfbc549baa2239eacdb5
refs/heads/master
<file_sep># facebook-tool Để đảm bảo an toàn cho việc dùng token facebook vào mục đích cá nhân và tiết kiệm thời gian như đã nói ở trên thì bạn nên dùng phương pháp lấy token trực tiếp trên facebook theo các bước bên dưới. Bước 1: Đăng nhập vào tài khoản Facebook trên trình duyệt tại https://fb.com Bước 2: Bấm vào đường link này (cũng là của facebook nên yên tâm chỉ có mình bạn biết): https://m.facebook.com/composer/ocelot/async_loader/?publisher=feed Bước 3: Copy chuỗi ký tự bắt đầu bằng "EAA..." (có thể bấm Ctrl + F để tìm cho nhanh) Bước 4: Vào link facebook này kiểm tra xem token đã full quyền chưa https://developers.facebook.com/tools/debug/accesstoken/ (1) : copy token để kiểm tra. (2) : xem đã full quyền hay chưa. Reference: - https://ahachat.com/help/blog/cach-lay-token-facebook - https://developers.facebook.com/blog/post/2013/04/03/new-apis-for-comment-replies/ Copy token ở bước 3. Vào terminal gõ `export FB_TOKEN=<token ở bước 3>` <file_sep>import requests class Page: def __init__(self, page_id, page_token=None, user_token=None): if page_token is None and user_token is None: raise Exception("'page_token' or 'user_token' must set") self.page_token = page_token self.page_id = page_id self.user_token = user_token if page_token is None: self.page_token = self.get_page_token(page_id) print(f"Get page token ok. Page token is: {self.page_token}") def get_page_token(self, page_id): end_point = f"https://graph.facebook.com/{page_id}" params = { 'fields': 'access_token', 'access_token': self.user_token } response = requests.get(end_point, params=params) if response.status_code != 200: raise Exception( f'Cannot get page token from page {page_id}, status code: {response.status_code}, message: {response.json()}') response = response.json() data = response.get("access_token") return data def get_comments(self, post_id): host = "https://graph.facebook.com" end_point = f"{host}/{post_id}/comments" params = { "access_token": self.page_token, "limit": 2000 } response = requests.get(end_point, params=params) try: if response.status_code != 200: raise Exception( f'Cannot get comment from post {post_id}, status code: {response.status_code}, message: {response.json()}') response = response.json() data = response.get("data") return data except Exception as e: print(f"Error when get comment from {post_id}, {e}") return [] # def get_replies(self, comment_id): # host = "https://graph.facebook.com" # end_point = f"{host}/{comment_id}/comments" # params = { # "access_token": self.page_token, # "limit": 2000 # } # response = requests.get(end_point, params=params) # if response.status_code != 200: # raise Exception( # f'Cannot get comment from post {comment_id}, status code: {response.status_code}, message: {response.json()}') # response = response.json() # data = response.get("data") # return data def get_comment_with_replies(self, post_id): comments = self.get_comments(post_id) all_comments = comments.copy() for comment in comments: comment_id = comment.get('id') if comment_id is not None: sub_comments = self.get_comment_with_replies(comment_id) if len(sub_comments) > 0: all_comments += sub_comments return all_comments def send_message_to_user(self, user_id, message): end_point = 'https://graph.facebook.com/me/messages' params = { "access_token": self.page_token } headers = {"Content-Type": "application/json"} try: body = { "messaging_type": "<MESSAGING_TYPE>", "recipient": { "id": str(user_id) }, "message": { "text": message } } return True except Exception as e: print(f"Cannot send message to {user_id}, {e}") return False <file_sep>class MessageType: TEXT = 'Text' <file_sep>from core.page import Page import os import json if __name__ == '__main__': page_id = 913770675483798 user_token = os.environ.get('FB_TOKEN') page_token = os.environ.get('PAGE_TOKEN') if user_token is None and page_token is None: print("set FB_TOKEN, PAGE_TOKEN environment to your access token fb") exit(0) page_inst = Page(page_id=page_id, user_token=user_token, page_token=page_token) post_id = 941483042712561 # post_id = '941483042712561_941736682687197' comments = page_inst.get_comments(post_id) # print(json.dumps(comments, indent=4, ensure_ascii=False)) comment_id = '941483042712561_941736682687197' replies = page_inst.get_comments(comment_id) # print(json.dumps(replies, indent=4, ensure_ascii=False)) all_comments_with_replies = page_inst.get_comment_with_replies(post_id) print(json.dumps(all_comments_with_replies, indent=4, ensure_ascii=False)) for cmt in all_comments_with_replies: print(cmt.get("message")) user_id = 100005103257451 # truonghang message = "Hello Hang Ham"
2ca99e2862ab7e7b2d4cacf4ab0722af7c410661
[ "Markdown", "Python" ]
4
Markdown
vanchung1995/facebook-tool
ab0f43f704bb7e8ffe8dbe4aa6d97d96b27b46e8
5238d56ab2293b2d095bf0d6756a24c80dbccf5f
refs/heads/master
<file_sep>// // APIs.h // Demo布丁动画 // // Created by apple on 15/12/8. // Copyright © 2015年 apple. All rights reserved. // #ifndef APIs_h #define APIs_h #define kHomePath @"http://pudding.cc/api/v1/" #define kCategoryScrollImages @"config?fields=featured_banner&apiKey=yuki_android&version=2.6.5&timestamp=1442737459&auth1=<KEY>" #define kCategoryCollectionViewCell @"/category?offset=0&limit=18&apiKey=yuki_android&version=2.6.5&timestamp=1442739762&auth1=76d6029863f2c0c3081e9dea9b67d0ee" #define kScrollImagesArray @"featured_banner" #define kCellId @"cellId" #endif /* APIs_h */
4e9177ab55750a1d122e16789251a6224fc55690
[ "C" ]
1
C
CoderFShieh/gitskills
18f572222ed6303f1a22be52476d114843a42eb9
fa2948d628c6d3737f258da9fbc76c1c1b26a33a
refs/heads/master
<repo_name>mrAndersen/vulkan_1<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.13) set(CMAKE_CXX_STANDARD 14) project(vulkan_1) #find opengl in system find_package(OpenGL REQUIRED) # find vulkan in system find_package(Vulkan REQUIRED) if (${Vulkan_FOUND}) message(STATUS "Vulkan FOUND") message(STATUS "Vulkan Include in ${Vulkan_INCLUDE_DIRS}") message(STATUS "Vulkan Lib in ${Vulkan_LIBRARIES}") endif () # build gflw from soubmodules add_subdirectory(vendor/glfw) set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) #includes include_directories( ${Vulkan_INCLUDE_DIRS} ${OPENGL_INCLUDE_DIR} vendor/glfw/include ) set( LIBS ${Vulkan_LIBRARIES} glfw ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY} ) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) add_executable(vulkan_1 main.cpp src/core/vulkan_init.cpp src/core/vulkan_init.h src/core/macro.h) target_include_directories(vulkan_1 PUBLIC ${OPENGL_INCLUDE_DIR}) target_link_libraries(vulkan_1 ${LIBS})<file_sep>/main.cpp #include <iostream> #include "src/core/vulkan_init.h" #include "src/core/macro.h" void glfwErrorCallback(int error, const char *description) { printf("\t -- GLFW \"%s\"\n", description); } int main() { glfwSetErrorCallback(glfwErrorCallback); glfwInit(); VkInstance vkInstance = createVkInstance(); VkPhysicalDevice vkPhysicalDevice = createVkPhysicalDevice(vkInstance); uint32_t queueFamilyIndex = getGraphicsBitQueueFamily(vkPhysicalDevice); VkDevice vkDevice = createVkDevice(vkPhysicalDevice, queueFamilyIndex); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); GLFWwindow *window = glfwCreateWindow(1366, 768, "vulkan_1 test", nullptr, nullptr); VkSurfaceKHR vkSurfaceKHR = createVkSurface(vkInstance, window); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); } vkDestroySurfaceKHR(vkInstance, vkSurfaceKHR, nullptr); vkDestroyDevice(vkDevice, nullptr); vkDestroyInstance(vkInstance, nullptr); glfwDestroyWindow(window); glfwTerminate(); return 0; }<file_sep>/src/core/macro.h #ifndef VULKAN_1_MACRO_H #define VULKAN_1_MACRO_H #include <cstdlib> #include <stdio.h> #include <GLFW/glfw3.h> #define ASSERT_VK(result) \ if(result != VK_SUCCESS){ \ printf("\t -- VK %d",result); \ exit(-1); \ } #define C_SIZE(array) sizeof(array) / sizeof(array[0]) #endif //VULKAN_1_MACRO_H <file_sep>/src/core/vulkan_init.cpp #include "vulkan_init.h" #ifdef WIN32 //#include <vulkan/vulkan_win32.h> //#include <windef.h> #endif const int maxGPUProcessors = 16; VkInstance createVkInstance() { VkInstance vkInstance = nullptr; const char *extensions[] = { VK_KHR_SURFACE_EXTENSION_NAME, #ifdef WIN32 //Это пиздецовый говнкод, но я не осилил нахождение хедера с HWND для винды "VK_KHR_win32_surface" #endif }; VkInstanceCreateInfo vkInstanceCreateInfo = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; vkInstanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; vkInstanceCreateInfo.ppEnabledExtensionNames = extensions; vkInstanceCreateInfo.enabledExtensionCount = C_SIZE(extensions); ASSERT_VK(vkCreateInstance(&vkInstanceCreateInfo, nullptr, &vkInstance)); return vkInstance; } VkPhysicalDevice createVkPhysicalDevice(VkInstance vkInstance) { VkPhysicalDevice physicalDevices[maxGPUProcessors]; uint32_t physicalDeviceCount = C_SIZE(physicalDevices); ASSERT_VK(vkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDevices)); VkPhysicalDevice physicalDevice = pickPhysicalDevice(physicalDevices); VkPhysicalDeviceProperties vkPhysicalDeviceProperties; vkGetPhysicalDeviceProperties(physicalDevice, &vkPhysicalDeviceProperties); return physicalDevice; } VkPhysicalDevice pickPhysicalDevice(VkPhysicalDevice *physicalDevices) { VkPhysicalDevice vkPhysicalDevice = nullptr; for (int i = 0; i < C_SIZE(physicalDevices); ++i) { VkPhysicalDeviceProperties vkPhysicalDeviceProperties; vkGetPhysicalDeviceProperties(physicalDevices[i], &vkPhysicalDeviceProperties); VkPhysicalDeviceFeatures vkPhysicalDeviceFeatures; vkGetPhysicalDeviceFeatures(physicalDevices[i], &vkPhysicalDeviceFeatures); if ( vkPhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && vkPhysicalDeviceFeatures.geometryShader ) { getGraphicsBitQueueFamily(physicalDevices[i]); printf( "Selected GPU_%d: Name -> %s, ID -> %d, ApiVersion -> %d, Vendor -> %d\n", i, vkPhysicalDeviceProperties.deviceName, vkPhysicalDeviceProperties.deviceID, vkPhysicalDeviceProperties.apiVersion, vkPhysicalDeviceProperties.vendorID ); return physicalDevices[i]; } } throw std::runtime_error("No suitable GPUs find in the system!"); } VkDevice createVkDevice(VkPhysicalDevice vkPhysicalDevice, uint32_t queueFamilyIndex) { VkDevice vkDevice = nullptr; const std::vector<const char *> deviceExtenstions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; float queuePriority = 1.0f; VkDeviceQueueCreateInfo queueCreateInfo = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; VkDeviceCreateInfo vkDeviceCreateInfo = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; vkDeviceCreateInfo.pQueueCreateInfos = &queueCreateInfo; vkDeviceCreateInfo.queueCreateInfoCount = 1; vkDeviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtenstions.size()); vkDeviceCreateInfo.ppEnabledExtensionNames = deviceExtenstions.data(); ASSERT_VK(vkCreateDevice(vkPhysicalDevice, &vkDeviceCreateInfo, nullptr, &vkDevice)); return vkDevice; } VkSurfaceKHR createVkSurface(VkInstance instance, GLFWwindow *window) { VkSurfaceKHR vkSurfaceKHR = nullptr; ASSERT_VK(glfwCreateWindowSurface(instance, window, nullptr, &vkSurfaceKHR)); return vkSurfaceKHR; } uint32_t getGraphicsBitQueueFamily(VkPhysicalDevice vkPhysicalDevice) { uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamilyCount, queueFamilies.data()); uint32_t i = 0; for (const auto &queueFamily:queueFamilies) { if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { return i; } i++; } throw std::runtime_error("No VK_QUEUE_GRAPHICS_BIT queue family found"); } VkQueue getGraphicsQueue(VkDevice vkDevice, uint32_t familyIndex) { VkQueue graphicsQueue = nullptr; vkGetDeviceQueue(vkDevice, familyIndex, 0, &graphicsQueue); return graphicsQueue; } <file_sep>/src/core/vulkan_init.h #ifndef VULKAN_1_VULKAN_CORE_H #define VULKAN_1_VULKAN_CORE_H #include <vulkan/vulkan.h> #include <stdexcept> #include "macro.h" #include <vector> VkInstance createVkInstance(); VkPhysicalDevice pickPhysicalDevice(VkPhysicalDevice *physicalDevices); VkPhysicalDevice createVkPhysicalDevice(VkInstance vkInstance); VkDevice createVkDevice(VkPhysicalDevice vkPhysicalDevice, uint32_t queueFamilyIndex); VkQueue getGraphicsQueue(VkDevice vkDevice, uint32_t familyIndex); uint32_t getGraphicsBitQueueFamily(VkPhysicalDevice vkPhysicalDevice); VkSurfaceKHR createVkSurface(VkInstance instance, GLFWwindow *window); #endif //VULKAN_1_VULKAN_CORE_H
9ff5d88b7d3a8dc51b7258063ead5bf300719275
[ "C", "CMake", "C++" ]
5
CMake
mrAndersen/vulkan_1
28206dd423518b646b905c6fd4c31d68937ad619
09dfe489c304e0865d1c481ca923d71b0bd57a07
refs/heads/main
<repo_name>smathur910/RegisterApp-Kotlin<file_sep>/app/src/main/java/com/example/registerapp/MainActivity.kt package com.example.registerapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import androidx.appcompat.app.AlertDialog import androidx.fragment.app.FragmentManager class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val firstFragment = NavFragment(); val fm: FragmentManager = supportFragmentManager fm.beginTransaction().add(R.id.mainLayout, firstFragment).commit() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.topbar_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val actionLogout = AlertDialog.Builder(this) .setTitle("Logout") .setMessage("Are you want to logout?") .setPositiveButton("Ok"){dialogInterface, which -> finish() } .setNegativeButton("Cancel", null) when(item.itemId){ R.id.iLogout -> actionLogout.show() } return true } }<file_sep>/app/src/main/java/com/example/registerapp/myadapter.kt package com.example.registerapp import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import java.util.* class myadapter(var dataholder: ArrayList<datamodel>) : RecyclerView.Adapter<myadapter.myviewholder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): myviewholder { val view: View = LayoutInflater.from(parent.context).inflate(R.layout.single_row, parent, false) return myviewholder(view) } override fun onBindViewHolder(holder: myviewholder, position: Int) { holder.img.setImageResource(dataholder[position].getImage()) holder.desc.text = dataholder[position].getDesc() } override fun getItemCount(): Int { return dataholder.size } inner class myviewholder(itemView: View) : RecyclerView.ViewHolder(itemView) { var img: ImageView var desc: TextView init { img = itemView.findViewById(R.id.img1) desc = itemView.findViewById(R.id.t1) } } } <file_sep>/settings.gradle rootProject.name = "RegisterApp" include ':app' <file_sep>/app/src/main/java/com/example/registerapp/NavFragment.kt package com.example.registerapp import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton class NavFragment : Fragment() { var recyclerView: RecyclerView? = null var dataholder: ArrayList<datamodel>? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val nav = inflater.inflate(R.layout.fragment_nav, container, false) val recyclerView = nav.findViewById<RecyclerView>(R.id.recview) recyclerView.layoutManager = LinearLayoutManager(context) val aBtn = nav.findViewById<FloatingActionButton>(R.id.addBtn) aBtn.setOnClickListener{ val secondFragment = AddFragment(); parentFragmentManager.beginTransaction().replace(R.id.mainLayout,secondFragment).commit(); } dataholder = java.util.ArrayList() val ob1 = datamodel(R.drawable.profile, "Angular") dataholder!!.add(ob1) val ob2 = datamodel(R.drawable.profile, "Java") dataholder!!.add(ob2) val ob3 = datamodel(R.drawable.profile, "Kotlin") dataholder!!.add(ob3) val ob4 = datamodel(R.drawable.profile, "js") dataholder!!.add(ob4) val ob5 = datamodel(R.drawable.profile, "html") dataholder!!.add(ob5) val ob6 = datamodel(R.drawable.profile, "game") dataholder!!.add(ob6) val ob7 = datamodel(R.drawable.profile, "football") dataholder!!.add(ob7) recyclerView.adapter = myadapter(dataholder!!) return nav } }<file_sep>/app/src/main/java/com/example/registerapp/AddFragment.kt package com.example.registerapp import android.app.DatePickerDialog import android.app.TimePickerDialog import android.os.Build import android.os.Bundle import android.util.Patterns import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.annotation.RequiresApi import java.text.SimpleDateFormat import java.util.* class AddFragment : Fragment() { @RequiresApi(Build.VERSION_CODES.N) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val add = inflater.inflate(R.layout.fragment_add, container, false) val dbBtn = add.findViewById<Button>(R.id.dobBtn) var dobDetail = add.findViewById<TextView>(R.id.dobPick) var tmDetail = add.findViewById<TextView>(R.id.timePick) val tmBtm = add.findViewById<Button>(R.id.timeBtn) var uName = add.findViewById<EditText>(R.id.userName) var uEmail = add.findViewById<EditText>(R.id.userEmail) var uGender = add.findViewById<RadioGroup>(R.id.userGender) var uCondition = add.findViewById<CheckBox>(R.id.uCheckBox) var btn = add.findViewById<Button>(R.id.okBtn) fun validUser(): Boolean { val userName = uName.text.toString().trim { it <= ' ' } return if (!userName.isEmpty()) { if (userName.length >= 5 && userName.length <= 30) { true } else { uName.error = "Please enter valid Username" false } } else { uName.error = "Please enter a Username" true } } fun validEmail(): Boolean { val userEmail = uEmail.text.toString().trim { it <= ' ' } val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+" return if (userEmail.isEmpty()) { uEmail.error = "Please enter Email" false } else if (!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()) { uEmail.error = "Please enter valid Email" false } else { uEmail.error = null true } } fun validateGender(): Boolean { return if (uGender.checkedRadioButtonId == -1) { Toast.makeText(requireContext(), "Please Select Gender", Toast.LENGTH_SHORT).show() false } else { true } } fun validateCheck(): Boolean { return if (uCondition.isChecked) { true } else { Toast.makeText(requireContext(), "Please Select T&C", Toast.LENGTH_SHORT).show() false } } // fun validateDate(): Boolean { // val dobD = dobDetail.text.toString().trim { it <= ' ' } // return if (dobD.isEmpty()) { // dobDetail.error = "Please Choose DOB" // false // } else { // dobDetail.error = null // true // } // } val c = Calendar.getInstance() val year = c.get(Calendar.YEAR) val month = c.get(Calendar.MONTH) val day = c.get(Calendar.DAY_OF_MONTH) dbBtn.setOnClickListener{ val dpd = DatePickerDialog( requireContext(), DatePickerDialog.OnDateSetListener{view, mYear, mMonth, mDay -> dobDetail.text = ""+mDay+"/"+mMonth+"/"+mYear }, year, month, day ) dpd.show() } tmBtm.setOnClickListener{ val timeSetListener = TimePickerDialog.OnTimeSetListener{view: TimePicker?, hourOfDay: Int, minute: Int -> c.set(Calendar.HOUR_OF_DAY, hourOfDay) c.set(Calendar.MINUTE, minute) tmDetail.text = SimpleDateFormat("HH:mm").format(c.time) } TimePickerDialog(requireContext(), timeSetListener, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false).show() } btn.setOnClickListener{ if(!validUser() or !validEmail() or !validateGender() or !validateCheck()){ return@setOnClickListener } val bundle = Bundle() bundle.putString("Name", uName.toString()) bundle.putString("Email", uEmail.toString()) bundle.putString("Gender", uGender.toString()) val thirdFragment = DisplayFragment(); thirdFragment.setArguments(bundle); parentFragmentManager.beginTransaction().replace(R.id.mainLayout,thirdFragment).commit(); } return add } }<file_sep>/app/src/main/java/com/example/registerapp/datamodel.kt package com.example.registerapp class datamodel { private var img:Int private var desc:String constructor(img: Int, desc: String) { this.img = img this.desc = desc } fun getImage(): Int { return img } fun setImage(image: Int) { img = image } fun getDesc(): String? { return desc } fun setDesc(desc: String?) { this.desc = desc!! } }
1bbd630ae3cfcb149cc4aa51a6fe0a2eb0f04188
[ "Kotlin", "Gradle" ]
6
Kotlin
smathur910/RegisterApp-Kotlin
503aecfd0a4439a3d6b69817c0d2eef7b4d4d7e1
fca41f29b8223184473b096edfd2b3511515673b
refs/heads/main
<file_sep>import io from 'socket.io-client'; import { processBoardUpdate, processUserUpdate } from './state'; import { showErrorMsg } from './htmlController' const Constants = require('../shared/constants'); const socketProtocol = (window.location.protocol.includes('https')) ? 'wss' : 'ws'; const socket = io(`${socketProtocol}://${window.location.host}`, { reconnection: false }); const connectedPromise = new Promise(resolve => { socket.on('connect', () => { console.log('Connected to server!'); resolve(); }); }); export const connect = () => ( connectedPromise.then(() => { // Register callbacks socket.on(Constants.MSG_TYPES.BOARD_UPDATE, processBoardUpdate); socket.on(Constants.MSG_TYPES.USER_UPDATED,processUserUpdate); socket.on(Constants.MSG_TYPES.SERVER_ERROR, showErrorMsg) socket.on('disconnect', () => { console.log('Disconnected from server.'); }); }) ); export const draw = line => { socket.emit(Constants.MSG_TYPES.DRAW, line); }; export const eraseLine = line => { socket.emit(Constants.MSG_TYPES.ERASE, line); }; export const connectToRoom = (roomname,name) => { socket.emit(Constants.MSG_TYPES.CONNECT,roomname,name); }; export const createRoom = (roomname,name) => { socket.emit(Constants.MSG_TYPES.CREATE_BOARD,roomname,name); }; export const changePermission = (sockedId, permision) => { socket.emit(Constants.MSG_TYPES.SET_PERMISSION,permision,sockedId); }<file_sep>const express = require('express'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const socketio = require('socket.io'); const Constants = require('../shared/constants'); const BoardCollection = require('./boardCollection'); const webpackConfig = require('../../webpack.dev.js'); // Setup an Express server const app = express(); app.use(express.static('public')); if (process.env.NODE_ENV === 'development') { // Setup Webpack for development const compiler = webpack(webpackConfig); app.use(webpackDevMiddleware(compiler)); } else { // Static serve the dist/ folder in production app.use(express.static('dist')); } // Listen on port const port = 3000; const server = app.listen(port); console.log(`Server listening on port ${port}`); // Setup socket.io const io = socketio(server); // Setup the Board const boards = new BoardCollection(); // Listen for socket.io connections io.on('connection', socket => { socket.on(Constants.MSG_TYPES.CREATE_BOARD, handleCreateBoard) socket.on(Constants.MSG_TYPES.CONNECT, handleAddUser) socket.on(Constants.MSG_TYPES.DRAW, handleDraw); socket.on(Constants.MSG_TYPES.ERASE, handleErase); socket.on(Constants.MSG_TYPES.GET_BOARD, handleGetBoard); socket.on(Constants.MSG_TYPES.SET_PERMISSION, handelSetPermission) socket.on('disconnect', onDisconnect); }); function handelSetPermission(permission,socketId){ let board = boards.getRoomById(this.id); if(board){ board.changePermission(io,this,permission,socketId); } } function handleCreateBoard(roomName,name) { let succes = boards.createNewRoom(roomName); let board = boards.getRoomByName(roomName); if(board && succes){ this.join(roomName) board.addUser(io,this,name,succes) board.handleGetBoard(this) }else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Can't create Room. Name already in Use") } } function handleDraw(line) { let board = boards.getRoomById(this.id); if(board){ board.handleDraw(this, line,io); } else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Server Error") } } function handleErase(line){ let board = boards.getRoomById(this.id); if(board){ board.handleErase(this,line,io) }else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Server Error") } } function handleGetBoard() { let board = boards.getRoomById(this.id); if(board){ board.handleGetBoard(this); }else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Server Error") } } function onDisconnect(){ let board = boards.getRoomById(this.id) if(board){ board.removeUser(io,this); }else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Server Error") } } function handleAddUser(roomName,name){ let board = boards.getRoomByName(roomName); if(board){ this.join(roomName) //make the socke join the room board.addUser(io,this,name) board.handleGetBoard(this) }else{ this.emit(Constants.MSG_TYPES.SERVER_ERROR, "Server Error: Most likely the RoomName is wrong") } } <file_sep>import { changePermission } from './networking'; import { getUserName } from './state'; export function renderHTMLUserList(users){ //socked:id:{"name": , "permission": } document.getElementById("userpanel").innerHTML = ""; let allowed = users[Object.keys(users).filter(id => users[id]["name"] == getUserName())[0]]["permission"] != 0 Object.keys(users).forEach(userId => { let element = `<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>\ <div class="dropdown">\ <button onclick="${allowed ? `toggleMenue('${userId}')` : ""}" class="dropbtn">${users[userId]["name"]}</button>\ <div id="dropdown-${userId}" class="dropdown-content">\ <a id="changeButton-${userId}">${users[userId]["permission"] == 0 ? "Make Admin" : "Make User"}</a>\ </div>\ </div><br>`; document.getElementById("userpanel").innerHTML += element; }) Object.keys(users).forEach(userId => { document.getElementById("changeButton-"+userId).onclick = () => changePermission(userId,users[userId]["permission"] == 0 ? 1 : 0); }) } export function showErrorMsg(msg){ document.getElementById("error-alert").style.display = "block"; document.getElementById("error-msg").innerHTML = msg; } export function getColor(){ if(document.getElementById("colorPicker")){ return document.getElementById("colorPicker").value; } return "#00000" }<file_sep>import { connect, createRoom, connectToRoom } from './networking'; import { startRendering, stopRendering } from './render'; import { startCapturingInput, stopCapturingInput } from './input'; import { setUserName } from './state'; import './css/bootstrap-reboot.css'; import './css/main.css'; window.addEventListener('DOMContentLoaded', (event) => { document.getElementById("createRoomButton").onclick = ()=>{ var roomId = document.getElementById("roomId").value; var name = document.getElementById("name").value; if(roomId != "" && name != ""){ newRoom(name,roomId) document.getElementById('myModal').style.display = "none"; } }; document.getElementById("joinRoomButton").onclick = ()=>{ var roomId = document.getElementById("roomId").value; var name = document.getElementById("name").value; if(roomId != "" && name != ""){ joinRoom(name,roomId) document.getElementById('myModal').style.display = "none"; } }; }); function joinRoom(name,roomid){ Promise.all([ connect(), ]).then(() => { setUserName(name) connectToRoom(roomid,name); startCapturingInput(); startRendering(); }).catch(console.error); } function newRoom(name,roomid){ Promise.all([ connect(), ]).then(() => { setUserName(name) createRoom(roomid,name); startCapturingInput(); startRendering(); }).catch(console.error); } <file_sep># OpenBoard A online Whiteboard. Everyone can create a Room and then users can join using a pin code. The creator of the Room is able to manage roles and allow specific users to draw. <file_sep>module.exports = Object.freeze({ MSG_TYPES: { BOARD_UPDATE: 'update_board', GET_BOARD: 'get_board', DRAW: 'draw', ERASE: 'erase', CONNECT: 'connect_user', DISSCONNECT: 'discnect_user', CREATE_BOARD: 'create_board', SET_PERMISSION: 'set_permission', USER_UPDATED: 'user_updated', SERVER_ERROR: 'server_error' }, }); <file_sep>import { getCurrentDrawing, upToDate } from './input'; import { renderHTMLUserList } from './htmlController'; import { backToXY } from './input'; import { getBounds } from './render' let board = []; let users = {}; let userName = ""; let middlePostion = [0,0] let endMiddlePosition = [0,0] let scale = 1; export function setUserName(name){ userName = name; } export function getUserName(){ return userName; } export function processBoardUpdate(update) { let {draw, erase} = update; //if the presentationmode is enabled, alwas set center the last written Element if(document.getElementById("presentationButton").innerHTML == "End Presentation Mode"){ let xy = (draw[0].points[draw[0].points.length - 1]); endMiddlePosition = [-xy[0]+getBounds()[0],-xy[1]+getBounds()[1]]; } board = board.concat(draw); erase.forEach(line => deleteLine(line)); upToDate(); } export function processUserUpdate(newUsers) { users = newUsers; renderHTMLUserList(users); } export function getCurrentState() { return [...board,getCurrentDrawing()]; } export function deleteLine(line){ board = board.filter((l) => JSON.stringify(l)!=JSON.stringify(line)) } export function addMiddlePosition(x,y){ middlePostion = [middlePostion[0]+x,middlePostion[1]+y] } export function getMiddlePosition(){ return middlePostion; } export function update(){ if(document.getElementById("presentationButton").innerHTML == "End Presentation Mode"){ const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); if(!equals(middlePostion,endMiddlePosition)){ middlePostion[0] += (endMiddlePosition[0] - middlePostion[0]) /10; middlePostion[1] += (endMiddlePosition[1] - middlePostion[1]) /10; } } } export function addScale(s){ if(s > 0){ scale = scale/(10/9); }else{ scale = scale*(10/9); } } export function addScaleTouch(s){ if(scale + s > 0){ scale += s; } } export function getScale(){ return scale; }<file_sep>import { deleteLine } from './state' import { eraseLine } from './networking' export function checkCollission(position, lines){ let m = position[0]; let n = position[1]; lines.forEach(line => { let points = line["points"] for(var i = 1; i < points.length;i++){ let A = difference(points[i][1] ,points[i-1][1]); let B = difference(points[i][0] ,points[i-1][0]); let S = Math.sqrt(A*A+B*B) let S1 = Math.sqrt((difference(points[i][0],m))**2+(difference(points[i][1],n))**2) let S2 = Math.sqrt((difference(points[i-1][0],m))**2+(difference(points[i-1][1],n))**2) if((S1+S2)-S < 0.5){ deleteLine(line); eraseLine(line); break; } } }); } function difference(a,b){ if(a > b){ return a-b; } return b-a; }
8e49875276547e56dbdd0d938b587b5ed6a0d5d4
[ "JavaScript", "Markdown" ]
8
JavaScript
Chris022/WeberBoard
9f88cc4c1016d7a9e4484eaf44c08dad558fa8ce
cde0cab6d8a61c8cdd49f472a151f6c148748ad3
refs/heads/master
<repo_name>dovancanhdev/E--Cordova-project<file_sep>/Brook/src/com/truong/brook/client/event/SelectCategoryEvent.java package com.truong.brook.client.event; import com.google.gwt.event.shared.GwtEvent; import com.truong.brook.shared.Category; public class SelectCategoryEvent extends GwtEvent<SelectCategoryEventHandler> { public static Type<SelectCategoryEventHandler> TYPE = new Type<SelectCategoryEventHandler>(); private Category category; public SelectCategoryEvent(Category category) { this.setCategory(category); } @Override public com.google.gwt.event.shared.GwtEvent.Type<SelectCategoryEventHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(SelectCategoryEventHandler handler) { handler.onSelectCategory(this); } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } <file_sep>/Brook/src/com/truong/brook/client/event/SelectBookEvent.java package com.truong.brook.client.event; import com.google.gwt.event.shared.GwtEvent; import com.truong.brook.shared.Book; public class SelectBookEvent extends GwtEvent<SelectBookEventHandler> { public static Type<SelectBookEventHandler> TYPE = new Type<SelectBookEventHandler>(); private Long bookId; private Book book; public SelectBookEvent(Long bookId) { this.bookId = bookId; } public SelectBookEvent(Book film) { this.book = film; } @Override public com.google.gwt.event.shared.GwtEvent.Type<SelectBookEventHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(SelectBookEventHandler handler) { handler.onTapBook(this); } public Long getBookId() { return bookId; } public void setBookId(Long bookId) { this.bookId = bookId; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } } <file_sep>/Brook/compile.sh echo "Begin" echo "copy GWT.xml file" root="/Users/truongnguyen/Documents/workspace" project="$root/Cordova/Cordova-Brook" gwtProject="$root/Brook" ant -f build.xml echo "removing previous compiled folder" rm -rf $project/www/brook/* rm -rf $project/www/css/* rm -rf $project/www/images/* rm -rf $project/platforms/ios/www/brook/* rm -rf $project/platforms/ios/www/css/* rm -rf $project/platforms/ios/www/images/* rm -rf $project/platforms/android/assets/www/brook/* rm -rf $project/platforms/android/assets/www/css/* rm -rf $project/platforms/android/assets/www/images/* echo "copying newly compiled folder" cp -r $gwtProject/war/brook/* $project/www/brook/ cp -r $gwtProject/war/css/* $project/www/css/ cp -r $gwtProject/war/images/* $project/www/images/ cp -r $gwtProject/war/brook/* $project/platforms/ios/www/brook/ cp -r $gwtProject/war/css/* $project/platforms/ios/www/css/ cp -r $gwtProject/war/images/* $project/platforms/ios/www/images/ cp -r $gwtProject/war/brook/* $project/platforms/android/assets/www/brook/ cp -r $gwtProject/war/css/* $project/platforms/android/assets/www/css/ cp -r $gwtProject/war/images/* $project/platforms/android/assets/www/images/ ant -f $project/platforms/android/build.xml clean ant -f $project/platforms/android/build.xml release adb uninstall com.fut.brook adb install $project/platforms/android/bin/brook-release.apk echo "Done! enjoy result ^^" <file_sep>/Brook/src/com/truong/brook/client/sliding/MenuSliding.java package com.truong.brook.client.sliding; import java.util.List; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.RootPanel; import com.googlecode.mgwt.dom.client.event.tap.TapEvent; import com.googlecode.mgwt.dom.client.event.tap.TapHandler; import com.googlecode.mgwt.dom.client.recognizer.swipe.SwipeEndEvent; import com.googlecode.mgwt.dom.client.recognizer.swipe.SwipeEndHandler; import com.googlecode.mgwt.dom.client.recognizer.swipe.SwipeEvent.DIRECTION; import com.googlecode.mgwt.ui.client.util.CssUtil; import com.googlecode.mgwt.ui.client.widget.touch.TouchPanel; import com.truong.brook.client.ClientData; import com.truong.brook.client.ClientUtils; import com.truong.brook.client.CssToken; import com.truong.brook.client.view.CategoryViewItem; import com.truong.brook.shared.Category; public class MenuSliding extends SlidingPanel { private TouchPanel touchPanel = new TouchPanel(); private int widthMenu = 220; private boolean showCategory = false; public MenuSliding() { super(); slidingPanel.setHeight("100%"); this.setStyleName("leftMenuSliding", true); touchPanel.setWidth(ClientUtils.getScreenWidth()-widthMenu + "px"); touchPanel.setStyleName("tyty", true); touchPanel.setHeight("100%"); this.add(touchPanel); touchPanel.getElement().getStyle().setProperty("float", "left"); slidingPanel.getElement().getStyle().setProperty("float", "left"); scrollPanel.setWidth(widthMenu + "px"); scrollPanel.getElement().getStyle().setBackgroundColor("#1d1d1d"); touchPanel.addTapHandler(new TapHandler() { @Override public void onTap(TapEvent event) { hide(); } }); touchPanel.addSwipeEndHandler(new SwipeEndHandler() { @Override public void onSwipeEnd(SwipeEndEvent event) { if(event.getDirection() == DIRECTION.RIGHT_TO_LEFT) { hide(); } } }); scrollPanel.refresh(); } @Override public void show() { super.show(); if(!showCategory) showCategories(); scrollPanel.setHeight(ClientUtils.getScreenHeight() + 50+ "px"); CssUtil.translate(RootPanel.get().getElement(), widthMenu, 0); CssUtil.setTransitionDuration(RootPanel.get().getElement(), 200); } private void showCategories() { showCategory = true; ClientUtils.log("Show categories"); ClientData.getCategories(new AsyncCallback<List<Category>>() { @Override public void onSuccess(List<Category> result) { ClientUtils.log("Result: " + result.size()); for(Category category : result) { CategoryViewItem item = new CategoryViewItem(category); item.setStyleName(CssToken.BUTTON_FLATSTYLE + " " + CssToken.LEFTMENU_BUTTON, true); mainPanel.add(item); } scrollPanel.refresh(); } @Override public void onFailure(Throwable caught) { } }); } @Override public void hide() { super.hide(); CssUtil.translate(RootPanel.get().getElement(), 0, 0); CssUtil.setTransitionDuration(RootPanel.get().getElement(), 200); } @Override protected String getAnimationCss() { return "xxy"; } @Override protected void setPosition() { this.getElement().getStyle().setPosition(Position.ABSOLUTE); this.getElement().getStyle().setTop(0, Unit.PX); this.getElement().getStyle().setLeft(-220, Unit.PX); } public static void clearAll() { if(MenuSliding.currentSliding != null) { MenuSliding.currentSliding.removeFromParent(); } } } <file_sep>/Brook/src/com/truong/brook/client/activities/home/NewHomeViewImpl.java package com.truong.brook.client.activities.home; import java.util.List; import com.google.gwt.dom.client.Style.Unit; import com.googlecode.mgwt.ui.client.widget.list.celllist.BasicCell; import com.googlecode.mgwt.ui.client.widget.list.celllist.CellList; import com.truong.brook.client.activities.basic.BasicViewImpl; import com.truong.brook.shared.Book; import com.truong.brook.shared.IBasic; public class NewHomeViewImpl extends BasicViewImpl implements HomeView{ public NewHomeViewImpl() { super(); cellList = new CellList<IBasic>(new BasicCell<IBasic>() { @Override public String getDisplayString(IBasic model) { return ((Book)model).getTitle(); } }); layout.getScrollPanel().add(cellList); cellList.getElement().getStyle().setMarginLeft(0, Unit.PX); layout.getScrollPanel().setScrollingEnabledX(false); } @Override public void refreshView() { super.refreshView(); } @Override public void viewBooks(List<IBasic> list) { cellList.render(list); layout.getScrollPanel().refresh(); } } <file_sep>/Brook/src/com/truong/brook/client/event/SelectBookEventHandler.java package com.truong.brook.client.event; import com.google.gwt.event.shared.EventHandler; public interface SelectBookEventHandler extends EventHandler{ public void onTapBook(SelectBookEvent event); } <file_sep>/Brook/src/com/truong/brook/shared/Config.java package com.truong.brook.shared; public class Config { public static final boolean ADMIN_MODE = false; public static final Long ROOT_CATEGORY_ID = -1L; public static final long NULL_ID = -1; public static final String TEXT_EMPTY = ""; public static final double ZERO_VALUE = 0; public static final int TYPE_CATEGORY = 0; public static final int TYPE_AUTHOR = 1; public static final String APP_HOST_DOMAIN = "http://xxx.appspot.com/"; } <file_sep>/Brook/src/com/truong/brook/client/activities/PhoneActivityMapper.java package com.truong.brook.client.activities; import com.google.gwt.activity.shared.Activity; import com.google.gwt.activity.shared.ActivityMapper; import com.google.gwt.place.shared.Place; import com.truong.brook.client.activities.admin.AdminActivity; import com.truong.brook.client.activities.admin.AdminPlace; import com.truong.brook.client.activities.admin.createBook.CreateBookActivity; import com.truong.brook.client.activities.admin.createBook.CreateBookPlace; import com.truong.brook.client.activities.admin.createCategory.CreateCategoryActivity; import com.truong.brook.client.activities.admin.createCategory.CreateCategoryPlace; import com.truong.brook.client.activities.basic.BasicPlace; import com.truong.brook.client.activities.book.BookActivity; import com.truong.brook.client.activities.book.BookPlace; import com.truong.brook.client.activities.category.CategoryActivity; import com.truong.brook.client.activities.category.CategoryPlace; import com.truong.brook.client.activities.home.HomeActivity; import com.truong.brook.client.activities.home.HomePlace; public class PhoneActivityMapper implements ActivityMapper { private ClientFactory clientFactory; public PhoneActivityMapper(ClientFactory clientFactory){ this.clientFactory = clientFactory; } @Override public Activity getActivity(Place place) { if (place instanceof HomePlace) return new HomeActivity(clientFactory,(BasicPlace)place); if (place instanceof CategoryPlace) return new CategoryActivity(clientFactory, (BasicPlace)place); if (place instanceof BookPlace) return new BookActivity(clientFactory, (BasicPlace)place); if (place instanceof AdminPlace) return new AdminActivity(clientFactory, (BasicPlace)place); if (place instanceof CreateCategoryPlace) return new CreateCategoryActivity(clientFactory, (BasicPlace)place); if (place instanceof CreateBookPlace) return new CreateBookActivity(clientFactory, (BasicPlace)place); return null; } } <file_sep>/Brook/src/com/truong/brook/client/activities/basic/BasicActivity.java package com.truong.brook.client.activities.basic; import com.google.gwt.event.shared.EventBus; import com.google.gwt.place.shared.Place; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.googlecode.gwtphonegap.client.event.BackButtonPressedEvent; import com.googlecode.gwtphonegap.client.event.BackButtonPressedHandler; import com.googlecode.gwtphonegap.client.event.MenuButtonPressedEvent; import com.googlecode.gwtphonegap.client.event.MenuButtonPressedHandler; import com.googlecode.gwtphonegap.client.event.SearchButtonPressedEvent; import com.googlecode.gwtphonegap.client.event.SearchButtonPressedHandler; import com.googlecode.mgwt.dom.client.event.tap.TapEvent; import com.googlecode.mgwt.dom.client.event.tap.TapHandler; import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity; import com.truong.brook.client.Brook; import com.truong.brook.client.ClientUtils; import com.truong.brook.client.activities.ClientFactory; import com.truong.brook.client.activities.book.BookPlace; import com.truong.brook.client.activities.category.CategoryPlace; import com.truong.brook.client.event.SelectBookEvent; import com.truong.brook.client.event.SelectBookEventHandler; import com.truong.brook.client.event.SelectCategoryEvent; import com.truong.brook.client.event.SelectCategoryEventHandler; import com.truong.brook.client.sliding.SlidingPanel; public class BasicActivity extends MGWTAbstractActivity { protected final ClientFactory clientFactory; protected EventBus eventBus; protected BasicPlace place = null; public BasicActivity(ClientFactory clientFactory, BasicPlace place) { this.clientFactory = clientFactory; this.place = place; } @Override public void start(AcceptsOneWidget panel, final EventBus eventBus) { super.start(panel, eventBus); this.eventBus = eventBus; cancelAllHandlerRegistrations(); } public void start(AcceptsOneWidget panel, final EventBus eventBus, final BasicView basicView) { this.eventBus = eventBus; loadData(); bind(); if(basicView!=null) { basicView.refreshView(); addHandlerRegistration(basicView.getLayout().getHeaderPanel().getBackButton().addTapHandler(new TapHandler() { @Override public void onTap(TapEvent event) { onBackButtonPressed(); } })); //Add handler for leftmenu addHandlerRegistration(basicView.getLayout().getHeaderPanel().getLeftMenuButton().addTapHandler( new TapHandler() { @Override public void onTap(TapEvent event) { onMenuButtonPressed(); } })); addHandlerRegistration(eventBus.addHandler(SelectCategoryEvent.TYPE, new SelectCategoryEventHandler() { @Override public void onSelectCategory(SelectCategoryEvent event) { goTo(new CategoryPlace(place,event.getCategory())); basicView.getMenuSliding().hide(); } })); addHandlerRegistration(eventBus.addHandler(SelectBookEvent.TYPE, new SelectBookEventHandler() { @Override public void onTapBook(SelectBookEvent event) { goTo(new BookPlace(place,event.getBook())); } })); } } protected void bind() { addHandlerRegistration(Brook.phoneGap.getEvent().getBackButton().addBackButtonPressedHandler(new BackButtonPressedHandler() { @Override public void onBackButtonPressed(BackButtonPressedEvent event) { BasicActivity.this.onBackButtonPressed(); } })); addHandlerRegistration(Brook.phoneGap.getEvent().getMenuButton().addMenuButtonPressedHandler(new MenuButtonPressedHandler() { @Override public void onMenuButtonPressed(MenuButtonPressedEvent event) { BasicActivity.this.onMenuButtonPressed(); } })); addHandlerRegistration(Brook.phoneGap.getEvent().getSearchButton().addSearchButtonHandler(new SearchButtonPressedHandler() { @Override public void onSearchButtonPressed(SearchButtonPressedEvent event) { } })); } protected void onMenuButtonPressed() { if(clientFactory.getBasicView().getMenuSliding().isShowing()) clientFactory.getBasicView().getMenuSliding().hide(); else clientFactory.getBasicView().getMenuSliding().show(); } protected void onLeftMenuPressed() { } protected void loadData() { } protected void onBackButtonPressed() { if(SlidingPanel.hideSliding()) return; } protected void onRefreshScrollPanel() { } protected void goTo(Place newPlace) { if(newPlace == null) return; ClientUtils.log("Go to : " + newPlace.getClass().getName()); clientFactory.getPlaceController().goTo(newPlace); } } <file_sep>/Brook/src/com/truong/brook/client/activities/basic/BasicView.java package com.truong.brook.client.activities.basic; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.IsWidget; import com.googlecode.mgwt.ui.client.widget.list.celllist.HasCellSelectedHandler; import com.truong.brook.client.activities.basic.BasicViewImpl.Layout; import com.truong.brook.client.sliding.MenuSliding; public interface BasicView extends IsWidget{ Layout getLayout(); FlowPanel getContentPanel(); void refreshView(); int getViewId(); MenuSliding getMenuSliding(); HasCellSelectedHandler getCellList(); } <file_sep>/Brook/src/com/truong/brook/shared/Book.java package com.truong.brook.shared; import java.util.List; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Ignore; import com.googlecode.objectify.annotation.Index; @Entity @Cache public class Book extends IBasic{ /** * */ private static final long serialVersionUID = 1L; @Id private Long id; @Index private Long parentId = Config.NULL_ID; @Index private Long authorId = Config.NULL_ID; @Index private boolean hasChild = false; @Index private Double vote = Config.ZERO_VALUE; @Index private int voteCount; @Index private int viewedNumber; @Index private Long lastUpdate; private String title = Config.TEXT_EMPTY; private String description = Config.TEXT_EMPTY; private String author = Config.TEXT_EMPTY; private String avatarUrl = Config.TEXT_EMPTY; private String streamUrl = Config.TEXT_EMPTY; private Double price = Config.ZERO_VALUE; @Ignore private List<IBasic> childBooks = null; public Book() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAvatarUrl() { return avatarUrl; } public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public String getStreamUrl() { return streamUrl; } public void setStreamUrl(String streamUrl) { this.streamUrl = streamUrl; } public Long getAuthorId() { return authorId; } public void setAuthorId(Long authorId) { this.authorId = authorId; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Double getVote() { return vote; } public void setVote(Double vote) { this.vote = vote; } public int getVoteCount() { return voteCount; } public void setVoteCount(int voteCount) { this.voteCount = voteCount; } public int getViewedNumber() { return viewedNumber; } public void setViewedNumber(int viewedNumber) { this.viewedNumber = viewedNumber; } public Long getLastUpdate() { return lastUpdate; } public void setLastUpdate(Long lastUpdate) { this.lastUpdate = lastUpdate; } public boolean isHasChild() { return hasChild; } public void setHasChild(boolean hasChild) { this.hasChild = hasChild; } public List<IBasic> getChildBooks() { return childBooks; } public void setChildBooks(List<IBasic> childBooks) { this.childBooks = childBooks; } } <file_sep>/Brook/src/com/truong/brook/client/activities/book/BookActivity.java package com.truong.brook.client.activities.book; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.truong.brook.client.Brook; import com.truong.brook.client.activities.ClientFactory; import com.truong.brook.client.activities.basic.BasicActivity; import com.truong.brook.client.activities.basic.BasicPlace; import com.truong.brook.client.sliding.SlidingPanel; import com.truong.brook.shared.Book; public class BookActivity extends BasicActivity { private BookView view; private Book currentBook; public BookActivity(ClientFactory clientFactory, BasicPlace place) { super(clientFactory, place); currentBook = ((BookPlace)place).getBook(); } @Override public void start(AcceptsOneWidget panel, EventBus eventBus) { view = clientFactory.getBookView(); super.start(panel, eventBus, view); panel.setWidget(view); view.getLayout().getHeaderPanel().setCenter(currentBook.getTitle()); } @Override protected void bind() { super.bind(); } @Override protected void loadData() { view.viewBooks(currentBook); } @Override protected void onBackButtonPressed() { if (SlidingPanel.hideSliding()) { return; } Brook.getAudioPlayer().stopAudio(); goTo(place.getPreviousPlace()); } } <file_sep>/Brook/src/com/truong/brook/client/activities/category/CategoryViewImpl.java package com.truong.brook.client.activities.category; import com.truong.brook.client.activities.home.NewHomeViewImpl; public class CategoryViewImpl extends NewHomeViewImpl implements CategoryView{ } <file_sep>/Brook/src/com/truong/brook/client/activities/admin/createCategory/CreateCategoryPlace.java package com.truong.brook.client.activities.admin.createCategory; import com.truong.brook.client.activities.basic.BasicPlace; import com.truong.brook.shared.Category; public class CreateCategoryPlace extends BasicPlace { private Long parentId; private Category category; public CreateCategoryPlace(BasicPlace place, Category category, Long parentId) { super(place); this.category = category; this.parentId = parentId; } public Category getCategory() { return category; } public Long getParentId() { return parentId; } public String getToken() { return "createcategory"; } } <file_sep>/Brook/src/com/truong/brook/client/activities/book/BookView.java package com.truong.brook.client.activities.book; import com.truong.brook.client.activities.basic.BasicView; import com.truong.brook.shared.Book; public interface BookView extends BasicView{ void viewBooks(Book currentBook); } <file_sep>/Brook/src/com/truong/brook/client/activities/AppPlaceHistoryMapper.java package com.truong.brook.client.activities; import com.google.gwt.place.shared.PlaceHistoryMapper; import com.google.gwt.place.shared.WithTokenizers; import com.truong.brook.client.activities.home.HomePlace; @WithTokenizers({HomePlace.Tokenizer.class}) public interface AppPlaceHistoryMapper extends PlaceHistoryMapper { } <file_sep>/Brook/src/com/truong/brook/server/DataServiceImpl.java package com.truong.brook.server; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.googlecode.objectify.ObjectifyService; import com.truong.brook.client.DataService; import com.truong.brook.shared.Book; import com.truong.brook.shared.Category; import com.truong.brook.shared.Config; import com.truong.brook.shared.IBasic; public class DataServiceImpl extends DataManager implements DataService { /** * */ private static final long serialVersionUID = 1L; static { ObjectifyService.register(Book.class); ObjectifyService.register(Category.class); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp){ } @Override public Category getRootCategory() { Category root = new Category(); root.setTitle("Root"); root.setId(-1L); root.setChildCategories(getCategories(Config.ROOT_CATEGORY_ID)); return root; } @Override public List<IBasic> getChildrent(Long parentId) { List<IBasic> iBasics = new ArrayList<IBasic>(); List<Category> categories = getCategories(parentId); if(categories == null || categories.isEmpty()) { List<Book> books = getBooks(parentId); for(Book book : books) { iBasics.add(book); } } else { for(Category category : categories) { iBasics.add(category); } } return iBasics; } @Override public Long updateCategory(Category category) { return super.updateCategory(category); } @Override public Long updateBook(Book book) { return super.updateBook(book); } } <file_sep>/Brook/src/com/truong/brook/client/activities/admin/AdminView.java package com.truong.brook.client.activities.admin; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.Widget; import com.truong.brook.shared.Book; import com.truong.brook.shared.Category; public interface AdminView { Widget asWidget(); void refresh(); void showCategory(Category category); HasClickHandlers getCreateCategoryButton(); HasClickHandlers getCreateBookButton(); void showBooks(Book book); }
57fa7cf58527ea7f41e4d35a24bf7aa736d8a0da
[ "Java", "Shell" ]
18
Java
dovancanhdev/E--Cordova-project
be015999b441afdfd2cedf1e5b379790ebf71d50
f4b4833469ea3c304c869e03579458ee04939b59
refs/heads/master
<file_sep>rootProject.name = 'reactive-service' <file_sep>package com.example.practice; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @RestController public class TestController { @GetMapping("/nums/{num}") public Flux<String> num(@PathVariable("num") int num) { return Flux.just("Hello Number:"+num); } }
5a65df64ac1627a080735e358af47a2cccc39ffa
[ "Java", "Gradle" ]
2
Gradle
KarthikBashyam/spring-reactive
7d6271105a06656639619fb0082b1bc78e1f5142
b90018f8b48640cc481b0c0259ea12c73d0bfd85
refs/heads/master
<repo_name>simonjwright/ACATS<file_sep>/docs/ug-563.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Expected Results for Class L Tests</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} DIV.Indented1 {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 2.0em; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-562.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-564.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>5.6.3 Expected Results for Class L Tests</H1> <div class="Normal">Class L tests are expected to be rejected before execution begins. They must be submitted to the compiler and to the linker/binder. If an executable is generated, then it must be submitted for execution. Unless otherwise documented, the test is graded as &quot;failed&quot; if it begins execution, regardless of whether any output is produced.. (Twenty-eight L tests contain documentation indicating that they may execute. See below.)</div> <div class="Normal">In general, an L test is expected to be rejected at link/bind time. Some tests contain <TT>-- ERROR:</TT> indications; an implementation that reports an error associated with one of these lines is judged to have passed the test (provided, of course, that the link attempt fails).</div> <div class="Normal" style="margin-bottom: 0.4em">The following tests are exceptions to the general rule that an L test must not execute:</div> <div class="Indented1"><SPAN STYLE="font-size: 80%">Test LXE3002, for the Distributed Systems Annex, is a test that has two partitions, each of which may execute. As documented in the source code, this test is graded &quot;failed&quot; if both partitions report &quot;TENTATIVELY PASSED&quot;. Other outcomes are graded as appropriate for Class L tests.</SPAN></div> <div class="Indented1"><SPAN STYLE="font-size: 80%">Tests LA14001..27 and LA20002 (twenty-seven core language tests), as documented in the source code, may execute if automatic recompilation is supported. These tests are graded as &quot;passed&quot; if they execute and report &quot;PASSED&quot;. Other outcomes are graded as appropriate for Class L tests.</SPAN>&nbsp;</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-562.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-564.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/UPDATING.md # Updating the repository # There are two branches: * `acats-4.1` contains the original source code from the [ACATS website][Ada-Auth] (reorganised to match the GCC test suite layout) * `master` contains the same, with minor changes and with scripts and other data to support running in the GCC context. Obtain the updated test data (e.g. `mod_4_1bb.tar.Z`) and the documentation (e.g. `mod-list-4.1bb.txt`) from the [ACATS website][Ada-Auth]. Switch to the `acats-4.1` branch. Create a new directory for the updated test data (e.g. `bb/`) and change directory into it. Unpack the archive, e.g. `tar zxvf /where/ever/mod_4_1bb.tar.Z`. The files in the archive are stored in a flat structure: move them to the appropriate place in the GCC structure by `../unpack_mod_list.sh` (there should be no files left: if any were included in the archive in error, they will be in `../support/`). Change directory back to the top level. Check the documentation; if there are any removed tests, delete them. This isn't always obvious: start at the section "Changes from the last list". For confirmation, check in the "Main list" for lines with the `Org VCS Label` set to (e.g.) `A4_1BB` and marked `Withdrawn`. (There were none in this modification list). Mark the changes: ``` git add tests/ support/ ``` (you may prefer to be more circumspect!) and commit, e.g.: ``` git commit -m 'Updated to ACATS 4.1BB.' ``` and push. ``` git push ``` Now, * switch to the `master` branch and merge the `acats-4.1` branch (you may be able to cherry-pick the commit just made in the other branch); * update `README.md` and commit the change; * tag the release, e.g. `tag -s -m 'Tagging acats-4.1bb' acats-4.1bb` * `push`, and `push --tags`. [Ada-Auth]: http://www.ada-auth.org/acats.html <file_sep>/docs/ug-1.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Introduction</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-11.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>Section 1: Introduction</H1> <div class="Normal">The Ada Conformity Assessment Test Suite (ACATS) provides the official tests used to check conformity of an Ada implementation with the Ada programming language standard (<A HREF="UG-01.HTM#Ada2012">ANSI/ISO/IEC 8652:2012</A> and later corrigenda, including <A HREF="UG-01.HTM#TC1-2012">ANSI/ISO/IEC 8652:2012/COR 1:2016</A>). The ACATS User's Guide is part of the ACATS and is distributed with the test programs and testing support packages. It explains the contents and use of the test suite.<A NAME="I1001"></A><A NAME="I1002"></A><A NAME="I1003"></A><A NAME="I1004"></A><A NAME="I1005"></A></div> <div class="Normal">The ACATS is an important part of the conformity assessment process described in ISO/IEC-18009, Ada: Conformity of a Language Processor <A HREF="UG-01.HTM#ISO99">[ISO99]</A>. This standard provides a framework for testing language processors, providing a stable and reproducible basis for testing. The Ada Resource Association (ARA) has sponsored an instantiation of that process since October 1998. The process is managed by the Ada Conformity Assessment Authority (ACAA).<A NAME="I1006"></A><A NAME="I1007"></A><A NAME="I1008"></A></div> <div class="Normal">Prior to the ISO standard, the U.S. Department of Defense sponsored a similar conformity assessment process under the Ada Joint Program Office (AJPO). The test suite for that process was known as the Ada Compiler Validation Capability (ACVC).<A NAME="I1009"></A><A NAME="I1010"></A><A NAME="I1011"></A> The AJPO developed ACVC versions based on <A HREF="UG-01.HTM#Ada83">ANSI/MIL-STD-1815A-1983, ISO/8652:1987</A> (Ada 83), which were numbered 1.x where x ranged from 1 to 11. It later developed ACVC versions based on ANSI/ISO/IEC 8652:1995 (<A HREF="UG-01.HTM#Ada95">[Ada95]</A>), numbered 2.0, 2.0.1, 2.1, and 2.2.</div> <div class="Normal">When the ACAA took over Ada conformity assessment, it adopted the ACVC as the basis for its test suite. The ACAA determined to continue to use the same version numbering for the test suite in order to avoid confusion. The version of the ACVC current at the time (2.1) was initially used as ACATS 2.1. Later, the already developed but unreleased ACVC 2.2 was released and used as ACATS 2.2. The ACAA later released ACATS 2.3, ACATS 2.4, ACATS 2.5, and then ACATS 2.6 to include maintenance changes and a few new tests.</div> <div class="Normal">In 2007, the ACAA developed ACATS version 3.0 to check for conformity to new language features defined in ISO/IEC 8652:1995/AMD 1:2007 (<A HREF="UG-01.HTM#Amend1">[Amend1]</A>), as well as test programs to check for conformity to language features defined in earlier versions of Ada, including <A HREF="UG-01.HTM#Ada95">[Ada95]</A> and <A HREF="UG-01.HTM#Ada83">[Ada83]</A>. The ACAA later released ACATS 3.1 to improve the coverage and correctness of the ACATS for features defined in <A HREF="UG-01.HTM#Amend1">[Amend1]</A>.</div> <div class="Normal">In 2014, the ACAA developed ACATS version 4.0 to test the enhancements and changes of the third edition of the Ada Standard, ISO/IEC 8652:2012 (<A HREF="UG-01.HTM#Ada2012">[Ada2012]</A>). This version of the ACATS, version 4.1, was released to improve the coverage and correctness of the ACATS for features defined in <A HREF="UG-01.HTM#Ada2012">[Ada2012]</A>, including features originally defined in earlier versions of the Ada Standard. Subsequent maintenance or enhancement versions of the suite, if they are required, will be numbered 4.2, etc.</div> <div class="Normal">The ACATS User's Guide describes the set of ACATS tests and how they are to be used in preparation for conformity assessment. The formal procedures for conformity assessment are described in <A HREF="UG-01.HTM#Pro31">[Pro31]</A>, and the rules in that document govern all conformity assessments, notwithstanding anything in this document that may be interpreted differently. Moreover, this guide does not discuss specific requirements on processing of the ACATS test suite, or submission and grading of results that an Ada Conformity Assessment Laboratory (ACAL) may impose.<A NAME="I1012"></A><A NAME="I1013"></A></div> <div class="Normal">The User's Guide is intended to be used by compiler implementers, software developers who maintain a version of the ACATS as a quality control or software acceptance tool, and third-party testers (e.g., Ada Conformity Assessment Laboratories).</div> <div class="Normal">Section <A HREF="UG-2.HTM">2</A> of the User's Guide for ACATS 4.1 summarizes the changes between ACATS 4.0 and ACATS 4.1. Section <A HREF="UG-3.HTM">3</A> describes test objectives and their relationship to ACATS tests and to the rules of the Ada Standards documents. Section <A HREF="UG-4.HTM">4</A> describes the configuration of the ACATS, including a description of the ACATS software and delivery files. Section <A HREF="UG-5.HTM">5</A> provides step-by-step instructions for installing and using the test programs and test support packages, and for grading test results. The appendices include other information that characterizes the ACATS 4.1 release, along with information on test construction.</div> <div class="Normal">Refer to <A HREF="UG-F.HTM">Annex F</A> and Section <A HREF="UG-56.HTM">5.6</A> for the definition of an acceptable result and the rules for grading ACATS 4.1 test program results. Section <A HREF="UG-572.HTM">5.7.2</A> provides instructions for submitting a petition against a test program if a user believes that a deviation from the acceptable results for a given test program is in fact conforming behavior.</div> <div class="Normal">The ACATS test suite is available from any ACAL and from the ACAA web site. See <A HREF="http://www.ada-auth.org/acats.html">http://www.ada-auth.org/acats.html</A>.</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-11.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/docs/ug-411.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Physical Organization</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} DIV.Indented1 {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 2.0em; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-41.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-412.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>4.1.1 Physical Organization</H1> <div class="Normal">The preceeding table summarizes the number of files that compose ACATS 4.1. In addition to files containing test code proper, the ACATS 4.1 test suite includes various support files.</div> <div class="Normal">Note that the number of files containing test code is larger than the number of tests in the ACATS suite because some tests use code included in separate files.</div> <div class="Normal">A file name consists of a name plus an extension. Multiple files that contain code used by a single test have related names. File names are the same as that of the test contained in the file when possible. File names conform to MS-DOS naming conventions; therefore they may be shorter than the software name because of file name length restrictions (e.g., enumchek rather than enumcheck). File (and test) names follow conventions that indicate their function in the test suite; naming conventions are explained in Section <A HREF="UG-43.HTM">4.3</A>. The files are organized into distinct directories and subdirectories based on their function in the test suite. The directory organization is explained in Section <A HREF="UG-47.HTM">4.7</A>.</div> <div class="Normal" style="margin-bottom: 0.4em">The ACATS is available to the general public from an ACAL or on the Internet. Links to the ACATS distribution can be found on the ACAA's ACATS page:&nbsp;</div> <div class="Indented1"><SPAN STYLE="font-size: 80%"><A HREF="http://www.ada-auth.org/acats.html">http://www.ada-auth.org/acats.html</A></SPAN>. </div> <div class="Normal">Note that the ACATS files are available in both compressed Unix tar and DOS zipped formats. Section <A HREF="UG-512.HTM">5.1.2</A> provides a discussion of techniques to convert these files to a usable format.</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-41.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-412.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/unpack_mod_list.sh # Assuming you've unpacked the current mod list (say m) into ACATS/$m, # change directory to ACATS/$m and execute this script to move the # files into the appropriate place. # l/ exists as well as lx?/, so do the lx? files first for t in ../tests/lx* ../tests/*; do base=`basename $t` for f in ${base}*; do mv -v $f ../tests/${base}/ done done mv -v * ../support/ <file_sep>/docs/ug-426.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Class L</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-425.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-427.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>4.2.6 Class L</H1> <div class="Normal">Class L tests check that all library unit dependences within a program are satisfied before the program can be bound and executed, that circularity among units is detected, or that pragmas that apply to an entire partition are correctly processed. These tests are normally expected to compile successfully but not to bind or execute. Some implementations may report errors at compile time; potentially illegal constructs are flagged with &quot;-- ERROR:&quot;. Some class L tests indicate where bind errors are expected. Successful processing does not require that a binder match error messages with these indications.</div> <div class="Normal">An implementation passes a class L test if does not successfully complete the bind phase. It passes a class L test if it detects an error and issues a compile time error message. It fails if the test successfully binds and/or begins execution. An L test need not report &quot;FAILED&quot; (although many do if they execute).</div> <div class="Normal">As with B-tests, the test designers determined that some constructs may or may not generate an error report, and that either behavior would be appropriate. Such lines are marked with &quot;-- OPTIONAL ERROR:&quot; In such cases, an implementation is allowed to report an error or fail to report an error. If an error is reported at compile time, the binder need not be invoked. If no errors are reported at compile time, the binder must be invoked and must not successfully complete the bind phase (as indicated by the inability to begin execution).</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-425.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-427.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/tests/cxb/cxb30240.c /* -- CXB30240.C -- -- Grant of Unlimited Rights -- -- The Ada Conformity Assessment Authority (ACAA) holds unlimited -- rights in the software and documentation contained herein. Unlimited -- rights are the same as those granted by the U.S. Government for older -- parts of the Ada Conformity Assessment Test Suite, and are defined -- in DFAR 252.227-7013(a)(19). By making this public release, the ACAA -- intends to confer upon all recipients unlimited rights equal to those -- held by the ACAA. These rights include rights to use, duplicate, -- release or disclose the released technical data and computer software -- in whole or in part, in any manner and for any purpose whatsoever, and -- to have or permit others to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE ACAA MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. -- -- Notice -- -- The ACAA has created and maintains the Ada Conformity Assessment Test -- Suite for the purpose of conformity assessments conducted in accordance -- with the International Standard ISO/IEC 18009 - Ada: Conformity -- assessment of a language processor. This test suite should not be used -- to make claims of conformance unless used in accordance with -- ISO/IEC 18009 and any applicable ACAA procedures. --* -- -- FUNCTION NAME: CXB30240 -- -- FUNCTION DESCRIPTION: -- This C function converts a value of type variant_t into a string -- value representing that value. -- -- INPUTS: -- This function requires that two parameters be passed to it, a pointer -- to the value of type variant_t, and a pointer to a buffer for the -- string result. -- -- OUTPUTS: -- The resulting string will be written as a nul-terminated string to -- the buffer. Note that the routine does not check that the string will -- fit in the buffer! -- -- OBJECTIVE -- See CXB30241.AM. -- -- TEST DESCRIPTION -- See CXB30241.AM. -- -- TEST FILES: -- This test consists of the following files: -- -> CXB30240.C -- CXB30241.AM -- -- CHANGE HISTORY: -- 06 Sep 2015 BJM Created function. -- 25 Nov 2015 RLB Changed naming consistent with ACATS. -- 09 Dec 2015 RLB Removed void pointer case. -- --!*/ #include <stdio.h> typedef enum { INTEGER = 0, CHARACTER = 1, STRING = 2, REAL = 3} data_kind_t; typedef struct { data_kind_t type; union { int integer; char character; char *string; float real; } x; } variant_t; void CXB30240 (const variant_t *var, char *output) { switch (var->type) { case INTEGER: sprintf(output, "Type: Integer, Val: %d", var->x.integer); break; case CHARACTER: sprintf(output, "Type: Character, Val: '%c'", var->x.character); break; case STRING: sprintf(output, "Type: String, Val: %s", var->x.string); break; case REAL: sprintf(output, "Type: Real, Val: %.2f", var->x.real); break; default: sprintf(output, "Type %d, ERR: Invalid!", var->type); } } <file_sep>/docs/ug-612.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Annotated Grading Tool Example</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} DIV.Examples {font-family: "Courier New", monospace; font-size: 90%; line-height: 122%; margin-left: 2.2em; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-611.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-613.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>6.1.2 Annotated Grading Tool Example</H1> <div class="Normal">Following is an example of using the grading tool on Chapter 5 C-Tests for an implementation that has not yet implemented most of Ada 2012. For this example, file ChapC5.csv is an event trace containing the events generated by processing the 102 ACATS C-Tests for chapter 5. The file C5-Sum.csv is the test summary file for the 102 ACATS C-Tests for chapter 5. Man.Txt is an empty file (there are no manual grading requests for this run).</div> <div class="Normal">In the following, <I>annotations are given in italics</I>, and are not part of the output of the Grading Tool.</div> <div class="Normal" style="margin-bottom: 0.4em">The command line used for the example is:</div> <div class="Examples">Grade&nbsp;ChapC5.csv&nbsp;C5-Sum.csv&nbsp;Man.Txt&nbsp;&quot;C-Tests&nbsp;for&nbsp;Chapter&nbsp;5&quot;&nbsp;-&nbsp;Use_Timestamps&nbsp;-Check_All_Compiles&nbsp;-No_Positions</div> <div class="Normal" style="margin-bottom: 0.4em">This gives the following expected results:</div> <div class="Examples">ACATS&nbsp;Grading&nbsp;Tool&nbsp;-&nbsp;version&nbsp;1.0<BR> &nbsp;&nbsp;Compile&nbsp;Checks:&nbsp;CHECK_ALL<BR> &nbsp;&nbsp;Make&nbsp;checks&nbsp;of&nbsp;time&nbsp;stamps&nbsp;in&nbsp;event&nbsp;log<BR> &nbsp;&nbsp;Use&nbsp;only&nbsp;line&nbsp;numbers&nbsp;of&nbsp;error&nbsp;messages&nbsp;when&nbsp;grading<BR> &nbsp;&nbsp;Report&nbsp;verbosity:&nbsp;NORMAL<BR> &nbsp;&nbsp;779&nbsp;event&nbsp;trace&nbsp;records&nbsp;read&nbsp;from&nbsp;ChapC5.csv<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;non-comment&nbsp;records&nbsp;in&nbsp;the&nbsp;event&nbsp;trace&nbsp;file.</I></SPAN><BR> &nbsp;&nbsp;117&nbsp;test&nbsp;summary&nbsp;trace&nbsp;records&nbsp;read&nbsp;from&nbsp;C5-Sum.csv<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;non-comment&nbsp;records&nbsp;in&nbsp;the&nbsp;test&nbsp;summary&nbsp;file.&nbsp;All&nbsp;tests&nbsp;in&nbsp;this&nbsp;file&nbsp;are&nbsp;graded,</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>whether&nbsp;or&nbsp;not&nbsp;they&nbsp;appear&nbsp;in&nbsp;the&nbsp;event&nbsp;trace.&nbsp;Extra&nbsp;tests&nbsp;in&nbsp;the&nbsp;event&nbsp;trace&nbsp;are&nbsp;ignored.</I></SPAN><BR> &nbsp;&nbsp;0&nbsp;manual&nbsp;grading&nbsp;requests&nbsp;read&nbsp;from&nbsp;New-Man.Txt<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;number&nbsp;of&nbsp;tests&nbsp;for&nbsp;which&nbsp;manual&nbsp;grading&nbsp;was&nbsp;requested,&nbsp;excluding&nbsp;comments.</I></SPAN><BR> --&nbsp;Test&nbsp;C51004A&nbsp;passed&nbsp;execution<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;result&nbsp;for&nbsp;an&nbsp;individual&nbsp;test.&nbsp;The&nbsp;passed&nbsp;results&nbsp;can&nbsp;be&nbsp;suppressed&nbsp;with&nbsp;the&nbsp;-quiet&nbsp;option&nbsp;rather&nbsp;than&nbsp;-normal.</I></SPAN><BR> --&nbsp;Test&nbsp;C52005A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52005B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52005C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52005D&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52005E&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52005F&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52008A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52008B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52009A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52009B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52010A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52011A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52011B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52101A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52102A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52102B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52102C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52102D&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103F&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103G&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103H&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103K&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103L&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103M&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103P&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103Q&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103R&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52103X&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104F&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104G&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104H&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104K&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104L&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104M&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104P&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104Q&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104R&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104X&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C52104Y&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C53007A&nbsp;passed&nbsp;execution<BR> **&nbsp;Test&nbsp;C540001&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;144&nbsp;in&nbsp;file&nbsp;C540001.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Feature&nbsp;not&nbsp;implemented<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;test&nbsp;uses&nbsp;an&nbsp;Ada&nbsp;2012&nbsp;feature&nbsp;not&nbsp;implemented&nbsp;in&nbsp;the&nbsp;test&nbsp;implementation.&nbsp;Thus,&nbsp;this&nbsp;test</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>(and&nbsp;several&nbsp;others)&nbsp;fail.&nbsp;The&nbsp;message&nbsp;is&nbsp;not&nbsp;part&nbsp;of&nbsp;the&nbsp;grading&nbsp;(and&nbsp;is&nbsp;suppressed&nbsp;if&nbsp;-quiet&nbsp;is</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>used),&nbsp;but&nbsp;should&nbsp;be&nbsp;helpful&nbsp;in&nbsp;determining&nbsp;the&nbsp;reason&nbsp;a&nbsp;test&nbsp;has&nbsp;failed.</I></SPAN><BR> **&nbsp;Test&nbsp;C540002&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;112&nbsp;in&nbsp;file&nbsp;C540002.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Unable&nbsp;to&nbsp;resolve&nbsp;expression<BR> **&nbsp;Test&nbsp;C540003&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;69&nbsp;in&nbsp;file&nbsp;C540003.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Feature&nbsp;not&nbsp;implemented<BR> --&nbsp;Test&nbsp;C54A03A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A04A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A07A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A13A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A13B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A13C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A13D&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A22A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A23A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A24A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A24B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42D&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42E&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42F&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C54A42G&nbsp;passed&nbsp;execution<BR> **&nbsp;Test&nbsp;C550001&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;72&nbsp;in&nbsp;file&nbsp;C550001.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Feature&nbsp;not&nbsp;implemented<BR> **&nbsp;Test&nbsp;C552001&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;150&nbsp;in&nbsp;file&nbsp;C552001.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;This&nbsp;must&nbsp;name&nbsp;a&nbsp;type<BR> ++&nbsp;Test&nbsp;C552002&nbsp;N/A&nbsp;because&nbsp;of&nbsp;expected&nbsp;error&nbsp;at&nbsp;line&nbsp;59&nbsp;in&nbsp;file&nbsp;C552002.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Feature&nbsp;not&nbsp;implemented<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>Note&nbsp;that&nbsp;the&nbsp;text&nbsp;of&nbsp;error&nbsp;messages&nbsp;does&nbsp;not&nbsp;have&nbsp;any&nbsp;effect&nbsp;on&nbsp;test&nbsp;grading.&nbsp;This&nbsp;test&nbsp;is</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>Not&nbsp;Applicable&nbsp;because&nbsp;the&nbsp;first&nbsp;error&nbsp;occurred&nbsp;on&nbsp;a&nbsp;N/A&nbsp;=&gt;&nbsp;Error&nbsp;line,&nbsp;regardless&nbsp;of&nbsp;the&nbsp;message&nbsp;text.</I></SPAN><BR> **&nbsp;Test&nbsp;C552A01&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;73&nbsp;in&nbsp;file&nbsp;C552A01.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;F552A00_PRIME_NUMBERS;&nbsp;WITHed&nbsp;compilation&nbsp;unit&nbsp;not&nbsp;found<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>Here,&nbsp;a&nbsp;foundation&nbsp;(which&nbsp;is&nbsp;not&nbsp;graded&nbsp;by&nbsp;itself)&nbsp;failed&nbsp;to&nbsp;compile.&nbsp;The&nbsp;failure&nbsp;to&nbsp;compile&nbsp;the</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>foundation&nbsp;(because&nbsp;of&nbsp;an&nbsp;unimplemented&nbsp;feature)&nbsp;caused&nbsp;this&nbsp;test&nbsp;to&nbsp;fail.</I></SPAN><BR> **&nbsp;Test&nbsp;C552A02&nbsp;has&nbsp;unexpected&nbsp;compile&nbsp;error&nbsp;at&nbsp;line&nbsp;94&nbsp;in&nbsp;file&nbsp;C552A02.A<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;F552A00_SPARSE_ARRAYS;&nbsp;WITHed&nbsp;compilation&nbsp;unit&nbsp;not&nbsp;found<BR> --&nbsp;Test&nbsp;C55B03A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B04A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B05A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B06A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B06B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B07A&nbsp;passed&nbsp;execution<BR> ++&nbsp;Test&nbsp;C55B07B&nbsp;N/A&nbsp;because&nbsp;of&nbsp;expected&nbsp;error&nbsp;at&nbsp;line&nbsp;45&nbsp;in&nbsp;file&nbsp;C55B07B.DEP<BR> &nbsp;&nbsp;&nbsp;because:&nbsp;Identifier&nbsp;is&nbsp;not&nbsp;defined<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;test&nbsp;is&nbsp;Not&nbsp;Applicable&nbsp;because&nbsp;the&nbsp;implementation&nbsp;in&nbsp;question&nbsp;does&nbsp;not&nbsp;define&nbsp;a&nbsp;type&nbsp;Short_Integer.</I></SPAN><BR> --&nbsp;Test&nbsp;C55B10A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B11A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B11B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B15A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55B16A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55C02A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C55C02B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C56002A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C57003A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C57004A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C57004B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58004C&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58004D&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58004G&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58005A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58005B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58005H&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58006A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C58006B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C59002A&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C59002B&nbsp;passed&nbsp;execution<BR> --&nbsp;Test&nbsp;C59002C&nbsp;passed&nbsp;execution</div> <div class="Examples">=======================================</div> <div class="Examples">Summary&nbsp;for&nbsp;C-Tests&nbsp;for&nbsp;Chapter&nbsp;5</div> <div class="Examples">Result&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Overall&nbsp;&nbsp;B-Tests&nbsp;&nbsp;C-Tests&nbsp;&nbsp;L-Tests&nbsp;&nbsp;Other&nbsp;Tests</div> <div class="Examples">&nbsp;&nbsp;&nbsp;Total&nbsp;Tests&nbsp;Graded&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;102&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;102&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;total&nbsp;tests&nbsp;graded.&nbsp;The&nbsp;numbers&nbsp;in&nbsp;each&nbsp;column&nbsp;reflect&nbsp;the&nbsp;number&nbsp;of&nbsp;tests&nbsp;of&nbsp;the&nbsp;appropriate&nbsp;type&nbsp;for</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>the&nbsp;category&nbsp;in&nbsp;question.</I></SPAN></div> <div class="Examples">**&nbsp;Failed&nbsp;(Process)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>A&nbsp;process&nbsp;failure&nbsp;is&nbsp;some&nbsp;problem&nbsp;with&nbsp;the&nbsp;test&nbsp;processing,&nbsp;such&nbsp;as&nbsp;running&nbsp;a&nbsp;test&nbsp;before&nbsp;it&nbsp;is&nbsp;compiled&nbsp;or</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>compiling&nbsp;units&nbsp;out&nbsp;of&nbsp;the&nbsp;required&nbsp;order.&nbsp;Usually,&nbsp;correcting&nbsp;the&nbsp;test&nbsp;processing&nbsp;is&nbsp;all&nbsp;that&nbsp;is&nbsp;needed&nbsp;to</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>eliminate&nbsp;this&nbsp;error.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Compile&nbsp;Missing)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;some&nbsp;required&nbsp;unit&nbsp;was&nbsp;not&nbsp;compiled.&nbsp;This&nbsp;is&nbsp;a&nbsp;failure&nbsp;even&nbsp;if&nbsp;the&nbsp;test&nbsp;executed&nbsp;and&nbsp;passed.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Compiler&nbsp;Crash)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;some&nbsp;compilation&nbsp;started&nbsp;but&nbsp;did&nbsp;not&nbsp;finish&nbsp;normally.&nbsp;This&nbsp;usually&nbsp;reflects&nbsp;some&nbsp;internal</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>compiler&nbsp;error.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Error&nbsp;in&nbsp;OK&nbsp;area)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;an&nbsp;error&nbsp;was&nbsp;reported&nbsp;in&nbsp;the&nbsp;range&nbsp;of&nbsp;an&nbsp;OK&nbsp;tagged&nbsp;line.&nbsp;These&nbsp;are&nbsp;counted&nbsp;separately&nbsp;as&nbsp;these</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>typically&nbsp;indicate&nbsp;a&nbsp;significant&nbsp;compiler&nbsp;bug.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Unexpected&nbsp;Error)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;an&nbsp;error&nbsp;was&nbsp;reported&nbsp;outside&nbsp;of&nbsp;the&nbsp;range&nbsp;of&nbsp;any&nbsp;test&nbsp;tag.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Missing&nbsp;Error)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;no&nbsp;error&nbsp;was&nbsp;reported&nbsp;where&nbsp;one&nbsp;was&nbsp;required&nbsp;(for&nbsp;instance,&nbsp;for&nbsp;an&nbsp;error&nbsp;tag).&nbsp;This&nbsp;is&nbsp;only</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>likely&nbsp;for&nbsp;a&nbsp;B-Test.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Bind&nbsp;Missing)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;no&nbsp;bind&nbsp;operation&nbsp;was&nbsp;found&nbsp;for&nbsp;the&nbsp;test&nbsp;(and&nbsp;no&nbsp;other&nbsp;failure&nbsp;occurred&nbsp;first).</I></SPAN><BR> **&nbsp;Failed&nbsp;(Bind&nbsp;Crash)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;bind&nbsp;started&nbsp;but&nbsp;did&nbsp;not&nbsp;finish&nbsp;normally.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Bind&nbsp;Error)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;bind&nbsp;reported&nbsp;an&nbsp;error.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Run&nbsp;Missing)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;no&nbsp;test&nbsp;execution&nbsp;was&nbsp;found&nbsp;(and&nbsp;no&nbsp;other&nbsp;error&nbsp;was&nbsp;detected&nbsp;first).</I></SPAN><BR> **&nbsp;Failed&nbsp;(Run&nbsp;Crash)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;test&nbsp;execution&nbsp;started&nbsp;but&nbsp;did&nbsp;not&nbsp;complete&nbsp;and&nbsp;report&nbsp;a&nbsp;result.</I></SPAN><BR> **&nbsp;Failed&nbsp;(Runtime&nbsp;Message)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;test&nbsp;execution&nbsp;explicitly&nbsp;reported&nbsp;Failed.</I></SPAN><BR> ++&nbsp;Not-Applicable&nbsp;(Annex&nbsp;C)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;did&nbsp;not&nbsp;meet&nbsp;an&nbsp;Annex&nbsp;C&nbsp;Requirement;&nbsp;if&nbsp;Annex&nbsp;C&nbsp;is&nbsp;being&nbsp;tested,</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>this&nbsp;should&nbsp;be&nbsp;considered&nbsp;a&nbsp;failure.</I></SPAN><BR> ++&nbsp;Not-Applicable&nbsp;(Compile)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;had&nbsp;an&nbsp;error&nbsp;in&nbsp;an&nbsp;N/A&nbsp;=&gt;&nbsp;Error&nbsp;range.</I></SPAN><BR> ++&nbsp;Not-Applicable&nbsp;(Runtime)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;execution&nbsp;reported&nbsp;that&nbsp;it&nbsp;was&nbsp;Not&nbsp;Applicable.</I></SPAN><BR> !!&nbsp;Special&nbsp;Handling&nbsp;(Runtime)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;execution&nbsp;reported&nbsp;that&nbsp;it&nbsp;required&nbsp;special&nbsp;handling.</I></SPAN><BR> !!&nbsp;Manual&nbsp;Grading&nbsp;Requested&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;failed&nbsp;for&nbsp;some&nbsp;reason&nbsp;and&nbsp;manual&nbsp;test&nbsp;grading&nbsp;was&nbsp;requested.&nbsp;If&nbsp;the&nbsp;test&nbsp;grades</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>as&nbsp;Passed&nbsp;or&nbsp;Not&nbsp;Applicable,&nbsp;the&nbsp;manual&nbsp;grading&nbsp;request&nbsp;is&nbsp;ignored&nbsp;and&nbsp;the&nbsp;test&nbsp;will&nbsp;be&nbsp;counted&nbsp;in&nbsp;the</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>appropriate&nbsp;other&nbsp;category.</I></SPAN><BR> ==&nbsp;Passed&nbsp;(Expected&nbsp;Errors)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;had&nbsp;compile-time&nbsp;errors&nbsp;as&nbsp;expected,&nbsp;and&nbsp;no&nbsp;extra&nbsp;errors.</I></SPAN><BR> ==&nbsp;Passed&nbsp;(Bind&nbsp;Error)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;had&nbsp;bind&nbsp;errors&nbsp;as&nbsp;expected&nbsp;(this&nbsp;is&nbsp;most&nbsp;likely&nbsp;for&nbsp;an&nbsp;L-Test.</I></SPAN><BR> ==&nbsp;Passed&nbsp;(Runtime)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;93&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;93&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>This&nbsp;means&nbsp;that&nbsp;the&nbsp;test&nbsp;reported&nbsp;Passed&nbsp;when&nbsp;executed.</I></SPAN><BR> =======================================</div> <div class="Examples">Overall&nbsp;result&nbsp;for&nbsp;C-Tests&nbsp;for&nbsp;Chapter&nbsp;5&nbsp;is&nbsp;**FAILED**<BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>The&nbsp;overall&nbsp;result&nbsp;is&nbsp;Failed&nbsp;unless&nbsp;all&nbsp;tests&nbsp;either&nbsp;pass,&nbsp;are&nbsp;not&nbsp;applicable,&nbsp;or&nbsp;had&nbsp;manual&nbsp;grading</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>requested.&nbsp;For&nbsp;this&nbsp;implementation,&nbsp;the&nbsp;result&nbsp;of&nbsp;failed&nbsp;is&nbsp;expected.&nbsp;The&nbsp;implementer&nbsp;could&nbsp;have&nbsp;requested</I></SPAN><BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<SPAN Class="roman"><I>manual&nbsp;grading&nbsp;for&nbsp;the&nbsp;tests&nbsp;that&nbsp;were&nbsp;not&nbsp;expected&nbsp;to&nbsp;work,&nbsp;in&nbsp;order&nbsp;to&nbsp;change&nbsp;this&nbsp;result&nbsp;to&nbsp;Passed.</I></SPAN></div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-611.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-613.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/run_all.sh #!/bin/sh # Run ACATS with the GNU Ada compiler # The following functions are to be customized if you run in cross # environment or want to change compilation flags. Note that for # tests requiring checks not turned on by default, this script # automatically adds the needed flags to pass (ie: -gnato or -gnatE). # The default options are -gnatws -g -O2. You can pass additional # options at runtime by using RUNTESTFLAGS: # # make check-acats RUNTESTFLAGS="--target_board=unix/-O3/-gnatN" # # compiles with -gnatws -gnatN -g -O2 -O3 (as well as other # test-specific options). # # N.B. if you wish to pass any GNAT-specific options (e.g. -gnat*) you # must only run this suite (make check-acats), because -gnat* will # fail with most other tools ("unrecognized debug output level # 'nat*"). # N.B. do not use RUNTESTFLAGS with -j<n>: it doesn't get passed to # sub-makes (at 2018-02-10). # # The default options are -g -O2 -gnatws. gccflags="-g -O2" gnatflags="-gnatws" flags=`echo $RUNTESTFLAGS | fmt -1 | grep target_board=unix | sed -E -e "s/^.*=unix//" -e "s;/; ;g"` for f in $flags; do case $f in -gnat*) gnatflags="$gnatflags $f";; *) gccflags="$gccflags $f";; esac; done; # End of customization section. # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith display_noeol () { printf "$@" printf "$@" >> $dir/acats.sum printf "$@" >> $dir/acats.log } display () { echo "$@" echo "$@" >> $dir/acats.sum echo "$@" >> $dir/acats.log } log () { echo "$@" >> $dir/acats.sum echo "$@" >> $dir/acats.log } dir=`${PWDCMD-pwd}` if [ "$dir" = "$testdir" ]; then echo "error: srcdir must be different than objdir, exiting." exit 1 fi if [ "$BASE" ]; then GCC="$BASE/xgcc -B$BASE/" else GCC="${GCC-`which gcc`}" fi target_gnatchop () { if [ "$BASE" ]; then $BASE/gnatchop --GCC="$BASE/xgcc" $* else host_gnatchop $* fi return $? } target_gnatmake () { if [ "$BASE" ]; then echo $BASE/gnatmake --GNATBIND=$BASE/gnatbind --GNATLINK=$BASE/gnatlink --GCC="$GCC" $gnatflags $gccflags $* -largs $EXTERNAL_OBJECTS --GCC="$GCC" $BASE/gnatmake --GNATBIND=$BASE/gnatbind --GNATLINK=$BASE/gnatlink --GCC="$GCC" $gnatflags $gccflags $* -largs $EXTERNAL_OBJECTS --GCC="$GCC" else echo gnatmake $gnatflags $gccflags $* -largs $EXTERNAL_OBJECTS host_gnatmake $gnatflags $gccflags $* -largs $EXTERNAL_OBJECTS fi } target_gcc () { $GCC $gccflags $* } target_run () { eval $EXPECT -f $testdir/run_test.exp $* } clean_dir () { rm -f "$binmain" *.o *.ali > /dev/null 2>&1 } find_main () { # Must handle the cases that aren't correctly identified (ACATS 4.1) # $1 is the test case ${1} in c3a1003) main=c3a10032 ;; c3a1004) main=c3a10042 ;; ca11023) main=ca110232 ;; *) ls ${1}?.adb > ${1}.lst 2> /dev/null ls ${1}*m.adb >> ${1}.lst 2> /dev/null ls ${1}.adb >> ${1}.lst 2> /dev/null main=`tail -1 ${1}.lst` ;; esac } handle_pass () { # check that a pass for test $1 wasn't supposed to fail grep ${1} $testdir/xfail.lst >/dev/null 2>&1 inlist=$? echo ${1} | egrep '^[bl]' >/dev/null 2>&1 b_or_l=$? if [ $inlist -ne 0 -a $b_or_l -ne 0 ]; then # OK to have passed log "PASS: $1" as_fn_arith $glob_countok + 1 glob_countok=$as_val else # should have failed log "XPASS: $1" as_fn_arith $glob_countxp + 1 glob_countxp=$as_val fi } handle_fail () { # check that a fail for test $1 wasn't supposed to pass grep ${1} $testdir/xfail.lst >/dev/null 2>&1 inlist=$? echo ${1} | egrep '^[bl]' >/dev/null 2>&1 b_or_l=$? if [ $inlist -eq 0 -o $b_or_l -eq 0 ]; then # OK to have failed log "XFAIL: $1" as_fn_arith $glob_countxf + 1 glob_countxf=$as_val else # should have passed display "FAIL: $1" as_fn_arith $glob_countf + 1 glob_countf=$as_val failed="${failed}${tst} " fi } run_one_test () { tst=$1 grep $tst $testdir/norun.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then log "UNSUPPORTED: $tst" as_fn_arith $glob_countu + 1 glob_countu=$as_val clean_dir return fi extraflags="-gnat2012" grep $tst $testdir/overflow.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then extraflags="$extraflags -gnato" fi grep $tst $testdir/elabd.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then extraflags="$extraflags -gnatE" fi grep $tst $testdir/floatstore.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then extraflags="$extraflags -ffloat-store" fi grep $tst $testdir/stackcheck.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then extraflags="$extraflags -fstack-check" fi grep $tst $testdir/listing.lst > /dev/null 2>&1 if [ $? -eq 0 ]; then extraflags="$extraflags -gnatl" fi test=$dir/tests/$chapter/$tst rm -rf $test mkdir $test && cd $test >> $dir/acats.log 2>&1 if [ $? -ne 0 ]; then handle_fail $tst clean_dir return fi target_gnatchop -c `ls ${test}*.a ${test}*.ada ${test}*.au ${test}*.adt ${test}*.am ${test}*.dep 2> /dev/null` > chop.log 2>&1 chopped=$? cat chop.log >>$dir/acats.log # If gnatchop failed because the same unit appears more than once in # the sources, handle as UNSUPPORTED. Otherwise, let the compiler # report any problems. if [ $chopped -ne 0 ]; then grep 'use -w to overwrite' chop.log > /dev/null 2>$1 if [ $? -eq 0 ]; then log "UNSUPPORTED: $tst" as_fn_arith $glob_countu + 1 glob_countu=$as_val clean_dir return fi fi main="" find_main $i if [ -z "$main" ]; then sync find_main $i fi binmain=`echo $main | sed -e 's/\(.*\)\..*/\1/g'` echo "BUILD $main" >> $dir/acats.log case $tst in cxb3004) EXTERNAL_OBJECTS="$dir_support/cxb30040.o";; cxb3006) EXTERNAL_OBJECTS="$dir_support/cxb30060.o";; cxb3013) EXTERNAL_OBJECTS="$dir_support/cxb30130.o $dir_support/cxb30131.o";; cxb3017) EXTERNAL_OBJECTS="$dir_support/cxb30170.o";; cxb3018) EXTERNAL_OBJECTS="$dir_support/cxb30180.o";; cxb3023) EXTERNAL_OBJECTS="$dir_support/cxb30230.o";; cxb3024) EXTERNAL_OBJECTS="$dir_support/cxb30240.o";; *) EXTERNAL_OBJECTS="";; esac if [ "$main" = "" ]; then handle_fail $tst clean_dir return fi target_gnatmake $extraflags -I$dir_support $main \ > $dir/tests/$chapter/${tst}/${tst}.log 2>&1 compilation_status=$? cat $dir/tests/$chapter/${tst}/${tst}.log >> $dir/acats.log if [ $compilation_status -ne 0 ]; then grep 'not supported in this configuration' \ $dir/tests/$chapter/${tst}/${tst}.log > /dev/null 2>&1 if [ $? -eq 0 ]; then log "UNSUPPORTED: $tst" as_fn_arith $glob_countu + 1 glob_countu=$as_val else handle_fail $tst fi clean_dir return fi echo "RUN $binmain" >> $dir/acats.log cd $dir/run if [ ! -x $dir/tests/$chapter/$tst/$binmain ]; then sync fi target_run $dir/tests/$chapter/$tst/$binmain > $dir/tests/$chapter/$tst/${tst}.log 2>&1 cd $dir/tests/$chapter/$tst cat ${tst}.log >> $dir/acats.log # check for a status report from execution status=`egrep -e '(==== |\+\+\+\+ |\!\!\!\! )' ${tst}.log` if [ $? -ne 0 ]; then grep 'tasking not implemented' ${tst}.log > /dev/null 2>&1 if [ $? -ne 0 ]; then handle_fail $tst else log "UNSUPPORTED: $tst" as_fn_arith $glob_countu + 1 glob_countu=$as_val fi else case `echo $status | cut -c1-4` in "====") handle_pass $tst;; "++++") log "UNSUPPORTED: $tst" as_fn_arith $glob_countna + 1 glob_countna=$as_val;; "!!!!") log "UNRESOLVED: $tst" as_fn_arith $glob_counti + 1 glob_counti=$as_val;; *) log "ERROR: $tst" as_fn_arith $glob_counti + 1 glob_counti=$as_val;; esac fi clean_dir } EXTERNAL_OBJECTS="" # Global variable to communicate external objects to link with. rm -f $dir/acats.sum $dir/acats.log display "Test Run By $USER on `date`" display " === acats configuration ===" target=`$GCC -dumpmachine` display target gcc is $GCC display `$GCC -v 2>&1` display host=`gcc -dumpmachine` display target=$target display `type gnatmake` gnatls -v >> $dir/acats.log display "" if [ -n "$GCC_RUNTEST_PARALLELIZE_DIR" ]; then dir_support=$dir/../acats/support rm -rf $dir/run mv $dir/tests $dir/tests.$$ 2> /dev/null rm -rf $dir/tests.$$ & mkdir -p $dir/run cp -pr $dir/../acats/tests $dir/ else dir_support=$dir/support # Only build support if needed if [ ! -d $dir_support ] || [ $# -eq 0 ] || [ $1 = "NONE" ]; then display " === acats support ===" display_noeol "Generating support files..." rm -rf $dir/support mkdir -p $dir/support cd $dir/support cp $testdir/support/*.ada $testdir/support/*.a $testdir/support/*.tst $dir/support # Find out the size in bit of an address on the target target_gnatmake $testdir/support/impbit.adb >> $dir/acats.log 2>&1 if [ $? -ne 0 ]; then display "**** Failed to compile impbit" exit 1 fi target_run $dir/support/impbit > $dir/support/impbit.out 2>&1 target_bit=`cat $dir/support/impbit.out` echo target_bit="$target_bit" >> $dir/acats.log case "$target_bit" in *32*) target_max_int="9223372036854775807" target_min_int="-9223372036854775808" ;; *64*) target_max_int="170141183460469231731687303715884105727" target_min_int="-170141183460469231731687303715884105728" ;; *) display "**** Unsupported bits per word" exit 1 esac echo target_max_insn="$target_max_int" >> $dir/acats.log echo target_min_insn="$target_min_int" >> $dir/acats.log # Find out a suitable asm statement # Adapted from configure.ac gcc_cv_as_dwarf2_debug_line case "$target" in ia64*-*-* | s390*-*-*) target_insn="nop 0" ;; mmix-*-*) target_insn="swym 0" ;; *) target_insn="nop" ;; esac echo target_insn="$target_insn" >> $dir/acats.log sed -e "s,ACATS4GNATDIR,$dir,g" \ < $testdir/support/impdef.a > $dir/support/impdef.a sed -e "s,ACATS4GNATDIR,$dir,g" \ < $testdir/support/impdefc.a > $dir/support/impdefc.a sed -e "s,ACATS4GNATDIR,$dir,g" \ -e "s,ACATS4GNATBIT,$target_bit,g" \ -e "s,ACATS4GNATINSN,$target_insn,g" \ -e "s,ACATS4GNATMAXINT,$target_max_int,g" \ -e "s,ACATS4GNATMININT,$target_min_int,g" \ < $testdir/support/macro.dfs > $dir/support/MACRO.DFS sed -e "s,ACATS4GNATDIR,$dir,g" \ < $testdir/support/tsttests.dat > $dir/support/TSTTESTS.DAT cp $testdir/tests/cd/*.c $dir/support cp $testdir/tests/cxb/*.c $dir/support rm -rf $dir/run mv $dir/tests $dir/tests.$$ 2> /dev/null rm -rf $dir/tests.$$ & mkdir -p $dir/run cp -pr $testdir/tests $dir/ for i in $dir/support/*.ada $dir/support/*.a; do host_gnatchop $i >> $dir/acats.log 2>&1 done # These tools are used to preprocess some ACATS sources. # They need to be compiled native on the host. host_gnatmake -q -gnatws macrosub.adb if [ $? -ne 0 ]; then display "**** Failed to compile macrosub" exit 1 fi ./macrosub >> $dir/acats.log 2>&1 rm -f $dir/support/macrosub rm -f $dir/support/*.ali rm -f $dir/support/*.o display " done." # From here, all compilations will be made by the target compiler display_noeol "Compiling support files..." # This program is used to support Annex C tests via impdefc.a. target_gnatmake $testdir/support/send_sigint_to_parent.adb \ >> $dir/acats.log 2>&1 if [ $? -ne 0 ]; then display "**** Failed to compile send_sigint_to_parent" exit 1 fi target_gcc -c *.c >> $dir/acats.log 2>&1 if [ $? -ne 0 ]; then display "**** Failed to compile C code" exit 1 fi target_gnatchop *.adt >> $dir/acats.log 2>&1 target_gnatmake -c -gnato -gnatE *.adb >> $dir/acats.log 2>&1 display " done." display "" fi fi display " === acats tests ===" if [ $# -eq 0 ]; then # Run all the tests. chapters=`cd $dir/tests; echo *` else chapters=$* fi # number of passed tests glob_countok=0 # number of tests that should be inspected glob_counti=0 # number of unsupported tests, as reported by the compiler glob_countu=0 # number of not-applicable tests, as determined by running the test. glob_countna=0 # number of failures glob_countf=0 # number of expected failures glob_countxf=0 # number of unexpected passes glob_countxp=0 # These for possible parallel execution, see below par_count=0 par_countm=0 par_last= for chapter in $chapters; do # Used to generate support once and finish after that. [ "$chapter" = "NONE" ] && continue display Running chapter $chapter ... if [ ! -d $dir/tests/$chapter ]; then display "*** CHAPTER $chapter does not exist, skipping." display "" continue fi cd $dir/tests/$chapter ls *.a *.ada *.adt *.am *.au *.dep 2> /dev/null | \ sed -e 's/\(.*\)\..*/\1/g' | \ cut -c1-7 | sort | uniq \ > $dir/tests/$chapter/${chapter}.lst for i in `cat $dir/tests/$chapter/${chapter}.lst`; do # If running multiple run_all.sh jobs in parallel, decide # if we should run this test in the current instance. if [ -n "$GCC_RUNTEST_PARALLELIZE_DIR" ]; then case "$i" in # Ugh, some tests have inter-test dependencies, those # tests have to be scheduled on the same parallel instance # as previous test. ce2108f | ce2108h | ce3112d) ;; # All others can be hopefully scheduled freely. *) as_fn_arith $par_countm + 1 par_countm=$as_val [ $par_countm -eq 10 ] && par_countm=0 if [ $par_countm -eq 1 ]; then as_fn_arith $par_count + 1 par_count=$as_val if mkdir $GCC_RUNTEST_PARALLELIZE_DIR/$par_count 2>/dev/null; then par_last=1 else par_last= fi fi;; esac if [ -z "$par_last" ]; then continue fi fi run_one_test $i done done display " === acats Summary ===" # text must be as expected by contrib/dg-extract-results.py (including # tabs) display "# of expected passes $glob_countok" display "# of unexpected failures $glob_countf" if [ $glob_countxf -ne 0 ]; then display "# of expected failures $glob_countxf" fi if [ $glob_countxp -ne 0 ]; then display "# of unexpected successes $glob_countxp" fi # preparing output for standard run; must only use names supported # by contrib/dg-extract-results.py if [ $glob_counti -ne 0 ]; then display "# of unresolved testcases $glob_counti" fi as_fn_arith $glob_countu + $glob_countna unsupported=$as_val if [ $unsupported -ne 0 ]; then display "# of unsupported tests $unsupported" fi if [ $glob_countf -ne 0 ]; then display "*** FAILURES: $failed" fi display "$0 completed at `date`" exit 0 # for Emacs # Local Variables: # sh-indentation: 2 # sh-basic-offset: 2 # End: <file_sep>/docs/ug-d2f.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>File I/O Tests</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} DIV.Indented2 {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 4.0em; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-D2E.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-D2G.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>D.2.15 File I/O Tests</H1> <div class="Normal">If sequential, text, wide text, wide wide text, direct access, and stream files are not supported, along with directory operations on them, then the tests contained in the following files should eport NOT_APPLICABLE:</div> <div class="Indented2"><table width="70%"> <TR><TD align="left">CE2102A.ADA<TD align="left">CE2401E.ADA<TD align="left">CE3407C.ADA<TD align="left">CE3806G.ADA<TD align="left"> <TR><TD align="left">CE2102B.ADA<TD align="left">CE2401F.ADA<TD align="left">CE3408A.ADA<TD align="left">CE3806H.ADA<TD align="left"> <TR><TD align="left">CE2102C.TST<TD align="left">CE2401H.ADA<TD align="left">CE3408B.ADA<TD align="left">CE3902B.ADA<TD align="left"> <TR><TD align="left">CE2102G.ADA<TD align="left">CE2401I.ADA<TD align="left">CE3408C.ADA<TD align="left">CE3904A.ADA<TD align="left"> <TR><TD align="left">CE2102H.TST<TD align="left">CE2401J.ADA<TD align="left">CE3409A.ADA<TD align="left">CE3904B.ADA<TD align="left"> <TR><TD align="left">CE2102K.ADA<TD align="left">CE2401K.ADA<TD align="left">CE3409C.ADA<TD align="left">CE3905A.ADA<TD align="left"> <TR><TD align="left">CE2102N.ADA<TD align="left">CE2401L.ADA<TD align="left">CE3409D.ADA<TD align="left">CE3905B.ADA<TD align="left"> <TR><TD align="left">CE2102O.ADA<TD align="left">CE2403A.TST<TD align="left">CE3409E.ADA<TD align="left">CE3905C.ADA<TD align="left"> <TR><TD align="left">CE2102P.ADA<TD align="left">CE2404A.ADA<TD align="left">CE3410A.ADA<TD align="left">CE3905L.ADA<TD align="left"> <TR><TD align="left">CE2102Q.ADA<TD align="left">CE2404B.ADA<TD align="left">CE3410C.ADA<TD align="left">CE3906A.ADA<TD align="left"> <TR><TD align="left">CE2102R.ADA<TD align="left">CE2405B.ADA<TD align="left">CE3410D.ADA<TD align="left">CE3906B.ADA<TD align="left"> <TR><TD align="left">CE2102S.ADA<TD align="left">CE2406A.ADA<TD align="left">CE3410E.ADA<TD align="left">CE3906C.ADA<TD align="left"> <TR><TD align="left">CE2102T.ADA<TD align="left">CE2407A.ADA<TD align="left">CE3411A.ADA<TD align="left">CE3906E.ADA<TD align="left"> <TR><TD align="left">CE2102U.ADA<TD align="left">CE2407B.ADA<TD align="left">CE3411C.ADA<TD align="left">CE3906F.ADA<TD align="left"> <TR><TD align="left">CE2102V.ADA<TD align="left">CE2408A.ADA<TD align="left">CE3412A.ADA<TD align="left">CXA8001.A<TD align="left"> <TR><TD align="left">CE2102W.ADA<TD align="left">CE2408B.ADA<TD align="left">CE3413A.ADA<TD align="left">CXA8002.A<TD align="left"> <TR><TD align="left">CE2102X.ADA<TD align="left">CE2409A.ADA<TD align="left">CE3413B.ADA<TD align="left">CXA8003.A<TD align="left"> <TR><TD align="left">CE2102Y.ADA<TD align="left">CE2409B.ADA<TD align="left">CE3413C.ADA<TD align="left">CXA9001.A<TD align="left"> <TR><TD align="left">CE2103A.TST<TD align="left">CE2410A.ADA<TD align="left">CE3414A.ADA<TD align="left">CXA9002.A<TD align="left"> <TR><TD align="left">CE2103B.TST<TD align="left">CE2410B.ADA<TD align="left">CE3602A.ADA<TD align="left">CXAA001.A<TD align="left"> <TR><TD align="left">CE2103C.ADA<TD align="left">CE2411A.ADA<TD align="left">CE3602B.ADA<TD align="left">CXAA002.A<TD align="left"> <TR><TD align="left">CE2103D.ADA<TD align="left">CE3102A.ADA<TD align="left">CE3602C.ADA<TD align="left">CXAA003.A<TD align="left"> <TR><TD align="left">CE2104A.ADA<TD align="left">CE3102B.TST<TD align="left">CE3602D.ADA<TD align="left">CXAA004.A<TD align="left"> <TR><TD align="left">CE2104B.ADA<TD align="left">CE3102F.ADA<TD align="left">CE3603A.ADA<TD align="left">CXAA005.A<TD align="left"> <TR><TD align="left">CE2104C.ADA<TD align="left">CE3102G.ADA<TD align="left">CE3604A.ADA<TD align="left">CXAA006.A<TD align="left"> <TR><TD align="left">CE2104D.ADA<TD align="left">CE3102H.ADA<TD align="left">CE3604B.ADA<TD align="left">CXAA007.A<TD align="left"> <TR><TD align="left">CE2106A.ADA<TD align="left">CE3102J.ADA<TD align="left">CE3605A.ADA<TD align="left">CXAA008.A<TD align="left"> <TR><TD align="left">CE2106B.ADA<TD align="left">CE3102K.ADA<TD align="left">CE3605B.ADA<TD align="left">CXAA009.A<TD align="left"> <TR><TD align="left">CE2108E.ADA<TD align="left">CE3103A.ADA<TD align="left">CE3605C.ADA<TD align="left">CXAA010.A<TD align="left"> <TR><TD align="left">CE2108F.ADA<TD align="left">CE3104A.ADA<TD align="left">CE3605D.ADA<TD align="left">CXAA011.A<TD align="left"> <TR><TD align="left">CE2108G.ADA<TD align="left">CE3104B.ADA<TD align="left">CE3605E.ADA<TD align="left">CXAA012.A<TD align="left"> <TR><TD align="left">CE2108H.ADA<TD align="left">CE3104C.ADA<TD align="left">CE3606A.ADA<TD align="left">CXAA013.A<TD align="left"> <TR><TD align="left">CE2109A.ADA<TD align="left">CE3106A.ADA<TD align="left">CE3606B.ADA<TD align="left">CXAA014.A<TD align="left"> <TR><TD align="left">CE2109B.ADA<TD align="left">CE3106B.ADA<TD align="left">CE3704A.ADA<TD align="left">CXAA015.A<TD align="left"> <TR><TD align="left">CE2109C.ADA<TD align="left">CE3107A.TST<TD align="left">CE3704B.ADA<TD align="left">CXAA016.A<TD align="left"> <TR><TD align="left">CE2110A.ADA<TD align="left">CE3107B.ADA<TD align="left">CE3704C.ADA<TD align="left">CXAA017.A<TD align="left"> <TR><TD align="left">CE2110C.ADA<TD align="left">CE3108A.ADA<TD align="left">CE3704D.ADA<TD align="left">CXAA018.A<TD align="left"> <TR><TD align="left">CE2111A.ADA<TD align="left">CE3108B.ADA<TD align="left">CE3704E.ADA<TD align="left">CXAA019.A<TD align="left"> <TR><TD align="left">CE2111B.ADA<TD align="left">CE3110A.ADA<TD align="left">CE3704F.ADA<TD align="left">CXAA020.A<TD align="left"> <TR><TD align="left">CE2111C.ADA<TD align="left">CE3112C.ADA<TD align="left">CE3704M.ADA<TD align="left">CXAA021.A<TD align="left"> <TR><TD align="left">CE2111E.ADA<TD align="left">CE3112D.ADA<TD align="left">CE3704N.ADA<TD align="left">CXAA022.A<TD align="left"> <TR><TD align="left">CE2111F.ADA<TD align="left">CE3114A.ADA<TD align="left">CE3704O.ADA<TD align="left">CXAB001.A<TD align="left"> <TR><TD align="left">CE2111G.ADA<TD align="left">CE3115A.ADA<TD align="left">CE3705A.ADA<TD align="left">CXAB002.AU<TD align="left"> <TR><TD align="left">CE2111I.ADA<TD align="left">CE3207A.ADA<TD align="left">CE3705B.ADA<TD align="left">CXAB003.AU<TD align="left"> <TR><TD align="left">CE2201A.ADA<TD align="left">CE3301A.ADA<TD align="left">CE3705C.ADA<TD align="left">CXAB004.AU<TD align="left"> <TR><TD align="left">CE2201B.ADA<TD align="left">CE3302A.ADA<TD align="left">CE3705D.ADA<TD align="left">CXAB005.AU<TD align="left"> <TR><TD align="left">CE2201C.ADA<TD align="left">CE3304A.TST<TD align="left">CE3705E.ADA<TD align="left">CXAC001.A<TD align="left"> <TR><TD align="left">CE2201D.DEP<TD align="left">CE3305A.ADA<TD align="left">CE3706D.ADA<TD align="left">CXAC002.A<TD align="left"> <TR><TD align="left">CE2201E.DEP<TD align="left">CE3401A.ADA<TD align="left">CE3706F.ADA<TD align="left">CXAC003.A<TD align="left"> <TR><TD align="left">CE2201F.ADA<TD align="left">CE3402A.ADA<TD align="left">CE3706G.ADA<TD align="left">CXAC004.A<TD align="left"> <TR><TD align="left">CE2201G.ADA<TD align="left">CE3402C.ADA<TD align="left">CE3804A.ADA<TD align="left">CXAC005.A<TD align="left"> <TR><TD align="left">CE2201H.ADA<TD align="left">CE3402D.ADA<TD align="left">CE3804B.ADA<TD align="left">CXAC006.A<TD align="left"> <TR><TD align="left">CE2201I.ADA<TD align="left">CE3403A.ADA<TD align="left">CE3804C.ADA<TD align="left">CXAC007.A<TD align="left"> <TR><TD align="left">CE2201J.ADA<TD align="left">CE3403B.ADA<TD align="left">CE3804D.ADA<TD align="left">CXAC008.A<TD align="left"> <TR><TD align="left">CE2201K.ADA<TD align="left">CE3403C.ADA<TD align="left">CE3804E.ADA<TD align="left">CXACA01.A<TD align="left"> <TR><TD align="left">CE2201L.ADA<TD align="left">CE3403E.ADA<TD align="left">CE3804F.ADA<TD align="left">CXACA02.A<TD align="left"> <TR><TD align="left">CE2201M.ADA<TD align="left">CE3403F.ADA<TD align="left">CE3804G.ADA<TD align="left">CXACB01.A<TD align="left"> <TR><TD align="left">CE2201N.ADA<TD align="left">CE3404B.ADA<TD align="left">CE3804H.ADA<TD align="left">CXACB02.A<TD align="left"> <TR><TD align="left">CE2203A.TST<TD align="left">CE3404C.ADA<TD align="left">CE3804I.ADA<TD align="left">CXACC01.A<TD align="left"> <TR><TD align="left">CE2204A.ADA<TD align="left">CE3404D.ADA<TD align="left">CE3804J.ADA<TD align="left">CXAG001.A<TD align="left"> <TR><TD align="left">CE2204B.ADA<TD align="left">CE3405A.ADA<TD align="left">CE3804M.ADA<TD align="left">CXAG002.A<TD align="left"> <TR><TD align="left">CE2204C.ADA<TD align="left">CE3405C.ADA<TD align="left">CE3804O.ADA<TD align="left">CXF3A06.A<TD align="left"> <TR><TD align="left">CE2204D.ADA<TD align="left">CE3405D.ADA<TD align="left">CE3804P.ADA<TD align="left">CXG1003.A<TD align="left"> <TR><TD align="left">CE2205A.ADA<TD align="left">CE3406A.ADA<TD align="left">CE3805A.ADA<TD align="left">EE3203A.ADA<TD align="left"> <TR><TD align="left">CE2206A.ADA<TD align="left">CE3406B.ADA<TD align="left">CE3805B.ADA<TD align="left">EE3204A.ADA<TD align="left"> <TR><TD align="left">CE2208B.ADA<TD align="left">CE3406C.ADA<TD align="left">CE3806A.ADA<TD align="left">EE3402B.ADA<TD align="left"> <TR><TD align="left">CE2401A.ADA<TD align="left">CE3406D.ADA<TD align="left">CE3806B.ADA<TD align="left">EE3409F.ADA<TD align="left"> <TR><TD align="left">CE2401B.ADA<TD align="left">CE3407A.ADA<TD align="left">CE3806D.ADA<TD align="left">EE3412C.ADA <TD align="left"> <TR><TD align="left">CE2401C.ADA<TD align="left">CE3407B.ADA<TD align="left">CE3806E.ADA<TD align="left">&nbsp;<TD align="left"> </table></div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-D2E.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-D2G.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/README.md # ACATS # This repository contains a version of the [Ada Conformity Assessment Test Suite][Ada-Auth] customised for use with FSF GCC. They can be used instead of the current GCC tests (based on ACATS 2.6). The current version here is 4.1DD. ## Notes ## To run the tests, you'll need `expect` (and `tcl`) installed. ### Test changes ### Test CXH1001 as released fails; if the GNAT binder encounters the configuration pragma `Normalize_Scalars`, it requires all the units in the partition to have been compiled with it, including the runtime system. Replaced here by the GNAT-specific `Initialize_Scalars`. Some individual tests are in any case suppressed (by inclusion in the file `norun.lst`), because they involve another language (Fortran, Cobol). The tests that involve timing mostly included very long timeouts (up to an hour in some cases), which were scaled here (as in the GCC version) by multiplying by `One_Nominal_Second` (0.001 seconds) or `One_Nominal_Long_Second` (0.1 seconds). This problem was corrected in ACATS 4.1M, and the code here matches the official version. ### Testing in GCC ### You can run the GCC checks with this version of the tests (provided you have `dejagnu` installed as well as `expect`) by replacing `gcc/testsuite/ada/acats` in the source tree by (a link to) this code and then, in the `gcc` directory of the build tree, run `make check-acats`. (You can also run `make check-gnat` for the GNAT tests, or `make check-ada` for both). You can run the tests in parallel, which of course makes most sense if you have multiple cores, by for example `make -j4 check-acats`. If you do this, the screen output during execution is misleading; only the final `acats.log` and `acats.sum` in `<build-dir>/gcc/testsuite/ada/acats/` are meaningful. The default compiler options are `-gnatws -g -O2` (`-gnat2012` is always added). You can pass additional options using the `RUNTESTFLAGS` feature: make check-acats RUNTESTFLAGS="--target_board=unix/-O3/-gnatN" runs the tests with `-gnatws -gnatN -g -O2 -O3`. If you wish to pass any GNAT-specific options (e.g. `-gnat*`) you must only run this suite (`make check-acats`), because `-gnat*` will fail with most other tools (`unrecognized debug output level 'nat*'`). Don't use `RUNTESTFLAGS` with `-j<n>`: it doesn't get passed to sub-makes (as of 2018-02-10). ### Local testing ### You can also run the tests, or individual chapters of the tests, by using the `run_local.sh` script (from a different directory). For example, mkdir ~/tmp/acats cd ~/tmp/acats ~/ACATS/run_local.sh cxd cxe (assuming this repository is installed at `~/ACATS`) will run just chapters CXD, CXE (execution tests on Annexes D and E), using the current compiler. With no arguments, all tests are run. The above command will only build the support code if it isn't already built. To force a rebuild, say ~/ACATS/run_local.sh NONE cxd cxe ### Reports ### The reports are in `acats.log` and `acats.sum`. `acats.log` is a full report of test compilation, build and execution. `acats.sum` is a report of just the outcome of each test and a summary. The outcomes are reported in the style `OUTCOME: test`, e.g. `PASS: a22006b`, where the possible outcomes are * `PASS`: the test passed * `FAIL`: the test was expected to pass but failed * `XFAIL`: the test was expected to fail and did so * `XPASS`: the test was expected to fail but passed * `UNRESOLVED`: the test requires visual examination to finally determine pass/fail * `UNSUPPORTED`: the test was either deemed not applicable by the test itself (for example, C45322A requires `Machine_Overflows` to be `True`), not supported by the compiler (for example, CXAG002 will not compile because it requires support for `Hierarchical_File_Names`), or not compatible with simple use of _gnatchop_ (because the test contains the same unit in several source files, expecting them to be used in multiple passes). Note, these outcome names are not ideal, but they have to match the requirements of the GCC test infrastructure that supports parallel test execution. The summary is reported in the form below (this is for ACATS 4.1BB, running under GCC 12.2.0 on macOS) ``` none === acats Summary === # of expected passes 2544 # of unexpected failures 10 # of expected failures 1493 # of unresolved testcases 11 # of unsupported tests 124 *** FAILURES: c250002 c324006 c415001 cxa4038 cxd1003 cxd1004 cxd1005 cxd2006 cxd3001 cxd3002 ``` [Ada-Auth]: http://www.ada-auth.org/acats.html <file_sep>/docs/ug-614.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Grading Tool Reference</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} DIV.Examples {font-family: "Courier New", monospace; font-size: 90%; line-height: 122%; margin-left: 2.2em; margin-bottom: 0.6em} DIV.Indented3MediumHanging-Body {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 6.0em; margin-top: 0em; margin-bottom: 0.6em} DIV.Indented3MediumHanging-Term {float: left; font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 2.0em; margin-top: 0em; margin-bottom: 0em} DIV.Indented4MediumHanging-Body {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 8.0em; margin-top: 0em; margin-bottom: 0.6em} DIV.Indented4MediumHanging-Term {float: left; font-family: "Times New Roman", Times, serif; line-height: 122%; margin-left: 4.0em; margin-top: 0em; margin-bottom: 0em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-613.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-615.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>6.1.4 Grading Tool Reference</H1> <div class="Normal" style="margin-bottom: 0.4em">The command line for the Grading Tool is:</div> <div class="Examples">&nbsp;&nbsp;Grade&nbsp;&lt;Event_Trace_File_Name&gt;&nbsp;&lt;Summary_of_Tests_File_Name&gt;&nbsp;&lt;Manual_Grading_Request_Name&gt;&nbsp;&lt;Quoted&nbsp;Report&nbsp;Title&gt;&nbsp;[options]</div> <div class="Indented3MediumHanging-Term">&lt;Event_Trace_File_Name&gt;</div><div class="Indented3MediumHanging-Body"><br clear="left"> The name of an event trace file (see <A HREF="UG-62.HTM">6.2</A>). This can use any file name acceptable to the implementation that compiled the tool (in particular, full paths may be used on most implementations). The event trace should contain traces of the processing of at least the tests to be graded; it is acceptable to include traces for additional tests that are not being graded.</div> <div class="Indented3MediumHanging-Term">&lt;Summary_of_Tests_File_Name&gt;</div><div class="Indented3MediumHanging-Body"><br clear="left"> The name of a test summary file (see <A HREF="UG-63.HTM">6.3</A>). This can use any file name acceptable to the implementation that compiled the tool (in particular, full paths may be used on most implementations). The test summary file should contain the summaries of exactly the tests that need to be graded; all of the tests summarized in the file will be graded regardless of the contents of the event trace. If the event trace does not include a test that is in the summary file, the test will be graded &quot;Failed - Compile Missing&quot;.</div> <div class="Indented3MediumHanging-Term">&lt;Manual_Grading_Request_Name&gt;</div><div class="Indented3MediumHanging-Body"><br clear="left"> The name of a manual grading request file (see <A HREF="UG-64.HTM">6.4</A>). This can use any file name acceptable to the implementation that compiled the tool (in particular, full paths may be used on most implementations). This file may include names of tests not included in the test summary file; such names will have no effect on grading.</div> <div class="Indented3MediumHanging-Term">&lt;Quoted Report Title&gt;</div><div class="Indented3MediumHanging-Body"><br clear="left"> A double quoted string containing the name of the test report. This is primarily intended so that similar-looking reports can be differentiated.</div> <div class="Indented3MediumHanging-Term">[options]</div><div class="Indented3MediumHanging-Body"> Zero or more optional setting flags for the Grading Tool. These are case-insensitive, and can be:&nbsp;</div> <div class="Indented4MediumHanging-Term">-Specs_Optional</div><div class="Indented4MediumHanging-Body"><br clear="left"> Compiling of specifications is optional. Use for source-based compilers (such as the commonly used GNAT compiler) that don't compile specifications in normal operation. Compilation of bodies, instances, and so on are checked.</div> <div class="Indented4MediumHanging-Term">-Check_All_Compiles</div><div class="Indented4MediumHanging-Body"><br clear="left"> All compilations are checked and must be present (unless processing the unit is marked as optional). This is the default.</div> <div class="Indented4MediumHanging-Term">-No_Compile_Checks</div><div class="Indented4MediumHanging-Body"><br clear="left"> No compilation checks are made. This option is not allowed for formal conformity assessments.</div> <div class="Indented4MediumHanging-Term">-Use_Time_Stamps</div><div class="Indented4MediumHanging-Body"><br clear="left"> Check event trace time stamp information as part of checking, specifically, enforce that all units of a test are compiled and run in an appropriate order and reasonably close in time. This is the default.</div> <div class="Indented4MediumHanging-Term">-No_Time_Stamps</div><div class="Indented4MediumHanging-Body"><br clear="left"> Do not make any check of event trace time stamps. Use this option only if there is no meaningful timestamps in the event trace. This option is not allowed for formal conformity assessments.</div> <div class="Indented4MediumHanging-Term">-Use_Positions</div><div class="Indented4MediumHanging-Body"><br clear="left"> Use position information when checking whether errors are appropriately detected. This is the default.</div> <div class="Indented4MediumHanging-Term">-No_Positions</div><div class="Indented4MediumHanging-Body"><br clear="left"> Use only line information when checking whether errors are appropriately detected. Use this option if the event trace doesn't have position information. It is acceptable to use this option for formal conformity assessments.</div> <div class="Indented4MediumHanging-Term">-Quiet</div><div class="Indented4MediumHanging-Body"> Produce minimal information: a list of failed tests and the summary report.</div> <div class="Indented4MediumHanging-Term">-Verbose</div><div class="Indented4MediumHanging-Body"> Produce information about every test processed (including passed tests), along with the summary report. In this mode, the grading tool also produces a warning for multiple messages for one error tag.</div> <div class="Indented4MediumHanging-Term">-Normal</div><div class="Indented4MediumHanging-Body"> Produce details about each failed test, along with the summary report. This is the default.&nbsp;</div> <div class="Normal">Only one of the options -Specs_Optional, -Check_All_Compiles, or -No_Compile_Checks can be given. Only one of the options -Use_Positions or -No_Positions can be given. Only one of the options -Quiet, -Verbose, or -Normal can be given. Only one of the options -Use_Time_Stamps or -No_Time_Stamps can be given.</div> <div class="Normal">An annotated example using the grading tool is given in subclause <A HREF="UG-612.HTM">6.1.2</A>, &ldquo;<A HREF="UG-612.HTM">Annotated Grading Tool Example</A>&rdquo;. That example explains the output of the grading tool.</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-613.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-615.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/docs/ug-623.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Creating an Event Trace from Listings</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-622.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-63.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>6.2.3 Creating an Event Trace from Listings</H1> <div class="Normal">If it is not possible or desirable to modify the implementation to create an event trace, an event trace can be created from a listing of test processing. Such a listing would capture all of the compile, bind, and run steps for a set of tests. The Generate_Event_Trace_File constant in Report.A would remain False.</div> <div class="Normal">A tool then would have to be constructed to read those listings and convert them to an event trace. This would be specific to a particular implementation, and the tool would potentially break due to future changes in an implementation.</div> <div class="Normal">The tool would probably have to gather information from several parts of a listing. For instance, most programs don't display a time stamp when they run, so it would be necessary to use a system tool or tiny Ada program to add those to strategic points in a listing. (Using a single timestamp for an entire compilation of a compilation unit, including any reported errors, is sufficient to meet the requirements of the Grading Tool.) Note that the initial message from Report includes a timestamp, so there is no need to add one for the execution of tests.</div> <div class="Normal">The listing converter tool would have to be able to extract events from the compiler, the binder, and running of ACATS tests. Each of these likely has a different format, so the tool would need many rules to extract all of the events.</div> <div class="Normal">While a listing converted tool is potentially more fragile (due to more dependence on the exact layout of messages for an implementation), it would have the possibility of detecting test failures after the reporting of Passed (due to a finalization or tasking failure) - such &quot;aberrant behavior&quot; (as defined in <A HREF="UG-561.HTM">5.6.1</A>) cannot be detected when Report.A itself writes the event trace (as the failure happens outside of the control of Report).</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-622.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-63.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/docs/ug-a.htm <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Version Description</TITLE> <META http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <META NAME="Author" CONTENT="JTC1/SC22/WG9/ARG, by <NAME>, ARG Editor"> <META NAME="GENERATOR" CONTENT="Arm_Form.Exe, Ada Reference Manual generator"> <STYLE type="text/css"> H4.centered {text-align: center} SPAN.swiss {font-family: Arial, Helvetica, sans-serif; font-size: 92%} SPAN.roman {font-family: "Times New Roman", Times, serif} TT {font-family: "Courier New", monospace} DT {display: compact} A.Bar:link {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} A.Bar:visited {font-family: Arial, Helvetica, sans-serif; font-style: normal; text-decoration: none; color: rgb(204,204,51)} DIV.Normal {font-family: "Times New Roman", Times, serif; line-height: 122%; margin-bottom: 0.6em} </STYLE> </HEAD> <BODY TEXT="#000000" BGCOLOR="#FFFFE8" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000"> <DIV><SPAN Style="font-size:200%; color: rgb(0,0,153)"><B>ACATS 4.1 User's Guide</B></SPAN></DIV> <DIV Class="Normal"><I><B><A HREF="UG-TTL.HTM">Title Page</A></B></I></DIV> <div style="margin-top: 0.6em; margin-bottom: 0.0em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-65.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-A1.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> <HR> <H1>Annex A<BR> Version Description</H1> <div class="Normal">ACATS 4.1 includes 39nn tests in 45nn files, not including foundation and other support units. From Version 4.0 to 4.1, 134 tests were added, comprising 179 files (including six foundation files). 13 tests and one foundation (14 files) were modified. Seven support files were added and two deleted. Three tests (3 files) were removed. 36 documentation files were added, 161 documentation files were modified, and one documentation file was deleted.</div> <div class="Normal">The following sections present a detailed description of ACATS 4.1, as follows:</div> <div class="Normal"><A HREF="UG-A1.HTM">A.1</A>, &ldquo;<A HREF="UG-A1.HTM">Core Test Files</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A2.HTM">A.2</A>, &ldquo;<A HREF="UG-A2.HTM">Specialized Needs Annex Test Files</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A3.HTM">A.3</A>, &ldquo;<A HREF="UG-A3.HTM">Foundation Code Files</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A4.HTM">A.4</A>, &ldquo;<A HREF="UG-A4.HTM">Documentation Files</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A5.HTM">A.5</A>, &ldquo;<A HREF="UG-A5.HTM">Other Files</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A6.HTM">A.6</A>, &ldquo;<A HREF="UG-A6.HTM">Tests With Special Requirements</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A7.HTM">A.7</A>, &ldquo;<A HREF="UG-A7.HTM">Test Files Added Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A8.HTM">A.8</A>, &ldquo;<A HREF="UG-A8.HTM">Documentation Files Added Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-A9.HTM">A.9</A>, &ldquo;<A HREF="UG-A9.HTM">Support Files Added Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AA.HTM">A.10</A>, &ldquo;<A HREF="UG-AA.HTM">Test Files Modified Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AC.HTM">A.12</A>, &ldquo;<A HREF="UG-AC.HTM">Documentation Files Modified Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AB.HTM">A.11</A>, &ldquo;<A HREF="UG-AB.HTM">Support Files Modified Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AD.HTM">A.13</A>, &ldquo;<A HREF="UG-AD.HTM">Test Files Deleted Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AE.HTM">A.14</A>, &ldquo;<A HREF="UG-AE.HTM">Documentation Files Deleted Since ACATS 4.0</A>&rdquo;</div> <div class="Normal"><A HREF="UG-AF.HTM">A.15</A>, &ldquo;<A HREF="UG-AF.HTM">Support Files Deleted Since ACATS 4.0</A>&rdquo;</div> <HR> <div style="margin-top: 0.0em; margin-bottom: 0.6em"><A HREF="UG-TOC.HTM"><IMG SRC="CONT.GIF" ALT="Contents" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-02.HTM"><IMG SRC="INDEX.GIF" ALT="Index" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-01.HTM"><IMG SRC="LIB.GIF" ALT="References" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-65.HTM"><IMG SRC="PREV.GIF" ALT="Previous" BORDER=0></A>&nbsp; &nbsp;<A HREF="UG-A1.HTM"><IMG SRC="NEXT.GIF" ALT="Next" BORDER=0></A>&nbsp; </div> </BODY> </HTML> <file_sep>/run_local.sh #!/bin/sh # Run the whole suite (or just one chapter, in $1) using the installed # compiler. # # Only tested on macOS. testdir=`(cd $(dirname "$0"); pwd)` export testdir GCC=${GCC-`which gcc`} export GCC unset BASE export BASE EXPECT=${EXPECT-`which expect`} export EXPECT host_gnatchop=`which gnatchop` host_gnatmake=`which gnatmake` echo '#!/bin/sh' > host_gnatchop echo PATH=`dirname $host_gnatchop`:'$PATH' >> host_gnatchop echo unset ADA_INCLUDE_PATH ADA_OBJECTS_PATH GCC_EXEC_PREFIX >> host_gnatchop echo export PATH >> host_gnatchop echo exec gnatchop '"$@"' >> host_gnatchop chmod +x host_gnatchop echo '#!/bin/sh' > host_gnatmake echo PATH=`dirname $host_gnatmake`:'$PATH' >> host_gnatmake echo unset ADA_INCLUDE_PATH ADA_OBJECTS_PATH GCC_EXEC_PREFIX >> host_gnatmake echo export PATH >> host_gnatmake echo exec gnatmake '"$@"' >> host_gnatmake chmod +x host_gnatmake # Limit the stack to 16MB for stack checking ulimit -s 16384 PATH=$PWD:$PATH export PATH exec $testdir/run_all.sh ${1+"$@"}
833a50cc71f864c46ed4f02b07bfbc4575755e56
[ "Markdown", "C", "HTML", "Shell" ]
15
HTML
simonjwright/ACATS
b642dbafda665a1351812abdce961be7a931bd8d
58f7ffbfdbf08a058cdc2134e82aa07379a628d4
refs/heads/master
<file_sep>package modules; import com.sun.nio.sctp.Notification; import services.UserServiceRemote; import services.WinnerManagementRemote; import static com.sun.xml.internal.ws.api.model.wsdl.WSDLBoundOperation.ANONYMOUS.optional; import java.net.URL; //import java.sql.Date; import java.util.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.paint.Paint; import javafx.util.Duration; import persistence.User; import persistence.Winner; import static sun.text.normalizer.NormalizerImpl.convert; import java.util.Optional; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; public class WinnerController implements Initializable { @FXML private Button youssef; @FXML private TextField wintxt; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } /* public static String convert(java.sql.Date d) { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String text = df.format(d); return text; } */ @FXML private void randombutt(ActionEvent event) throws ParseException { Context context2 = null; try { context2 = new InitialContext(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } WinnerManagementRemote win = null; try { win = (WinnerManagementRemote) context2 .lookup("theblizzards-ear/theblizzards-ejb/WinnerManagement!Service.WinnerManagementRemote"); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Context context = null; try { context = new InitialContext(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } UserServiceRemote serviceRemote = null; try { serviceRemote = (UserServiceRemote) context .lookup("theblizzards-ear/theblizzards-ejb/UserService!Service.UserServiceRemote"); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } User user = serviceRemote.findById(3);//(win.winnerOfTheDay()); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); Winner pp = new Winner(dateFormat.format(cal.getTime()) , user.getIdUser() ); String DD = win.maxwinnerdate(); int MAXWINN = DD.length(); String bb = dateFormat.format(cal.getTime()); int AUTRE = bb.length(); System.out.println("bb"+AUTRE); System.out.println("dd"+MAXWINN); //// String carac = bb+""; /// int lasthope = carac.length(); //// System.out.println(lasthope); System.out.println("ahmedkkkkkkkkkkkkkk"+DD); System.out.println("aaaaaaaaaaaaaaaaaaa"+dateFormat.format(cal.getTime())); if (bb.equals(DD)) { System.out.println("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("sorry"); alert.setHeaderText("we have already have a winner for today"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { wintxt.clear(); } } else { System.out.println("lllllllllllllllllllllllllllllllllllllllllllll"); win.add(pp); wintxt.setText("The winner of the day is: \n"+user.toString()); } } } <file_sep>package services; import java.util.List; import javax.ejb.Remote; import javax.jws.WebService; import persistence.User; @Remote @WebService public interface UserServiceRemote { public User add(User u); public User update(User u); public Boolean remove(Integer id); public List<User> findAll(); public User findById(Integer id); public User findByEmail(String l); } <file_sep>package services; import java.sql.Date; import java.util.List; import javax.ejb.Local; import persistence.Company; import persistence.Contract; import persistence.User; @Local public interface ContractServiceLocal { void SigneContract(Date sdate, Date edate, int montant,String des, User u, Company com); void deleteContract(Contract C ); List<Contract> findContractsbyCompanybyID(int idcom); List<Contract> findAllContracts(); void SigneContract(Date sdate, Date edate, int montant, String des, int iduser, int idCompany); void SigneContract(java.util.Date dd1, java.util.Date dd2, int a, String st, int iduser, int idCompany); void SigneContract(java.util.Date dd1, java.util.Date dd2, int a, String st, User u, Company c); } <file_sep>package persistence; import java.io.Serializable; import java.util.Date; //import java.util.List; 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.ManyToMany; import javax.persistence.OneToMany; //import javax.persistence.OneToMany; /** * Entity implementation class for Entity: User * */ @Entity public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int idUser; private String lastName; private String firstName; private Date birthDate; private String gender; private String userType; private String email; private int number; private int cin; private String password; private String avatar; @ManyToMany(mappedBy = "users") private List<Event> events; @OneToMany(mappedBy="user") private List<Event>evens; @OneToMany private List<Company> companies; @OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.MERGE) private List<Contract> contract; private static final long serialVersionUID = 1L; public User() { super(); } public int getIdUser() { return idUser; } public void setIdUser(int idUser) { this.idUser = idUser; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int getCin() { return cin; } public void setCin(int cin) { this.cin = cin; } public List<Event> getEvents() { return events; } public void setEvents(List<Event> events) { this.events = events; } public List<Event> getEvens() { return evens; } public void setEvens(List<Event> evens) { this.evens = evens; } public List<Company> getCompanies() { return companies; } public void setCompanies(List<Company> companies) { this.companies = companies; } public List<Contract> getContract() { return contract; } public void setContract(List<Contract> contract) { this.contract = contract; } public static long getSerialversionuid() { return serialVersionUID; } public User(int idUser) { super(); this.idUser = idUser; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } }
1677725150dc97bd53c7231d56fb352e9c04f307
[ "Java" ]
4
Java
9allel22/scaling-dollop
6e873e4310b324feab6cf5fee1b165d9677d8f89
6534e66f3b56c02499098f2b94ccd10c9f4ee40a
refs/heads/master
<file_sep>#include "BossBulletThree.h" #include "Data.h" BossBulletThree::BossBulletThree(float speed) { texture.loadFromFile("picture/bossBullet3.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); this->speed=speed*sqrt(sqrt(Data::level)); } BossBulletThree::~BossBulletThree() { //dtor } void BossBulletThree::fire(float x,float y) { sprite.setPosition(rand()%800,0); move(); } void BossBulletThree::move() { sprite.move(0,speed); boundingBox=sprite.getGlobalBounds(); draw(); collision(); } void BossBulletThree::destory() { sprite.setPosition(0,HEIGHT+100); } void BossBulletThree::draw() { Data::window.draw(sprite); } bool BossBulletThree::is_over() { int y=sprite.getPosition().y; int x=sprite.getPosition().x; return (y>HEIGHT)||(x>WIDTH)||(y<0)||(x<0); } void BossBulletThree::collision() { if(Data::bomb.getElapsedTime().asSeconds()>0.5&&boundingBox.intersects(Data::player.bound())) { Data::life--; destory(); } } <file_sep>#include "Data.h" Data::Data() { } Data::~Data() { //dtor } <file_sep>#include "Text.h" #include "Data.h" #include <cstdlib> Text::Text() { font.loadFromFile("fonts/font.ttf"); score.setFont(font); life.setFont(font); level.setFont(font); bomb.setFont(font); power.setFont(font); score.setCharacterSize(20); life.setCharacterSize(20); level.setCharacterSize(20); bomb.setCharacterSize(20); power.setCharacterSize(20); score.setColor(sf::Color::Red); life.setColor(sf::Color::Blue); level.setColor(sf::Color::Red); bomb.setColor(sf::Color::Green); power.setColor(sf::Color::Black); } Text::~Text() { //dtor } void Text::draw() { sprintf(s,"Your score:%d",Data::score); sprintf(l,"\nYour life:%d",Data::life); sprintf(lev,"\n\nlevel:%d",Data::level); sprintf(b,"\n\n\nbomb:%d",Data::bombNum); if(Data::power>4) { Data::power=4; } sprintf(p,"\n\n\n\npower:%.2f/4.00",Data::power); score.setString(s); life.setString(l); level.setString(lev); bomb.setString(b); power.setString(p); Data::window.draw(score); Data::window.draw(life); Data::window.draw(level); Data::window.draw(bomb); Data::window.draw(power); return; } void Text::endText() { endGame.setFont(font); endGame.setCharacterSize(30); endGame.setColor(sf::Color::Red); sprintf(end,"Congratualtions!\nYour score:%d\nPlease Press R to restart this game\nPress F1 to continue game",Data::score); endGame.setString(end); endGame.setPosition(WIDTH/2-200,HEIGHT/2-100); Data::window.draw(endGame); } <file_sep>#include "Power.h" #include "Data.h" Power::Power(sf::Vector2f position) { texture.loadFromFile("picture/power.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(position); boundingbox=sprite.getGlobalBounds(); } Power::~Power() { //dtor } void Power::move() { sprite.move(0,MOVE_SPEED); boundingbox=sprite.getGlobalBounds(); Data::window.draw(sprite); bound(); } void Power::bound() { if(boundingbox.intersects(Data::player.Playerbound())) { float powerNum=(float)(rand()%5)/100+0.02; Data::power+=powerNum; isDestory=true; } } bool Power::isAdd() { return isDestory; } bool Power::isOver() { float y=sprite.getPosition().y; return y>HEIGHT; } <file_sep>#ifndef PLAYER_H #define PLAYER_H #include <SFML/Graphics.hpp> #include "Bullet.h" #include "PlayerBullet.h" #define PLAYER_BULLET_MAX 3 class Player { public: Player(); virtual ~Player(); void move(); void fire(); void draw(); sf::FloatRect bound(); sf::FloatRect Playerbound(); void bullet_destory(); PlayerBullet bullet[PLAYER_BULLET_MAX]; void resetPosition(); sf::Vector2f getPosition(); protected: private: sf::Texture texture; sf::Sprite sprite; sf::Texture bombTexture; sf::Sprite bombsSprite; sf::Texture effectTexture; sf::Sprite effectSprite; sf::Clock fire_speed; bool isFire=false; float moveSpeed; bool isBomb=false; }; #endif // PLAYER_H <file_sep>#include "Boss.h" #include "Data.h" #include "EnemyBulletOne.h" #include "EnemyBulletTwo.h" #include "BossBulletThree.h" #include "BossBulletOne.h" #include "BossBulletTwo.h" #include <random> Boss::Boss() { texture.loadFromFile("picture/boss.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(WIDTH/2-202/2,0-206); fire.restart(); hp=Data::level*33; } Boss::~Boss() { //dtor } void Boss::init() { texture.loadFromFile("picture/boss.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(WIDTH/2-202/2,0-206); hp=Data::level*25; fire.restart(); isinit=true; for(int i=0;i<BULLET_MAX;i++) { if(bullet[i]!=NULL) { delete(bullet[i]); bullet[i]=NULL; } } } void Boss::move() { Data::window.draw(sprite); if(sprite.getPosition().y<=20) { sprite.move(0,0.2); return; } for(int i=0;i<BULLET_MAX;i++) { if(bullet[i]!=NULL) { bullet[i]->move(); if(bullet[i]->is_over()) { delete(bullet[i]); bullet[i]=NULL; } } } if(fire.getElapsedTime().asSeconds()>0.2) { shoot(); fire.restart(); } } void Boss::shoot() { int num=rand()%10+5; for(int i=0;i<BULLET_MAX;i++) { if(bullet[i]==NULL) { int type=rand()%100; if(type<60) { bullet[i]=new BossBulletOne(((rand()%20)-10)/10+0.2); bullet[i]->fire(sprite.getPosition().x+202/2,sprite.getPosition().y+200); } else if(type<70) { bullet[i]=new BossBulletThree(((rand()%20)-10)/10+0.2); bullet[i]->fire(0,0); } else if(type<90) { bullet[i]=new EnemyBulletOne(((rand()%20)-10)/10+0.2); bullet[i]->fire(sprite.getPosition().x+21.5,sprite.getPosition().y+60); } else if(type<99) { bullet[i]=new EnemyBulletTwo((((rand()%10)-10)/10+0.2)/2); bullet[i]->fire(sprite.getPosition().x+21.5+rand()%50-25,sprite.getPosition().y+60+rand()%50-25); } else if(type==99) { bullet[i]=new BossBulletTwo(((rand()%20)-10)/10+0.2); bullet[i]->fire(sprite.getPosition().x+202/2,sprite.getPosition().y+200); } num--; } if(num==0) { break; } } } sf::FloatRect Boss::collision() { return sprite.getGlobalBounds(); } void Boss::boom() { Data::score+=5010; isinit=false; isBomb(); } bool Boss::is_boom() { return (hp<=0); } void Boss::isShoot() { hp-=1; } bool Boss::isInit() { return isinit; } void Boss::isBomb() { for(int i=0;i<BULLET_MAX;i++) { if(bullet[i]!=NULL) { delete(bullet[i]); bullet[i]=NULL; } } } <file_sep>#ifndef ENEMYBULLETTWO_H #define ENEMYBULLETTWO_H #include "Data.h" class EnemyBulletTwo:public Bullet { public: EnemyBulletTwo(float speed); virtual ~EnemyBulletTwo(); void fire(float x,float y); void move(); void destory(); void draw(); sf::FloatRect boundingBox; bool is_over(); void collision(); protected: private: sf::Sprite sprite; sf::Texture texture; sf::Clock t; float speed; }; #endif // ENEMYBULLETTWO_H <file_sep>#ifndef BULLET_H #define BULLET_H #include <SFML/Graphics.hpp> class Bullet { public: Bullet(){}; Bullet(float a){}; virtual ~Bullet(){}; virtual void fire(float x,float y){}; virtual void move(){}; virtual void destory(){}; virtual void draw(){}; sf::FloatRect boundingBox; virtual bool is_over(){return true;}; virtual void collision(){}; protected: private: sf::Sprite sprite; sf::Texture texture; float speed; }; #endif // BULLET_H <file_sep>#include "Player.h" #include "Data.h" #include <SFML/Graphics.hpp> Player::Player() { texture.loadFromFile("picture/player.png"); bombTexture.loadFromFile("picture/bomb_boom.png"); effectTexture.loadFromFile("picture/effect.png"); texture.setSmooth(true); bombTexture.setSmooth(true); effectTexture.setSmooth(true); sprite.setTexture(texture); bombsSprite.setTexture(bombTexture); effectSprite.setTexture(effectTexture); sprite.setPosition(WIDTH/2-16,HEIGHT-46); effectSprite.setPosition(WIDTH/2-5,HEIGHT-23-2.5); moveSpeed=1; fire_speed.restart(); } Player::~Player() { //dtor } void Player::move() { draw(); for(int i=0;i<PLAYER_BULLET_MAX;i++) { if(bullet[i].isFire) { bullet[i].move(); } } if(sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) { moveSpeed=0.5; Data::window.draw(effectSprite); } else { moveSpeed=1; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { sprite.move(-moveSpeed,0); effectSprite.move(-moveSpeed,0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { sprite.move(moveSpeed,0); effectSprite.move(moveSpeed,0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { sprite.move(0,-moveSpeed); effectSprite.move(0,-moveSpeed); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { sprite.move(0,moveSpeed); effectSprite.move(0,moveSpeed); } if(sprite.getPosition().x>WIDTH-32) { sprite.move(-moveSpeed,0); effectSprite.move(-moveSpeed,0); } if(sprite.getPosition().x<0) { sprite.move(moveSpeed,0); effectSprite.move(moveSpeed,0); } if(sprite.getPosition().y>HEIGHT-46) { sprite.move(0,-moveSpeed); effectSprite.move(0,-moveSpeed); } if(sprite.getPosition().y<0) { sprite.move(0,moveSpeed); effectSprite.move(0,moveSpeed); } if(fire_speed.getElapsedTime().asSeconds()>=0.5-Data::power*0.1) { fire_speed.restart(); isFire=false; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::X)&&Data::bombNum>0&&!isBomb) { bombsSprite.setPosition(128,0); bombsSprite.setScale(1.0,1.0); isBomb=true; Data::bombNum--; Data::bomb.restart(); } if(Data::bomb.getElapsedTime().asSeconds()>1) { isBomb=false; } if(isBomb) { bombsSprite.scale(1.01,1.01); bombsSprite.move(0.7,0.2); Data::window.draw(bombsSprite); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) { fire(); } bullet_destory(); } void Player::draw() { Data::window.draw(sprite); } void Player::fire() { if(isFire==false) { for(int i=0;i<PLAYER_BULLET_MAX;i++) { if(!bullet[i].isFire) { bullet[i].fire(sprite.getPosition().x+8,sprite.getPosition().y); break; } } isFire=true; } } void Player::bullet_destory() { for(int i=0;i<PLAYER_BULLET_MAX;i++) { if(bullet[i].is_over()) { bullet[i].isFire=false; } } return; } sf::FloatRect Player::bound() { return effectSprite.getGlobalBounds(); } sf::FloatRect Player::Playerbound() { return sprite.getGlobalBounds(); } void Player::resetPosition() { sprite.setPosition(WIDTH/2-16,HEIGHT-46); effectSprite.setPosition(WIDTH/2-5,HEIGHT-23-2.5); } sf::Vector2f Player::getPosition() { return effectSprite.getPosition(); } <file_sep>#include "Bomb.h" #include "Data.h" Bomb::Bomb(sf::Vector2f position) { texture.loadFromFile("picture/bomb.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(position); boundingbox=sprite.getGlobalBounds(); } Bomb::~Bomb() { //dtor } void Bomb::move() { sprite.move(0,MOVE_SPEED); boundingbox=sprite.getGlobalBounds(); Data::window.draw(sprite); bound(); } void Bomb::bound() { if(boundingbox.intersects(Data::player.Playerbound())) { Data::bombNum++; isDestory=true; } } bool Bomb::isAdd() { return isDestory; } bool Bomb::isOver() { float y=sprite.getPosition().y; return y>HEIGHT; } <file_sep>#include "EnemyBulletOne.h" #include <SFML/Graphics.hpp> #include <cmath> EnemyBulletOne::EnemyBulletOne(float speed) { texture.loadFromFile("picture/enemy_bullet1.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); this->speed=speed*sqrt(sqrt(Data::level)); k=(rand()%200000)*PI/100000; } EnemyBulletOne::~EnemyBulletOne() { } void EnemyBulletOne::fire(float x,float y) { sprite.setPosition(x,y); move(); } void EnemyBulletOne::move() { sprite.move(4*speed*cos(k),4*speed*sin(k)); boundingBox=sprite.getGlobalBounds(); draw(); collision(); } void EnemyBulletOne::draw() { Data::window.draw(sprite); } bool EnemyBulletOne::is_over() { int y=sprite.getPosition().y; int x=sprite.getPosition().x; return (y>HEIGHT)||(x>WIDTH)||(y<0)||(x<0); } void EnemyBulletOne::destory() { sprite.setPosition(0,HEIGHT+100); } void EnemyBulletOne::collision() { if(Data::bomb.getElapsedTime().asSeconds()>0.5&&boundingBox.intersects(Data::player.bound())) { Data::life--; destory(); } } <file_sep>#include "Data.h" #include "Bullet.h" #include "Music.h" #include "Enemy.h" #include "Text.h" #include "Item.h" #include "Score.h" #include "Life.h" #include "Power.h" #include "Bomb.h" #include "Boss.h" #define ENEMY_MAX_NUM 8 sf::RenderWindow Data::window(sf::VideoMode(WIDTH,HEIGHT),"Wy window"); int Data::score=14999; int Data::life=3; int Data::level=1; int Data::bombNum=3; float Data::power=1.0; sf::Clock Data::bomb; Player Data::player; Text text; Boss boss; Enemy* enemy[ENEMY_MAX_NUM]; sf::Clock enemyInit; sf::Clock refresh; sf::Texture backgroundTexture; sf::Sprite backgroundSprite; float enemyInterval=rand()%3+0.5; bool isRestart=false; Item* item[ENEMY_MAX_NUM*5]; Music music; bool collision(sf::FloatRect enemybound); void init(); void enemy_action(); void item_action(); void text_print(); void init_enemy(); void boss_fight(); void init_item(sf::Vector2f position); int main() { bool isClose=false; Data::window.setFramerateLimit(240); for(;!isClose;) { init(); while(Data::window.isOpen()) { sf::Event event; while(Data::window.pollEvent(event)) { if(event.type==sf::Event::Closed) { isClose=true; Data::window.close(); break; } } if(Data::level%3!=0) { init_enemy(); } if(Data::life<0) { text.endText(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::R)) { break; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::F1)) { isRestart=true; break; } } else { Data::player.move(); } text_print(); if(Data::level%3!=0) { enemy_action(); } else { boss_fight(); } item_action(); } } Data::window.close(); return 0; } void init() { backgroundTexture.loadFromFile("picture/background.png"); backgroundSprite.setTexture(backgroundTexture); Data::player.resetPosition(); Data::life=3; Data::bombNum=3; if(isRestart) { isRestart=false; Data::bomb.restart(); return; } music.replay(); boss.init(); Data::score=0; Data::level=1; Data::power=1.0; for(int i=0;i<ENEMY_MAX_NUM;i++) { if(enemy[i]!=NULL) { delete(enemy[i]); enemy[i]=NULL; } } for(int i=0;i<ENEMY_MAX_NUM*5;i++) { if(item[i]!=NULL) { delete(item[i]); item[i]=NULL; } } } void init_enemy() { if(enemyInit.getElapsedTime().asSeconds()>enemyInterval) { for(int i=0;i<ENEMY_MAX_NUM;i++) { if(enemy[i]==NULL) { enemy[i]=new Enemy(); enemyInterval=(rand()%43-Data::level*3)/10; enemyInit.restart(); break; } } } } bool collision(sf::FloatRect enemybound) { if(Data::bomb.getElapsedTime().asSeconds()<0.5) { return true; } for(int i=0;i<PLAYER_BULLET_MAX;i++) { if(!Data::player.bullet[i].isFire) { continue; } if(enemybound.intersects(Data::player.bullet[i].boundingBox)) { Data::player.bullet[i].destory(); return true; } } return false; } void enemy_action() { Data::window.draw(backgroundSprite); for(int i=0;i<ENEMY_MAX_NUM;i++) { if(enemy[i]==NULL) { continue; } if(!enemy[i]->isShooted()) { if(collision(enemy[i]->collision())) { enemy[i]->boom(); } } if(enemy[i]->is_boom()||enemy[i]->is_over()) { if(enemy[i]->is_boom()) { init_item(enemy[i]->position()); } delete(enemy[i]); enemy[i]=NULL; continue; } enemy[i]->move(); } } void item_action() { for(int i=0;i<ENEMY_MAX_NUM*5;i++) { if(item[i]==NULL) { continue; } item[i]->move(); if(item[i]->isAdd()||item[i]->isOver()) { delete(item[i]); item[i]=NULL; } } } void init_item(sf::Vector2f position) { int num=rand()%5+1; for(int i=0;i<ENEMY_MAX_NUM*5;i++) { if(item[i]==NULL) { int type=rand()%100; sf::Vector2f initPosition=position; initPosition.x+=10*num-30; initPosition.y+=10*num-30; if(type<3) { item[i]=new Life(initPosition); } else if(type<8) { item[i]=new Bomb(initPosition); } else if(type<30) { item[i]=new Score(initPosition); } else if(type<55) { item[i]=new Power(initPosition); } num--; if(num==0) { break; } } } } void text_print() { Data::level=Data::score/5000+1; text.draw(); Data::window.display(); } void boss_fight() { Data::window.draw(backgroundSprite); if(!boss.isInit()) { for(int i=0;i<ENEMY_MAX_NUM;i++) { if(enemy[i]!=NULL) { delete(enemy[i]); enemy[i]=NULL; } } boss.init(); } boss.move(); for(int i=0;i<PLAYER_BULLET_MAX;i++) { if(boss.collision().intersects(Data::player.bullet[i].boundingBox)) { boss.isShoot(); Data::player.bullet[i].destory(); } } if(Data::bomb.getElapsedTime().asSeconds()<0.5) { boss.isBomb(); } if(boss.is_boom()) { boss.boom(); } } <file_sep>#ifndef ENEMYBULLETONE_H #define ENEMYBULLETONE_H #include "Data.h" #include "Bullet.h" class EnemyBulletOne:public Bullet { public: EnemyBulletOne(float speed); virtual ~EnemyBulletOne(); void fire(float x,float y); void move(); void destory(); void draw(); sf::FloatRect boundingBox; bool is_over(); void collision(); protected: private: sf::Sprite sprite; sf::Texture texture; float speed; float k; }; #endif // ENEMYBULLETONE_H <file_sep>#include "BossBulletOne.h" #include "Data.h" BossBulletOne::BossBulletOne(float speed) { texture.loadFromFile("picture/bossBullet1.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); this->speed=speed*sqrt(sqrt(Data::level)); k=(rand()%200000-100000)*PI/100000; } BossBulletOne::~BossBulletOne() { //dtor } void BossBulletOne::fire(float x,float y) { sprite.setPosition(x,y); move(); } void BossBulletOne::move() { sprite.move(4*speed*cos(k),4*speed*sin(k)); boundingBox=sprite.getGlobalBounds(); draw(); collision(); } void BossBulletOne::destory() { sprite.setPosition(0,HEIGHT+100); } void BossBulletOne::draw() { Data::window.draw(sprite); } bool BossBulletOne::is_over() { int y=sprite.getPosition().y; int x=sprite.getPosition().x; return (y>HEIGHT)||(x>WIDTH)||(y<0)||(x<0); } void BossBulletOne::collision() { if(Data::bomb.getElapsedTime().asSeconds()>0.5&&boundingBox.intersects(Data::player.bound())) { Data::life--; destory(); } } <file_sep>#ifndef ITEM_H #define ITEM_H #include <SFML/Graphics.hpp> #define MOVE_SPEED 0.3 class Item { public: Item(); Item(sf::Vector2f position); virtual ~Item(); virtual void move(){}; virtual void bound(){}; virtual bool isAdd(){return false;}; virtual bool isOver(){return false;} protected: private: sf::Sprite sprite; sf::Texture texture; sf::FloatRect boundingbox; bool isDestory=false; }; #endif // ITEM_H <file_sep># Fighture a STG coding with sfml 学习用 <file_sep>#include "Music.h" Music::Music() { bgm.loadFromFile("sound/bgm.ogg"); } Music::~Music() { } void Music::replay() { bgm_sound.setBuffer(bgm); bgm_sound.setLoop(true); bgm_sound.play(); } <file_sep>#include "EnemyBulletTwo.h" #include <SFML/Graphics.hpp> #include <cmath> EnemyBulletTwo::EnemyBulletTwo(float speed) { texture.loadFromFile("picture/enemy_bullet2.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); this->speed=speed*sqrt(sqrt(Data::level)); t.restart(); } EnemyBulletTwo::~EnemyBulletTwo() { } void EnemyBulletTwo::fire(float x,float y) { sprite.setPosition(x,y); move(); } void EnemyBulletTwo::move() { float x=PI*t.getElapsedTime().asSeconds(); sprite.move(speed*(cos(x)-x*sin(x)),speed*(sin(x)+x*cos(x))); boundingBox=sprite.getGlobalBounds(); draw(); collision(); } void EnemyBulletTwo::draw() { Data::window.draw(sprite); } bool EnemyBulletTwo::is_over() { int y=sprite.getPosition().y; int x=sprite.getPosition().x; return (y>HEIGHT+100)||(x>WIDTH+100)||(y<-100)||(x<-100); } void EnemyBulletTwo::destory() { sprite.setPosition(0,HEIGHT+100); } void EnemyBulletTwo::collision() { if(Data::bomb.getElapsedTime().asSeconds()>0.5&&boundingBox.intersects(Data::player.bound())) { Data::life--; destory(); } } <file_sep>#ifndef BOSS_H #define BOSS_H #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Bullet.h" #define BULLET_MAX 150 class Boss { public: Boss(); virtual ~Boss(); void move(); void shoot(); void isShoot(); sf::FloatRect collision(); void boom(); void init(); bool is_boom(); bool isInit(); void isBomb(); sf::Vector2f position(); protected: private: sf::Texture texture; sf::Sprite sprite; Bullet* bullet[BULLET_MAX]={NULL}; sf::Sound boom_music; sf::SoundBuffer boom_buffer; bool isDestory=false; bool isinit=false; sf::Clock fire; sf::Clock boom_time; float fireInterval=0.5; int hp; }; #endif // BOSS_H <file_sep>#ifndef DATA_H #define DATA_H #include "Player.h" #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <iostream> #include <random> #include <cmath> #define WIDTH 800 #define HEIGHT 600 #define PI acos(-1) class Data { public: Data(); virtual ~Data(); static int score; static int life; static sf::RenderWindow window; static Player player; static int level; static sf::Clock bomb; static int bombNum; static float power; protected: private: }; #endif // DATA_H <file_sep>#include "Enemy.h" #include "Data.h" #include <random> #define Random(a) (rand()%a) Enemy::Enemy() { image.loadFromFile("picture/enemy.png"); texture.loadFromImage(image); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(Random(WIDTH-43),-52); boundingBox=sprite.getGlobalBounds(); fireInterval=Random(3); hp=Random(3)+Data::level*2; score=hp*10; fire.restart(); } Enemy::~Enemy() { for(int i=0;i<BULLET_MAX_NUM;i++) { if(bullet[i]!=NULL) { delete(bullet[i]); bullet[i]=NULL; } } } void Enemy::move() { for(int i=0;i<BULLET_MAX_NUM;i++) { if(bullet[i]==NULL) { continue; } bullet[i]->move(); if(bullet[i]->is_over()) { delete(bullet[i]); bullet[i]=NULL; } } if(sprite.getPosition().y>HEIGHT) { return; } draw(); if(isDestory) { float t=boom_time.getElapsedTime().asSeconds(); sprite.setScale(t*2.2,t*2.2); return; } if(fire.getElapsedTime().asSeconds()>fireInterval) { isFire=false; fireInterval=Random(60)/10-sqrt(Data::level); fire.restart(); } shoot(); if(!isDestory) { sprite.move(0,0.1); } boundingBox=sprite.getGlobalBounds(); } void Enemy::draw() { Data::window.draw(sprite); } void Enemy::shoot() { if(!isFire&&!isDestory) { for(int i=0;i<BULLET_MAX_NUM;i++) { if(bullet[i]==NULL) { int type=rand()%3; if(type==1||type==0) { bullet[i]=new EnemyBulletOne(((rand()%20)-10)/10+0.2); bullet[i]->fire(sprite.getPosition().x+21.5,sprite.getPosition().y+60); } else if(type==2) { bullet[i]=new EnemyBulletTwo((((rand()%10)-10)/10+0.2)/2); bullet[i]->fire(sprite.getPosition().x+21.5+rand()%50-25,sprite.getPosition().y+60+rand()%50-25); } isFire=true; fire.restart(); break; } } } return; } sf::FloatRect Enemy::collision() { return boundingBox; } void Enemy::boom() { if(hp>0) { hp--; return; } image.loadFromFile("picture/enemy_boom.png"); texture.loadFromImage(image); texture.setSmooth(true); sprite.setTexture(texture); boom_buffer.loadFromFile("sound/boom.ogg"); boom_music.setBuffer(boom_buffer); boom_music.play(); if(!isDestory) { boom_time.restart(); } isDestory=true; sprite.move(0,20); Data::score+=score; } bool Enemy::isShooted() { return isDestory; } bool Enemy::is_boom() { return (boom_time.getElapsedTime().asSeconds()>0.5&&isDestory); } bool Enemy::is_over() { int x=sprite.getPosition().x; int y=sprite.getPosition().y; for(int i=0;i<BULLET_MAX_NUM;i++) { if(bullet[i]==NULL) { continue; } if(!bullet[i]->is_over()) { return false; } } return ((y>=HEIGHT)||(x<=0)); } sf::Vector2f Enemy::position() { return sprite.getPosition(); } <file_sep>#ifndef MUSIC_H #define MUSIC_H #include <SFML/Audio.hpp> class Music { public: Music(); virtual ~Music(); void replay(); protected: private: sf::SoundBuffer bgm; sf::Sound bgm_sound; }; #endif // MUSIC_H <file_sep>#include "Life.h" #include "Data.h" Life::Life(sf::Vector2f position) { texture.loadFromFile("picture/life.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(position); boundingbox=sprite.getGlobalBounds(); } Life::~Life() { //dtor } void Life::move() { sprite.move(0,MOVE_SPEED); boundingbox=sprite.getGlobalBounds(); Data::window.draw(sprite); bound(); } void Life::bound() { if(boundingbox.intersects(Data::player.Playerbound())) { Data::life+=1; isDestory=true; } } bool Life::isAdd() { return isDestory; } bool Life::isOver() { float y=sprite.getPosition().y; return y>HEIGHT; } <file_sep>#ifndef EMENY_H #define EMENY_H #include <SFML/Graphics.hpp> #include "Bullet.h" class Emeny { public: Emeny(); virtual ~Emeny(); void move(); void shoot(); sf::Sprite draw(); sf::Sprite draw_bullet(); protected: private: sf::Texture texture; sf::Sprite sprite; Bullet *bullet; float x,y; }; #endif // EMENY_H <file_sep>#ifndef BOMB_H #define BOMB_H #include "Item.h" class Bomb:public Item { public: Bomb(sf::Vector2f position); virtual ~Bomb(); void move(); void bound(); bool isAdd(); bool isOver(); protected: private: sf::Sprite sprite; sf::Texture texture; sf::FloatRect boundingbox; bool isDestory=false; }; #endif // BOMB_H <file_sep>#include "PlayerBullet.h" #include <SFML/Graphics.hpp> #include "Data.h" PlayerBullet::PlayerBullet() { texture.loadFromFile("picture/fire.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); speed=-8; } PlayerBullet::~PlayerBullet() { } void PlayerBullet::fire(float x,float y) { isFire=true; sprite.setPosition(x,y); move(); } void PlayerBullet::move() { if(!isFire) { return; } sprite.move(0,speed); boundingBox=sprite.getGlobalBounds(); draw(); } void PlayerBullet::draw() { Data::window.draw(sprite); } bool PlayerBullet::is_over() { int y=sprite.getPosition().y; return (y<0); } void PlayerBullet::destory() { sprite.setPosition(0,-100); } <file_sep>#ifndef BOSSBULLETTHREE_H #define BOSSBULLETTHREE_H #include "Bullet.h" class BossBulletThree:public Bullet { public: BossBulletThree(float speed); virtual ~BossBulletThree(); void fire(float x,float y); void move(); void destory(); void draw(); sf::FloatRect boundingBox; bool is_over(); void collision(); protected: private: sf::Sprite sprite; sf::Texture texture; float speed; }; #endif // BOSSBULLETTHREE_H <file_sep>#include "Score.h" #include "Data.h" Score::Score(sf::Vector2f position) { texture.loadFromFile("picture/score.png"); texture.setSmooth(true); sprite.setTexture(texture); sprite.setPosition(position); boundingbox=sprite.getGlobalBounds(); } Score::~Score() { //dtor } void Score::move() { sprite.move(0,MOVE_SPEED); boundingbox=sprite.getGlobalBounds(); Data::window.draw(sprite); bound(); } void Score::bound() { if(boundingbox.intersects(Data::player.Playerbound())) { Data::score+=300; isDestory=true; } } bool Score::isAdd() { return isDestory; } bool Score::isOver() { float y=sprite.getPosition().y; return y>HEIGHT; } <file_sep>#ifndef POWER_H #define POWER_H #include <SFML/Graphics.hpp> #include "Item.h" class Power:public Item { public: Power(sf::Vector2f position); virtual ~Power(); void move(); void bound(); bool isAdd(); bool isOver(); protected: private: sf::Sprite sprite; sf::Texture texture; sf::FloatRect boundingbox; bool isDestory=false; }; #endif // POWER_H <file_sep>#ifndef EMENY_H #define EMENY_H #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Bullet.h" #include "EnemyBulletOne.h" #include "EnemyBulletTwo.h" #define BULLET_MAX_NUM 20 class Enemy { public: Enemy(); virtual ~Enemy(); void move(); void shoot(); void draw(); sf::FloatRect collision(); void boom(); bool isShooted(); bool is_boom(); bool is_over(); sf::Vector2f position(); protected: private: sf::Texture texture; sf::Sprite sprite; Bullet* bullet[BULLET_MAX_NUM]={NULL}; sf::FloatRect boundingBox; sf::Sound boom_music; sf::SoundBuffer boom_buffer; sf::Image image; bool isDestory=false; bool isFire=false; sf::Clock fire; sf::Clock boom_time; float fireInterval; int hp; int score; }; #endif // EMENY_H <file_sep>#ifndef TEXT_H #define TEXT_H #include <SFML/Graphics.hpp> class Text { public: Text(); virtual ~Text(); void draw(); void endText(); protected: private: sf::Font font; sf::Text score; sf::Text life; sf::Text level; sf::Text bomb; sf::Text power; sf::Text endGame; char s[20]; char l[20]; char lev[20]; char b[20]; char p[20]; char end[80]; }; #endif // TEXT_H <file_sep>#ifndef PLAYERBULLET_H #define PLAYERBULLET_H #include "Bullet.h" class PlayerBullet:public Bullet { public: PlayerBullet(); virtual ~PlayerBullet(); void fire(float x,float y); void move(); void destory(); void draw(); sf::FloatRect boundingBox; bool is_over(); bool isFire=false; protected: private: sf::Sprite sprite; sf::Texture texture; float speed; float k; }; #endif // PLAYERBULLET_H <file_sep>#include "BossBulletTwo.h" #include "Data.h" BossBulletTwo::BossBulletTwo(float speed) { texture.loadFromFile("picture/bossBullet2.png"); texture.setSmooth(true); sprite.setTexture(texture); boundingBox=sprite.getGlobalBounds(); this->speed=speed*sqrt(sqrt(Data::level)); } BossBulletTwo::~BossBulletTwo() { //dtor } void BossBulletTwo::fire(float x,float y) { sprite.setPosition(x,y); sf::Vector2f aim=Data::player.getPosition(); aim_x=aim.x-x; aim_y=aim.y-y; move(); } void BossBulletTwo::move() { sprite.move(aim_x*speed/150,aim_y*speed/150); boundingBox=sprite.getGlobalBounds(); draw(); collision(); } void BossBulletTwo::destory() { sprite.setPosition(0,HEIGHT+100); } void BossBulletTwo::draw() { Data::window.draw(sprite); } bool BossBulletTwo::is_over() { int y=sprite.getPosition().y; int x=sprite.getPosition().x; return (y>HEIGHT)||(x>WIDTH)||(y<0)||(x<0); } void BossBulletTwo::collision() { if(Data::bomb.getElapsedTime().asSeconds()>0.5&&boundingBox.intersects(Data::player.bound())) { Data::life--; destory(); } }
b1569087f30d7e235b2b5d93c264b8ba132a6278
[ "Markdown", "C++" ]
33
C++
pzhxbz/Fighture
c7b7c5e18808b4e47aaa63bbde33c9b7a9f3dcb6
949178ccffd4f862c0fbbedee6d0a6866ec5b870
refs/heads/master
<file_sep>package com.danupramei.weatherapp.Models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Daily { @SerializedName("dt") @Expose private Integer dt; @SerializedName("sunrise") @Expose private Integer sunrise; @SerializedName("sunset") @Expose private Integer sunset; @SerializedName("moonrise") @Expose private Integer moonrise; @SerializedName("moonset") @Expose private Integer moonset; @SerializedName("moon_phase") @Expose private Double moonPhase; @SerializedName("temp") @Expose private Daily temp; @SerializedName("pressure") @Expose private Integer pressure; @SerializedName("humidity") @Expose private Integer humidity; @SerializedName("dew_point") @Expose private Double dewPoint; @SerializedName("wind_speed") @Expose private Double windSpeed; @SerializedName("wind_deg") @Expose private Integer windDeg; @SerializedName("wind_gust") @Expose private Double windGust; @SerializedName("weather") @Expose private List<Daily> weather = null; @SerializedName("clouds") @Expose private Integer clouds; @SerializedName("pop") @Expose private Double pop; @SerializedName("uvi") @Expose private Double uvi; @SerializedName("id") @Expose private Integer id; @SerializedName("main") @Expose private String main; @SerializedName("description") @Expose private String description; @SerializedName("icon") @Expose private String icon; @SerializedName("day") @Expose private Double day; @SerializedName("min") @Expose private Double min; @SerializedName("max") @Expose private Double max; @SerializedName("night") @Expose private Double night; @SerializedName("eve") @Expose private Double eve; @SerializedName("morn") @Expose private Double morn; public Double getDay() { return day; } public void setDay(Double day) { this.day = day; } public Double getMin() { return min; } public void setMin(Double min) { this.min = min; } public Double getMax() { return max; } public void setMax(Double max) { this.max = max; } public Double getNight() { return night; } public void setNight(Double night) { this.night = night; } public Double getEve() { return eve; } public void setEve(Double eve) { this.eve = eve; } public Double getMorn() { return morn; } public void setMorn(Double morn) { this.morn = morn; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMain() { return main; } public void setMain(String main) { this.main = main; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getDt() { return dt; } public void setDt(Integer dt) { this.dt = dt; } public Integer getSunrise() { return sunrise; } public void setSunrise(Integer sunrise) { this.sunrise = sunrise; } public Integer getSunset() { return sunset; } public void setSunset(Integer sunset) { this.sunset = sunset; } public Integer getMoonrise() { return moonrise; } public void setMoonrise(Integer moonrise) { this.moonrise = moonrise; } public Integer getMoonset() { return moonset; } public void setMoonset(Integer moonset) { this.moonset = moonset; } public Double getMoonPhase() { return moonPhase; } public void setMoonPhase(Double moonPhase) { this.moonPhase = moonPhase; } public Daily getTemp() { return temp; } public void setTemp(Daily temp) { this.temp = temp; } public Integer getPressure() { return pressure; } public void setPressure(Integer pressure) { this.pressure = pressure; } public Integer getHumidity() { return humidity; } public void setHumidity(Integer humidity) { this.humidity = humidity; } public Double getDewPoint() { return dewPoint; } public void setDewPoint(Double dewPoint) { this.dewPoint = dewPoint; } public Double getWindSpeed() { return windSpeed; } public void setWindSpeed(Double windSpeed) { this.windSpeed = windSpeed; } public Integer getWindDeg() { return windDeg; } public void setWindDeg(Integer windDeg) { this.windDeg = windDeg; } public Double getWindGust() { return windGust; } public void setWindGust(Double windGust) { this.windGust = windGust; } public List<Daily> getWeather() { return weather; } public void setWeather(List<Daily> weather) { this.weather = weather; } public Integer getClouds() { return clouds; } public void setClouds(Integer clouds) { this.clouds = clouds; } public Double getPop() { return pop; } public void setPop(Double pop) { this.pop = pop; } public Double getUvi() { return uvi; } public void setUvi(Double uvi) { this.uvi = uvi; } } <file_sep>package com.danupramei.weatherapp.Models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Current { @SerializedName("dt") @Expose private Integer dt; @SerializedName("sunrise") @Expose private Integer sunrise; @SerializedName("sunset") @Expose private Integer sunset; @SerializedName("temp") @Expose private Double temp; @SerializedName("feels_like") @Expose private Double feelsLike; @SerializedName("pressure") @Expose private Integer pressure; @SerializedName("humidity") @Expose private Integer humidity; @SerializedName("dew_point") @Expose private Double dewPoint; @SerializedName("uvi") @Expose private Double uvi; @SerializedName("clouds") @Expose private Double clouds; @SerializedName("visibility") @Expose private Integer visibility; @SerializedName("wind_speed") @Expose private Double windSpeed; @SerializedName("wind_deg") @Expose private Integer windDeg; @SerializedName("weather") @Expose private List<Current> weather; @SerializedName("id") @Expose private Integer id; @SerializedName("main") @Expose private String main; @SerializedName("description") @Expose private String description; @SerializedName("icon") @Expose private String icon; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMain() { return main; } public void setMain(String main) { this.main = main; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getDt() { return dt; } public void setDt(Integer dt) { this.dt = dt; } public Integer getSunrise() { return sunrise; } public void setSunrise(Integer sunrise) { this.sunrise = sunrise; } public Integer getSunset() { return sunset; } public void setSunset(Integer sunset) { this.sunset = sunset; } public Double getTemp() { return temp; } public void setTemp(Double temp) { this.temp = temp; } public Double getFeelsLike() { return feelsLike; } public void setFeelsLike(Double feelsLike) { this.feelsLike = feelsLike; } public Integer getPressure() { return pressure; } public void setPressure(Integer pressure) { this.pressure = pressure; } public Integer getHumidity() { return humidity; } public void setHumidity(Integer humidity) { this.humidity = humidity; } public Double getDewPoint() { return dewPoint; } public void setDewPoint(Double dewPoint) { this.dewPoint = dewPoint; } public Double getUvi() { return uvi; } public void setUvi(Double uvi) { this.uvi = uvi; } public Double getClouds() { return clouds; } public void setClouds(Double clouds) { this.clouds = clouds; } public Integer getVisibility() { return visibility; } public void setVisibility(Integer visibility) { this.visibility = visibility; } public Double getWindSpeed() { return windSpeed; } public void setWindSpeed(Double windSpeed) { this.windSpeed = windSpeed; } public Integer getWindDeg() { return windDeg; } public void setWindDeg(Integer windDeg) { this.windDeg = windDeg; } public List<Current> getWeather() { return weather; } public void setWeather(List<Current> weather) { this.weather = weather; } } <file_sep>package com.danupramei.weatherapp; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import com.danupramei.weatherapp.Adapters.CityListAdapter; import com.danupramei.weatherapp.Models.City; import java.util.ArrayList; import java.util.List; import static com.danupramei.weatherapp.Utils.VariableGlobal.CITY; import static com.danupramei.weatherapp.Utils.VariableGlobal.LAT; import static com.danupramei.weatherapp.Utils.VariableGlobal.LNG; import static com.danupramei.weatherapp.Utils.VariableGlobal.REGION; public class CityListActivity extends AppCompatActivity { RecyclerView rcvCity; ImageView ivBack; CityListAdapter cityListAdapter; Context context = CityListActivity.this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_city_list); ivBack = findViewById(R.id.iv_back); rcvCity = findViewById(R.id.rcv_city); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); List<City> cities = new ArrayList<City>(); cities.add(new City("Gdansk", "Poland", "54.372158", "18.638306")); cities.add(new City("Warszawa", "Poland", "52.237049", "21.017532")); cities.add(new City("Krakow", "Poland", "50.049683", "19.944544")); cities.add(new City("Wroclaw", "Poland", "51.107883", "17.038538")); cities.add(new City("Lodz", "Poland", "51.759445", "19.457216")); cityListAdapter = new CityListAdapter(context, cities); rcvCity.setHasFixedSize(true); rcvCity.setNestedScrollingEnabled(false); rcvCity.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); rcvCity.setAdapter(cityListAdapter); cityListAdapter.setCitySelectListener(new CityListAdapter.CitySelectListener() { @Override public void onCitySelected(City city, int i) { Intent intent = new Intent(); intent.putExtra(REGION, city.getNegara()); intent.putExtra(CITY, city.getNamaKota()); intent.putExtra(LAT, city.getLat()); intent.putExtra(LNG, city.getLng()); setResult(RESULT_OK, intent); finish(); } }); } }<file_sep>package com.danupramei.weatherapp; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import com.danupramei.weatherapp.Adapters.WeatherAdapter; import com.danupramei.weatherapp.Models.Current; import com.danupramei.weatherapp.Presenters.WeatherPresenter; import com.danupramei.weatherapp.Utils.SpanningLinearLayoutManager; import java.io.IOException; import java.util.List; import java.util.Locale; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions; import static com.danupramei.weatherapp.Utils.DateConverter.toDate; import static com.danupramei.weatherapp.Utils.IconWeather.getIcon; import static com.danupramei.weatherapp.Utils.StatusView.STATUS_SUKSES; import static com.danupramei.weatherapp.Utils.VariableGlobal.CITY; import static com.danupramei.weatherapp.Utils.VariableGlobal.LAT; import static com.danupramei.weatherapp.Utils.VariableGlobal.LNG; import static com.danupramei.weatherapp.Utils.VariableGlobal.REGION; public class MainActivity extends AppCompatActivity implements WeatherPresenter.ViewWeatherForcase, EasyPermissions.PermissionCallbacks { int REQUEST_CITY = 1; WeatherAdapter mAdapterWeather; RecyclerView rcvWeathers; TextView tvHumidity, tvEstimated, tvDeskWeater, tvTemperature, tvDate, tvLocation; ImageView ivWeatherImg; SwipeRefreshLayout refresh; LinearLayout llPilihCity, llAdd; WeatherPresenter presenter; Context context = MainActivity.this; private FusedLocationProviderClient fusedLocationClient; SharedPreferences sp; String city; String region; String lat; String lng; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rcvWeathers = findViewById(R.id.rcv_weathers); tvHumidity = findViewById(R.id.tv_humidity); tvEstimated = findViewById(R.id.tv_estimated); tvDeskWeater = findViewById(R.id.tv_desk_weater); tvTemperature = findViewById(R.id.tv_temperature); tvDate = findViewById(R.id.tv_date); tvLocation = findViewById(R.id.tv_location); ivWeatherImg = findViewById(R.id.iv_weather_img); refresh = findViewById(R.id.refresh); llPilihCity = findViewById(R.id.ll_pilih_city); llAdd = findViewById(R.id.ll_add); //Presenter presenter = new WeatherPresenter(this, context); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); sp = context.getSharedPreferences("location",Context.MODE_PRIVATE); city = sp.getString(CITY, ""); region = sp.getString(REGION, ""); lat = sp.getString(LAT, null); lng = sp.getString(LNG, null); if (lat == null && lng == null) { Intent intent = new Intent(context, CityListActivity.class); someActivityResultLauncher.launch(intent); } else { refresh.setRefreshing(true); presenter.loadWeather(lat, lng, "minutely, alerts, hourly"); tvLocation.setText(city+", "+region); } llPilihCity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, CityListActivity.class); someActivityResultLauncher.launch(intent); } }); refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { presenter.loadWeather(lat, lng, "minutely, alerts, hourly"); } }); llAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { refresh.setRefreshing(true); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } fusedLocationClient.getLastLocation() .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { refresh.setRefreshing(false); lat = String.valueOf(location.getLatitude()); lng = String.valueOf(location.getLongitude()); Geocoder geocoder = new Geocoder(context, Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); city = addresses.get(0).getSubAdminArea(); region = addresses.get(0).getCountryName(); } catch (IOException e) { e.printStackTrace(); } SharedPreferences.Editor spe = sp.edit(); spe.putString(LAT, lat); spe.putString(LNG, lng); spe.putString(CITY, city); spe.putString(REGION, region); spe.apply(); presenter.loadWeather(lat, lng, "minutely, alerts, hourly"); tvLocation.setText(city+", "+region); } } }); } }); } ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if (result.getResultCode() == Activity.RESULT_OK) { // There are no request codes Intent data = result.getData(); city = data.getStringExtra(CITY); region = data.getStringExtra(REGION); lat = data.getStringExtra(LAT); lng = data.getStringExtra(LNG); SharedPreferences.Editor spe = sp.edit(); spe.putString(LAT, lat); spe.putString(LNG, lng); spe.putString(CITY, city); spe.putString(REGION, region); spe.apply(); refresh.setRefreshing(true); presenter.loadWeather(lat, lng, "minutely, alerts, hourly"); tvLocation.setText(city+", "+region); } } }); @Override public void setCurrentWeater(Current current, int status) { refresh.setRefreshing(false); String[] temps = String.valueOf(current.getTemp()).split("\\."); tvHumidity.setText(current.getPressure()+" hPa."); tvEstimated.setText(current.getHumidity()+"%"); tvDeskWeater.setText(current.getWeather().get(0).getDescription()); tvTemperature.setText(temps[0]); getIcon(current.getWeather().get(0).getId(), current.getWeather().get(0).getMain(), ivWeatherImg); tvDate.setText(toDate(current.getDt())); } @Override public void setAdapterWeather(WeatherAdapter mAdapter, int status) { refresh.setRefreshing(false); if (status == STATUS_SUKSES){ rcvWeathers.setHasFixedSize(true); rcvWeathers.setNestedScrollingEnabled(false); rcvWeathers.setLayoutManager(new SpanningLinearLayoutManager(MainActivity.this, SpanningLinearLayoutManager.HORIZONTAL, false)); rcvWeathers.setAdapter(mAdapter); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // Forward results to EasyPermissions EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) { new AppSettingsDialog.Builder(this).build().show(); } } }<file_sep>package com.danupramei.weatherapp.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.danupramei.weatherapp.Models.Daily; import com.danupramei.weatherapp.R; import java.util.List; import static com.danupramei.weatherapp.Utils.DateConverter.toDay; import static com.danupramei.weatherapp.Utils.IconWeather.getIcon; public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.ViewHolder> { private List<Daily> weatherList; private Context context; public WeatherAdapter(Context context, List<Daily> weatherList) { super(); this.weatherList = weatherList; this.context = context; } public class ViewHolder extends RecyclerView.ViewHolder { ImageView ivWeatherIcon; TextView tvTemperatureItem, tvDayItem; public ViewHolder(@NonNull View itemView) { super(itemView); ivWeatherIcon = itemView.findViewById(R.id.iv_weather_icon); tvTemperatureItem = itemView.findViewById(R.id.tv_temperature_item); tvDayItem = itemView.findViewById(R.id.tv_day_item); } } @NonNull @Override public WeatherAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recyclerview_forcase, parent, false); return new WeatherAdapter.ViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull WeatherAdapter.ViewHolder holder, int position) { Daily weather = weatherList.get(position); String[] temperature = String.valueOf(weather.getTemp().getDay()).split("\\."); getIcon(weather.getWeather().get(0).getId(), weather.getWeather().get(0).getMain(), holder.ivWeatherIcon); holder.tvTemperatureItem.setText(temperature[0]); holder.tvDayItem.setText(toDay(weather.getDt())); } @Override public int getItemCount() { return 7; } } <file_sep>package com.danupramei.weatherapp.Models; public class City { private String namaKota; private String negara; private String lat; private String lng; public City(String namaKota, String negara, String lat, String lng) { this.namaKota = namaKota; this.negara = negara; this.lat = lat; this.lng = lng; } public String getNamaKota() { return namaKota; } public void setNamaKota(String namaKota) { this.namaKota = namaKota; } public String getNegara() { return negara; } public void setNegara(String negara) { this.negara = negara; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } } <file_sep>package com.danupramei.weatherapp.REST; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { private final static String BASE_URL = "https://api.openweathermap.org/data/2.5/"; public static Retrofit getClient() { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(1, TimeUnit.MINUTES) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .addInterceptor(httpLoggingInterceptor) .build(); return new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient) .build(); } } <file_sep>package com.danupramei.weatherapp.Utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateConverter { public static String toDay(Integer tanggal) { long time = tanggal * (long) 1000; Date date = new Date(time); String res = ""; if (tanggal != 0) { try { SimpleDateFormat sdf2 = new SimpleDateFormat("EEE", new Locale("en", "US")); sdf2.setTimeZone(TimeZone.getDefault()); res = sdf2.format(date); } catch (Exception e) { e.printStackTrace(); } } return res; } public static String toDate(Integer tanggal) { long time = tanggal * (long) 1000; Date date = new Date(time); String res = ""; if (tanggal != 0) { try { SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, MMM yyyy", new Locale("en", "US")); sdf2.setTimeZone(TimeZone.getDefault()); res = sdf2.format(date); } catch (Exception e) { e.printStackTrace(); } } return res; } } <file_sep>package com.danupramei.weatherapp.Utils; public interface VariableGlobal { String API_KEY = "be3d0059461e7a77eecd4acfc56994d1"; String REGION = "region"; String CITY = "city"; String LAT = "lat"; String LNG = "lng"; } <file_sep>package com.danupramei.weatherapp.REST; import com.danupramei.weatherapp.Models.Weather; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Query; public interface ApiInterface { // MOVIES @GET("onecall") Observable<Weather> getForcase(@Query("lat") String lat, @Query("lon") String lng, @Query("exclude") String exclude, @Query("units") String units, @Query("APPID") String key); }
560d4396526099c371762b88126ffdf0e1e5e587
[ "Java" ]
10
Java
danupramei/WeatherApp
02eca4c9bcb8d51d4e378b067b0c1a63915983a3
78459a1a406da412aae11fe35445a9ddf49e899f
refs/heads/master
<repo_name>Echo-EG/Baig_darbas<file_sep>/jquery_plugin/js/script.js // sticky navbar window.onscroll = function() {myFunction()}; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else { navbar.classList.remove("sticky"); } } // expanding burger const toggleButton = document.getElementsByClassName('toggle-button')[0] const navbarLinks = document.getElementsByClassName('main-nav')[0] toggleButton.addEventListener('click', () => { navbarLinks.classList.toggle('active') }) // smooth scroll header const links = document.querySelectorAll(".main-header ul a, .section1 a"); for (const link of links) { link.addEventListener("click", clickHandler); } function clickHandler(e) { e.preventDefault(); const href = this.getAttribute("href"); const offsetTop = document.querySelector(href).offsetTop; scroll({ top: offsetTop, behavior: "smooth" }); } // NICE scroll // ======================= $("body").niceScroll({ cursorcolor:"gray", cursorwidth:"6px" }); <file_sep>/src/db.php <?php define("DB_SERVER", "localhost"); define("DB_USER", "root"); define("DB_PASWORD", ""); define("DB_NAME", "baig_darbas"); $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASWORD, DB_NAME); if($mysqli->connect_error){ echo "Atsiprasome, bet svetaine susidure su problema. \n"; echo 'Klaida: ' . $mysqli->connect_error . '\n'; exit(); } mysqli_query($mysqli, "INSERT INTO contact_form (vardas, email, message) VALUES('$_POST[vardas]', '$_POST[email]', '$_POST[message]')");<file_sep>/index.php <?php require __DIR__ . '/src/app.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="jquery_plugin/css/jquery.fancybox.min.css" rel="stylesheet"> <script src="https://kit.fontawesome.com/7336d25165.js" crossorigin="anonymous"></script> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Lato:wght@100;300;700&family=Open+Sans&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/newStyle.css"> <link rel="stylesheet" href="css/responsive.css"> <title>IDEA studija</title> </head> <body> <!-- ========================================= --> <div> <section id="section1" class="section1"> <div class="container"> <div class="logo"><img src="images/ideja-studija2.png" alt="Idea studija" class="scale-img"> </div> <h1>Interjero dizaino paslaugos</h1> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit.</p> <a href="#section2">Read more</a> <img class="arow" src="images/arrow-down.png" alt="arow down" > </div> </section> </div> <!-- ============================================== --> <div id="navbar" class="main-header"> <div class="header-container flex-container container"> <div class="onepage">I.D.E.A STUDIJA</div> <a href="#/" class="toggle-button"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </a> <nav class="main-nav"> <ul class="flex-container"> <li><a href="#section1">HOME</a></li> <li><a href="#section2">ABOUT US</a></li> <li><a href="#section3">PORTFOLIO</a></li> <li><a href="#section4">CONTACT</a></li> </ul> </nav> </div> </div> <!-- ========================================== --> <section id="section2" class="section2"> <div class="container"> <div class="section-heading"> <h2>About Us</h2> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, nostrum.</p> </div> <div class="section2-content flex-container"> <div class="service"> <div class="circleOne"></div> <h2>Responsive</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </div> <div class="service"> <div class="circleTwo"></div> <h2>Minimalist</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </div> <div class="service"> <div class="circleThree"></div> <h2>Freebies</h2> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </div> </div> </div> </section> <!-- ===================================================== --> <section id="section3" class="section3 "> <div class="container"> <div class="section-heading"> <h2>Portfolio</h2> </div> <!-- FANCYBOX --> <div class="grid"> <a data-fancybox="gallery" href="images/big-img/8 4.3.jpg"><img src="images/11.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/1.10.jpg"><img src="images/2.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/1.1.jpg"><img src="images/3.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/2.1.jpg"><img src="images/9.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/5.jpg"><img src="images/5.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/50.jpg"><img src="images/6.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/7.jpg"><img src="images/7.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/8.jpg"><img src="images/8.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/4.jpg"><img src="images/4.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/big-img/50.jpg"><img src="images/1.jpg" alt="gallery image 1"></a> <a data-fancybox="gallery" href="images/10.jpg"><img src="images/10.jpg" alt="gallery image 1"></a> </div> </div> <!-- ============================================ --> </section> <section class="partners "> <div class="container"> <div class="partnersList"> <h2>Thanks to our partners</h2> <ul class="partner-list flex-container"> <li class="grinducentras"><a href="https://grinducentras.lt/?gclid=Cj0KCQjwgtWDBhDZARIsADEKwgP7UzJkVOR5o3a-DxGO8-i4VH-FM4S-br9Aag9EykD1o5CogQ8CQRYaAjojEALw_wcB" target="blank"><img src="images/partners/image-1-1.png" alt="Grindu centras"></a></li> <li class="trukme"><a href="https://www.trukme.lt/en/" target="_blank"><img src="images/partners/logo-top.png" alt="Trukme"></a></li> <li class="lisota"><a href="https://www.prattandlambert.com/" target="_blank"><img src="images/partners/plskaidrus.png" alt="Pratt & Lambert Paints"></a></li> </ul> </div> </div> </section> <!--=============================================================== --> <section id="section4" class="contacts"> <div class="container"> <div class="section-heading contacts-heading"> <h2>Contact</h2> </div> <div class="section-content"> <form class="contact-form css-grid" action="index.php" method="post"> <div class="contact-text" action="index.php" method="post"> <p class="contact-text1">To contact us please use the contact form visible <br> When sending files, please use the following e-mail <br> <strong><NAME></strong> <br> e-mail: <strong><EMAIL></strong> </p> </div> <div class="input1"> YOUR NAME <br> <input class="name" type="text" name="vardas" required> </div> <div class="input2"> YOUR E-MAIL <br> <input class="email" type="email" name="email" required> </div> <div class="textarea1"> MESSAGE <br> <textarea class="textarea" name="message" rows="6" required></textarea> </div> <div class="btn-form"> <button class="btn" type="submit" name="submit" >SEND</button> </div> </form> </div> </div> </section> <!-- ================================================================ --> <div class="main-footer"> <div class="container"> <div class="footer-logo"> <img src="images/ideja-studija2.png" alt="idea studija"> </div> <div class="social-media"> <ul class="flex-container"> <li><a href="https://www.facebook.com/ideastudija.lt" target="blank"><i class="fab fa-facebook-f fa-lg"></i></a></li> <li><a href="https://www.instagram.com/idea.studija/" target="_blank"><i class="fab fa-instagram fa-lg"></i></a></li> <li><a href="#"><i class="fab fa-pinterest fa-lg"></i></a></li> <li><a href="#"><i class="fab fa-twitter fa-lg"></i></a></li> </ul> </div> <div class="copyright"> &copy; <?php echo date("Y"); ?>. All rights reserved. </div> </div> </div> <script src="jquery_plugin/js/jquery-3.6.0.min.js" type="text/javascript"></script> <script src="jquery_plugin/js/jquery.fancybox.min.js"></script> <!-- <script src="jquery_plugin/js/jquery.nicescroll.min.js"></script> --> <script src="jquery_plugin/js/script.js"></script> </body> </html><file_sep>/src/app.php <?php if (isset($_POST['submit'])){ $vardas =trim ($_POST['vardas']) ; $email = trim($_POST['email']); $message = trim($_POST['message']); include'db.php'; }
ffe4c5a209a7005a09f902dedc285fdc94c0891c
[ "JavaScript", "PHP" ]
4
JavaScript
Echo-EG/Baig_darbas
e857e65101985f8b6d9d86bf1d8d1fe3491232a6
f4fd870ae376ac7d34937ef9917113165edc7316
refs/heads/master
<repo_name>novsunheng/codewars<file_sep>/(7 kyu) Form The Largest/(7 kyu) Form The Largest.js // #1 // function maxNumber(n) { // const str = String(n); // const arr = str.split(''); // arr.sort((a, b) => b - a); // const res = arr.join(''); // return parseInt(res); // } // #2 // function maxNumber(n) { // return parseInt( // String(n) // .split('') // .sort((a, b) => b - a) // .join(''), // ); // } // #3 // const maxNumber = (n) => // parseInt( // String(n) // .split('') // .sort((a, b) => b - a) // .join(''), // ); // #4 // const maxNumber = (n) => Number(String(n).split``.sort().reverse().join``); // #5 const maxNumber = (n) => +String(n).split``.sort().reverse().join``; <file_sep>/(5 kyu) Calculating with Functions/(5 kyu) Calculating with Functions.md # Calculating with Functions (5 kyu) https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39/ This time we want to write calculations using functions and get the results. Let's have a look at some examples: ``` seven(times(five())); // must return 35 four(plus(nine())); // must return 13 eight(minus(three())); // must return 5 six(dividedBy(two())); // must return 3 ``` Requirements: - There must be a function for each number from 0 ("zero") to 9 ("nine") - There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy - Each calculation consist of exactly one operation and two number - The most outer function represents the left operand, the most inner function represents the right operand <file_sep>/(7 kyu) Number of People in the Bus/(7 kyu) Number of People in the Bus.py # #1 # from functools import reduce # def number(stops): # nums = [a[0] - a[1] for a in stops] # return reduce(lambda a, b: a + b, nums) #2 def number(bus_stops): return sum([a[0] - a[1] for a in bus_stops]) <file_sep>/(6 kyu) Playing with digits/(6 kyu) Playing with digits.ts export class G964 { public static digPow = (n: number, p: number): number => { let t: number = 0; let k: number = 0; n.toString() .split('') .forEach( (el: string, i: number): void => { t += Math.pow(parseInt(el), p + i); }, ); while (k <= 0xffff) { if (n * k++ == t) { return k - 1; } } return -1; }; } <file_sep>/(6 kyu) Follow that Spy/(6 kyu) Follow that Spy.md # Follow that Spy (6 kyu) https://www.codewars.com/kata/follow-that-spy/ We are tracking down our rogue agent <NAME> A.K.A. <NAME> and he travels from places to places to avoid being tracked. Each of his travels are based on a list of itineraries in an unusual or incorrect order. The task is to determine the routes he will take in his every journey. You are given an array of routes of his itineraries. List down only the places where he will go. ### Example: ``` routes = [[USA, BRA], [JPN, PHL], [BRA, UAE], [UAE, JPN]] result: "USA, BRA, UAE, JPN, PHL" ``` NOTE: It is safe to assume that there will be no repeating place with different route and there are no empty routes and could have at least one (1) route (from one waypoint to another). <file_sep>/(7 kyu) Thinkful - String Drills. Repeater/(7 kyu) Thinkful - String Drills. Repeater.cpp #include <iostream> #include <string> using namespace std; std::string repeater(std::string str, int n) { std::string res; for (int i = 0; i < n; i++) res += str; return res; }<file_sep>/(7 kyu) Last/(7 kyu) Last.py # #1 # def last(*args): # last = args[-1] # try: # return last[-1] # except TypeError: # return last #2 def last(*args): try: return args[-1][-1] except: return args[-1] <file_sep>/(7 kyu) Shortest Word/(7 kyu) Shortest Word.cpp #include <iostream> #include <string> #include <vector> #include <sstream> using namespace std; int find_short(std::string str) { std::vector<std::string> array; std::stringstream ss(str); std::string x; while (ss >> x) { array.push_back(x); } int length = array.size(); int min = 1000; for (int i = 0; i < length; i++) { if (array[i].length() < min) { min = array[i].length(); } } return min; }<file_sep>/(6 kyu) Help the bookseller/(6 kyu) Help the bookseller.ts export class G964 { public static stockList = (listOfArt: string[], listOfCat: string[]) => { if (!listOfArt.length || !listOfCat.length) { return ''; } const books = {}; const result = []; listOfArt.forEach((book: string) => { const [title, num] = book.split(' '); books[title[0]] = (books[title[0]] | 0) + +num; }); return listOfCat .map((letter: string) => `(${letter} : ${books[letter] | 0})`) .join(' - '); }; } <file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.cpp #include <iostream> #include <string> using namespace std; std::string generate_shape(int n) { std::string res; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) res += "+"; if (i < n - 1) res += "\n"; } return res; }<file_sep>/(8 kyu) Opposite number/(8 kyu) Opposite number.cpp int opposite(int number) { return -number; }<file_sep>/(8 kyu) Sort and Star/(8 kyu) Sort and Star.cpp #include <string> #include <vector> #include <algorithm> std::string twoSort(std::vector<std::string> s) { std::sort(s.begin(), s.end()); std::string ret; std::string word = s[0]; for (int32_t i = 0; i < word.length() - 1; ++i) { ret = ret + word[i] + "***"; } return ret + word.back(); }<file_sep>/(7 kyu) Get the Middle Character/(7 kyu) Get the Middle Character.cpp #include <iostream> #include <string> using namespace std; std::string get_middle(std::string input) { int middle = input.length() / 2; string res = ""; if (input.length() % 2 == 0) res += input[middle - 1]; res += input[middle]; return res; }<file_sep>/(8 kyu) Sort and Star/(8 kyu) Sort and Star.ts export function twoSort(s: string[]): string { return s .sort()[0] .split('') .join('***'); } <file_sep>/(7 kyu) Exes and Ohs/7 kyu Exes and Ohs.py # #1 # def xo(s): # equal = 0 # for c in s: # if c.lower() == 'x': equal += 1 # if c.lower() == 'o': equal -= 1 # return equal == 0 #2 def xo(s): return s.lower().count('x') == s.lower().count('o') <file_sep>/(7 kyu) Frequency sequence/(7 kyu) Frequency sequence.py # #1 # def freq_seq(s, sep): # freq = {} # newStr = [] # for i in s: # if freq.get(i) == None: # freq[i] = 1 # else: # freq[i] += 1 # for i in s: # newStr.append(str(freq[i])) # return sep.join(newStr) # #2 # def freq_seq(s, sep): # s = list(s) # counts = {char:str(s.count(char)) for char in set(s)} # for i,char in enumerate(s): # s[i] = counts[char] # return sep.join(s) #3 def freq_seq(s, sep): return sep.join([str(s.count(i)) for i in s])<file_sep>/(6 kyu) CamelCase Method/(6 kyu) CamelCase Method.js // #1 // String.prototype.camelCase = function() { // return this // .split(' ') // .map((s) => { // return s // .charAt(0) // .toUpperCase() + s.slice(1); // }) // .join(''); // } // #2 // String.prototype.camelCase = function() { // return this.split` `.map((s) => s.charAt(0).toUpperCase() + s.slice(1)) // .join``; // }; // #3 String.prototype.camelCase = function() { return this.trim().replace(/(^|\s)\w/g, (match) => match.trim().toUpperCase(), ); }; <file_sep>/(6 kyu) Hard Time Bomb/(6 kyu) Hard Time Bomb.md # Hard Time Bomb (6 kyu) https://www.codewars.com/kata/hard-time-bomb A bomb has been set to go off! You have to find the wire and cut it in order to stop the timer. There is a global `var` that holds the numeric ID to which wire to cut. Find that and then you can `Bomb.CutTheWire(wireKey);` <file_sep>/(4 kyu) IP Validation/(4 kyu) IP Validation.js const isValidIP = (str) => { const ip = str.split`.`; if ( ip.length !== 4 || ip.filter( (x) => x > 255 || (!+x && x !== '0') || x.trim().length !== x.length || (x[0] === '0' && x !== '0'), ).length ) return false; return true; }; <file_sep>/(4 kyu) Strip Comments/(4 kyu) Strip Comments.js const solution = (input, markers) => input .split('\n') .map((s) => markers.reduce((t, m) => t.split(m)[0].trim(), s)) .join('\n'); <file_sep>/(6 kyu) Salesman's Travel/(6 kyu) Salesman's Travel.ts export class G964 { public static travel = (r: string, zipcode: string): string => { const list = r.split(',').map((x: string) => { const addr = x.match(/(^\d+) ([a-zA-z.\s]+) ([A-Z]{2} \d+)$/); return { house: addr[1], street: addr[2], zip: addr[3], }; }); let streets: string[] = []; let houses: string[] = []; list.forEach((record) => { if (record.zip === zipcode) { streets.push(record.street); houses.push(record.house); } }); return `${zipcode}:${streets.join(',')}/${houses.join(',')}`; }; } <file_sep>/(7 kyu) Even numbers in an array/(7 kyu) Even numbers in an array.py def even_numbers(arr, n): return list(filter(lambda x: x % 2 == 0, arr))[-n::] <file_sep>/(8 kyu) Square(n) Sum/(8 kyu) Square(n) Sum.cpp #include <vector> int square_sum(const std::vector<int> &numbers) { int res = 0; for (auto &i : numbers) { res += i * i; } return res; }<file_sep>/(6 kyu) Salesman's Travel/(6 kyu) Salesman's Travel.py import re def travel(r, zipcode): # #1 addresses = r.split(",") records = [] for x in addresses: addr = re.search(r"(^\d+) ([a-zA-z.\s]+) ([A-Z]{2} \d+)$", x) records.append({ "house": addr.group(1), "street": addr.group(2), "zip": addr.group(3) }) streets = [] houses = [] for r in records: if (r["zip"] == zipcode): streets.append(r["street"]) houses.append(r["house"]) return "{}:{}/{}".format( zipcode, ",".join(streets), ",".join(houses) ) def travel(r, zipcode): # #2 streets = [] houses = [] addresses = r.split(",") for x in addresses: if " ".join(x.split()[-2:]) == zipcode: streets.append(" ".join(x.split()[1:-2])) houses += x.split()[:1] return "{}:{}/{}".format(zipcode, ",".join(streets), ",".join(houses)) <file_sep>/(7 kyu) Recursion 2 - Fibonacci/(7 kyu) Recursion 2 - Fibonacci.py def fibonacci(n): return 1 if n < 3 else fibonacci(n - 1) + fibonacci(n - 2) <file_sep>/(7 kyu) Shortest Word/(7 kyu) Shortest Word.py # #1 # def find_short(s): # lengths = [] # for word in s.split(" "): # lengths.append(len(word)) # return min(lengths) # #2 def find_short(s): return min(len(x) for x in s.split())<file_sep>/(6 kyu) Square Digits Sequence/(6 kyu) Square Digits Sequence.ts export function squareDigitsSequence(a: number): number { const nums: number[] = []; while (-1 === nums.indexOf(a)) { nums.push(a); a = String(a) .split('') .reduce((s: number, n: string) => s + Math.pow(Number(n), 2), 0); } return nums.length + 1; } <file_sep>/(7 kyu) Get the Middle Character/(7 kyu) Get the Middle Character.py def get_middle(s): return s[(len(s) - 1) / 2:len(s) / 2 + 1]<file_sep>/(7 kyu) Form The Largest/(7 kyu) Form The Largest.rs // #1 // fn max_number(n: u32) -> u32 { // let str = n.to_string(); // let mut temp = str.chars().collect::<Vec<char>>(); // temp.sort(); // let res = temp.into_iter().rev().collect::<String>(); // res.parse::<u32>().unwrap() // } // #2 fn max_number(n: u32) -> u32 { let str = n.to_string().chars().collect::<Vec<char>>(); str.sort(); str.iter().rev().collect::<String>().parse::<u32>().unwrap() } <file_sep>/(7 kyu) Number of People in the Bus/(7 kyu) Number of People in the Bus.ts export function number(busStops: number[][]): number { return busStops.reduce((a, c) => (a += c[0] - c[1]), 0); } <file_sep>/(7 kyu) Exes and Ohs/7 kyu Exes and Ohs.cpp #include <iostream> #include <string> #include <algorithm> using namespace std; bool XO(const std::string &str) { string res = ""; for (int i = 0; i < str.length(); i++) res += tolower(str[i]); int x = std::count(res.begin(), res.end(), 'x'); int o = std::count(res.begin(), res.end(), 'o'); return x == o; }<file_sep>/(8 kyu) Even or Odd/(8 kyu) Even or Odd.cpp #include <string> std::string even_or_odd(int number) { return (number % 2) ? "Odd" : "Even"; }<file_sep>/(7 kyu) Exes and Ohs/7 kyu Exes and Ohs.ts export class Kata { static xo(str: string) { let equal = 0; str.split('').forEach((c) => { if ('x' === c.toLowerCase()) { equal += 1; } if ('o' === c.toLowerCase()) { equal -= 1; } }); return equal === 0; } } <file_sep>/(7 kyu) Simple beads count/(7 kyu) Simple beads count.rs // #1 // fn count_red_beads(n: u32) -> u32 { // match n { // 0...1 => 0, // _ => (n - 1) * 2, // } // } // #2 fn count_red_beads(n: u32) -> u32 { 2 * n.checked_sub(1).unwrap_or(0) } <file_sep>/(6 kyu) Reverse or rotate/(6 kyu) Reverse or rotate.ts export class G964 { public static revrot(str: string, sz: number) { if (sz <= 0 || str == '' || sz > str.length) { return ''; } const arr = []; const s = str.split(''); while (s.length >= sz) { arr.push(s.splice(0, sz)); } const res = arr.map((x) => { const sum = x.reduce((a: number, c: number) => a + Math.pow(c, 3), 0); if (sum % 2) { x.push(x[0]); x.shift(); return x.join(''); } else { return x.reverse().join(''); } }); return res.join(''); } } <file_sep>/(6 kyu) Count the smiley faces/(6 kyu) Count the smiley faces.md # Count the smiley faces! (6 kyu) http://www.codewars.com/kata/count-the-smiley-faces Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Rules for a smiling face: - Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ; - A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~ - Every smiling face must have a smiling mouth that should be marked with either ) or D. No additional characters are allowed except for those mentioned. Valid smiley face examples: ``` :) :D ;-D :~) ``` Invalid smiley faces: ``` ;( :> :} :] ``` <file_sep>/(7 kyu) Mumbling/(7 kyu) Mumbling.py def accum(s): # #1 #return "-".join([c.upper() + c.lower() * i for i, c in enumerate(s)]) #2 return '-'.join((c * i).title() for i, c in enumerate(s, 1))<file_sep>/(8 kyu) Square(n) Sum/(8 kyu) Square(n) Sum.ts export function squareSum(numbers: number[]): number { return numbers.reduce((a, x) => a + x * x, 0); } <file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.js // #1 // const century = (year) => Math.floor(year / 100) + (year % 100 ? 1 : 0); // #2 // const century = (year) => Math.ceil(year / 100); // #3 // Bitwise OR a | b // Returns a 1 in each bit position for which // the corresponding bits of either or both operands are 1s. const century = (year) => ((year + 99) / 100) | 0; <file_sep>/(5 kyu) Memoized Fibonacci/(5 kyu) Memoized Fibonacci.md # Memoized Fibonacci (5 kyu) https://www.codewars.com/kata/memoized-fibonacci ## Problem Context The Fibonacci sequence is traditionally used to explain tree recursion. ``` function fibonacci(n) { if(n==0 || n == 1) return n; return fibonacci(n-1) + fibonacci(n-2); } ``` This algorithm serves welll its educative purpose but it's tremendously inefficient, not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. fibonacci(n-2)) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. fibonacci(n-1)). This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in CodeWars you will most likely get a code timeout before any answers. For this particular Kata we want to implement the memoization solution. This will be cool because it will let us keep using the tree recursion algorithm while still keeping it sufficiently optimized to get an answer very rapidly. The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number. Refactor the function into a recursive Fibonacci function that using a memoized data structure avoids the deficiencies of tree recursion Can you make it so the memoization cache is private to this function? <file_sep>/(6 kyu) CamelCase Method/(6 kyu) CamelCase Method.py def camel_case(string): # #1 # return "".join(c.capitalize() for c in string.split()) # #2 return string.title().replace(" ", "") <file_sep>/(8 kyu) Remove String Spaces/(8 kyu) Remove String Spaces.cpp #include <string> // #1 // #include <algorithm> // std::string no_space(std::string x) // { // x.erase(std::remove(x.begin(), x.end(), ' '), x.end()); // return x; // } // #2 #include <regex> std::string no_space(std::string s) { return std::regex_replace(s, std::regex(" "), ""); }<file_sep>/(8 kyu) Find the smallest integer in the array/(8 kyu) Find the smallest integer in the array.cpp #include <vector> #include <algorithm> using namespace std; // #1 // int findSmallest(vector<int> list) // { // sort(list.begin(), list.end()); // return list[0]; // } // #2 int findSmallest(vector<int> list) { return *std::min_element(list.begin(), list.end()); }<file_sep>/(8 kyu) Return Negative/(8 kyu) Return Negative.ts export const makeNegative = (num: number): number => { return -Math.abs(num); }; <file_sep>/(8 kyu) Reversed sequence/(8 kyu) Reversed sequence.cpp #include <vector> std::vector<int> reverseSeq(int n) { std::vector<int> res; for (int32_t i = n; i > 0; --i) { res.push_back(i); } return res; }<file_sep>/(8 kyu) Abbreviate a Two Word Name/(8 kyu) Abbreviate a Two Word Name.cpp #include <iostream> #include <cctype> std::string abbrevName(std::string name) { // #1 // size_t pos = name.find(" "); // char first_initial = std::toupper(name[0]); // char second_initial = std::toupper(name[pos + 1]); // std::string abbr; // abbr += first_initial; // abbr += "."; // abbr += second_initial; // return abbr; // #2 // std::string abbr; // abbr.push_back(toupper(name[0])); // abbr.push_back('.'); // abbr.push_back(toupper(name[name.find(' ') + 1])); // return abbr; // #3 // std::string abbr = ""; // abbr += toupper(name[0]); // abbr += '.'; // abbr += toupper(name[name.find(' ') + 1]); // return abbr; // #4 // std::string first_initial{toupper(name[0])}; // std::string second_initial{toupper(name[name.find_last_of(' ') + 1])}; // return first_initial + "." + second_initial; // #5 return {toupper(name[0]), '.', toupper(name[name.find_last_of(' ') + 1])}; }<file_sep>/(5 kyu) Count IP Addresses/(5 kyu) Count IP Addresses.md # Count IP Addresses (5 kyu) https://www.codewars.com/kata/526989a41034285187000de4 Write a function that accepts a starting and ending IPv4 address, and returns the number of IP addresses from start to end, excluding the end IP address. All input to the ipsBetween function will be valid IPv4 addresses in the form of strings. The ending address will be at least one address higher than the starting address. ### Examples: ``` ipsBetween("10.0.0.0", "10.0.0.50") => returns 50 ipsBetween("10.0.0.0", "10.0.1.0") => returns 256 ipsBetween("192.168.3.11", "192.168.127.12") => returns 246 ``` <file_sep>/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine.md # Ninety Nine Thousand Nine Hundred Ninety Nine (5 kyu) https://www.codewars.com/kata/ninety-nine-thousand-nine-hundred-ninety-nine Write a method that takes a number and returns a string of that number in English. For example: ``` numberToEnglish(27) // => 'twenty seven' ``` Your method should be able to handle any number between 0 and 99999. If given numbers outside of that range or non-Integer numbers, the method should return an empty string. <file_sep>/(5 kyu) Memoized Fibonacci/(5 kyu) Memoized Fibonacci.js const cache = [0, 1]; const fibonacci = (n) => cache[n] !== undefined ? cache[n] : (cache[n] = fibonacci(n - 1) + fibonacci(n - 2)); <file_sep>/(7 kyu) String ends with/(7 kyu) String ends with.rs fn solution(word: &str, ending: &str) -> bool { word.ends_with(ending) } <file_sep>/(7 kyu) Frequency sequence/(7 kyu) Frequency sequence.rs fn freq_seq(s: &str, sep: &str) -> String { s.chars() .map(|c| s.matches(c).count().to_string()) .collect::<Vec<String>>() .join(sep) } <file_sep>/(7 kyu) Jaden Casing Strings/(7 kyu) Jaden Casing Strings.cpp #include <string> #include <sstream> #include <cctype> using namespace std; string jadenCase(string input) { stringstream result; while (input.find(" ") != string::npos) { string word = input.substr(0, input.find(" ")); result << (char)toupper(word.at(0)); result << word.substr(1) << " "; input = input.substr(input.find(" ") + 1); } // The rest of the string if (!input.empty()) { result << (char)toupper(input.at(0)); result << input.substr(1); } return result.str(); }<file_sep>/(5 kyu) Count IP Addresses/(5 kyu) Count IP Addresses.js const ipsBetween = (start, end) => { const calc = (n, m = 1) => (end.split`.`[n] - start.split`.`[n]) * m; return calc(0, 256 * 256 * 256) + calc(1, 256 * 256) + calc(2, 256) + calc(3); }; <file_sep>/(4 kyu) Snail/(4 kyu) Snail.md # Snail Sort (4 kyu) https://www.codewars.com/kata/snail/javascript Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. ``` array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] ``` For better understanding, please follow the numbers of the next array consecutively: ``` array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9] ``` <file_sep>/(7 kyu) Reverse words/(7 kyu) Reverse words.js // #1 // function reverseWords(str) { // const spaces = str.match(/\s+/g); // const space = spaces ? spaces[0] : ''; // const words = str.split(/\s+/g); // return words.map((x) => x.split``.reverse().join``).join(space); // } // #2 // function reverseWords(str) { // return str.split` `.map((w) => w.split``.reverse().join``).join` `; // } // #3 const reverseWords = (str) => str.split` `.map((w) => w.split``.reverse().join``).join` `; <file_sep>/(7 kyu) Reverse words/(7 kyu) Reverse words.cpp #include <iostream> #include <string> using namespace std; std::string reverse_words(std::string str) { std::string res; std::string word; int length = str.length(); for (int i = 0; i < length; i++) { if (str[i] != ' ') { word = str[i] + word; } else { if (word.length() > 0) { res += word; word = ""; } res += " "; } } return res + word; }<file_sep>/(7 kyu) Simple beads count/(7 kyu) Simple beads count.md # Simple beads count (7 kyu) https://www.codewars.com/kata/simple-beads-count Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads. **@** @@ **@** @@ **@** @@ **@** @@ **@** @@ **@** Implement `count_red_beads(n)` (in PHP `count_red_beads($n)`; in Java, Javascript, C, C++ `countRedBeads(n)`) so that it returns the number of _red_ beads. If there are less than 2 blue beads return 0. <file_sep>/(7 kyu) Recursion 2 - Fibonacci/(7 kyu) Recursion 2 - Fibonacci.md # Recursion #2 - Fibonacci (7 kyu) https://www.codewars.com/kata/recursion-number-2-fibonacci/ ## 2 - Fibonacci number In mathematical terms, the sequence `f(n)` of [fibonacci](https://en.wikipedia.org/wiki/Fibonacci_number) numbers is defined by the recurrence relation ```js f(n) = f(n-1) + f(n-2) ``` with seed values ```js f(1) = 1 and f(2) = 1 ``` ## Your task You have to create the function fibonacci that receives n and returns `f(n)`. You have to use recursion. <file_sep>/(7 kyu) Jaden Casing Strings/(7 kyu) Jaden Casing Strings.ts String.prototype.toJadenCase = function() { return this.split(' ') .map(function(s: string): string { return s.charAt(0).toUpperCase() + s.slice(1); }) .join(' '); }; <file_sep>/(7 kyu) Simple beads count/(7 kyu) Simple beads count.cpp unsigned int countRedBeads(unsigned int n) { return n < 2 ? 0 : (n - 1) * 2; }<file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.js // #1 // function generateShape(int) { // let string = ''; // for (let i = 0; i < int * int; i++) { // if (i % int === 0 && i !== 0) { // string += '\n'; // } // string += '+'; // } // return string; // } // #2 // function generateShape(int) { // let str = ''; // let arr = []; // for (let i = 0; i < int; i++) { // str += '+'; // } // for (let i = 0; i < int; i++) { // arr.push(str); // } // return arr.join('\n'); // } // #3 // function generateShape(int) { // let arr = []; // for (let i = 0; i < int; i++) { // arr.push('+'.repeat(int)); // } // return arr.join('\n'); // } // #4 // function generateShape(int) { // return [...Array(int)].map((x) => '+'.repeat(int)).join('\n'); // } // #5 const generateShape = (int) => [...Array(int)].map((x) => '+'.repeat(int)).join`\n`; <file_sep>/(7 kyu) String ends with/(7 kyu) String ends with.js // #1 // function solution(str, ending) { // const result = str.substr(str.length - ending.length, str.length); // return ending === result; // } // #2 // function solution(str, ending) { // return ending === str.substr(-ending.length); // } // #3 const solution = (str, ending) => str.endsWith(ending); <file_sep>/(4 kyu) Reverse it, quickly/(4 kyu) Reverse it, quickly.js weirdReverse = (a) => a.sort((_) => 1); <file_sep>/(8 kyu) Counting sheep/(8 kyu) Counting sheep.ts export function countSheeps(arrayOfSheep: boolean[]): number { return arrayOfSheep.filter((x) => x === true).length; } <file_sep>/(7 kyu) Complementary DNA/(7 kyu) Complementary DNA.js // #1 // function DNAStrand(dna) { // const dictionary = { A: 'T', T: 'A', C: 'G', G: 'C' }; // return dna // .split('') // .map((c) => dictionary[c]) // .join(''); // } // #2 // const DNAStrand = (dna) => { // return dna // .replace(/A/g, 't') // .replace(/T/g, 'a') // .replace(/C/g, 'g') // .replace(/G/g, 'c') // .toUpperCase(); // }; // #3 const DNAStrand = (dna) => dna.replace(/./g, (c) => ({ A: 'T', T: 'A', G: 'C', C: 'G' }[c])); <file_sep>/(7 kyu) Last/(7 kyu) Last.rs // #1 // fn last<T: Clone>(slice: &[T]) -> T { // let n = slice.len() - 1; // return slice[n].to_owned(); // } // #2 // fn last<T: Clone>(slice: &[T]) -> T { // slice.last().unwrap().to_owned() // } // #3 fn last<T: Clone>(slice: &[T]) -> T { let l = slice.last(); match l { None => panic!("empty"), Some(x) => x.clone(), } } <file_sep>/(8 kyu) Count of positives - sum of negatives/(8 kyu) Count of positives - sum of negatives.ts export function countPositivesSumNegatives(input: any) { return input && input.length ? [ input.filter((p: number) => p > 0).length, input .filter((n: number) => n < 0) .reduce((a: number, b: number) => a + b, 0), ] : []; } <file_sep>/(6 kyu) Decode the Morse code/(6 kyu) Decode the Morse code.md # Decode the Morse code (6 kyu) https://www.codewars.com/kata/decode-the-morse-code/ In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world. The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·. NOTE: Extra spaces before or after the code have no meaning and should be ignored. Your task is to implement a function decodeMorse(morseCode), that would take the morse code as input and return a decoded human-readable string. ### Example: ``` decodeMorse('.... . -.-- .--- ..- -.. .') //should return "HEY JUDE" ``` The Morse code table is preloaded for you as a dictionary MORSE_CODE['.--'] <file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.rs // #1 // fn century(year: u32) -> u32 { // year / 100 + if year % 100 == 0 { 0 } else { 1 } // } // #2 fn century(year: u32) -> u32 { (year - 1) / 100 + 1 } <file_sep>/(6 kyu) Easy Balance Checking/(6 kyu) Easy Balance Checking.js // #1 Original solution function balance(book) { const lines = book.split`\n`; // take each lines from a book const budget = parseInt(lines.shift()); // store an Original Balance // we need to clear all record from special characters, so // a helper function: remove special characters // (only alphanums and a '.' are allowed) const filterChars = (r) => r.split``.filter((a) => /[\w,\.]/.test(a)).join``; // take each line from a book const expences = lines // split each line by a whitespace .map((record) => record.split` `) // store only not empty lines .filter((r) => r[2]) // for that lines take 3 records .map( (r) => [ r[0], // take a record's number, it's a string filterChars(r[1]), // remove special chars from a title parseFloat(filterChars(r[2])), ], // remove special chars from a price // and take a float number value ); let balance = budget; // use for a dynamic budget let totalExpense = 0; const calcLines = expences.map((r) => { balance -= r[2]; // calculate current balance totalExpense += r[2]; // calculate a Total expense // for a result formatted line return `${r[0]} ${r[1]} ${r[2].toFixed(2)} Balance ${balance.toFixed(2)}`; }); // return all records as a text // Original balance return ( `Original Balance: ${budget.toFixed(2)}\r\n` + // join all formatted into a one string calcLines.join('\r\n') + '\r\n' + // add a Total expense `Total expense ${totalExpense.toFixed(2)}\r\n` + // and calculate an Average expense `Average expense ${(totalExpense / calcLines.length).toFixed(2)}` ); } // #2 Optimized solution function balance(book) { let [budget, ...lines] = book .trim() .replace(/[^a-z0-9\s.]+/gi, '') .replace(/\s{2,}/g, (m) => m[0]) .split(/\n/); let totalExpense = 0; const calcLines = lines.map((r) => r.replace(/\S+$/g, (r) => { totalExpense += parseFloat(r); return `${parseFloat(r).toFixed(2)} Balance ${( budget - totalExpense ).toFixed(2)}`; }), ); return ( `Original Balance: ${parseFloat(budget).toFixed(2)}\r\n` + calcLines.join('\r\n') + '\r\n' + `Total expense ${totalExpense.toFixed(2)}\r\n` + `Average expense ${(totalExpense / calcLines.length).toFixed(2)}` ); } <file_sep>/(7 kyu) Highest and Lowest/(7 kyu) Highest and Lowest.cpp #include <iostream> #include <algorithm> #include <string> #include <vector> #include <sstream> using namespace std; std::string highAndLow(const std::string &numbers) { std::vector<int> v; std::stringstream ss(numbers); std::string x; while (ss >> x) v.push_back(std::stoi(x)); auto result = std::minmax_element(v.begin(), v.end()); int low = result.first - v.begin(); int high = result.second - v.begin(); return std::to_string(v[high]) + " " + std::to_string(v[low]); }<file_sep>/(8 kyu) The Feast of Many Beasts/(8 kyu) The Feast of Many Beasts.ts export function feast(beast: string, dish: string): boolean { return beast[0] === dish[0] && beast.slice(-1) === dish.slice(-1); } <file_sep>/(7 kyu) Reverse words/(7 kyu) Reverse words.ts export function reverseWords(str: string): string { return str .split(' ') .map( (w: string): string => w .split('') .reverse() .join(''), ) .join(' '); } <file_sep>/(7 kyu) Highest and Lowest/(7 kyu) Highest and Lowest.ts export class Kata { static highAndLow(numbers: string) { const max = Math.max(...numbers.split(' ').map((i) => +i)); const min = Math.min(...numbers.split(' ').map((i) => +i)); return `${max} ${min}`; } } <file_sep>/(7 kyu) Sort Numbers/(7 kyu) Sort Numbers.rs // #1 fn sort_numbers(arr: &Vec<i32>) -> Vec<i32> { let mut res = arr.clone(); res.sort(); res } <file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.py # #1 # def generateShape(int): # str = [] # for i in range(int): # str.append('+' * int) # return "\n".join(str) # #2 # def generateShape(n): # return "\n".join("+" * n for i in range(n)) def generateShape(int): # 3 return (("+" * int + "\n") * int)[:-1] <file_sep>/(7 kyu) Last/(7 kyu) Last.js // #1 // function last(list) { // if (arguments.length > 1) { // return arguments[arguments.length - 1]; // } else if (list.length > 1) { // return list[list.length - 1]; // } else { // return list; // } // } // #2 function last(list) { return arguments.length > 1 ? arguments[arguments.length - 1] : list[list.length - 1] || arguments[arguments.length - 1]; } // #3 function last(list) { const last = arguments[arguments.length - 1]; return last[last.length - 1] || last; } <file_sep>/(7 kyu) Last/(7 kyu) Last.ts export function last<T>(list: Array<T>): T { const last = arguments[arguments.length - 1]; return last[last.length - 1] || last; } <file_sep>/(8 kyu) The Feast of Many Beasts/(8 kyu) The Feast of Many Beasts.cpp #include <string> bool feast(std::string beast, std::string dish) { return beast.front() == dish.front() && beast.back() == dish.back(); }<file_sep>/(8 kyu) Jenny's secret message/(8 kyu) Jenny's secret message.cpp #include <string> // #1 // std::string greet(std::string name) // { // return (name == "Johnny") // ? "Hello, my love!" // : "Hello, " + name + "!"; // } // #2 std::string greet(std::string name) { return "Hello, " + (name == "Johnny" ? "my love" : name) + "!"; }<file_sep>/(5 kyu) Fibonacci Generator/(5 kyu) Fibonacci Generator.js function* fibonacci(current = 0, next = 1) { while (true) { yield current; [current, next] = [next, current + next]; } } function genfib() { const sequence = fibonacci(); return function fib() { return sequence.next().value; }; } <file_sep>/(7 kyu) Jaden Casing Strings/(7 kyu) Jaden Casing Strings.js // #1 // String.prototype.toJadenCase = function() { // const words = this.split(' '); // for (let i = 0, wordsLen = words.length; i < wordsLen; i++) { // words[i] = words[i][0].toUpperCase() + words[i].slice(1); // } // return words.join(' '); // }; // #2 // String.prototype.toJadenCase = function() { // return this.split(' ') // .map(function(s) { // return s.charAt(0).toUpperCase() + s.slice(1); // }) // .join(' '); // }; // #3 String.prototype.toJadenCase = function() { // cannot be an "arrow function", because it has no context "this" return this.split` `.map((s) => s[0].toUpperCase() + s.slice(1)).join` `; }; <file_sep>/(7 kyu) Two to One/(7 kyu) Two to One.py # #1 # def longest(s1, s2): # res = s1 + s2 # res = list(res) # res = dict.fromkeys(res) # res = sorted(res) # res = ''.join(res) # return res # #2 # def longest(s1, s2): # return ''.join(sorted(dict.fromkeys(s1 + s2))) # #3 def longest(s1, s2): return ''.join(sorted((set(s1 + s2)))) <file_sep>/(8 kyu) String repeat/(8 kyu) String repeat.cpp #include <sstream> std::string repeat_str(int32_t n, std::string s) { std::stringstream ss; for (int32_t i = 0; i < n; ++i) { ss << s; } return ss.str(); }<file_sep>/(7 kyu) Even numbers in an array/(7 kyu) Even numbers in an array.cpp #include <vector> using namespace std; std::vector<int> evenNumbers(vector<int> arr, int n) { vector<int> result; for (auto x : arr) if (x % 2 == 0) result.push_back(x); return vector<int>(result.end() - n, result.end()); }<file_sep>/(7 kyu) String ends with/(7 kyu) String ends with.ts export function solution(str: string, ending: string): boolean { return str.substr(-ending.length) === ending; } <file_sep>/(6 kyu) Hard Time Bomb/(6 kyu) Hard Time Bomb.js // Initial code // var wireCode; // Find the wire. // Bomb.CutTheWire(wireCode); // Initial code really doesn't help at all // As we have in the description: // "There is a global var that holds the numeric ID" // So I need to look something weird in global variables (in "this") for (let x in this) { console.log(x); } // Ho-ho! Now I have a clue: "boom0" or "boom" or "Bomb" // According to the phrase: "that holds the numeric ID" // I supose it is "boom0". Let's try. I compare it against a RegExp: // a word "boom" plus a digit. for (let x in this) { if (x.match(/boom\d+/)) { Bomb.CutTheWire(this[x]); } } // That works! <file_sep>/(6 kyu) Multiples of 3 or 5/(6 kyu) Multiples of 3 or 5.rs // #1 // fn solution(num: i32) -> i32 { // let mut result = 0; // for i in 1..num { // result += if 0 == i % 3 || 0 == i % 5 {i} else {0} // } // result // } // #2 fn solution(num: i32) -> i32 { (1..num).filter(|i| 0 == i % 3 || 0 == i % 5).sum() } <file_sep>/(7 kyu) Form The Largest/(7 kyu) Form The Largest.md # Form The Largest (7kyu) https://www.codewars.com/kata/form-the-largest ## Task Given a number, Return The Maximum number could be formed from the digits of the number given. ## Notes - Only Positve numbers passed to the function, numbers Contain digits [1:9] inclusive - Digit Duplications could occur, So also consider it when forming the Largest ## Input >> Output Examples: ```js 1- maxNumber (213) ==> return (321) ``` ## Explanation: As 321 is The Maximum number could be formed from the digits of the number 213. ```js 2- maxNumber (7389) ==> return (9873) ``` ## Explanation: As 9873 is The Maximum number could be formed from the digits of the number 7389. ```js 3- maxNumber (63729) ==> return (97632) ``` ## Explanation: As 97632 is The Maximum number could be formed from the digits of the number 63729. ```js 4- maxNumber (566797) ==> return (977665) ``` ##Explanation: As 977665 is The Maximum number could be formed from the digits of the number 566797. _Note : Digit duplications are considered when forming the largest._ ```js 5- maxNumber (17693284) ==> return (98764321) ``` ## Explanation: As 98764321 is The Maximum number could be formed from the digits of the number 17693284. Enjoy Learning !! Zizou <file_sep>/(8 kyu) Basic subclasses - Adam and Eve/(8 kyu) Basic subclasses - Adam and Eve.ts export class God { /** * @returns Human[] */ static create(): Human[] { const Adam = new Man(); const Eve = new Woman(); return [Adam, Eve]; } } export class Human {} export class Woman extends Human {} export class Man extends Human {} <file_sep>/(6 kyu) Square Digits Sequence/(6 kyu) Square Digits Sequence.md # Square Digits Sequence (6 kyu) https://www.codewars.com/kata/simple-fun-number-23-square-digits-sequence Consider a sequence of numbers a0, a1, ..., an, in which an element is equal to the sum of squared digits of the previous element. The sequence ends once an element that has already been in the sequence appears again. Given the first element a0, find the length of the sequence. ## Example For a0 = 16, the output should be `9` Here's how elements of the sequence are constructed: ``` a0 = 16 a1 = 1^2 + 6^2 = 37 a2 = 3^2 + 7^2 = 58 a3 = 5^2 + 8^2 = 89 a4 = 8^2 + 9^2 = 145 a5 = 1^2 + 4^2 + 5^2 = 42 a6 = 4^2 + 2^2 = 20 a7 = 2^2 + 0^2 = 4 a8 = 42 = 16, which has already occurred before (a0) ``` Thus, there are 9 elements in the sequence.<br> For a0 = 103, the output should be `4`<br> The sequence goes as follows: 103 -> 10 -> 1 -> 1, 4 elements altogether. ## Input/Output - `[input]` integer a0<br> First element of a sequence, positive integer.<br> Constraints: 1 ≤ a0 ≤ 650. - `[output]` an integer <file_sep>/(7 kyu) Two to One/(7 kyu) Two to One.ts export class G964 { public static longest = (s1, s2) => { let res = s1 + s2; res = res.split(''); res = [...new Set(res)]; res = res.sort(); return res.join(''); }; } <file_sep>/(7 kyu) Sort Numbers/(7 kyu) Sort Numbers.ts export function solution(nums: number[]): number[] { return nums ? nums.sort((a, b) => a - b) : []; } <file_sep>/(8 kyu) Return Negative/(8 kyu) Return Negative.js // #1 // function makeNegative(num) { // if (num < 0) { // return num; // } else { // return (num = num * -1); // } // } // #2 // function makeNegative(num) { // if (num < 0) { // return num; // } else { // return -num; // } // } // #3 // function makeNegative(num) { // return num < 0 ? num : -num; // } // #4 // const makeNegative = (num) => (num < 0 ? num : -num); // #5 const makeNegative = (num) => -Math.abs(num); <file_sep>/(7 kyu) Complementary DNA/(7 kyu) Complementary DNA.ts export class Kata { static dnaStrand(dna: string) { return dna .replace(/A/g, 't') .replace(/T/g, 'a') .replace(/C/g, 'g') .replace(/G/g, 'c') .toUpperCase(); } } <file_sep>/(7 kyu) Even numbers in an array/(7 kyu) Even numbers in an array.ts export function evenNumbers(array: number[], n: number): number[] { const result = []; for (let i = 0; i <= array.length; i++) { if (array[i] % 2 == 0) result.push(array[i]); } return result.splice(result.length - n, n); } <file_sep>/(7 kyu) Number of People in the Bus/(7 kyu) Number of People in the Bus.js // #1 // function number(busStops) { // let totalPeople = 0; // for (let i = 0; i < busStops.length; i++) { // totalPeople += busStops[i][0]; // totalPeople -= busStops[i][1]; // } // return totalPeople; // } // #2 // function number(busStops) { // return busStops.reduce((people, next) => { // const [on, off] = next; // return people + on - off; // }, 0); // } // #3 const number = (busStops) => busStops.reduce((a, c) => a + c[0] - c[1], 0); <file_sep>/(7 kyu) Recursion 2 - Fibonacci/(7 kyu) Recursion 2 - Fibonacci.rs fn fibonacci(n: u32) -> u32 { match n { 0...2 => 1, _ => fibonacci(n - 1) + fibonacci(n - 2), } } <file_sep>/(6 kyu) Multiples of 3 or 5/(6 kyu) Multiples of 3 or 5.py def solution(number): # #1 # result = 0 # for i in range(1, number): # result += i if 0 == i % 3 or 0 == i % 5 else 0 # return result # #2 return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0) <file_sep>/(8 kyu) Return Negative/(8 kyu) Return Negative.cpp #include <cstdlib> int makeNegative(int num) { return -std::abs(num); }<file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.ts export const centuryFromYear = (year: number): number => { return Math.ceil(year / 100); }; <file_sep>/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine.py def number_to_english(n): return "" if n < 0 or n > 99999 or type(n) != int else [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"][n] if n < 20 else " ".join( [ ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"][(n-20)//10], number_to_english(n % 10)] ).replace(" zero", "").rstrip() if n < 100 else " ".join( [number_to_english(n//100)+" hundred", number_to_english(n % 100)] ).replace(" zero", "").rstrip() if n < 1000 else " ".join( [number_to_english(n//1000)+" thousand", number_to_english(n % 1000)] ) <file_sep>/(7 kyu) Sort Numbers/(7 kyu) Sort Numbers.md # Sort Numbers (7 kyu) https://www.codewars.com/kata/sort-numbers/ Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array. For example: ```rust sort_numbers(&vec![1, 2, 3, 10, 5]); // should return vec![1, 2, 3, 5, 10] sort_numbers(&vec![]); // should return !vec[] ``` <file_sep>/(6 kyu) Fibonacci Generator Function/(6 kyu) Fibonacci Generator Function.js function* fibonacci(fn1 = 1, fn2 = 0, current = 0) { while (true) { [current, fn2, fn1] = [fn2, fn1, fn1 + fn2]; yield current; } } <file_sep>/(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe/(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe.ts export function toAlternatingCase(s: string): string { return s .split('') .map((c) => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase())) .join(''); } <file_sep>/(7 kyu) Frequency sequence/(7 kyu) Frequency sequence.ts export function freqSeq(str: string, sep: string): string { const freq = {}; let newStr = ''; for (let i = 0; i < str.length; i++) { freq[str[i]] = freq[str[i]] ? (freq[str[i]] += 1) : 1; } for (let i = 0; i < str.length; i++) { newStr += i ? sep + freq[str[i]] : freq[str[i]]; } return newStr; } <file_sep>/(6 kyu) Fibonacci Generator Function/(6 kyu) Fibonacci Generator Function.md # Fibonacci Generator Function (6 kyu) https://www.codewars.com/kata/fibonacci-generator-function This is a simple Kata to test your knowledge of generators. You will create a generator function which produces a fibonacci sequence. The first number in the sequence is 0. The next number in the sequence is 1. Each subsequent number is the summation of the previous two numbers. The next number after 1 would be 1 because 0 + 1 = 1. The next number would be 2 because 1 + 1 = 2. The fibonacci sequence starts at zero, calling fib.next() should step through the next number in the fibonacci sequence and fib.next().value will step through and produce the value. <file_sep>/(7 kyu) Two to One/(7 kyu) Two to One.js // #1 // function longest(s1, s2) { // let res = s1 + s2; // res = res.split(''); // res = [...new Set(res)]; // res = res.sort(); // return res.join(''); // } // #2 // const longest = (s1, s2) => [...new Set([...(s1 + s2)])].sort().join(''); // #3 const longest = (s1, s2) => [...new Set(s1 + s2)].sort().join``; <file_sep>/(7 kyu) Mumbling/(7 kyu) Mumbling.ts export class G964 { public static accum(s: string): string { return s .split('') .map((el, i) => /^[a-zA-Z]$/ ? el.toUpperCase() + el.repeat(i).toLowerCase() : '', ) .join('-'); } } <file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.py def century(year): return year // 100 + (0 if year % 100 == 0 else 1) <file_sep>/(6 kyu) Square Digits Sequence/(6 kyu) Square Digits Sequence.rs use std::collections::HashSet; // #1 fn square_digits_sequence(a0: u32) -> usize { let mut nums: HashSet<u32> = HashSet::new(); let mut x = a0; while !nums.contains(&x) { nums.insert(x); let digits: String = x.to_string(); x = digits.chars().fold(0, |mut sum, d| { let n = d.to_digit(10).unwrap(); sum += n * n; sum }); } nums.len() + 1 } // #2 fn square_digits_sequence(mut n: u32) -> usize { let mut seen = HashSet::new(); while !seen.contains(&n) { seen.insert(n); n = n.to_string().chars().map(|c| c.to_digit(10).unwrap().pow(2)).sum(); } seen.len() + 1 } <file_sep>/(7 kyu) Form The Largest/(7 kyu) Form The Largest.py # #1 # def max_number(n): # s = list(str(n)) # s.sort() # res = s[::-1] # return int("".join(res)) # #2 # def max_number(n): # s = list(str(n)) # return int(''.join(sorted(s, reverse=True))) #3 def max_number(n): return int(''.join(sorted(str(n), reverse=True))) <file_sep>/(8 kyu) Abbreviate a Two Word Name/(8 kyu) Abbreviate a Two Word Name.ts export function abbrevName(name: string): string { return name .split(' ') .map((s) => s[0].toUpperCase()) .join('.'); } <file_sep>/(6 kyu) Salesman's Travel/(6 kyu) Salesman's Travel.cpp #include <regex> #include <string> #include <vector> class SalesmanTravel { public: static std::string travel(const std::string &orgr, std::string zipcode) { std::vector<std::string> fullAddresses; auto it = std::find(orgr.begin(), orgr.end(), ','); auto prevIt = orgr.begin(); do { fullAddresses.emplace_back(prevIt, it); prevIt = ++it; it = std::find(it, orgr.end(), ','); } while (it != orgr.end()); std::string numbers; std::string addresses; std::regex zipcodeRegex("(\\d+)\\s(.+)\\s+" + zipcode + "$"); std::smatch match; for (auto &&fullAddress : fullAddresses) { if (std::regex_match(fullAddress, match, zipcodeRegex) && match.size() == 3) { addresses += (addresses.empty() ? "" : ",") + std::string(match[2]); numbers += (numbers.empty() ? "" : ",") + std::string(match[1]); } } return zipcode + ":" + addresses + "/" + numbers; } };<file_sep>/(7 kyu) Simple beads count/(7 kyu) Simple beads count.py # #1 # def count_red_beads(n): # return 0 if n < 2 else (n - 1) * 2 def count_red_beads(n): # 2 return max(0, 2 * (n-1)) <file_sep>/(7 kyu) Shortest Word/(7 kyu) Shortest Word.ts export function findShort(s: string): number { return Math.min(...s.split(' ').map((w) => w.length)); } <file_sep>/(6 kyu) Salesman's Travel/(6 kyu) Salesman's Travel.rs pub fn travel(r: &str, zipcode:&str) -> String { if zipcode == "" { return String::from(":/") } let (nums, street): (Vec<&str>, Vec<&str>) = r.split(",") .filter(|s| s.ends_with(zipcode)) .map(|s| { let iter: Vec<&str> = s.trim().splitn(2, " ").collect(); let len = iter[1].chars().count(); (iter[0], &iter[1][..len-zipcode.len()-1]) }) .unzip(); format!("{}:{}/{}", zipcode, street.join(","), nums.join(",")) }<file_sep>/(8 kyu) Return Negative/(8 kyu) Return Negative.rs fn make_negative(number: i32) -> i32 { number.abs() * -1 } <file_sep>/(7 kyu) Form The Minimum/(7 kyu) Form The Minimum.ts export const minValue = (values: number[]): number => { const arr = [...values].sort(); const dedupe = arr.filter( (x: number, i: number, a: number[]): boolean => i === a.indexOf(x), ); return +dedupe.join(''); }; <file_sep>/(6 kyu) Reverse or rotate/(6 kyu) Reverse or rotate.js // #1 // function revrot(str, sz) { // if (sz <= 0 || str == '' || sz > str.length) { // return ''; // } // const arr = []; // const s = str.split(''); // while (s.length >= sz) { // arr.push(s.splice(0, sz)); // } // const res = arr.map((x) => { // const sum = x.reduce((a, c) => a + Math.pow(c, 3), 0); // if (sum % 2) { // x.push(x[0]); // x.shift(); // return x.join(''); // } else { // return x.reverse().join(''); // } // }); // return res.join(''); // } // #2 function revrot(str, sz) { const isEven = (v) => v.split('').reduce((cubeSum, d) => (cubeSum += d ** 3), 0) % 2 === 0; const reverse = (v) => v .split('') .reverse() .join(''); const rotate = (v) => v.slice(1) + v.slice(0, 1); return (str.match(new RegExp(`.{${sz}}`, 'g')) || []) .map((v) => (isEven(v) ? reverse(v) : rotate(v))) .join(''); } <file_sep>/(3 kyu) The soul of wit - reverse an array/(3 kyu) The soul of wit - reverse an array.md # The soul of wit: reverse an array (3 kyu) https://www.codewars.com/kata/the-soul-of-wit-reverse-an-array No time for stories. Reverse an array, return the result. Do whatever you want with the original array. Don't use Array.prototype.reverse. You have 30 bytes to spare. ``` Example: [1, 2, 3] → [3, 2, 1] ``` <file_sep>/(5 kyu) Calculating with Functions/(5 kyu) Calculating with Functions.js const number = (op, num) => (op ? op[0](num, op[1]) : num); const zero = (op) => number(op, 0); const one = (op) => number(op, 1); const two = (op) => number(op, 2); const three = (op) => number(op, 3); const four = (op) => number(op, 4); const five = (op) => number(op, 5); const six = (op) => number(op, 6); const seven = (op) => number(op, 7); const eight = (op) => number(op, 8); const nine = (op) => number(op, 9); const plus = (x) => [(a, b) => a + b, x]; const minus = (x) => [(a, b) => a - b, x]; const times = (x) => [(a, b) => a * b, x]; const dividedBy = (x) => [(a, b) => a / b, x]; <file_sep>/(7 kyu) Shortest Word/(7 kyu) Shortest Word.rs // #1 // fn find_short(s: &str) -> u32 { // let words = s.split(" ").collect::<Vec<_>>(); // let mut min = <usize>::max_value(); // for w in words { // if w.len() < min { // min = w.len() // } // } // min as u32 // } // #2 // fn find_short(s: &str) -> u32 { // s // .split_whitespace() // .min_by_key(|s| s.len()) // .unwrap() // .len() as u32 // } // #3 fn find_short(s: &str) -> usize { s.split_whitespace().map(str::len).min().unwrap() } <file_sep>/(6 kyu) Square Digits Sequence/(6 kyu) Square Digits Sequence.py def square_digits_sequence(n): s = set() while n not in s: s.add(n) n = sum(int(d)**2 for d in str(n)) return len(s)+1 <file_sep>/(6 kyu) CamelCase Method/(6 kyu) CamelCase Method.md # CamelCase Method (6 kyu) https://www.codewars.com/kata/camelcase-method/ Write simple .camelcase method (camel_case function in PHP) for strings. All words must have their first letter capitalized without spaces. Example: ```js "hello case".camelCase() => HelloCase "camel case word".camelCase() => CamelCaseWord ``` <file_sep>/(6 kyu) IQ Test/(6 kyu) IQ Test.ts export function iqTest(numbers: string): number { const nums = numbers.split(' ').map((el: string) => +el); const odd = nums.filter((el: number) => el % 2 === 1); const even = nums.filter((el: number) => el % 2 === 0); return odd.length < even.length ? nums.indexOf(odd[0]) + 1 : nums.indexOf(even[0]) + 1; } <file_sep>/(7 kyu) Get the Middle Character/(7 kyu) Get the Middle Character.rs fn get_middle(s: &str) -> &str { // #1 // let even = s.len() % 2 == 0; // let middle = s.len() / 2; // &s[if even { middle - 1 } else { middle }..middle + 1] // #2 s[(s.len() - 1) / 2..s.len() / 2 + 1] } <file_sep>/(6 kyu) Find the odd int/(6 kyu) Find the odd int.md # Find the odd int (6 kyu) https://www.codewars.com/kata/find-the-odd-int/ Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times. <file_sep>/(7 kyu) Even numbers in an array/(7 kyu) Even numbers in an array.js // #1 // function evenNumbers(array, number) { // const result = []; // for (let i = 0; i <= array.length; i++) { // if (array[i] % 2 == 0) result.push(array[i]); // } // return result.splice(result.length - number, number); // } // #2 // function evenNumbers(array, number) { // const result = []; // array.map((x) => { // if (x % 2 === 0) { // result.push(x); // } // }); // return result.slice(-number); // } // #3 // function evenNumbers(array, number) { // return array.filter((x) => !(x % 2)).splice(-number); // } // #4 const evenNumbers = (array, number) => array.filter((x) => !(x % 2)).splice(-number); <file_sep>/(7 kyu) Canvas Fun 1 - Draw Lines/(7 kyu) Canvas Fun 1 - Draw Lines.js function drawLines(points) { var canvas = new Canvas(100, 100); //Create a 100 x 100 canvas var ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, 100, 100); //Draw background ctx.strokeStyle = '#ff0000'; //Set pen's color ctx.beginPath(); //Don't delete or modify the code above //Your code starts here: /* #1 const xCoordinate = 0; const yCoordinate = 1; ctx.moveTo(points[0][xCoordinate], points[0][yCoordinate]); for (let i = 1; i < points.length; i++) { ctx.lineTo(points[i][xCoordinate], points[i][yCoordinate]); } */ /* #2 ctx.moveTo(...points[0]) for (let i = 1; i < points.length; i++) { ctx.lineTo(...points[i]); } */ /* #3 */ // start from 0 point ctx.moveTo(...points.shift()); points.forEach((p) => // draw a line to the next point ctx.lineTo(...p), ); //Don't delete or modify the following code ctx.stroke(); //Draw the path you made above return canvas.toDataURL(); //Returns the image data } <file_sep>/(7 kyu) Sort Numbers/(7 kyu) Sort Numbers.py # #1 def solution(nums): return [] if not nums else sorted(nums) <file_sep>/(8 kyu) Reversed sequence/(8 kyu) Reversed sequence.ts export const reverseSeq = (n: number): number[] => { return [...Array(n)].map((x, i) => n - i); }; <file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.rs // #1 // fn generate_shape(n: i32) -> String { // let mut str = vec![]; // for _ in 0..n { // str.push("+".repeat(n as usize)); // } // str.join("\n") // } // #2 // fn generate_shape(n: i32) -> String { // vec!["+".repeat(n as usize); n as usize].join("\n") // } // #3 fn generate_shape(n: usize) -> String { vec!["+".repeat(n); n].join("\n") } <file_sep>/(7 kyu) Get the Middle Character/(7 kyu) Get the Middle Character.md # (7 kyu) Get the Middle Character https://www.codewars.com/kata/get-the-middle-character/ You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. Examples: ```js Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A" ``` <file_sep>/(8 kyu) Count of positives - sum of negatives/(8 kyu) Count of positives - sum of negatives.cpp #include <vector> // #1 // std::vector<int> countPositivesSumNegatives(std::vector<int> input) // { // if (input.size() == 0) // return {}; // std::vector<int> result(2); // for (auto x : input) // { // if (x > 0) // result[0]++; // if (x < 0) // result[1] += x; // } // return result; // } // #2 std::vector<int> countPositivesSumNegatives(std::vector<int> input) { if (input.empty()) return {}; int countPositives{0}, sumNegatives{0}; for (int x : input) x > 0 ? countPositives++ : (x != 0 ? sumNegatives += x : 0); return {countPositives, sumNegatives}; }<file_sep>/(7 kyu) Thinkful - String Drills. Repeater/(7 kyu) Thinkful - String Drills. Repeater.js //#1 // function repeater(string, n) { // var res = ''; // while (n > 0) { // res += string; // n--; // } // return res; // } // #2 // function repeater(string, n) { // return new Array(n + 1).join(string); // } const repeater = (string, n) => string.repeat(n); <file_sep>/(8 kyu) Remove String Spaces/(8 kyu) Remove String Spaces.ts export function noSpace(x: string): string { return x.replace(/\s+/g, ''); } <file_sep>/(6 kyu) IQ Test/(6 kyu) IQ Test.js // #1 Using for loop // function iqTest(numbers) { // numbers = numbers.split(' '); // const evens = []; // const odds = []; // for (let i = 0; i < numbers.length; i++) { // numbers[i] & 1 ? odds.push(i + 1) : evens.push(i + 1); // } // return evens.length === 1 ? evens[0] : odds[0]; // } // #2 Using "some" // const iqTest = (numbers) => { // const evenOdd = [[0, 0], [0, 0]]; // numbers.split(' ').some((num, i) => { // const n = num % 2; // evenOdd[n][0]++; // store quantity // evenOdd[n][1] = i; // store its index // if (evenOdd[n][0] > 1 && evenOdd[+!n][0] == 1) { // return true; // stop iterating when found // } // }); // return ++evenOdd[evenOdd[0][0] == 1 ? 0 : 1][1]; // }; // #3 Using "filter" // const iqTest = (numbers) => { // numbers = numbers.split(' ').map((el) => +el); // const odd = numbers.filter((el) => el % 2 === 1); // const even = numbers.filter((el) => el % 2 === 0); // return odd.length < even.length // ? numbers.indexOf(odd[0]) + 1 // : numbers.indexOf(even[0]) + 1; // }; // #4 Using "reduce" const iqTest = (numbers) => { numbers = numbers.split` `.map((x) => +x % 2); return ( (numbers.reduce((x, y) => x + y) === 1 ? numbers.indexOf(1) : numbers.indexOf(0)) + 1 ); }; <file_sep>/(6 kyu) Multiples of 3 or 5/(6 kyu) Multiples of 3 or 5.ts export class Challenge { static solution(number) { let result = 0; for (let i = 1; i < number; i++) { result += 0 === i % 3 || 0 === i % 5 ? i : 0; } return result; } } <file_sep>/(8 kyu) Find the smallest integer in the array/(8 kyu) Find the smallest integer in the array.ts export function findSmallestInt(args: number[]): number { return Math.min(...args); } <file_sep>/(4 kyu) Decode the Morse code, advanced/(4 kyu) Decode the Morse code, advanced.md # Decode the Morse code, advanced (4 kyu) https://www.codewars.com/kata/decode-the-morse-code-advanced In this kata you have to write a Morse code decoder for wired electrical telegraph. Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key). <file_sep>/(7 kyu) Mumbling/(7 kyu) Mumbling.cpp #include <string> #include <cctype> // #1 // class Accumul // { // public: // static std::string accum(const std::string &s) // { // std::string res; // for (int i = 0; i < s.length(); i++) // { // std::string word; // for (int j = 0; j <= i; j++) // if (j == 0) // word += std::toupper(s[i]); // else // word += std::tolower(s[i]); // res += word; // if (i < s.length() - 1) // res += "-"; // } // return res; // } // }; // #2 class Accumul { public: static std::string accum(const std::string &s) { std::string result; for (int i = 0; i < s.length(); i++) { result.append("-"); result.append(std::string(1, toupper(s[i]))); result.append(std::string(i, tolower(s[i]))); } return result.substr(1, result.length()); } };<file_sep>/(7 kyu) Reverse words/(7 kyu) Reverse words.rs fn reverse_words(str: &str) -> String { let words = str.split(" ").collect::<Vec<_>>(); let mut res = "".to_string(); for w in words { let mut x = w.to_string(); x += " "; x = x.chars().rev().collect(); res.push_str(&x); } res[1..].to_string() } <file_sep>/(8 kyu) Reversed Strings/(8 kyu) Reversed Strings.cpp #include <string> #include <algorithm> using namespace std; string reverseString(string str) { reverse(str.begin(), str.end()); return str; }<file_sep>/(7 kyu) Canvas Fun 1 - Draw Lines/(7 kyu) Canvas Fun 1 - Draw Lines.md # Canvas Fun #1: Draw Lines (7 kyu) http://www.codewars.com/kata/canvas-fun-number-1-draw-lines Given some points, your task is to draw lines between two adjacent points. `points` is given by a 2D integer array. Each subarray has two elements, means the x-coordinate, y-coordinate of each point. The basic canvas(width 100 x height 100), background color(white) and pen's color(red) are already defined in the initial code(please don't delete or modify them). <file_sep>/(8 kyu) DNA to RNA Conversion/(8 kyu) DNA to RNA Conversion.cpp #include <string> #include <regex> // #1 // std::string DNAtoRNA(std::string dna) // { // std::regex e("T"); // std::string result; // std::regex_replace(std::back_inserter(result), // dna.begin(), dna.end(), e, "U"); // return result; // } // #2 std::string DNAtoRNA(std::string dna) { std::replace(dna.begin(), dna.end(), 'T', 'U'); return dna; }<file_sep>/(7 kyu) Remove duplicate words/(7 kyu) Remove duplicate words.ts export function removeDuplicateWords(s: string): string { return s .split(' ') .filter((el, index, arr) => arr.indexOf(el) == index) .join(' '); } <file_sep>/(7 kyu) Sort Numbers/(7 kyu) Sort Numbers.js // #1 // function solution(nums) { // if (nums) { // return nums.sort((a, b) => a - b); // } else { // return []; // } // } // #2 // function solution(nums) { // return nums ? nums.sort((a, b) => a - b) : []; // } // #3 // const solution = (nums) => (nums ? nums.sort((a, b) => a - b) : []); // #4 const solution = (nums) => (nums || []).sort((a, b) => a - b); <file_sep>/(7 kyu) Form The Minimum/(7 kyu) Form The Minimum.rs // #1 // fn min_value(mut digits: Vec<i32>) -> i32 { // digits.sort(); // digits.dedup_by(|a, b| a == b); // let mut res = "".to_string(); // for i in digits { // res.push_str(&i.to_string()); // } // res.parse::<i32>().unwrap() // } // #2 // fn min_value(mut digits: Vec<i32>) -> i32 { // digits.sort(); // digits.dedup(); // digits // .iter() // .map(|x| x.to_string()) // .collect::<String>() // .parse::<i32>() // .unwrap() // } // #3 fn min_value(mut digits: Vec<i32>) -> i32 { digits.sort(); digits.dedup(); digits.into_iter().fold(0, |acc, x| acc * 10 + x) } <file_sep>/(7 kyu) Complementary DNA/(7 kyu) Complementary DNA.cpp // #1 // #include <string> // using namespace std; // std::string DNAStrand(const std::string& dna) // { // string res = ""; // for(int i = 0; i < dna.length(); i++) // { // if (dna[i] == 'T') res += 'A'; // if (dna[i] == 'A') res += 'T'; // if (dna[i] == 'G') res += 'C'; // if (dna[i] == 'C') res += 'G'; // } // return res; // } // #2 #include <string> #include <unordered_map> std::unordered_map<char, char> pairs = {{'A', 'T'}, {'T', 'A'}, {'C', 'G'}, {'G', 'C'}}; std::string DNAStrand(const std::string &dna) { std::string complement; for (const char &c : dna) { complement += pairs[c]; } return complement; }<file_sep>/(7 kyu) Reverse words/(7 kyu) Reverse words.py # #1 # def reverse_words(text): # words = text.split(" ") # result = [] # for w in words: # result.append(w[::-1]) # return " ".join(result) # #2 def reverse_words(text): return " ".join(text[::-1].split(" ")[::-1]) <file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.ts export function generateShape(int: number): string { let string = ''; for (let i = 0; i < int * int; i++) { if (i % int === 0 && i !== 0) { string += '\n'; } string += '+'; } return string; } <file_sep>/(7 kyu) String ends with/(7 kyu) String ends with.py def solution(string, ending): return string.endswith(ending) <file_sep>/(6 kyu) Playing with digits/(6 kyu) Playing with digits.py def dig_pow(n, p): # #1 string = str(n) res = 0 for s in string: res += int(s) ** p p += 1 return res / n if res % n == 0 else -1 def dig_pow(n, p): # #2 res = 0 for i, s in enumerate(str(n)): res += int(s) ** (p + i) return res / n if res % n == 0 else -1 def dig_pow(n, p): # #3 res = sum(int(s) ** (p + i) for i, s in enumerate(str(n))) return res // n if res % n == 0 else -1 <file_sep>/(6 kyu) Help the bookseller/(6 kyu) Help the bookseller.js // #1 Use forEach // function stockList(listOfArt, listOfCat) { // if (!listOfArt.length || !listOfCat.length) { // return ''; // } // const books = {}; // const result = []; // listOfArt.forEach((book) => { // const [title, num] = book.split` `; // books[title[0]] = books[title[0]] ? (books[title[0]] += +num) : +num; // }); // listOfCat.forEach((letter) => { // const num = books[letter] || 0; // result.push(`(${letter} : ${num})`); // }); // return result.join` - `; // } // #2 Optimazed forEach // function stockList(listOfArt, listOfCat) { // if (!listOfArt.length || !listOfCat.length) { // return ''; // } // const books = {}; // listOfArt.forEach((book) => { // const title = book[0]; // books[title] = (books[title] | 0) + +book.split` `[1]; // }); // return listOfCat.map((letter) => { // return `(${letter} : ${books[letter] | 0})`; // }).join` - `; // } // #3 Use reduce function stockList(listOfArt, listOfCat) { if (!listOfArt.length || !listOfCat.length) { return ''; } return listOfCat .map((book) => { const sum = listOfArt.reduce( (acc, title) => acc + (title[0] === book ? +title.split(' ')[1] : 0), 0, ); return `(${book} : ${sum})`; }) .join(' - '); } <file_sep>/(7 kyu) Mumbling/(7 kyu) Mumbling.rs fn accum(s: &str) -> String { // #1 // let vec_str = s.split_terminator("").skip(1).collect::<Vec<_>>(); // let last_sym = s.len() - 1; // let mut res = String::new(); // for (index, curr_char) in vec_str.iter().enumerate() { // res.push_str(&format!( // "{}{}", // &curr_char.to_uppercase(), // &curr_char.to_lowercase().repeat(index) // )); // if index < last_sym { // res.push_str("-"); // } // } // res // #2 s.chars() .enumerate() .map(|(index, curr_char)| { curr_char.to_string().to_uppercase() + &(0..index) .map(|_| curr_char.to_string().to_lowercase()) .collect::<String>() }).collect::<Vec<_>>() .join("-") } <file_sep>/(7 kyu) Exes and Ohs/7 kyu Exes and Ohs.rs // #1 // fn xo(string: &'static str) -> bool { // let mut equal = 0; // for c in string.to_lowercase().chars() { // equal += match c { // 'x' => 1, // 'o' => -1, // _ => 0, // } // } // equal == 0 // } // #2 fn xo(string: &'static str) -> bool { string.to_lowercase().chars().fold(0, |a, c| match c { 'x' => a + 1, 'o' => a - 1, _ => a, }) == 0 } <file_sep>/(4 kyu) Reverse it, quickly/(4 kyu) Reverse it, quickly.md # -Reverse it, quickly! (4 kyu) https://www.codewars.com/kata/reverse-it-quickly Typically, reversing an array is a pretty straightforward task even for novice programmers. But not when a crowd of angry zombies scratching your door, looking for a fresh brains. In this case even skilled ninja-geek probably prefer to quickly push his code on github to have enough time to find a chainsaw. So there's two obstacles: 1. Your code needs to be as short as possible, in fact not longer than 28 characters 1. Because you are scared and stressed you have forgotten how to use the standard reverse() method Input: an array containing data of any types. Ex: [1,2,3,'a','b','c',[]] Output: [[],'c','b','a',3,2,1] <file_sep>/(7 kyu) Even numbers in an array/(7 kyu) Even numbers in an array.rs fn even_numbers(array: Vec<i32>, number: usize) -> Vec<i32> { let arr = array.into_iter().filter(|&i|i % 2 == 0).collect::<Vec<_>>(); let from = arr.len() - number; arr[from..].to_vec() } <file_sep>/(4 kyu) Human readable duration format/(4 kyu) Human readable duration format.js function formatDuration(seconds) { const pluralization = (x, y) => (x ? `${x} ${y}${x > 1 ? 's' : ''}` : ''); const join = (x, y, z) => (x && y ? (z ? ', ' : ' and ') : '') + y; const sufix = ['year', 'day', 'hour', 'minute', 'second']; const [y, d] = [seconds / 31536e3, (seconds / 864e2) % 365].map((t, i) => pluralization(Math.floor(t), sufix[i]), ); const [h, m, s] = new Date(1e3 * seconds).toISOString().substr(11, 8) .split`:`.map((t, i) => pluralization(+t, sufix[i + 2])); return ( y + join(y, d, h) + join(d, h, m) + join(h, m, s) + join(m, s, false) || 'now' ); } <file_sep>/(4 kyu) IP Validation/(4 kyu) IP Validation.md # IP Validation (4 kyu) https://www.codewars.com/kata/ip-validation Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between 0..255 (included). Input to the function is guaranteed to be a single string. ### Examples ``` // valid inputs: 1.2.3.4 172.16.31.10 // invalid inputs: 1.2.3 1.2.3.4.5 123.456.78.90 123.045.067.089 ``` Note: leading zeros (e.g. 01.02.03.04) are considered not valid in this kata! <file_sep>/(7 kyu) Frequency sequence/(7 kyu) Frequency sequence.md # Frequency sequence (7 kyu) https://www.codewars.com/kata/frequency-sequence/ Return an output string that translates an input string `s/$s` by replacing each character in `s/$s` with a number representing the number of times that character occurs in `s/$s` and separating each number with the character(s) `sep/$sep`. Example: ```js freqSeq('hello world', '-'); // => '1-1-3-3-2-1-1-2-1-3-1' freqSeq('^^^**$', 'x'); // => '3x3x3x2x2x1' freqSeq('19999999', ':'); // => 'fc00:db20:35b:7399::5' ``` <file_sep>/(7 kyu) Two to One/(7 kyu) Two to One.cpp #include <iostream> #include <algorithm> using namespace std; class TwoToOne { public: static string longest(const string &s1, const string &s2) { string word = s1 + s2; sort(word.begin(), word.end()); auto ip = unique(word.begin(), word.end()); return string(word.begin(), ip); }; };<file_sep>/(7 kyu) Get the Middle Character/(7 kyu) Get the Middle Character.ts export class Challenge { static getMiddle(s: string) { const middle = s.length / 2; if (s.length % 2) { return s.charAt(Math.floor(middle)); } else { return s.slice(middle - 1, middle + 1); } } } <file_sep>/(6 kyu) Playing with passphrases/(6 kyu) Playing with passphrases.ts export class G964 { public static playPass(s: string, n: number): string { let res = s.split('').map((a: string, i: number) => { if (/\d/.test(a)) { return String(9 - Number(a)); } else if (/\w/.test(a)) { let x: number = a.charCodeAt(0) + n; if (x > 90) { x -= 26; } const l: string = String.fromCharCode(x); if (i % 2) { return l.toLowerCase(); } else { return l; } } else { return a; } }); return res.reverse().join(''); } } <file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.md # Century From Year (8 kyu) https://www.codewars.com/kata/century-from-year/ ## Introduction The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc. ## Task Given a year, return the century it is in. ## Input, Output, Examples ```js centuryFromYear(1705) returns (18) centuryFromYear(1900) returns (19) centuryFromYear(1601) returns (17) centuryFromYear(2000) returns (20) ``` Hope you enjoy it .. Awaiting for Best Practice Codes Enjoy Learning !!! <file_sep>/(5 kyu) Fibonacci Generator/(5 kyu) Fibonacci Generator.md # Fibonacci Generator (5 kyu) https://www.codewars.com/kata/522498c9906b0cfcb40001fc Create a function generator genfib() that returns a function fib() which always returns the next fibonacci number on each invocation (and returns 0 when being called the first time). ### Example: ``` var fib = genfib(); fib(); // -> returns 0 fib(); // -> returns 1 fib(); // -> returns 1 fib(); // -> returns 2 ``` <file_sep>/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine.cpp #include <string> #include <vector> std::string numberToEnglish(unsigned int n) { if (n < 0 || n > 99999 || n % 1 != 0) { return ""; } if (n < 20) { return std::vector<std::string>{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}[n]; } if (n < 100) { return std::vector<std::string>{ "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}[(n - 20) / 10] + (n % 10 ? " " + numberToEnglish(n % 10) : ""); } if (n < 1000) { return numberToEnglish(n / 100) + " hundred" + (n % 100 ? " " + numberToEnglish(n % 100) : ""); } return numberToEnglish(n / 1000) + " thousand" + (n % 1000 ? " " + numberToEnglish(n % 1000) : ""); }<file_sep>/(7 kyu) Form The Minimum/(7 kyu) Form The Minimum.py # #1 # def min_value(digits): # s = set(digits) # l = list(s) # l.sort() # r = [] # for x in l: # r.append(str(x)) # res = ''.join(r) # return int(res) #2 def min_value(digits): l = sorted(list(set(digits))) return int(''.join(str(x) for x in l)) #3 def min_value(digits): return int("".join(map(str,sorted(set(digits))))) <file_sep>/(8 kyu) Basic subclasses - Adam and Eve/(8 kyu) Basic subclasses - Adam and Eve.py # #1 # def God(): # return [Man(), Woman()] # class Human(object): # pass # class Man(Human): # pass # class Woman(Human): # pass # #2 class Human(object): def __init__(self): pass class Man(Human): def __init__(self, name): self.name = name class Woman(Human): def __init__(self, name): self.name = name def God(): Adam = Man('Adam') Eva = Woman('Eva') return [Adam, Eva] <file_sep>/(6 kyu) Multiples of 3 or 5/(6 kyu) Multiples of 3 or 5.cpp int solution(int number) { int result = 0; int i; for (i = 1; i < number; i++) { if (i % 3 == 0 || i % 5 == 0) { result += i; } } return result; }<file_sep>/(7 kyu) String ends with/(7 kyu) String ends with.cpp #include <iostream> #include <string> using namespace std; bool solution(std::string const &str, std::string const &ending) { if (str.length() >= ending.length()) { return (0 == str.compare(str.length() - ending.length(), ending.length(), ending)); } else { return false; } }<file_sep>/(7 kyu) Thinkful - String Drills. Repeater/(7 kyu) Thinkful - String Drills. Repeater.md # Thinkful - String Drills. Repeater (7 kyu) https://www.codewars.com/kata/thinkful-string-drills-repeater/ Write a class function named `repeat()` that takes two arguments (a string and a long integer), and returns a new string where the input string is repeated that many times. For example: ```js Repeater.repeat('a', 5); ``` should return ```js 'aaaaa'; ``` <file_sep>/(8 kyu) Century From Year/(8 kyu) Century From Year.cpp int centuryFromYear(int year) { return (year - 1) / 100 + 1; }<file_sep>/(8 kyu) If you can't sleep, just count sheep/(8 kyu) If you can't sleep, just count sheep.cpp #include <string> using namespace std; string countSheep(int number) { string ret = ""; for (int i = 1; i <= number; i++) { ret += (to_string(i) + " sheep..."); } return ret; };<file_sep>/(5 kyu) Human Readable Time/(5 kyu) Human Readable Time.js const humanReadable = (seconds) => [ ('0' + Math.floor(seconds / 3600)).slice(-2), ('0' + Math.floor((seconds % 3600) / 60)).slice(-2), ('0' + (seconds % 60)).slice(-2), ].join(':'); <file_sep>/(7 kyu) Thinkful - String Drills. Repeater/(7 kyu) Thinkful - String Drills. Repeater.rs fn repeater(string: &str, n: u32) -> String { string.repeat(n as usize) } <file_sep>/(3 kyu) Base64 Encoding/(3 kyu) Base64 Encoding.md # Base64 Encoding (3 kyu) https://www.codewars.com/kata/5270f22f862516c686000161 Extend the String object (JS) or create a function (Python, C#) that converts the value of the String to and from Base64 using the ASCII (UTF-8 for C#) character set. Do not use built in functions. Usage: ``` // should return 'dGhpcyBpcyBhIHN0cmluZyEh' 'this is a string!!'.toBase64(); // should return 'this is a string!!' 'dGhpcyBpcyBhIHN0cmluZyEh'.fromBase64(); ``` You can learn more about Base64 encoding and decoding here. <file_sep>/(7 kyu) Remove duplicate words/(7 kyu) Remove duplicate words.cpp #include <string> #include <map> std::string removeDuplicateWords(const std::string &str) { std::string result, word; std::map<std::string, bool> words; auto output = [&]() { if ((word.size() > 0) && (!words[word])) { result.append(((result.size() > 0) ? " " : "") + word); } }; for (auto c : str) { if (c == ' ') { output(); words[word] = true; word = ""; } else { word.push_back(c); } } output(); return std::move(result); }<file_sep>/(8 kyu) Abbreviate a Two Word Name/(8 kyu) Abbreviate a Two Word Name.js // #1 // function abbrevName(name) { // const arr = name.split(' '); // const firstname = arr[0]; // const surname = arr[1]; // const result = firstname[0].toUpperCase() + '.' + surname[0].toUpperCase(); // return result; // } // #2 // function abbrevName(name){ // const arr = name.split(' ') // const [firstname, surname] = arr // const result = `${firstname[0].toUpperCase()}.${surname[0].toUpperCase()}` // return result // } // #3 // function abbrevName(name){ // const arr = name.split(' ') // const result = arr.map(s => s[0].toUpperCase()).join('.') // return result // } // #4 // function abbrevName(name) { // return name.split` `.map((s) => s[0].toUpperCase()).join`.`; // } // #5 const abbrevName = (name) => name .split(' ') .map((s) => s[0].toUpperCase()) .join('.'); <file_sep>/(7 kyu) Last/(7 kyu) Last.md # Last (7 kyu) https://www.codewars.com/kata/541629460b198da04e000bb9 Find the last element of the given argument(s). Examples: ```js last([1, 2, 3, 4]); // => 4 last('xyz'); // => "z" last(1, 2, 3, 4); // => 4 ``` In `javascript` and `CoffeeScript` a list will be an array, a string or the list of arguments. (courtesy of haskell.org) <file_sep>/(7 kyu) Build a square/(7 kyu) Build a square.md # Build a square (7 kuy) https://www.codewars.com/kata/build-a-square/ I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 0 and 50. Example: Integer = 3; I expect a 3x3 square back just like below as a string. Solution: ``` +++ +++ +++ ``` <file_sep>/(7 kyu) Number of People in the Bus/(7 kyu) Number of People in the Bus.cpp #include <vector> // #1 // unsigned int number(const std::vector<std::pair<int, int>> &busStops) // { // int total_people = 0; // for (int i = 0; i < busStops.size(); i++) // { // total_people += busStops[i].first; // total_people -= busStops[i].second; // } // return total_people; // } //#2 unsigned int number(const std::vector<std::pair<int, int>> &busStops) { int passengers = 0; for (auto i : busStops) passengers += i.first - i.second; return passengers; }<file_sep>/(7 kyu) Form The Minimum/(7 kyu) Form The Minimum.js // #1 // function minValue(values) { // const arr = [...values]; // arr.sort(); // const dedupe = arr.filter((x, i, a) => i === a.indexOf(x)); // const res = dedupe.join(''); // return parseInt(res); // } // #2 // function minValue(values) { // const arr = [...values]; // arr.sort(); // const dedupe = [...new Set(arr)]; // const res = dedupe.join(''); // return parseInt(res); // } // #3 // function minValue(values) { // const res = [...new Set([...values])].sort().join``; // return parseInt(res); // } // #4 const minValue = (values) => +[...new Set([...values])].sort().join``; <file_sep>/(8 kyu) Basic subclasses - Adam and Eve/(8 kyu) Basic subclasses - Adam and Eve.js class God { /** * @returns Human[] */ static create() { const Adam = new Man(); const Eve = new Woman(); return [Adam, Eve]; } } class Human { constructor() {} } class Man extends Human { constructor() { super(); } } class Woman extends Human { constructor() { super(); } } <file_sep>/(7 kyu) Form The Largest/(7 kyu) Form The Largest.ts export function maxNumber(n: number): number { const str = String(n); const arr = str.split('').map(Number); arr.sort((a: number, b: number): number => b - a); const res = arr.join(''); return parseInt(res); } <file_sep>/(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe/(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe.cpp #include <iostream> #include <cctype> std::string to_alternating_case(const std::string &str) { std::string ret = str; for (char &c : ret) { c = isupper(c) ? tolower(c) : toupper(c); } return ret; }<file_sep>/(4 kyu) Decode the Morse code, advanced/(4 kyu) Decode the Morse code, advanced.js const decodeBits = (bits) => { const arrayOfBits = bits.match(/(\d)\1*/g); // split for parts // find the length of symbols const length = Math.min( Infinity, ...arrayOfBits .filter( ( x, i, // remove some extra 0's ) => (i === 0 && x[0] === '1') || (i > 0 && i < arrayOfBits.length - 1) || (i === arrayOfBits.length - 1 && x[0] === '1'), ) .map((x) => x.length), ); return arrayOfBits.map((x) => { const symLength = x.length / length; // find the correct length return +x[0] // decode bits to Morse code ? symLength > 1 ? '-' : '.' : symLength > 3 ? ' ' : symLength > 1 ? ' ' : ''; }).join``; }; const decodeMorse = (morseCode) => { return morseCode .trim() //remove extra spaces .split(' ') //devide by words .map(( str, //parse each word ) => str .split(' ') //devide by symbols .map((s) => MORSE_CODE[s]) //return Char .join(''), ) .join(' '); }; <file_sep>/(8 kyu) Return Negative/(8 kyu) Return Negative.py # #1 # def make_negative( number ): # return number if number < 0 else - number # #2 def make_negative( number ): return -abs(number)<file_sep>/(7 kyu) Thinkful - String Drills. Repeater/(7 kyu) Thinkful - String Drills. Repeater.ts export function repeater(str: string, n: number): string { return new Array(n + 1).join(str); } <file_sep>/(6 kyu) Multiples of 3 or 5/(6 kyu) Multiples of 3 or 5.js // #1 // function solution(number) { // let result = 0; // for (let i = 1; i < number; i++) { // if (i % 3 == 0 || i % 5 == 0) { // result += i; // } // } // return result; // } // #2 // function solution(number) { // let result = 0; // for (let i = 1; i < number; i++) { // result += 0 === i % 3 || 0 === i % 5 ? i : 0; // } // return result; // } // #3 function solution(number) { return number < 1 ? 0 : [...new Array(number).keys()] .filter((n) => n % 3 == 0 || n % 5 == 0) .reduce((a, b) => a + b); } <file_sep>/(8 kyu) Counting sheep/(8 kyu) Counting sheep.cpp #include <vector> using namespace std; // #1 // int count_sheep(vector<bool> arr) // { // int res = 0; // for (auto i : arr) // { // if (i) // res++; // } // return res; // } // #2 #include <algorithm> int count_sheep(std::vector<bool> arr) { return std::count(arr.begin(), arr.end(), true); }<file_sep>/(7 kyu) Number of People in the Bus/(7 kyu) Number of People in the Bus.rs // #1 // fn number(stops: &[(i32,i32)]) -> i32 { // stops.iter().map(|c| c.0 - c.1).sum() // } // #2 fn number(stops: &[(i32, i32)]) -> i32 { stops.iter().fold(0, |a, c| a + c.0 - c.1) } <file_sep>/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine/(5 kyu) Ninety Nine Thousand Nine Hundred Ninety Nine.ts export function numberToEnglish(x: number): string { let n = x.toString(); if (x < 0 || x > 99999 || n.indexOf('.') !== -1) { return ''; } const value = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninety', }; const getDozens = (n: number) => n <= 20 ? value[n] : `${value[n.toString()[0] + '0']} ${value[n.toString()[1]]}`; const getHundreds = (n: number) => n > 0 ? `${value[n.toString()]} hundred ` : ''; const getThousands = (n: number) => getDozens(n) + ' thousand '; let string: string; if (x <= 99) { string = getDozens(+n).replace(/\szero/g, ''); } else if (x === 100) { string = getHundreds(+n[0]); } else if (x > 100 && x < 999) { string = `${getHundreds(+n[0])}${getDozens(+n.slice(-2))}`; } else { const z = x < 9999 ? 1 : 2; string = `${getThousands(+n.slice(0, z))}${getHundreds( +n.slice(-3, -2), )}${getDozens(+n.slice(-2))}`; } return string.trim().replace(/\szero/g, ''); } <file_sep>/(7 kyu) Two to One/(7 kyu) Two to One.rs // #1 // fn longest(a1: &str, a2: &str) -> String { // let s = format!("{}{}", a1, a2); // let mut v = s.chars().collect::<Vec<char>>(); // v.sort(); // let mut res = String::new(); // for c in v.iter() { // if !res.contains(&c.to_string()) { // res.push(*c); // } // } // res.to_string() // } // #2 fn longest(a1: &str, a2: &str) -> String { let mut s = format!("{}{}", a1, a2).chars().collect::<Vec<char>>(); s.sort(); s.dedup(); s.into_iter().collect() } <file_sep>/(8 kyu) DNA to RNA Conversion/(8 kyu) DNA to RNA Conversion.ts export function DNAtoRNA(dna: string): string { return dna.replace(/T/g, 'U'); } <file_sep>/(8 kyu) If you can't sleep, just count sheep/(8 kyu) If you can't sleep, just count sheep.ts export function countSheep(num: number): string { let result = ''; for (let i = 1; i <= num; i++) { result += i + ' sheep...'; } return result; } <file_sep>/(7 kyu) Form The Minimum/(7 kyu) Form The Minimum.md # Form The Minimum (7kyu) https://www.codewars.com/kata/form-the-minimum ## Task Given a list of digits, return the smallest number that could be formed from these digits, using the digits only once ( ignore duplicates). ## Notes : - Only positive integers will be passed to the function (> 0 ), no negatives or zeros. ## Input >> Output Examples ```js 1- minValue ({1, 3, 1}) ==> return (13) ``` ## Explanation: (13) is the minimum number could be formed from {1, 3, 1}, Without duplications ```js 2- minValue({5, 7, 5, 9, 7}) ==> return (579) ``` ## Explanation: (579) is the minimum number could be formed from {5, 7, 5, 9, 7}, Without duplications ```js 3- minValue({1, 9, 3, 1, 7, 4, 6, 6, 7}) return ==> (134679) ``` ## Explanation: (134679) is the minimum number could be formed from {1, 9, 3, 1, 7, 4, 6, 6, 7}, Without duplications Enjoy Learning !! Zizou
6a2f5f466d8d9f445599c706166ce91dd6aa86a4
[ "JavaScript", "Markdown", "Rust", "Python", "TypeScript", "C++" ]
198
JavaScript
novsunheng/codewars
c54b1d822356889b91587b088d02ca0bd3d8dc9e
04fe3390df340d82155805fc94cc35cef2e178ed
refs/heads/master
<repo_name>gabeco123/supreme-scraper<file_sep>/main.py import requests import discord from discord.ext import commands from colorama import Fore, Back, Style class Bot(commands.Bot): def __init__(self): super().__init__(command_prefix="!", description="Supreme-Scraper") async def on_ready(self): await self.change_presence(activity=discord.Game("Supreme Info"), status=discord.Status.online, afk=False) print(Fore.GREEN + "Bot ready") async def on_message(self, message): if message.content[:1] == "!": try: response = requests.get("https://www.supremenewyork.com/mobile_stock.json") supreme = response.json() for i in supreme["products_and_categories"][message.content[1:].title()]: embed = discord.Embed(title="Product - " + str(i["name"]), description="", color=2899536) embed.set_author(name='Supreme-Scraper' , url="", icon_url='') embed.set_thumbnail(url="https:" + (i["image_url"])) embed.add_field(name='Item-name' , value=str(i["name"])) embed.add_field(name='Price', value="$" + str(i["price"]//100)) embed.add_field(name='ID', value=i["id"]) embed.add_field(name='Product-Link', value="https://supremenewyork.com/shop/" + str((i["id"]))) embed.set_footer(text='') product_response = requests.get("https://www.supremenewyork.com/shop/{}.json".format(i["id"])) product_api = product_response.json() for style in product_api["styles"]: for size in style["sizes"]: if size["stock_level"]: print(Fore.GREEN + "https://supremenewyork.com/shop/" + str(i["id"]) + " Is In Stock") else: print(Fore.GREEN + "https://supremenewyork.com/shop/" + str(i["id"]) + " Is Out Of Stock") await message.channel.send(embed=embed) except: await message.channel.send("") bot = Bot() bot.run("Insert-Your-Bot-Token-Here") <file_sep>/README.md # supreme-scraper supreme scraper discord bot
b44dd05467e8e9dee2f150942e7d50286834012f
[ "Markdown", "Python" ]
2
Python
gabeco123/supreme-scraper
17e4c4aba814b7619ace13e2d2558b3db550f9a9
ae3a7c252a0408e1ad56df8b63c6908780cbcee9
refs/heads/master
<repo_name>JustAboutJeff/trilogy_education<file_sep>/src/TrueFalse/TrueFalse.js import React, { Component } from "react" import PropTypes from "prop-types" import "./TrueFalse.css" import uid from "../uid" class TrueFalse extends Component { constructor(props) { super(props) this.nameUid = uid() } handleChange = e => { const response = e.target.value this.props.onChange(response) } render() { const { prompt, response } = this.props const trueChecked = response === "true" const falseChecked = response === "false" return ( <form className="true-false-form"> <fieldset onChange={this.handleChange} className="true-false-fieldset"> <legend>{prompt}</legend> <label className="true-false-label"> <input type="radio" name={this.nameUid} value="true" checked={trueChecked} className="true-false-input" /> {"True"} </label> <label className="true-false-label"> <input type="radio" name={this.nameUid} value="false" checked={falseChecked} className="true-false-input" /> {"False"} </label> </fieldset> </form> ) } } TrueFalse.propTypes = { onChange: PropTypes.func, prompt: PropTypes.string } TrueFalse.defaultProps = { onChange: Function.prototype, prompt: "" } export default TrueFalse <file_sep>/src/Score/Score.js import React, { Component } from "react" import PropTypes from "prop-types" import "./Score.css" class Score extends Component { isCorrect(answer, response) { const answerSet = answer instanceof Set const responseSet = response instanceof Set if (!answerSet && !responseSet) { return answer === response } if (answerSet && responseSet) { // NOTE: all responses appear in the answer for (const r of response) { if (!answer.has(r)) return false } // NOTE: all answers appear in the response for (const a of answer) { if (!response.has(a)) return false } return true } return false } stringify(subject) { const response = subject instanceof Set ? Array.from(subject).join(" ") : subject && subject.trim() return response || "No Response" } renderScore() { let correctCount = 0 return this.props.score .map(({ answer, response, prompt }, idx) => { const isCorrect = this.isCorrect(answer, response) const style = isCorrect ? (correctCount++, "score-correct") : "score-incorrect" const mark = isCorrect ? "✔︎" : "✗" return ( <p key={idx}> <small> <i>{prompt}</i> </small> <br/> <span className={style}>{`${mark} ${this.stringify(response)}`}</span> </p> ) }) .concat( <p key={"last"} className="score-summary"> {`${correctCount}/${this.props.score.length}`} </p> ) } render() { return ( <div className="score"> <p>Congratulations! You finished the quiz.</p> {this.renderScore()} </div> ) } } Score.propTypes = { score: PropTypes.array } Score.defaultProps = { score: [] } export default Score <file_sep>/src/Page/Page.js import React, { Component } from "react" import PropTypes from "prop-types" import "./Page.css" class Page extends Component { renderHeader() { const { page } = this.props return ( <header className="heading"> <h1 className="heading-h1">{"Code Quiz"}</h1> <div className="heading-spin">{"\u2328"}</div> <div className="heading-subtitle">{page.headerMessage}</div> </header> ) } renderMain() { const { onResponse, page, score } = this.props return ( <main className="main"> <page.type {...page} score={score} onChange={onResponse} /> </main> ) } renderFooter() { const { canPageBackward, canPageForward, onPageBackward, onPageForward, onReset } = this.props return ( <footer className="footer"> <button className="footer-button" disabled={!canPageBackward} onClick={onPageBackward} children={"\u23ea"} /> <button className="footer-button footer-reset" onClick={onReset} children={"Reset Entire Quiz"} /> <button className="footer-button" disabled={!canPageForward} onClick={onPageForward} children={"\u23e9"} /> </footer> ) } render() { return ( <div className="page"> {this.renderHeader()} {this.renderMain()} {this.renderFooter()} </div> ) } } Page.propTypes = { canPageBackward: PropTypes.bool, canPageForward: PropTypes.bool, onPageBackward: PropTypes.func, onPageForward: PropTypes.func, onResponse: PropTypes.func, onReset: PropTypes.func, score: PropTypes.array, page: PropTypes.shape({ choices: PropTypes.any, headerMessage: PropTypes.string, prompt: PropTypes.string, response: PropTypes.any, type: PropTypes.any }) } Page.defaultProps = { canPageBackward: false, canPageForwadr: false, onPageBackward: Function.prototype, onPageForward: Function.prototype, onResponse: Function.prototype, onReset: Function.prototype, score: [], page: { choices: [], prompt: "", response: "", type: "div" } } export default Page <file_sep>/src/Instructions/Instructions.js import React, { Component } from "react" import "./Instructions.css" class Instructions extends Component { render() { return ( <div className="instructions"> <p>{`Welcome! This is a quiz designed to test your code knowledge.`}</p> <p> {`You will work through each question, one at a time. You must provide an answer to move forward to the next question.`} </p> <p> {`You can always go backward and revisit a previous question using the navigation buttons at the bottom of the page.`} </p> <p> {`Your answers will be automatically saved as you work, and will be available even if you navigate to another question.`} </p> <p> {`When you are finished with all questions, you will be prompted to submit your quiz for scoring.`} </p> <p> {`After submitting, you can view your score but cannot edit any of your answers.`} </p> <p>{`Simply hit the reset button below to take the quiz again.`}</p> <p>{`Enjoy!`}</p> </div> ) } } export default Instructions <file_sep>/src/App/initialState.js import Instructions from "../Instructions" import MultipleChoice from "../MultipleChoice" import FillBlank from "../FillBlank" import TrueFalse from "../TrueFalse" import Score from "../Score" export default { didSubmit: false, page: 0, workflow: [ { type: Instructions, headerMessage: "Instructions" }, { type: MultipleChoice, headerMessage: "Question 1/3", prompt: "Which of the following programming languages were developed prior to 1960?", choices: ["Fortran", "Cobol", "Lisp", "Perl"], answer: new Set("Fortran Cobol Lisp".split(" ")), response: undefined }, { type: FillBlank, headerMessage: "Question 2/3", prompt: "In Javascript, 0 + {} would obviously result in what?", answer: "0[object Object]", response: undefined }, { type: TrueFalse, headerMessage: "Question 3/3", prompt: "Software development is a team sport?", answer: "true", response: undefined }, { type: Score, headerMessage: "Score" } ] } <file_sep>/src/App/App.test.js import React, { isValidElement } from "react" import ReactDOM from "react-dom" import App from "./index" describe("App", function() { const element = <App /> it("returns a valid React element", function() { expect(isValidElement(element)).toEqual(true) }) it("renders without crashing", function() { const div = document.createElement("div") ReactDOM.render(element, div) ReactDOM.unmountComponentAtNode(div) }) }) <file_sep>/src/MultipleChoice/MultipleChoice.js import React, { Component } from "react" import PropTypes from "prop-types" import "./MultipleChoice.css" import uid from "../uid" class MultipleChoice extends Component { handleChange = e => { const { checked: isChecked, value } = e.target const response = new Set(this.props.response) if (isChecked) { response.add(value) } else { response.delete(value) } this.props.onChange(response) } renderChoices() { const { response, choices } = this.props return choices.map((choice, idx) => { const choiceUid = uid() const isChecked = response.has(choice) return ( <div key={idx}> <label className="multiple-choice-label"> <input checked={isChecked} type="checkbox" name={choiceUid} value={choice} className="multiple-choice-input" /> {choice} </label> </div> ) }) } render() { const { prompt } = this.props return ( <form className="multiple-choice-form"> <fieldset onChange={this.handleChange} className="multiple-choice-fieldset" > <legend>{prompt}</legend> {this.renderChoices()} </fieldset> </form> ) } } MultipleChoice.propTypes = { choices: PropTypes.array, onChange: PropTypes.func, prompt: PropTypes.string, response: PropTypes.instanceOf(Set) } MultipleChoice.defaultProps = { choices: [], onChange: Function.prototype, prompt: "", response: new Set() } export default MultipleChoice <file_sep>/src/Score/index.js export { default } from "./Score" export * from "./Score" <file_sep>/src/App/App.js import React, { Component } from "react" import "./App.css" import initialState from "./initialState" import MultipleChoice from "../MultipleChoice" import FillBlank from "../FillBlank" import TrueFalse from "../TrueFalse" import Page from "../Page" class App extends Component { constructor(props) { super(props) this.state = Object.assign({}, initialState) } handleResponse = response => { const { workflow: original, page } = this.state const workflow = original.slice() workflow[page] = Object.assign({}, this.activePage, { response }) this.setState(prev => Object.assign({}, prev, { workflow })) } handlePageForward = e => { e.preventDefault() this.setState(function(prev) { const newState = { page: prev.page + 1 } const isLastPage = newState.page === prev.workflow.length - 1 if ( isLastPage && window.confirm( "Submit your quiz? You cannot edit your answers after this point" ) ) { newState.didSubmit = true } else if (isLastPage) { return prev } return Object.assign({}, prev, newState) }) } handlePageBackward = e => { e.preventDefault() this.setState(prev => Object.assign({}, prev, { page: prev.page - 1 })) } handleReset = e => { e.preventDefault() this.setState(prev => Object.assign({}, initialState)) } isQuestionPage({ type } = this.activePage) { return [MultipleChoice, FillBlank, TrueFalse].includes(type) } get activePage() { const { workflow, page } = this.state return workflow[page] } get score() { return this.state.workflow.filter(this.isQuestionPage) } get hasResponse() { return Boolean(!this.isQuestionPage() || this.activePage.response) } get canPageForward() { const { workflow, page } = this.state return this.hasResponse && page + 1 < workflow.length } get canPageBackward() { const { didSubmit, page } = this.state return !didSubmit && page - 1 >= 0 } render() { return ( <Page canPageBackward={this.canPageBackward} canPageForward={this.canPageForward} page={this.activePage} score={this.score} onPageBackward={this.handlePageBackward} onPageForward={this.handlePageForward} onResponse={this.handleResponse} onReset={this.handleReset} /> ) } } export default App <file_sep>/src/uid.test.js import uid from "./uid" describe("uid", function() { it("exports a function", function() { expect(typeof uid).toEqual("function") }) it("returns a unique string for each invocation", function() { const first = uid() const second = uid() expect(typeof first).toEqual("string") expect(typeof second).toEqual("string") expect(first).not.toEqual(second) }) }) <file_sep>/src/FillBlank/FillBlank.js import React, { Component } from "react" import PropTypes from "prop-types" import "./FillBlank.css" class FillBlank extends Component { handleChange = e => { const response = e.target.value this.props.onChange(response) } render() { const { prompt, response } = this.props return ( <form className="fill-blank-form"> <fieldset className="fill-blank-fieldset"> <legend>{prompt}</legend> <label> <input className="fill-blank-input" type="text" placeholder={"Enter your answer here"} value={response} onChange={this.handleChange} /> </label> </fieldset> </form> ) } } FillBlank.propTypes = { onChange: PropTypes.func, prompt: PropTypes.string, response: PropTypes.string } FillBlank.defaultProps = { onChange: Function.prototype, prompt: "", response: "" } export default FillBlank
e23760bc924377559f1f1a60a329f5351143577c
[ "JavaScript" ]
11
JavaScript
JustAboutJeff/trilogy_education
e9558d712762e60e4890d800105bb7293f1afbbe
7105e75e4a4d600189f051c8e1a802d1db108367
refs/heads/master
<repo_name>JacquiKane/CookieHierarchy<file_sep>/cookie.js var imagesAll = new Array(); for (i = 0; i < 7; i++) { imagesAll[i] = new Image(); imagesAll[i].src = 'mixer' + i + '.png'; } var ovensAll = new Array(); for (j = 0; j < 2; j++) { ovensAll[j] = new Image(); ovensAll[j].src = 'oven' + j + '.png'; } var cookiesOnPlate = new Array(); for (j = 0; j < 4; j++) { cookiesOnPlate[j] = new Image(); cookiesOnPlate[j].src = 'plate' + j + '.png'; } function animateMixer() { document.getElementById('mixingbowlwannabe').src = imagesAll[counter].src; counter = counter + 1; var ani = setTimeout('animateMixer()', 200); if (counter >= imagesAll.length) { clearTimeout(ani); counter = 0; } } function animateBake() { document.getElementById('oven').src = ovensAll[1].src; } function animateServe() { document.getElementById('servecookie').src = cookiesOnPlate[cookieNumber].src; } var counter = 0; var currentX = 100; var currentY = 100; function getDistanceToBowl() { var bb = document.querySelector('#mixingbowl') .getBoundingClientRect(), distance = bb.top - 150; return distance; } function disableInstanceMethods() { $('.methodButton').prop('disabled', true); } function enableInstanceMethods() { $('.methodButton').prop('disabled', false); if (mixed && baked) $("#servebutton").prop('disabled', false); else $("#servebutton").prop('disabled', true); } xDisp = 0; yDisp = 10; recurring = 0; var runAnimater; var ingredients; var cookieName; var cookieNumber; var mixed = false; var baked = false; function animateButter() { var distance = getDistanceToBowl(); runAnimater = setTimeout('animateButter()', 50); document.getElementById(ingredients).style.left = currentX + 'px'; document.getElementById(ingredients).style.top = currentY + 'px'; if (currentY > distance) { currentX = 0; currentY = 50; clearTimeout(runAnimater); enableInstanceMethods(); } else { currentX += xDisp; currentY += yDisp; } } function resetMethodImages() { document.getElementById('mixingbowlwannabe').src = imagesAll[0].src; document.getElementById('oven').src = ovensAll[0].src; document.getElementById('servecookie').src = cookiesOnPlate[0].src; } function resetIngredients() { /* var allIngredients = ['plainingredients', 'chocchipingredients', 'nutchocchipingredients']; alert("resetting ingreds"); for (var ingred in allIngredients) { document.getElementById(ingred).style.left = 50 + 'px'; document.getElementById(ingred).style.top = 10 + 'px'; } */ document.getElementById('plainingredients').style.left = 10 + 'px'; document.getElementById('plainingredients').style.top = 100 + 'px'; document.getElementById('chocchipingredients').style.left = 10 + 'px'; document.getElementById('chocchipingredients').style.top = 100 + 'px'; document.getElementById('nutchocchipingredients').style.left = 10 + 'px'; document.getElementById('nutchocchipingredients').style.top = 100 + 'px'; mixed = false; baked = false; disableInstanceMethods(); } function getCoordinates(elem) { var LeftPos = elem.offsetLeft; var TopPos = elem.offsetTop; return { X: LeftPos, Y: TopPos }; } function loaded() { $('#mix').on('click', function(e) { alert("Mixing ingredients!"); mixed = true; runMixer = setTimeout('animateMixer()', 100); }); $('#bake').on('click', function(e) { alert("Baking!"); baked = true; runBake = setTimeout('animateBake()', 100); }); $('#serve').on('click', function(e) { if (!(mixed && baked)) alert("Make sure you mix and bake first!"); else runServe = setTimeout('animateServe()', 100); }); $('#makeacookie').on('click', function(e) { resetIngredients(); resetMethodImages(); // All cookies var radioValue = $("input[name='cookies']:checked").val(); if (radioValue) { switch (radioValue) { case "1": ingredients = "plainingredients"; cookieName = "Plain Cookie"; cookieNumber = 1; break; case "2": ingredients = "chocchipingredients"; cookieName = "Chocolate Chip Cookie"; cookieNumber = 2; break; case "3": ingredients = "nutchocchipingredients"; cookieName = "Nut Chocolate Chip Cookie"; cookieNumber = 3; break; } jQuery(document).ready(function($) { alert("Calling constructor with ingredients! ... " + cookieName) }); } runAnimater = setTimeout('animateButter()', 100); }); disableInstanceMethods(); } window.addEventListener('load', loaded);<file_sep>/plaincookie.java /* * Grandparent class in a 3 layer hierarchy. Recipe! Typical for just 1 cookie. Vary ingredients to vary cookie. 2.5 grams soft unsalted butter 6 grams soft light brown sugar 5 grams caster sugar 0.4 teaspoons pure vanilla extract .05 egg 15 grams self raising flour 6 grams milk chocolate morsels or chips 6 grams mixed nuts */ package pkg9_inheritance; /** * * @author <NAME> */ public class PlainCookie { private double gramsButter; private double gramsSugar; private double quantityEgg; private double gramsSelfRaisingFlour; public PlainCookie(double gramsButter, double gramsSugar, double quantityEgg, double gramsSelfRaisingFlour) { this.gramsButter = gramsButter; this.gramsSugar = gramsSugar; this.quantityEgg = quantityEgg; this.gramsSelfRaisingFlour = gramsSelfRaisingFlour; } public double getGramsButter() { return gramsButter; } public void setGramsButter(double gramsButter) { this.gramsButter = gramsButter; } public double getGramsSugar() { return gramsSugar; } public void setGramsSugar(double gramsSugar) { this.gramsSugar = gramsSugar; } public double getQuantityEgg() { return quantityEgg; } public void setQuantityEgg(double quantityEgg) { this.quantityEgg = quantityEgg; } public double getGramsSelfRaisingFlour() { return gramsSelfRaisingFlour; } public void setGramsSelfRaisingFlour(double gramsSelfRaisingFlour) { this.gramsSelfRaisingFlour = gramsSelfRaisingFlour; } public void mix() { System.out.println("Mix wet and dry ingredients for 2 minutes"); } public void bake() { System.out.println("Add mixture to non-stick cookie pan\n" + "and bake at 350 degrees for 10 minutes."); } } <file_sep>/nutchocolatechipcookie.java /* * Child class or subclass of ChocolateChipCookie * Child class in a 3 layer hierarchy. Recipe! Typical for just 1 cookie. Vary ingredients to vary cookie. 2.5 grams soft unsalted butter 6 grams soft light brown sugar 5 grams caster sugar 0.4 teaspoons pure vanilla extract .05 egg 15 grams self raising flour 6 grams milk chocolate morsels or chips 6 grams mixed nuts */ package pkg9_inheritance; /** * * @author <NAME> */ public class NutChocolateChipCookie extends ChocolateChipCookie{ private double gramsMixedNuts; public NutChocolateChipCookie(double gramsMixedNuts, double gramsChocolateChips, double gramsButter, double gramsSugar, double quantityEgg, double gramsSelfRaisingFlour) { super(gramsChocolateChips, gramsButter, gramsSugar, quantityEgg, gramsSelfRaisingFlour); this.gramsMixedNuts = gramsMixedNuts; } public double getGramsMixedNuts() { return gramsMixedNuts; } public void setGramsMixedNuts(double gramsMixedNuts) { this.gramsMixedNuts = gramsMixedNuts; } public void bake() { System.out.println("Add mixture to non-stick cookie pan\n" + "and bake at 330 degrees for 8 minutes."); } }
4da7c21c7d733320e36e60d82a62a55b410ed4a6
[ "JavaScript", "Java" ]
3
JavaScript
JacquiKane/CookieHierarchy
e227417eda180fb91daac76bb0d4e8fb78fb8c7d
f69a91de080c25c28a5a6d4888f834329985dad6